release: Евномия, новая версия, линейка юристов
@@ -0,0 +1,18 @@
|
||||
# Подтверждение границы работы
|
||||
|
||||
08.09.2026. Сессия Эвномии прочитала `docs/LEGAL-BACKEND-HANDOFF.md`.
|
||||
|
||||
Правки общего backend остановлены. Агент графа подтвердил остановку;
|
||||
агент реестра и очереди прерван. Дальнейшие изменения этой сессии ограничены
|
||||
`eunomia/`, включая сервер, интерфейс и их тесты.
|
||||
|
||||
Уже внесённые изменения не откатываются. Помимо общего backend и его тестов,
|
||||
до уточнения границы были созданы `scripts/eunomia.py` и `Eunomia.command`;
|
||||
дальнейших правок этих файлов до передачи не будет.
|
||||
|
||||
Приняты замечания о блокировке загрузчика обзоров. Регистрация источника
|
||||
не подтверждает полноту, редакцию или готовность парсера. Интерфейс должен
|
||||
сохранять эти ограничения и использовать согласованные API основного backend.
|
||||
|
||||
Установку фонового задания и приёмку общего backend ведёт основная сессия.
|
||||
Сессия Эвномии не выполняет общий git add, commit или установку фонового задания.
|
||||
@@ -0,0 +1,108 @@
|
||||
# Эвномия — дизайн-контракт
|
||||
|
||||
08.09.2026. Полная пересборка по поручению владельца.
|
||||
|
||||
## Назначение
|
||||
|
||||
Современная, чистая и удобная правовая библиотека. Главный маршрут: поиск →
|
||||
статья → связанные разъяснения → точный пункт. Второй: раздел → документ →
|
||||
оглавление → чтение. Интерфейс остается быстрым на большой локальной базе.
|
||||
|
||||
## Фактический frontend-стек
|
||||
|
||||
- React `19.2.8` + TypeScript `7.0.2`.
|
||||
- Vite `8.2.2` и Tailwind CSS `4.3.3`.
|
||||
- Локальные shadcn-компоненты из registry shadcn/ui, выбранные по подборке `21st.dev`: sidebar, command,
|
||||
dialog, sheet, tooltip, button, input, separator и skeleton. Источники,
|
||||
лицензии и SHA-256 зафиксированы в [qa/component-sources.md](qa/component-sources.md).
|
||||
- `Context7` использован для сверки React 19, Vite и shadcn API.
|
||||
- Иконки — собственный CSS-спрайт; внешние icon-пакеты для визуала Эвномии
|
||||
не добавлялись.
|
||||
|
||||
## Выбранное направление
|
||||
|
||||
Редакционный минимализм: белые поверхности, ясная иерархия, спокойный хвойный
|
||||
акцент, книжная типографика. Плоские элементы управления и фотореалистичные
|
||||
коллекционные обложки выполняют две роли: управление и узнавание документа.
|
||||
|
||||
| Токен | Значение | Назначение |
|
||||
|---|---|---|
|
||||
| Фон | `#FFFFFF` | Основная поверхность и чтение |
|
||||
| Навигация | `#F6F7F8` | Боковая панель |
|
||||
| Текст | `#202824` | Заголовки и основной текст |
|
||||
| Акцент | `#244B40` | Действия, выбранный раздел, фокус |
|
||||
| Подложка | `#EDF4F0` | Активный элемент |
|
||||
| UI | native system sans, 16px | Подписи и управление |
|
||||
| Заголовки | Georgia, 36–60px | Разделы библиотеки |
|
||||
| Чтение | Georgia, 20px, 1.8 | Длинный текст, до 72ch |
|
||||
|
||||
Золото только внутри иллюстраций. Оно не обозначает проверенность,
|
||||
действующую редакцию или полноту документа.
|
||||
|
||||
## Экраны
|
||||
|
||||
- Библиотека: крупный поиск и примеры, пять разделов, полка четырех кодексов,
|
||||
переход к связям документов. Счетчики берутся из реальных данных.
|
||||
- Кодексы: индивидуальные обложки, точные названия, фильтр, части и оглавление.
|
||||
Остальные законы — текстовые плашки с настоящими названиями.
|
||||
- Пленумы: выбор направления, затем хронология, фильтры года и порядка.
|
||||
- Поиск: контекст совпадения, вид документа, точный переход к фрагменту.
|
||||
- Чтение: оглавление, текст, панель связей; режим сосредоточенного чтения;
|
||||
постоянная ссылка, масштаб текста, поиск, источник и история редакций.
|
||||
- История и обновления: реальные состояния; отсутствующие данные объяснены.
|
||||
- Граф: читаемые названия, явные действия просмотра связей и открытия текста;
|
||||
доказательство связи рядом с выбранным фрагментом.
|
||||
|
||||
При 1600px и шире доступны постоянные три колонки чтения. Ниже панель связей
|
||||
открывается по кнопке; до 1100px оглавление сворачивается. До 760px основная
|
||||
навигация открывается отдельно. Один основной скролл страницы.
|
||||
|
||||
## Движение и доступность
|
||||
|
||||
Нажатие: 120ms. Панель/обратная связь: 180–240ms, ease-out. Нет анимации
|
||||
перехода к статье или набора текста. Переходы по результатам поиска не ждут анимации.
|
||||
`prefers-reduced-motion` отключает движение. Нет бесконечной анимации.
|
||||
|
||||
Целевые критерии: кликабельные области от 44px; контраст обычного текста от 4.5:1; видимый фокус;
|
||||
подписи у иконок; логичный порядок Tab; Escape закрывает панели и возвращает
|
||||
фокус. Режим чтения имеет доступную кнопку выхода. Масштаб 200% и экран 390px
|
||||
не создают горизонтальной прокрутки. Полная WCAG-сертификация не заявляется.
|
||||
|
||||
## Изображения
|
||||
|
||||
Встроенный imagegen Codex. Отдельная новая обложка для каждого из 12 кодексов:
|
||||
светлая льняная фактура, точное название выгравировано и заполнено матовым
|
||||
золотом. В production используются lossless WebP; исходные PNG сохраняются
|
||||
как оригиналы. Надпись визуально сверяется; доступное название дублируется в
|
||||
HTML. Иконки — собственный лист 4×4, показываемый как CSS-спрайт.
|
||||
Исходники и промпты: `qa/covers-a.md`, `qa/covers-b.md`, `qa/icons-provenance.md`.
|
||||
|
||||
## Арсенал
|
||||
|
||||
Применены следующие скиллы:
|
||||
|
||||
- `ux-designer` — сценарии, информационная архитектура и состояния;
|
||||
- `frontend-design` — визуальное решение интерфейса;
|
||||
- `frontend-builder` — реализация React-поверхности и responsive-поведение;
|
||||
- `design-system-architect` — токены, компоненты и единый контракт;
|
||||
- `emil-design-eng` — умеренные анимации и motion-правила;
|
||||
- `accessibility` — keyboard, focus, contrast и семантика;
|
||||
- `imagegen` — 12 обложек и авторские изображения;
|
||||
- `ponytail` — простая реализация без лишних слоев;
|
||||
- `caveman` — краткая рабочая коммуникация;
|
||||
- `humanizer-ru` — живой русский текст.
|
||||
|
||||
Проверка — установленный Python Playwright и unittest. Зависимости закреплены в package-lock.json. Внешний дизайн-сервис для запуска не нужен.
|
||||
|
||||
## Основания и приемка
|
||||
|
||||
[Синтез базы знаний](qa/design-knowledge.md),
|
||||
[сравнение референсов](qa/design-references.md).
|
||||
|
||||
Проверяем реальные сценарии, клавиатуру, контраст, уменьшенное движение,
|
||||
размеры 390/720/1000/1440/1920, изображения и отсутствие ошибок JavaScript.
|
||||
Скриншоты и результаты — в `qa/`. Прежний `qa/latestqa.md` относится к старому
|
||||
интерфейсу и не считается приемкой этой версии.
|
||||
|
||||
Общий backend принадлежит другой сессии. Основная работа ограничена `eunomia/`, исправление проверок — `tests/test_eunomia.py`;
|
||||
допуск нормативных текстов и загрузчиков остается отдельной процедурой.
|
||||
@@ -0,0 +1,112 @@
|
||||
# Эвномия
|
||||
|
||||
Локальный React-интерфейс для чтения правовой базы Themiz. Новый экранный слой
|
||||
собран с нуля в направлении «Эвномия · Пантеон»: правовой поиск и чтение —
|
||||
главные сценарии, пантеонные образы и каменные плиты кодексов — ориентиры, а не
|
||||
декоративный фон. Исследовательская спецификация и ограничения находятся в
|
||||
`qa/pantheon-ux-research.md` и `PANTHEON-DESIGN.md`.
|
||||
|
||||
Frontend собран на React 19.2.8, TypeScript 7, Vite 8.2.2 и Tailwind CSS
|
||||
4.3.3. Базовые shadcn/Radix-примитивы взяты из registry shadcn/ui по подборке
|
||||
21st.dev; источники и лицензии записаны в `qa/component-sources.md`. API React,
|
||||
Vite и shadcn сверены через Context7.
|
||||
|
||||
## Запуск frontend
|
||||
|
||||
Из корня проекта:
|
||||
|
||||
```sh
|
||||
npm --prefix eunomia/frontend ci
|
||||
npm --prefix eunomia/frontend run build
|
||||
```
|
||||
|
||||
## Запуск локального приложения
|
||||
|
||||
Из корня проекта:
|
||||
|
||||
```sh
|
||||
python3 scripts/eunomia.py
|
||||
```
|
||||
|
||||
Сервер использует корень данных Themiz из конфигурации проекта и открывает
|
||||
`http://127.0.0.1:18765/`.
|
||||
|
||||
Для ручного запуска без автоматического открытия браузера:
|
||||
|
||||
```sh
|
||||
python3 scripts/eunomia.py --serve --root /actual/path/to/themiz --port 18765 --no-open
|
||||
```
|
||||
|
||||
`--root` принимает фактический путь к каталогу данных Themiz; значение выше —
|
||||
пример и не является зашитым путем.
|
||||
|
||||
## Что реализовано
|
||||
|
||||
- пантеонная библиотека с единым поиском, пятью типами корпуса и реальными
|
||||
действиями навигации;
|
||||
- образ Эвномии и двенадцать горизонтальных мраморных плит кодексов с точными
|
||||
короткими названиями, физически золотой гравировкой, PNG-оригиналами и
|
||||
lossless WebP для runtime;
|
||||
- чтение статьи с оглавлением, соседними статьями, источником, редакциями,
|
||||
копированием якоря, проверяемыми связями и возвратом к недавнему месту;
|
||||
- клавиатурный поиск `Cmd/Ctrl+K`, сворачиваемая навигация и мобильные панели;
|
||||
- локальные лицензии шрифтов Golos Text и Source Serif 4 в
|
||||
`frontend/src/pantheon/fonts/`.
|
||||
|
||||
Действующий дизайн-контракт — `PANTHEON-DESIGN.md`. Синтез базы знаний,
|
||||
исследования и список примененных скиллов — `qa/design-knowledge.md`,
|
||||
`qa/pantheon-ux-research.md` и `qa/pantheon-delivery.md`. Источники
|
||||
shadcn-компонентов — `qa/component-sources.md`.
|
||||
|
||||
|
||||
## Проверка Pantheon
|
||||
|
||||
```sh
|
||||
npm --prefix eunomia/frontend run build
|
||||
python3 -m unittest discover -s eunomia/tests -p 'test_*.py'
|
||||
python3 -m unittest discover -s tests -p 'test_eunomia.py'
|
||||
python3 eunomia/tests/pantheon_check.py
|
||||
python3 eunomia/tests/pantheon_visual.py
|
||||
python3 eunomia/tests/ui_stack_check.py
|
||||
```
|
||||
|
||||
`ui_stack_check.py` держит восемь дефектов аудита UI Stack от 22.09.2026: каждая проверка названа номером дефекта (Д-001…Д-008) и краснеет, если правка откатилась. В наборе `unittest` её запускает `test_ui_stack_gate.py` и сам поднимает сервер на свободном порту. axe-core ставится вместе с фронтендом (`npm ci` в `eunomia/frontend`).
|
||||
|
||||
Браузерные команды требуют запущенную Эвномию на `127.0.0.1:18765` и локальный Python Playwright/Chromium. Итог приемки: [qa/pantheon-delivery.md](qa/pantheon-delivery.md). Старые `browser_check.py` и `redesign_check.py` описывают предыдущий интерфейс; актуальные сценарии находятся в `pantheon_check.py`.
|
||||
|
||||
## Судебная практика
|
||||
|
||||
Раздел хранит акты СудАкта 2026 года: полный текст, адрес источника, время загрузки и SHA-256.
|
||||
|
||||
- Корпус собирает Lynceuz. Эвномия берет его только через `corpus export` и сверяет каждый текст с хешем экспорта. На sudact.ru Эвномия сама не ходит.
|
||||
- Хранилище лежит вне git: `.agent/maintenance/practice/practice.sqlite3`. В нем акты, сжатые тексты, полнотекстовый индекс и связи «акт — статья», которые считает `legal_graph.article_refs`.
|
||||
- Отрасли описаны в `eunomia/practice_taxonomy.json`. Первая — семейные споры, шесть подкатегорий. Акт попадает в подкатегорию по предмету требования или по статьям главы СК. Причина видна в карточке акта.
|
||||
- Задача обновления запускается каждый час и забирает новые акты из Lynceuz. Пока корпус не скачан до конца, она качает его частями подряд, без пауз, и после каждой части забирает новые акты в Эвномию. Быстрая скорость — до 10 запросов в секунду, части по 15 минут (решение владельца 02.10.2026). Если СудАкт отказал или в части больше 10% сбоев, задача переходит на вежливую скорость — до 2 запросов в секунду, части по 55 минут — и сама больше не ускоряется; после ответа 429 повторяет через час. Скорость видна в `status`. Когда карта СудАкта пройдена, сборка идет раз в неделю. При отказе СудАкта задача ждет неделю, по правилу Lynceuz. Если запрос не выпустил сам Lynceuz (`policy_denied`), сайт ни при чем: мешает сеть машины, обычно VPN. Тогда задача повторяет сборку при следующем запуске, в том числе сразу после `install`. Так же задача поступает, если robots.txt не ответил и после повторов Lynceuz: `robots_denied` позже 150 секунд — сбой сети, а не отказ. Итог виден на странице «Состояние базы» и в `/api/status`.
|
||||
- launchd не читает `~/.zshenv`. Поэтому `install` переносит в задачу переменную `LYNCEUZ_FAKE_IP_POOLS` из оболочки, где его запустили. Без нее VPN с fake-IP подменяет адрес СудАкта, и Lynceuz не выпускает запрос. Сменился пул VPN — снова выполните `install`: прежнее задание заменится и перезапустится.
|
||||
- Страница загрузки: `.agent/maintenance/practice/status/index.html` в корне Themiz, открывается в браузере как файл. Одна полоса от 0 до 100 %: сколько актов скачано из карты СудАкта, скорость и сколько осталось. Задача `com.themiz.practice-status` обновляет страницу раз в минуту. Если данные старше 3 минут, страница пишет «нет свежих данных». Скачанное считается по всем корням Lynceuz без повторов.
|
||||
- Параллельная докачка: задача `com.themiz.practice-parts` (решение владельца 02.10.2026, «Ступенями»). Карта делится на 10 частей по первой букве номера акта, у каждой части свой корень данных в `.agent/maintenance/practice/parts/`. Сначала идут 5 частей; кусок без отказа включает все 10. Отказ СудАкта или всплеск сбоев в любой части останавливает докачку всех частей насовсем. Чтобы снять остановку, удалите `parts/state.json`. После каждого куска новые акты частей идут в Эвномию. Предел на этом Mac — около 300 актов в минуту: упирается процессор, а не сайт. Замер и что исправить в Lynceuz — `docs/remont/lynceuz-skorost-2026-10-02.md`.
|
||||
- Каждый день части обходят карту СудАкта, докачивают новые акты и переносят их в Эвномию. Потом новые данные встраиваются в общий граф права `.agent/maintenance/practice/graph/graphify-out/graph.json`: у статей обновляется число актов, ребра практики заменяются, узлы норм и сообщества остаются, около 12 секунд. Полная сборка (около минуты) — только когда сменился снимок `legal_graph` или по команде `graph --full`. В нем нормативный граф `legal_graph` (кодексы, пленумы, индекс практики) без текстов и практика Эвномии: статьи с числом цитирующих актов, отрасли, ребра «цитируют вместе» (от 10 актов). Статьи сливаются по ID узла нормативного графа. Акты узлами не становятся. Сборка — библиотекой graphify, без LLM. Вопрос к графу: `graphify explain "Статья 333. Уменьшение неустойки" --graph .agent/maintenance/practice/graph/graphify-out/graph.json`.
|
||||
- Кнопки на странице «Состояние базы» (просьба владельца 03.10.2026). Карточка «Судебные акты» показывает полосу: сколько актов скачано из карты СудАкта, скорость и остаток, те же числа, что на странице загрузки. Кнопка «Обновить судебные акты» шлет `POST /api/practice/refresh`. Сервер кладет файл-просьбу `.agent/maintenance/practice/parts/refresh` и больше ничего не делает: Lynceuz не запускает, `parts/state.json` не пишет.
|
||||
- Задача частей запускается раз в минуту: при следующем запуске она снимает просьбу и начинает обход. Начало обхода сразу видно в `parts/state.json`: пропадает `done`, меняется `at`. Если части остановлены отказом СудАкта, сервер отвечает 409 и обход не запускает. Пока обход идет или просьба ждет задачу, кнопка занята.
|
||||
- Кнопка «Обновить законодательство» в карточке «Законодательство» шлет прежний `POST /api/update`: все документы библиотеки встают в очередь фоновой проверки. Полоса считает очередь `background_corpus.status()`: готово все, кроме заданий `queued` и `running`. Отложенные и недоступные источники очередь не держат, их число видно под полосой. Скорость считается по заданиям, законченным за 10 минут. Очередь не двигалась 10 минут: карточка пишет, что она стоит, и кнопка снова доступна.
|
||||
- Полосы опрашивают `GET /api/practice/progress` и `GET /api/update/progress` раз в 5 секунд, пока раздел открыт и вкладка видна. Сервер отдает один подсчет на 5 секунд: счет СудАкта по диску идет до 0,5 с.
|
||||
|
||||
```sh
|
||||
python3 eunomia/practice.py install # задача launchd: каждый час, первый запуск сразу
|
||||
python3 eunomia/practice.py status # сколько актов, когда импорт, что со сборкой
|
||||
python3 eunomia/practice.py tick --force-build # сборка и импорт вне очереди
|
||||
python3 eunomia/practice.py classify # переотнести акты после правки отраслей
|
||||
python3 eunomia/practice.py progress # доля скачанного по диску, JSON
|
||||
python3 eunomia/practice.py install --publish # страница загрузки, раз в минуту
|
||||
python3 eunomia/practice.py install --parts # параллельная докачка частями
|
||||
python3 eunomia/practice.py uninstall --parts # снять части
|
||||
python3 eunomia/practice.py graph [--full] # встроить практику в общий граф права; --full - пересобрать
|
||||
python3 -m unittest eunomia/tests/test_practice.py
|
||||
python3 eunomia/tests/practice_check.py
|
||||
```
|
||||
|
||||
`practice_check.py` открывает Chrome с диска и шлет запросы в обработчик Эвномии через socketpair, поэтому сервер и порт ему не нужны. `practice_check.py` проверяет кнопки «Состояния базы» на подмененных ответах: настоящий обход СудАкта и проверку законов приемка не запускает.
|
||||
|
||||
Замер 01.10.2026 на 2 701 акте: импорт — 31 с, связей со статьями — 32 875. Повторный импорт того же файла — 0,2 с, без изменений. Поиск словами — 92 мс, по статье — 41 мс, открытие акта — 11 мс. Ст. 333 ГК цитируют 218 актов. Семейных споров — 20 актов в шести подкатегориях, пересечений — три.
|
||||
|
||||
Замер 02.10.2026 на 97 236 актах: реальные акты размножены ×36, база — 1,9 ГБ. Список — 72 мс, поиск словами — 0,2–0,3 с, по статье — 0,12 с. Открытие акта — 42 мс, практика по статье — 2 мс. Фасеты и дерево отраслей считаются один раз после записи в базу — 1,2 с — и дальше идут из кеша. Импорт — 11,6 мс на акт; по расчету полный корпус в 96 тыс. актов займет 19 минут.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Эвномия
|
||||
|
||||
Локальный интерфейс для чтения правовой базы Themiz. Изменения интерфейса,
|
||||
сервера и его тестов изолированы в `eunomia/`. Общий нормативный backend
|
||||
остаётся в ведении основной сессии: `docs/LEGAL-BACKEND-HANDOFF.md`.
|
||||
|
||||
## Открыть
|
||||
|
||||
Из корня проекта:
|
||||
|
||||
```sh
|
||||
python3 scripts/eunomia.py
|
||||
```
|
||||
|
||||
Адрес: `http://127.0.0.1:18765/`. Уже открытая страница получает новый
|
||||
интерфейс после обычной перезагрузки браузера.
|
||||
|
||||
## Навигация
|
||||
|
||||
- Главная показывает пять разделов, а не весь массив документов.
|
||||
- Пленумы открываются по направлениям. Есть отдельный полный список.
|
||||
- В списках — максимум 12 документов на странице, фильтр по году,
|
||||
сортировка по дате акта от ранних к поздним и обратный порядок.
|
||||
- Дата акта извлекается из реквизитов или заголовка; дата редакции
|
||||
не используется вместо неё. Неизвестные даты помещаются в конец списка.
|
||||
- Направления — вспомогательная группировка по названию и предмету документа.
|
||||
Это не подтверждённая правовая связь. Один акт может быть в нескольких группах.
|
||||
- Название и кнопка «Читать» открывают сохранённый полный текст.
|
||||
- Поиск статьи открывает нужный фрагмент. Прямая ссылка сохраняет этот переход.
|
||||
- Оглавление группируется по главам; по статье или пункту можно искать отдельно.
|
||||
- В тексте доступны увеличение шрифта, поиск с подсветкой и переходами,
|
||||
копирование и ссылка на первоисточник.
|
||||
- Связанные материалы доступны из панели чтения. На широком экране панель
|
||||
расположена справа; на меньших экранах открывается отдельной кнопкой.
|
||||
- История относится к выбранному документу; копии выбираются явно «до» и «после».
|
||||
|
||||
## Визуальное решение
|
||||
|
||||
Светлый фон без узоров, тёмный читаемый текст, один синий акцент,
|
||||
русские подписи. Единственная декоративная иллюстрация — Эвномия на главной.
|
||||
В чтении декоративных иллюстраций нет.
|
||||
|
||||
Применены навыки UX Designer, Visual Designer, accessibility и imagegen.
|
||||
Проверка выполнена средствами браузера; исследование с реальными юристами
|
||||
разных возрастов пока не проводилось.
|
||||
|
||||
## Проверки от 08.09.2026
|
||||
|
||||
```sh
|
||||
python3 -m unittest discover -s eunomia/tests -p 'test*.py' -v
|
||||
python3 eunomia/tests/browser_check.py
|
||||
node --check eunomia/web/app.js
|
||||
```
|
||||
|
||||
Пять тестов данных прошли. Восемь браузерных сценариев прошли на реальной
|
||||
локальной библиотеке; ошибок JavaScript не обнаружено. Проверены ширины
|
||||
1440, 1000, 720 и 390 пикселей, прямое открытие статьи 131 ГПК,
|
||||
сортировка, выбор года, чтение, панель связей и мобильная навигация.
|
||||
Визуальная проверка дополнительно выявила и устранила перекрытие заголовка
|
||||
закреплённой панелью при переходе к статье.
|
||||
|
||||
Отчёт: `qa/browser-check.txt`. Скриншоты: `qa/home-final.png`,
|
||||
`qa/topics-final.png`, `qa/chronology-final.png`, `qa/reader-1440-final.png`,
|
||||
`qa/reader-390-final.png`.
|
||||
|
||||
Это приёмка нового интерфейса и его маршрутов. Она не заменяет отдельную
|
||||
приёмку загрузчиков, расписания и нормативного графа Themiz. Наличие текста
|
||||
не подтверждает его полноту или действующую редакцию; предупреждения сохранены.
|
||||
@@ -0,0 +1 @@
|
||||
"""Eunomia — локальный визуальный спутник Themiz."""
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,11 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#0067b9" />
|
||||
<meta name="description" content="Эвномия — локальная правовая библиотека" />
|
||||
<title>Эвномия — правовая библиотека</title>
|
||||
</head>
|
||||
<body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>
|
||||
</html>
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Paco Coursey
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 WorkOS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 shadcn
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "eunomia",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --host 127.0.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@radix-ui/react-dialog": "1.1.23",
|
||||
"@radix-ui/react-separator": "1.1.15",
|
||||
"@radix-ui/react-slot": "1.3.3",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"class-variance-authority": "0.7.1",
|
||||
"clsx": "2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"react-force-graph-2d": "^1.29.1",
|
||||
"react-force-graph-3d": "^1.29.1",
|
||||
"tailwind-merge": "3.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "4.3.3",
|
||||
"@types/node": "26.5.0",
|
||||
"@types/react": "19.2.18",
|
||||
"@types/react-dom": "19.2.7",
|
||||
"@vitejs/plugin-react": "6.1.1",
|
||||
"axe-core": "4.12.1",
|
||||
"tailwindcss": "4.3.3",
|
||||
"tw-animate-css": "1.4.0",
|
||||
"typescript": "7.0.2",
|
||||
"vite": "8.2.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react'
|
||||
import { Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInset, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, useSidebar } from '@/components/ui/sidebar'
|
||||
import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { Icon } from '@/components/Icon'
|
||||
import { api, docHref, href, kinds, type Bootstrap, type Kind, type Route, type SearchData } from '@/lib/api'
|
||||
import { Home, Category, Contents } from '@/views/Library'
|
||||
import Reader from '@/views/Reader'
|
||||
import { Empty, Search, History, Graph, Updates } from '@/views/Research'
|
||||
|
||||
function readRoute(): Route {
|
||||
const route = Object.fromEntries(new URLSearchParams(location.hash.slice(1)))
|
||||
return {...route, view: route.doc ? 'reader' : route.view || 'home'}
|
||||
}
|
||||
const tools = [{view:'graph', title:'Связи документов'}, {view:'history',title:'История редакций'}, {view:'updates',title:'Обновления'}]
|
||||
|
||||
function Navigation({route, ready}: {route: Route; ready: boolean}) {
|
||||
const {setOpenMobile, state, toggleSidebar} = useSidebar()
|
||||
const links = [{view:'home', title:'Библиотека', icon:'home'}, ...Object.entries(kinds).map(([kind,value]) => ({view:'category',kind,title:value[0],icon:kind}))]
|
||||
const item = (link: {view:string;kind?:string;title:string;icon?:string}) => {
|
||||
const active = route.view===link.view && (!link.kind || link.kind===route.kind)
|
||||
return <SidebarMenuItem key={link.kind || link.view}><SidebarMenuButton asChild isActive={active} tooltip={link.title}><a href={href({view:link.view,kind:link.kind})} aria-current={active?'page':undefined} onClick={()=>setOpenMobile(false)}><Icon name={link.icon || link.view} /><span>{link.title}</span></a></SidebarMenuButton></SidebarMenuItem>
|
||||
}
|
||||
return <Sidebar collapsible="icon" className="eunomia-sidebar"><SidebarHeader><a className="brand-link" href={href({view:'home'})} onClick={()=>setOpenMobile(false)} aria-label="Эвномия — библиотека"><span className="brand-mark" aria-hidden="true">Э</span><span className="brand-copy group-data-[collapsible=icon]:hidden"><strong>Эвномия</strong><small>ПРАВОВАЯ БИБЛИОТЕКА</small></span></a></SidebarHeader><SidebarContent><SidebarGroup><SidebarGroupLabel>Библиотека</SidebarGroupLabel><SidebarGroupContent><SidebarMenu>{links.map(item)}</SidebarMenu></SidebarGroupContent></SidebarGroup><SidebarGroup><SidebarGroupLabel>Инструменты</SidebarGroupLabel><SidebarGroupContent><SidebarMenu>{tools.map(item)}</SidebarMenu></SidebarGroupContent></SidebarGroup></SidebarContent><SidebarFooter><div className="sidebar-status group-data-[collapsible=icon]:hidden"><span className={ready?'connection-dot ready':'connection-dot'} /><span>{ready?'Документы на компьютере':'Подключаем библиотеку'}</span></div><SidebarMenu><SidebarMenuItem><SidebarMenuButton onClick={toggleSidebar} tooltip={state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-label={state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-expanded={state==='expanded'}><Icon name="menu" /><span>Свернуть меню</span></SidebarMenuButton></SidebarMenuItem></SidebarMenu><small className="sidebar-brand-note group-data-[collapsible=icon]:hidden">Themiz · Эвномия</small></SidebarFooter></Sidebar>
|
||||
}
|
||||
function Shell({route, data, refresh, notify, busy, onAction}: {route:Route;data:Bootstrap;refresh:()=>void;notify:(s:string)=>void;busy:boolean;onAction:(kind:'update'|'graph',id?:string)=>Promise<void>}) {
|
||||
const {toggleSidebar, state, isMobile} = useSidebar()
|
||||
const [searchOpen,setSearchOpen] = useState(false), [query,setQuery] = useState(''), [results,setResults] = useState<SearchData | null>(null), [searching,setSearching] = useState(false), [searchError,setSearchError] = useState('')
|
||||
const mainRef = useRef<HTMLElement>(null)
|
||||
useEffect(()=>{
|
||||
const handle=(event:KeyboardEvent)=>{document.body.dataset.input='keyboard';if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()==='k'){event.preventDefault();setSearchOpen(open=>!open)}}
|
||||
const pointer=()=>{document.body.dataset.input='pointer'}
|
||||
document.addEventListener('keydown',handle);document.addEventListener('pointerdown',pointer)
|
||||
return()=>{document.removeEventListener('keydown',handle);document.removeEventListener('pointerdown',pointer)}
|
||||
},[])
|
||||
useEffect(()=>{
|
||||
if(!searchOpen){setQuery('');setResults(null);setSearchError('');setSearching(false);return}
|
||||
if(!query.trim()){setResults(null);setSearchError('');setSearching(false);return}
|
||||
let live=true;const controller=new AbortController();setSearching(true);setSearchError('')
|
||||
const timer=setTimeout(()=>{api<SearchData>('/search?'+new URLSearchParams({q:query}),{signal:controller.signal}).then(value=>{if(live)setResults(value)}).catch(error=>{if(live&&error.name!=='AbortError')setSearchError(error.message)}).finally(()=>{if(live)setSearching(false)})},180)
|
||||
return()=>{live=false;controller.abort();clearTimeout(timer)}
|
||||
},[query,searchOpen])
|
||||
useEffect(()=>{setSearchOpen(false);if(!route.doc)window.scrollTo({top:0,behavior:'instant'})},[route])
|
||||
const go=(url:string)=>{setSearchOpen(false);location.hash=url.slice(1)}
|
||||
const doc=data.documents.find(d=>d.id===(route.doc||route.id))
|
||||
const title=route.view==='category'?kinds[route.kind as Kind]?.[0]:doc?doc.subject||doc.title:({home:'Библиотека',search:'Поиск',graph:'Связи документов',history:'История редакций',updates:'Обновления'}[route.view]||'Библиотека')
|
||||
useEffect(()=>{document.title=`${title} — Эвномия`;document.body.dataset.view=route.view},[title,route.view])
|
||||
return <><a href="#main-content" className="skip-link" onClick={e=>{e.preventDefault();mainRef.current?.focus()}}>К содержанию</a><Navigation route={route} ready={!data.status.index?.indexing} /><SidebarInset className="eunomia-main"><header className="topbar"><Tooltip><TooltipTrigger asChild><Button id="menu-toggle" variant="ghost" size="icon" aria-label={isMobile?'Открыть навигацию':state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-expanded={state==='expanded'} onClick={toggleSidebar}><Icon name="menu" /></Button></TooltipTrigger><TooltipContent>{isMobile?'Навигация':state==='expanded'?'Свернуть меню':'Развернуть меню'}</TooltipContent></Tooltip><nav className="breadcrumb" aria-label="Путь по разделам"><a href={href({view:'home'})}>Библиотека</a>{route.view!=='home'&&<><span aria-hidden="true">/</span><span aria-current="page">{title}</span></>}</nav><button className="search-launcher" onClick={()=>setSearchOpen(true)} aria-keyshortcuts="Meta+k Control+k" aria-label="Поиск по библиотеке"><Icon name="search" /><span>Поиск по библиотеке</span><kbd>⌘ K</kbd></button><Tooltip><TooltipTrigger asChild><Button variant="ghost" size="icon" disabled={busy} onClick={refresh} aria-label="Обновить сведения на экране"><Icon name="updates" /></Button></TooltipTrigger><TooltipContent>Обновить сведения на экране</TooltipContent></Tooltip></header><main id="main-content" className="content" tabIndex={-1} ref={mainRef}>{route.doc?<Reader key={route.doc} route={route} onNotify={notify} onUpdate={id=>onAction('update',id)} />:route.view==='category'?<Category route={route} docs={data.documents}/>:route.view==='contents'?<Contents route={route} docs={data.documents}/>:route.view==='search'?<Search route={route}/>:route.view==='history'?<History route={route} docs={data.documents}/>:route.view==='updates'?<Updates status={data.status} docs={data.documents} onAction={onAction}/>:route.view==='graph'?<Graph route={route}/>:<Home docs={data.documents}/>}</main></SidebarInset><CommandDialog open={searchOpen} onOpenChange={setSearchOpen}><CommandInput placeholder="Статья, название или фраза…" value={query} onValueChange={setQuery} aria-label="Запрос для поиска" /><CommandList>{query.trim()?<><CommandGroup heading="Поиск по текстам"><CommandItem value={`all ${query}`} onSelect={()=>go(href({view:'search',q:query.trim()}))}><Icon name="search" /><span>Все результаты по запросу «{query}»</span></CommandItem></CommandGroup><CommandSeparator/>{searching?<p className="command-status" role="status">Ищем…</p>:searchError?<p className="command-status" role="alert">{searchError}</p>:results?.results.length?<CommandGroup heading="Найденные фрагменты">{results.results.slice(0,6).map(row=><CommandItem key={row.id} value={`${query} ${row.id}`} onSelect={()=>go(docHref(row.resource_id,row.id))}><Icon name={row.kind}/><span><strong>{row.label}</strong><small>{row.document||row.title}</small></span></CommandItem>)}</CommandGroup>:<p className="command-status">Совпадений пока нет. Попробуйте другой запрос.</p>}</>:<><CommandGroup heading="Быстрый переход">{Object.entries(kinds).map(([kind,value])=><CommandItem key={kind} value={value[0]} onSelect={()=>go(href({view:'category',kind}))}><Icon name={kind}/><span>{value[0]}</span></CommandItem>)}</CommandGroup><CommandGroup heading="Примеры запросов">{['ст. 131 ГПК','ст. 395 ГК'].map(q=><CommandItem key={q} value={q} onSelect={()=>setQuery(q)}><Icon name="search"/>{q}</CommandItem>)}</CommandGroup></>}<CommandEmpty>Ничего не найдено.</CommandEmpty></CommandList><div className="command-footer"><span>↑ ↓ выбрать</span><span>Enter открыть</span><span>Esc закрыть</span></div></CommandDialog></>
|
||||
}
|
||||
export default function App() {
|
||||
const [route,setRoute]=useState(readRoute),[data,setData]=useState<Bootstrap|null>(null),[error,setError]=useState(''),[busy,setBusy]=useState(false),[message,setMessage]=useState('')
|
||||
const toastTimer=useRef<ReturnType<typeof setTimeout>|undefined>(undefined)
|
||||
const notify=useCallback((value:string)=>{clearTimeout(toastTimer.current);setMessage(value);toastTimer.current=setTimeout(()=>setMessage(''),5000)},[])
|
||||
useEffect(()=>()=>clearTimeout(toastTimer.current),[])
|
||||
useEffect(()=>{const change=()=>setRoute(readRoute());window.addEventListener('hashchange',change);return()=>window.removeEventListener('hashchange',change)},[])
|
||||
const refresh=useCallback(async()=>{setBusy(true);try{const value=await api<Bootstrap>('/bootstrap');setData(value);setError('')}catch(e){setError((e as Error).message)}finally{setBusy(false)}},[])
|
||||
useEffect(()=>{void refresh()},[refresh])
|
||||
useEffect(()=>{if(!data?.status.index?.indexing||data.documents.length)return;const timer=setTimeout(refresh,1500);return()=>clearTimeout(timer)},[data,refresh])
|
||||
const action=async(kind:'update'|'graph',id?:string)=>{try{const response=await api<{detail:string}>(kind==='graph'?'/graph/rebuild':'/update',{method:'POST',headers:{'Content-Type':'application/json','X-Eunomia-CSRF':data?.csrf||''},body:JSON.stringify(id?{id}:{})});notify(response.detail);await refresh()}catch(e){notify((e as Error).message)}}
|
||||
return <TooltipProvider delayDuration={300}><SidebarProvider className="eunomia-shell" style={{'--sidebar-width':'15rem','--sidebar-width-icon':'4rem'} as CSSProperties}>{data?.documents.length||data&&!data.status.index?.indexing?<Shell route={route} data={data} refresh={refresh} notify={notify} busy={busy} onAction={action}/>:<main className="content"><Empty title={error?'Не удалось подключиться к библиотеке':'Готовим библиотеку к чтению'}>{error||'Проверяем сохраненные документы.'}</Empty>{error&&<button className="button primary" onClick={refresh}>Повторить</button>}</main>}</SidebarProvider><div role="status" aria-live="polite" className={`toast ${message?'show':''}`}>{message}</div></TooltipProvider>
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
const positions: Record<string, number> = {home:0,code:1,'federal-law':2,bylaw:3,plenum:4,review:5,graph:6,history:7,updates:8,search:9,menu:10,arrow:11,copy:12,close:13,back:14,focus:15}
|
||||
export function Icon({name, className = ''}: {name: string; className?: string}) {
|
||||
const n = positions[name] ?? 2
|
||||
return <span aria-hidden="true" className={`ui-icon ${className}`} style={{'--icon-x': `${n % 4 * 100 / 3}%`, '--icon-y': `${Math.floor(n / 4) * 100 / 3}%`} as CSSProperties} />
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
return (
|
||||
<Comp
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,169 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { type DialogProps } from "@radix-ui/react-dialog"
|
||||
import { Command as CommandPrimitive } from "cmdk"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Dialog, DialogContent } from "@/components/ui/dialog"
|
||||
|
||||
const Command = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
Command.displayName = CommandPrimitive.displayName
|
||||
|
||||
type CommandDialogProps = DialogProps & {
|
||||
title?: string
|
||||
description?: string
|
||||
shouldFilter?: boolean
|
||||
}
|
||||
|
||||
const CommandDialog = ({
|
||||
children,
|
||||
title = "Поиск по библиотеке",
|
||||
description = "Найдите документ, статью или пункт.",
|
||||
shouldFilter = false,
|
||||
...props
|
||||
}: CommandDialogProps) => {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogContent
|
||||
title={title}
|
||||
description={description}
|
||||
className="overflow-hidden p-0 shadow-lg"
|
||||
>
|
||||
<Command shouldFilter={shouldFilter} className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
const CommandInput = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Input>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
|
||||
<Icon name="search" className="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
<CommandPrimitive.Input
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
|
||||
CommandInput.displayName = CommandPrimitive.Input.displayName
|
||||
|
||||
const CommandList = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.List
|
||||
ref={ref}
|
||||
className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandList.displayName = CommandPrimitive.List.displayName
|
||||
|
||||
const CommandEmpty = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Empty>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
|
||||
>((props, ref) => (
|
||||
<CommandPrimitive.Empty
|
||||
ref={ref}
|
||||
className="py-6 text-center text-sm"
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandEmpty.displayName = CommandPrimitive.Empty.displayName
|
||||
|
||||
const CommandGroup = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Group>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Group
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandGroup.displayName = CommandPrimitive.Group.displayName
|
||||
|
||||
const CommandSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Separator>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Separator
|
||||
ref={ref}
|
||||
className={cn("-mx-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
CommandSeparator.displayName = CommandPrimitive.Separator.displayName
|
||||
|
||||
const CommandItem = React.forwardRef<
|
||||
React.ElementRef<typeof CommandPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<CommandPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
|
||||
CommandItem.displayName = CommandPrimitive.Item.displayName
|
||||
|
||||
const CommandShortcut = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
CommandShortcut.displayName = "CommandShortcut"
|
||||
|
||||
export {
|
||||
Command,
|
||||
CommandDialog,
|
||||
CommandInput,
|
||||
CommandList,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandItem,
|
||||
CommandShortcut,
|
||||
CommandSeparator,
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Dialog = DialogPrimitive.Root
|
||||
|
||||
const DialogTrigger = DialogPrimitive.Trigger
|
||||
|
||||
const DialogPortal = DialogPrimitive.Portal
|
||||
|
||||
const DialogClose = DialogPrimitive.Close
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {
|
||||
title?: string
|
||||
description?: string
|
||||
}
|
||||
>(({ className, children, title = "Диалог", description = "Диалоговое окно", ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<DialogTitle className="sr-only">{title}</DialogTitle>
|
||||
<DialogDescription className="sr-only">{description}</DialogDescription>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="absolute right-3 top-3 flex size-11 items-center justify-center rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
||||
<Icon name="close" className="h-4 w-4" />
|
||||
<span className="sr-only">Закрыть</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
))
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName
|
||||
|
||||
const DialogHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogHeader.displayName = "DialogHeader"
|
||||
|
||||
const DialogFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
DialogFooter.displayName = "DialogFooter"
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"text-lg font-semibold leading-none tracking-tight",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogClose,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
|
||||
({ className, type, ...props }, ref) => {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
className={cn(
|
||||
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Input.displayName = "Input"
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Separator = React.forwardRef<
|
||||
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||
>(
|
||||
(
|
||||
{ className, orientation = "horizontal", decorative = true, ...props },
|
||||
ref
|
||||
) => (
|
||||
<SeparatorPrimitive.Root
|
||||
ref={ref}
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border",
|
||||
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
)
|
||||
Separator.displayName = SeparatorPrimitive.Root.displayName
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,140 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const Sheet = SheetPrimitive.Root
|
||||
|
||||
const SheetTrigger = SheetPrimitive.Trigger
|
||||
|
||||
const SheetClose = SheetPrimitive.Close
|
||||
|
||||
const SheetPortal = SheetPrimitive.Portal
|
||||
|
||||
const SheetOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Overlay
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
))
|
||||
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName
|
||||
|
||||
const sheetVariants = cva(
|
||||
"fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-150 data-[state=open]:duration-200",
|
||||
{
|
||||
variants: {
|
||||
side: {
|
||||
top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
|
||||
bottom:
|
||||
"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
|
||||
left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
|
||||
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",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
side: "right",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
interface SheetContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
|
||||
VariantProps<typeof sheetVariants> {}
|
||||
|
||||
const SheetContent = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Content>,
|
||||
SheetContentProps
|
||||
>(({ side = "right", className, children, ...props }, ref) => (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(sheetVariants({ side }), className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="absolute right-3 top-3 flex size-11 items-center justify-center rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||
<Icon name="close" className="h-4 w-4" />
|
||||
<span className="sr-only">Закрыть</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
))
|
||||
SheetContent.displayName = SheetPrimitive.Content.displayName
|
||||
|
||||
const SheetHeader = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col space-y-2 text-center sm:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetHeader.displayName = "SheetHeader"
|
||||
|
||||
const SheetFooter = ({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn(
|
||||
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
SheetFooter.displayName = "SheetFooter"
|
||||
|
||||
const SheetTitle = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn("text-lg font-semibold text-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetTitle.displayName = SheetPrimitive.Title.displayName
|
||||
|
||||
const SheetDescription = React.forwardRef<
|
||||
React.ElementRef<typeof SheetPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SheetPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SheetDescription.displayName = SheetPrimitive.Description.displayName
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetPortal,
|
||||
SheetOverlay,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
}
|
||||
@@ -0,0 +1,773 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { Icon } from "@/pantheon/Icon"
|
||||
import { useIsMobile } from "@/hooks/use-mobile"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
const SidebarProvider = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
onOpenChange: setOpenProp,
|
||||
className,
|
||||
style,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
}
|
||||
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile
|
||||
? setOpenMobile((open) => !open)
|
||||
: setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
setOpen,
|
||||
isMobile,
|
||||
openMobile,
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<div
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH,
|
||||
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
|
||||
...style,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarProvider.displayName = "SidebarProvider"
|
||||
|
||||
const Sidebar = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
}
|
||||
>(
|
||||
(
|
||||
{
|
||||
side = "left",
|
||||
variant = "sidebar",
|
||||
collapsible = "offcanvas",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full w-[var(--sidebar-width)] flex-col bg-sidebar text-sidebar-foreground",
|
||||
className
|
||||
)}
|
||||
ref={ref}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
|
||||
<SheetContent
|
||||
data-sidebar="sidebar"
|
||||
data-mobile="true"
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault()
|
||||
document.getElementById("menu-toggle")?.focus()
|
||||
}}
|
||||
className={cn("w-[var(--sidebar-width)] bg-sidebar p-0 text-sidebar-foreground", className)}
|
||||
style={
|
||||
{
|
||||
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
side={side}
|
||||
>
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Навигация</SheetTitle>
|
||||
<SheetDescription>Основная навигация по библиотеке.</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="group peer hidden text-sidebar-foreground md:block"
|
||||
data-state={state}
|
||||
data-collapsible={state === "collapsed" ? collapsible : ""}
|
||||
data-variant={variant}
|
||||
data-side={side}
|
||||
>
|
||||
{/* This is what handles the sidebar gap on desktop */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative w-[var(--sidebar-width)] bg-transparent transition-[width] duration-200 ease-linear",
|
||||
"group-data-[collapsible=offcanvas]:w-0",
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_1rem)]"
|
||||
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)]"
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-y-0 z-10 hidden h-svh w-[var(--sidebar-width)] transition-[left,right,width] duration-200 ease-linear md:flex",
|
||||
side === "left"
|
||||
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
|
||||
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
|
||||
// Adjust the padding for floating and inset variants.
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_1rem_+_2px)]"
|
||||
: "group-data-[collapsible=icon]:w-[var(--sidebar-width-icon)] group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-sidebar="sidebar"
|
||||
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
)
|
||||
Sidebar.displayName = "Sidebar"
|
||||
|
||||
const SidebarTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof Button>,
|
||||
React.ComponentProps<typeof Button>
|
||||
>(({ className, onClick, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
data-sidebar="trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn("h-7 w-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<Icon name="menu" />
|
||||
<span className="sr-only">Переключить боковую панель</span>
|
||||
</Button>
|
||||
)
|
||||
})
|
||||
SidebarTrigger.displayName = "SidebarTrigger"
|
||||
|
||||
const SidebarRail = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button">
|
||||
>(({ className, ...props }, ref) => {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
data-sidebar="rail"
|
||||
aria-label="Переключить боковую панель"
|
||||
tabIndex={-1}
|
||||
onClick={toggleSidebar}
|
||||
title="Переключить боковую панель"
|
||||
className={cn(
|
||||
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
|
||||
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
|
||||
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
|
||||
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarRail.displayName = "SidebarRail"
|
||||
|
||||
const SidebarInset = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"main">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<main
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"relative flex w-full flex-1 flex-col bg-background",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarInset.displayName = "SidebarInset"
|
||||
|
||||
const SidebarInput = React.forwardRef<
|
||||
React.ElementRef<typeof Input>,
|
||||
React.ComponentProps<typeof Input>
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<Input
|
||||
ref={ref}
|
||||
data-sidebar="input"
|
||||
className={cn(
|
||||
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarInput.displayName = "SidebarInput"
|
||||
|
||||
const SidebarHeader = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="header"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarHeader.displayName = "SidebarHeader"
|
||||
|
||||
const SidebarFooter = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="footer"
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarFooter.displayName = "SidebarFooter"
|
||||
|
||||
const SidebarSeparator = React.forwardRef<
|
||||
React.ElementRef<typeof Separator>,
|
||||
React.ComponentProps<typeof Separator>
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<Separator
|
||||
ref={ref}
|
||||
data-sidebar="separator"
|
||||
className={cn("mx-2 w-auto bg-sidebar-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarSeparator.displayName = "SidebarSeparator"
|
||||
|
||||
const SidebarContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarContent.displayName = "SidebarContent"
|
||||
|
||||
const SidebarGroup = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="group"
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroup.displayName = "SidebarGroup"
|
||||
|
||||
const SidebarGroupLabel = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & { asChild?: boolean }
|
||||
>(({ className, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="group-label"
|
||||
className={cn(
|
||||
"flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroupLabel.displayName = "SidebarGroupLabel"
|
||||
|
||||
const SidebarGroupAction = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & { asChild?: boolean }
|
||||
>(({ className, asChild = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="group-action"
|
||||
className={cn(
|
||||
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 after:md:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarGroupAction.displayName = "SidebarGroupAction"
|
||||
|
||||
const SidebarGroupContent = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="group-content"
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarGroupContent.displayName = "SidebarGroupContent"
|
||||
|
||||
const SidebarMenu = React.forwardRef<
|
||||
HTMLUListElement,
|
||||
React.ComponentProps<"ul">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ul
|
||||
ref={ref}
|
||||
data-sidebar="menu"
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenu.displayName = "SidebarMenu"
|
||||
|
||||
const SidebarMenuItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentProps<"li">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<li
|
||||
ref={ref}
|
||||
data-sidebar="menu-item"
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuItem.displayName = "SidebarMenuItem"
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
const SidebarMenuButton = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>
|
||||
>(
|
||||
(
|
||||
{
|
||||
asChild = false,
|
||||
isActive = false,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
tooltip,
|
||||
className,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
if (!tooltip || isMobile || state !== "collapsed") {
|
||||
return button
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={state !== "collapsed" || isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
)
|
||||
SidebarMenuButton.displayName = "SidebarMenuButton"
|
||||
|
||||
const SidebarMenuAction = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
}
|
||||
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-action"
|
||||
className={cn(
|
||||
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 after:md:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarMenuAction.displayName = "SidebarMenuAction"
|
||||
|
||||
const SidebarMenuBadge = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="menu-badge"
|
||||
className={cn(
|
||||
"pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
|
||||
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuBadge.displayName = "SidebarMenuBadge"
|
||||
|
||||
const SidebarMenuSkeleton = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
}
|
||||
>(({ className, showIcon = false, ...props }, ref) => {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
data-sidebar="menu-skeleton"
|
||||
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
|
||||
{...props}
|
||||
>
|
||||
{showIcon && (
|
||||
<Skeleton
|
||||
className="size-4 rounded-md"
|
||||
data-sidebar="menu-skeleton-icon"
|
||||
/>
|
||||
)}
|
||||
<Skeleton
|
||||
className="h-4 max-w-[var(--skeleton-width)] flex-1"
|
||||
data-sidebar="menu-skeleton-text"
|
||||
style={
|
||||
{
|
||||
"--skeleton-width": width,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton"
|
||||
|
||||
const SidebarMenuSub = React.forwardRef<
|
||||
HTMLUListElement,
|
||||
React.ComponentProps<"ul">
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ul
|
||||
ref={ref}
|
||||
data-sidebar="menu-sub"
|
||||
className={cn(
|
||||
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
SidebarMenuSub.displayName = "SidebarMenuSub"
|
||||
|
||||
const SidebarMenuSubItem = React.forwardRef<
|
||||
HTMLLIElement,
|
||||
React.ComponentProps<"li">
|
||||
>(({ ...props }, ref) => <li ref={ref} {...props} />)
|
||||
SidebarMenuSubItem.displayName = "SidebarMenuSubItem"
|
||||
|
||||
const SidebarMenuSubButton = React.forwardRef<
|
||||
HTMLAnchorElement,
|
||||
React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
}
|
||||
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-sidebar="menu-sub-button"
|
||||
data-size={size}
|
||||
data-active={isActive}
|
||||
className={cn(
|
||||
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
SidebarMenuSubButton.displayName = "SidebarMenuSubButton"
|
||||
|
||||
export {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupAction,
|
||||
SidebarGroupContent,
|
||||
SidebarGroupLabel,
|
||||
SidebarHeader,
|
||||
SidebarInput,
|
||||
SidebarInset,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuBadge,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSkeleton,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarProvider,
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const TooltipProvider = TooltipPrimitive.Provider
|
||||
|
||||
const Tooltip = TooltipPrimitive.Root
|
||||
|
||||
const TooltipTrigger = TooltipPrimitive.Trigger
|
||||
|
||||
const TooltipContent = React.forwardRef<
|
||||
React.ElementRef<typeof TooltipPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
|
||||
>(({ className, sideOffset = 4, ...props }, ref) => (
|
||||
<TooltipPrimitive.Content
|
||||
ref={ref}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[var(--radix-tooltip-content-transform-origin)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
TooltipContent.displayName = TooltipPrimitive.Content.displayName
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
|
||||
return !!isMobile
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export type Route = Record<string, string>
|
||||
export type Kind = 'code' | 'federal-law' | 'bylaw' | 'plenum' | 'review'
|
||||
export interface LegalDocument {
|
||||
id: string; title: string; subject?: string; kind: Kind; source_url?: string;
|
||||
revision?: string | null; act_date?: string | null; number?: string | null;
|
||||
available: boolean; integrity?: boolean; coverage?: {status?: string; scope?: string | null};
|
||||
warnings?: string[]; last_checked?: string | null; retrieved_at?: string | null; effective_date?: string | null;
|
||||
}
|
||||
export interface Anchor {id: string; label: string; offset: number}
|
||||
export interface Fragment {id: string; label: string; kind: string; text?: string; anchors?: Anchor[]}
|
||||
export interface ReaderData {document: LegalDocument; toc: Fragment[]; fragment: Fragment | null; selected_id: string | null}
|
||||
export interface SearchResult {id: string; resource_id: string; label: string; title: string; document: string; kind: Kind; snippet: string; revision?: string; warnings?: string[]}
|
||||
export interface SearchData {results: SearchResult[]; total: number}
|
||||
export interface GraphNode {id: string; label: string; resource_id: string; kind: string; document_kind?: Kind; document_title?: string; reader_id?: string | null; needs_review?: boolean}
|
||||
export interface Evidence {excerpt?: string; revision?: string; source_url?: string}
|
||||
export interface GraphEdge {source: string; target: string; relation?: string; evidence?: Evidence; source_node?: GraphNode; target_node?: GraphNode}
|
||||
export interface RelatedData {related: GraphEdge[]; loading?: boolean; node_id?: string}
|
||||
export interface StatusData {
|
||||
index?: {ready: boolean; indexing: boolean; error?: string};
|
||||
schedule?: {enabled: boolean; next_run?: string; next_due_at?: string; detail?: string};
|
||||
graph?: {available?: boolean; built_at?: string};
|
||||
queue?: Record<string, number>;
|
||||
jobs?: {id: string; state: string; detail?: string}[];
|
||||
practice?: PracticeStatus;
|
||||
}
|
||||
export interface PracticeStatus {
|
||||
ready: boolean; acts: number; links: number; error?: string;
|
||||
last_import?: {finished_at?: string; seconds?: number; added?: number; updated?: number; removed?: number; rejected?: number; watermark?: string} | null;
|
||||
build?: {meaning?: string; running?: boolean; attempted_at?: string; finished_at?: string; next_due?: string} | null;
|
||||
tick?: string | null;
|
||||
schedule?: {installed: boolean; interval_hours: number};
|
||||
}
|
||||
export interface PracticeCard {doc: string; title: string; kind: string; number?: string; act_date?: string | null; court?: string | null; area?: string | null; category?: string | null; excerpt?: string; subject?: string}
|
||||
export interface PracticeArticle {code: string; article: string; label: string; total?: number; reader?: {id: string; fragment: string} | null}
|
||||
export interface PracticeList {ready: boolean; items: PracticeCard[]; total: number; page: number; pages: number; terms: string[]; articles: PracticeArticle[]}
|
||||
export interface Facet {value: string; count: number}
|
||||
export interface PracticeFacets {ready: boolean; months: Facet[]; kinds: Facet[]; courts: Facet[]; categories: Facet[]}
|
||||
export interface PracticeLink {start: number; end: number; code: string; article: string}
|
||||
export interface PracticeActData {
|
||||
act: PracticeCard & {url: string; fetched_at?: string | null; lastmod?: string | null; sha256?: string | null; bytes?: number | null; verified: boolean; removed_at?: string | null; removed_code?: string | null};
|
||||
heading: string; court_line: string; text: string | null; links: PracticeLink[]; articles: PracticeArticle[];
|
||||
areas: {id: string; title: string; parent?: string | null; parent_title?: string | null; reason: string}[];
|
||||
}
|
||||
export interface PracticeNode {id: string; title: string; count: number}
|
||||
export interface PracticeTree {ready: boolean; total: number; productions: Facet[]; areas: (PracticeNode & {children: PracticeNode[]})[]}
|
||||
export interface PracticeAreaGraph {
|
||||
ready: boolean; area: PracticeNode; children: PracticeNode[]; productions: Facet[];
|
||||
intersections: {a: string; b: string; count: number}[];
|
||||
articles: {node: string; code: string; article: string; label: string; count: number}[];
|
||||
}
|
||||
export interface PracticeNorm {code: string | null; article: string | null; label?: string; total: number; ready: boolean}
|
||||
export type Action = 'update' | 'graph' | 'refresh'
|
||||
export interface Load {done: number; total: number; per_min: number; eta_min: number | null; updated_at: string; error?: string}
|
||||
export interface Walk {running: boolean; requested_at: string | null; stopped: string | null; at: string | null; next_due: string | null; found?: number | null}
|
||||
// Отметки свежести считает сервер по живому состоянию (eunomia/server.py: practice_freshness, law_freshness).
|
||||
export interface PracticeFreshness {fresh: boolean; label: string; as_of: string | null; interval_days: number}
|
||||
export interface LawFreshness {full: boolean; label: string; as_of: string | null; interval_days: number; missing: {id: string; title: string; reason: string}[]}
|
||||
export interface PracticeProgress extends Load {walk: Walk; freshness?: PracticeFreshness}
|
||||
export interface LawProgress extends Load {running: boolean; states: Record<string, number>; freshness?: LawFreshness}
|
||||
export interface Bootstrap {documents: LegalDocument[]; csrf: string; status: StatusData}
|
||||
export const kinds: Record<Kind, [string, string]> = {
|
||||
code: ['Кодексы', 'Основные отрасли права'],
|
||||
'federal-law': ['Федеральные законы', 'Законы по отдельным вопросам'],
|
||||
bylaw: ['Подзаконные акты', 'Постановления, приказы и правила'],
|
||||
plenum: ['Пленумы', 'Разъяснения по применению права'],
|
||||
review: ['Обзоры практики', 'Правовые позиции и выводы судов'],
|
||||
}
|
||||
export const normalized = (value = '') => value.toLocaleLowerCase('ru').replaceAll('ё', 'е')
|
||||
export function href(route: Record<string, string | number | undefined | null>) {
|
||||
return '#' + new URLSearchParams(Object.entries(route).filter(([,v]) => v !== undefined && v !== null && v !== '').map(([k,v]) => [k, String(v)])).toString()
|
||||
}
|
||||
export const docHref = (id: string, fragment?: string | null) => href({doc: id, fragment})
|
||||
export const shortDate = (value?: string | null) => {
|
||||
if (!value) return 'не указана'
|
||||
if (/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return value
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(+date) ? value : date.toLocaleDateString('ru-RU')
|
||||
}
|
||||
export const docCount = (n: number) => `${n} ${n % 10 === 1 && n % 100 !== 11 ? 'документ' : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? 'документа' : 'документов'}`
|
||||
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||
const response = await fetch('/api' + path, {...options, headers: {Accept: 'application/json', ...options.headers}})
|
||||
const data = await response.json()
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось получить данные. Попробуйте снова.')
|
||||
return data as T
|
||||
}
|
||||
export function useApi<T>(path: string | null) {
|
||||
const [state, setState] = useState<{data: T | null; error: string; loading: boolean}>({data: null, error: '', loading: true})
|
||||
useEffect(() => {
|
||||
if (!path) { setState({data: null, error: '', loading: false}); return }
|
||||
const controller = new AbortController(); let live = true
|
||||
setState({data: null, error: '', loading: true})
|
||||
api<T>(path, {signal: controller.signal}).then(data => {if(live)setState({data, error: '', loading: false})}).catch(error => {if(live && error.name !== 'AbortError')setState({data: null, error: error.message, loading: false})})
|
||||
return () => {live = false; controller.abort()}
|
||||
}, [path])
|
||||
return state
|
||||
}
|
||||
// Опрос, пока экран открыт: прежние данные остаются до нового ответа, скрытая вкладка запросов не шлет.
|
||||
export function usePoll<T>(path: string, ms: number) {
|
||||
const [state, setState] = useState<{data: T | null; error: string}>({data: null, error: ''})
|
||||
const [round, setRound] = useState(0)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController(); let timer = 0
|
||||
const load = async () => {
|
||||
if (!document.hidden) {
|
||||
try { const data = await api<T>(path, {signal: controller.signal}); setState({data, error: ''}) }
|
||||
catch (error) { if ((error as Error).name !== 'AbortError') setState(old => ({...old, error: (error as Error).message})) }
|
||||
}
|
||||
if (!controller.signal.aborted) timer = window.setTimeout(load, ms)
|
||||
}
|
||||
void load()
|
||||
return () => {controller.abort(); clearTimeout(timer)}
|
||||
}, [path, ms, round])
|
||||
return {...state, reload: () => setRound(n => n + 1)}
|
||||
}
|
||||
export function safeURL(value?: string) {
|
||||
try {const url = new URL(value || ''); return ['https:', 'http:'].includes(url.protocol) ? url.href : '#'} catch {return '#'}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) }
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './pantheon/App'
|
||||
import './pantheon/pantheon.css'
|
||||
import './pantheon/atmosphere.css'
|
||||
import './pantheon/atomic.css'
|
||||
import './pantheon/tricolor.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(<App />)
|
||||
@@ -0,0 +1,87 @@
|
||||
import {lazy, Suspense, useCallback, useEffect, useState, type CSSProperties} from 'react'
|
||||
import {Sidebar, SidebarContent, SidebarFooter, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, useSidebar} from '@/components/ui/sidebar'
|
||||
import {TooltipProvider} from '@/components/ui/tooltip'
|
||||
import {api, docHref, href, type Action, type Bootstrap, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import {SearchBox} from './SearchBox'
|
||||
import {Catalog, Contents} from './Catalog'
|
||||
import Document from './Document'
|
||||
import {Results, Editions, Service, RecentView} from './Research'
|
||||
import {PracticeAct, PracticeTeaser, PracticeView} from './Practice'
|
||||
import {remember, recentItems, clearRecent, type Recent} from './storage'
|
||||
|
||||
const Connections = lazy(() => import('./Connections').then(module => ({default:module.Connections})))
|
||||
function readRoute(): Route {
|
||||
const route = Object.fromEntries(new URLSearchParams(location.hash.slice(1)))
|
||||
return {...route, view:route.doc ? 'reader' : route.view || 'home'}
|
||||
}
|
||||
const nav = [{view:'home',title:'Библиотека',icon:'library'}, {view:'practice',title:'Судебная практика',icon:'document'}, {view:'recent',title:'Недавнее',icon:'history'}, {view:'graph',title:'Граф знаний',icon:'graph'}]
|
||||
function Navigation({route}: {route:Route}) {
|
||||
const {setOpenMobile,state,toggleSidebar} = useSidebar()
|
||||
const item = (view:string,title:string,icon:string) => <SidebarMenuItem key={view}>
|
||||
<SidebarMenuButton asChild isActive={view==='home' ? ['home','category','contents'].includes(route.view) : view==='practice' ? ['practice','act'].includes(route.view) : view===route.view} tooltip={title}>
|
||||
<a href={href({view})} onClick={() => setOpenMobile(false)} aria-current={route.view===view?'page':undefined}><Icon name={icon}/><span>{title}</span></a>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
return <Sidebar collapsible="icon" className="p-sidebar" role="navigation" aria-label="Меню библиотеки">
|
||||
<SidebarHeader><a href={href({view:'home'})} className="p-brand" aria-label="Эвномия — главная" onClick={() => setOpenMobile(false)}>
|
||||
<span className="p-monogram" aria-hidden="true">Э</span><span className="p-brand-name"><strong>Эвномия</strong><small>ПАНТЕОН · THEMIZ</small></span>
|
||||
</a></SidebarHeader>
|
||||
<SidebarContent><SidebarMenu>{nav.map(x => item(x.view,x.title,x.icon))}</SidebarMenu></SidebarContent>
|
||||
<SidebarFooter><SidebarMenu>{item('updates','Состояние базы','updates')}<SidebarMenuItem>
|
||||
<SidebarMenuButton onClick={toggleSidebar} tooltip={state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-label={state==='expanded'?'Свернуть меню':'Развернуть меню'}><Icon name="menu"/><span>Свернуть меню</span></SidebarMenuButton>
|
||||
</SidebarMenuItem></SidebarMenu><div className="p-sidebar-note"><span/>Локальная библиотека</div></SidebarFooter>
|
||||
</Sidebar>
|
||||
}
|
||||
function Surface({data,route,onNotify,refresh}: {data:Bootstrap;route:Route;onNotify:(s:string)=>void;refresh:()=>Promise<void>}) {
|
||||
const {toggleSidebar,openMobile,state,isMobile} = useSidebar()
|
||||
const [recent,setRecent] = useState<Recent[]>(recentItems)
|
||||
const onRecent = useCallback((id:string,fragment?:string) => {setRecent(remember(id,fragment))},[])
|
||||
const isHome = route.view==='home'
|
||||
const title = ({home:'Библиотека',category:'Библиотека',contents:'Оглавление',reader:'Чтение',search:'Результаты поиска',recent:'Недавнее',graph:'Граф знаний',history:'Редакции',updates:'Состояние базы',practice:'Судебная практика',act:'Судебный акт'}[route.view] || 'Библиотека')
|
||||
useEffect(() => {document.title=`${title} · Эвномия`; if(route.view!=='reader') window.scrollTo({top:0,behavior:'instant'})},[route,title])
|
||||
const action = async (kind:Action) => {
|
||||
const response = await api<{detail:string}>({update:'/update',graph:'/graph/rebuild',refresh:'/practice/refresh'}[kind],{method:'POST',headers:{'Content-Type':'application/json','X-Eunomia-CSRF':data.csrf},body:'{}'})
|
||||
onNotify(response.detail); if(kind!=='refresh') await refresh() // полосы опрашивают свои маршруты сами
|
||||
}
|
||||
return <>
|
||||
<a className="p-skip" href="#p-main" onClick={e => {e.preventDefault();document.getElementById('p-main')?.focus()}}>К содержанию</a>
|
||||
<Navigation route={route}/>
|
||||
<div className="p-surface">
|
||||
<header className="p-topbar">
|
||||
<button className="p-icon-button" id="menu-toggle" onClick={toggleSidebar} aria-label={isMobile?'Открыть меню':state==='expanded'?'Свернуть меню':'Развернуть меню'} aria-expanded={isMobile?openMobile:state==='expanded'}><Icon name="menu"/></button>
|
||||
<nav aria-label="Путь" className="p-breadcrumb"><a href={href({view:'home'})}>Эвномия</a><span aria-hidden="true">/</span><span>{title}</span></nav>
|
||||
{!isHome && <SearchBox initialQuery={route.view==='search' ? route.q : ''}/>}
|
||||
{isHome && <span className="p-local-note"><span/>Документы на вашем компьютере</span>}
|
||||
</header>
|
||||
<main id="p-main" tabIndex={-1} className={`p-main ${route.view==='reader'?'p-main-reading':route.view==='graph'?'p-main-graph':''}`}>
|
||||
{route.doc ? <Document key={route.doc} route={route} onNotify={onNotify} onRecent={onRecent}/> :
|
||||
route.view==='contents' ? <Contents documents={data.documents} route={route}/> :
|
||||
route.view==='search' ? <Results route={route}/> :
|
||||
route.view==='practice' ? <PracticeView route={route}/> :
|
||||
route.view==='act' ? <PracticeAct key={route.act} route={route}/> :
|
||||
route.view==='graph' ? <Suspense fallback={<p role="status">Загружаем граф знаний…</p>}><Connections route={route}/></Suspense> :
|
||||
route.view==='history' ? <Editions documents={data.documents} route={route}/> :
|
||||
route.view==='updates' ? <Service data={data} onAction={action}/> :
|
||||
route.view==='recent' ? <RecentView documents={data.documents} recent={recent} onClear={() => {clearRecent();setRecent([])}}/> :
|
||||
<Catalog documents={data.documents} route={route} hero={isHome} search={isHome?<SearchBox large/>:undefined} aside={isHome?<PracticeTeaser status={data.status.practice}/>:undefined}/>}
|
||||
</main>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
export default function App() {
|
||||
const [route,setRoute] = useState(readRoute)
|
||||
const [data,setData] = useState<Bootstrap|null>(null)
|
||||
const [error,setError] = useState('')
|
||||
const [message,setMessage] = useState('')
|
||||
const refresh = useCallback(async () => {
|
||||
try {setData(await api<Bootstrap>('/bootstrap'));setError('')} catch(e) {setError((e as Error).message)}
|
||||
},[])
|
||||
useEffect(() => {void refresh()},[refresh])
|
||||
useEffect(() => {const handle=()=>setRoute(readRoute());window.addEventListener('hashchange',handle);return()=>window.removeEventListener('hashchange',handle)},[])
|
||||
useEffect(() => {if(!data?.status.index?.indexing || data.documents.length) return;const timer=setTimeout(refresh,1500);return()=>clearTimeout(timer)},[data,refresh])
|
||||
useEffect(() => {if(!message)return;const timer=setTimeout(()=>setMessage(''),5000);return()=>clearTimeout(timer)},[message])
|
||||
return <TooltipProvider delayDuration={300}><SidebarProvider className="p-app" style={{'--sidebar-width':'224px','--sidebar-width-icon':'72px'} as CSSProperties}>
|
||||
{data && (data.documents.length || !data.status.index?.indexing) ? <Surface data={data} route={route} onNotify={setMessage} refresh={refresh}/> : <div className="p-start-state"><span className="p-monogram">Э</span><h1>{error?'Библиотека недоступна':'Открываем библиотеку'}</h1><p>{error||'Подготавливаем сохраненные тексты.'}</p>{error&&<button className="p-button p-primary" onClick={refresh}>Повторить</button>}</div>}
|
||||
</SidebarProvider><div role="status" aria-live="polite" className={`p-toast ${message?'is-visible':''}`}>{message}</div></TooltipProvider>
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useMemo, type ReactNode } from 'react'
|
||||
import { docHref, href, kinds, shortDate, useApi, type LegalDocument, type ReaderData, type Route, type Kind } from '@/lib/api'
|
||||
|
||||
const pantheonKinds: Kind[] = ['code', 'federal-law', 'bylaw', 'plenum', 'review']
|
||||
const plenaryTopics: Array<[string, RegExp]> = [
|
||||
['Гражданское право', /гражданск|договор|недвижим|потребител/i],
|
||||
['Гражданский процесс', /гражданск.{0,30}(процесс|судопроизвод)|исков|судебн.{0,20}расход/i],
|
||||
['Уголовное право', /уголовн|преступлен|наказан/i],
|
||||
['Уголовный процесс', /уголовн.{0,30}(процесс|судопроизвод)|следствен|доказательств/i],
|
||||
['Экономические споры', /арбитраж|экономичес|банкрот|предприним/i],
|
||||
['Административные дела', /административн|публичн|правонаруш/i],
|
||||
['Трудовые споры', /трудов|работник|работодател/i],
|
||||
['Семейные споры', /семейн|брак|алименты/i],
|
||||
]
|
||||
const stoneNames: Record<string, string> = {
|
||||
'gk-rf': 'Гражданский кодекс', 'gpk-rf': 'Гражданский процессуальный кодекс',
|
||||
'apk-rf': 'Арбитражный процессуальный кодекс', 'uk-rf': 'Уголовный кодекс',
|
||||
'upk-rf': 'Уголовно-процессуальный кодекс', 'kas-rf': 'Кодекс административного судопроизводства',
|
||||
'koap-rf': 'Кодекс об административных правонарушениях', 'tk-rf': 'Трудовой кодекс',
|
||||
'sk-rf': 'Семейный кодекс', 'zhk-rf': 'Жилищный кодекс', 'zk-rf': 'Земельный кодекс',
|
||||
'nk-rf-gosposhlina': 'Налоговый кодекс',
|
||||
}
|
||||
|
||||
function slug(id: string) { return id.split(':').pop() || id }
|
||||
function titleFor(document: LegalDocument) { return stoneNames[slug(document.id)] || document.subject || document.title }
|
||||
function countWord(count: number) { return `${count} ${count % 10 === 1 && count % 100 !== 11 ? 'материал' : count % 10 >= 2 && count % 10 <= 4 && !(count % 100 >= 12 && count % 100 <= 14) ? 'материала' : 'материалов'}` }
|
||||
|
||||
export function Catalog({documents, route, search, aside, hero = false}: {documents: LegalDocument[]; route: Route; search?: ReactNode; aside?: ReactNode; hero?: boolean}) {
|
||||
const selected = (route.kind as Kind) || 'code'
|
||||
const docs = documents.filter(document => document.kind === selected)
|
||||
return <section className="p-catalog" aria-labelledby="catalog-title">
|
||||
{hero && <div className="p-hero"><div className="p-hero-copy"><p className="p-eyebrow">Локальная правовая библиотека</p><h1>Найти норму.<br />Понять контекст.</h1><p>Тексты актов, редакции и проверяемые связи в одном рабочем месте.</p>{search}</div><div className="p-hero-figure"><img src="/assets/pantheon/eunomia-marble.webp" alt="Эвномия" onError={event => { event.currentTarget.hidden = true }} /></div></div>}
|
||||
{aside}
|
||||
<div className="p-catalog-head"><div><p className="p-eyebrow">Библиотека</p><h2 id="catalog-title">Корпус документов</h2></div><span className="p-catalog-total">{countWord(documents.length)}</span></div>
|
||||
<nav className="p-tabs" aria-label="Тип материала">{pantheonKinds.map(kind => <a key={kind} href={href({view: 'category', kind})} aria-current={selected === kind ? 'page' : undefined}>{kinds[kind][0]} <span>{documents.filter(document => document.kind === kind).length}</span></a>)}</nav>
|
||||
{selected === 'code' ? <CodeCatalog documents={docs} /> : selected === 'plenum' ? <PlenumCatalog documents={docs} route={route} /> : <DocumentList documents={docs} route={route} />}
|
||||
</section>
|
||||
}
|
||||
|
||||
function corpusStatus(document: LegalDocument) {
|
||||
if (!document.available) return 'Текст недоступен'
|
||||
if (document.warnings?.length) return 'Есть предупреждения корпуса'
|
||||
return 'Текст доступен'
|
||||
}
|
||||
|
||||
function CodeCatalog({documents}: {documents: LegalDocument[]}) {
|
||||
return <div className="p-stone-grid">{documents.map(document => {
|
||||
const civil = slug(document.id) === 'gk-rf'
|
||||
return <a className="p-stone" key={document.id} href={civil ? href({view: 'contents', id: document.id}) : docHref(document.id)}>
|
||||
<div className="p-stone-image"><img src={`/assets/pantheon/${slug(document.id)}.webp`} alt="" loading="lazy" decoding="async" width="1536" height="1024" /></div>
|
||||
<div className="p-stone-face"><strong>{titleFor(document)}</strong><span>{document.number || (civil ? 'Четыре части кодекса' : 'Кодекс Российской Федерации')}</span>
|
||||
<small>{civil ? 'Редакции указаны в каждой части' : document.revision ? `Редакция ${shortDate(document.revision)}` : 'Редакция не указана'}</small><small>{corpusStatus(document)}</small>
|
||||
</div>
|
||||
</a>
|
||||
})}</div>
|
||||
}
|
||||
|
||||
function pageFromRoute(route: Route, pageCount: number) {
|
||||
const value = Number(route.page)
|
||||
return Number.isInteger(value) && value >= 1 && value <= pageCount ? value : 1
|
||||
}
|
||||
|
||||
function PlenumCatalog({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
||||
const dateKey = (value?: string | null) => /^\d{2}\.\d{2}\.\d{4}$/.test(value || '') ? (value || '').split('.').reverse().join('-') : value || ''
|
||||
const years = [...new Set(documents.map(document => dateKey(document.act_date).slice(0, 4)).filter(Boolean))].sort().reverse()
|
||||
const sort = route.sort === 'old' ? 'old' : 'new'
|
||||
const year = route.year && years.includes(route.year) ? route.year : ''
|
||||
const topic = route.topic && plenaryTopics.some(([label]) => label === route.topic) ? route.topic : ''
|
||||
const topicMatcher = plenaryTopics.find(([label]) => label === topic)?.[1]
|
||||
const visible = documents.filter(document => {
|
||||
const text = `${document.subject || ''} ${document.title}`
|
||||
return (!year || (document.act_date || '').includes(year)) && (!topicMatcher || topicMatcher.test(text))
|
||||
}).sort((a, b) => (sort === 'new' ? dateKey(b.act_date).localeCompare(dateKey(a.act_date)) : dateKey(a.act_date).localeCompare(dateKey(b.act_date))))
|
||||
const pageCount = Math.max(1, Math.ceil(visible.length / 12))
|
||||
const page = pageFromRoute(route, pageCount)
|
||||
const setFilter = (patch: Partial<Record<'sort' | 'year' | 'topic', string | undefined>>) => { location.hash = href({...route, ...patch, page: undefined}) }
|
||||
return <><div className="p-topic-grid" aria-label="Тематика пленумов">{plenaryTopics.map(([label, matcher]) => { const count = documents.filter(document => matcher.test(`${document.subject || ''} ${document.title}`)).length; return count ? <button className={`p-topic${topic === label ? ' is-active' : ''}`} type="button" key={label} aria-pressed={topic === label} onClick={() => setFilter({topic: topic === label ? undefined : label})}><strong>{label}</strong><span>{count}</span></button> : null })}</div><div className="p-filterbar"><label>Сортировка<select value={sort} onChange={event => setFilter({sort: event.target.value === 'new' ? undefined : event.target.value})}><option value="new">Сначала новые</option><option value="old">Сначала ранние</option></select></label><label>Год<select value={year} onChange={event => setFilter({year: event.target.value})}><option value="">Все годы</option>{years.map(value => <option key={value}>{value}</option>)}</select></label></div><DocumentRows documents={visible.slice((page - 1) * 12, page * 12)} /><Pagination page={page} pageCount={pageCount} total={visible.length} onChange={next => location.hash = href({...route, page: next})} /></>
|
||||
}
|
||||
|
||||
function DocumentList({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
||||
const pageCount = Math.max(1, Math.ceil(documents.length / 12))
|
||||
const page = pageFromRoute(route, pageCount)
|
||||
return <><DocumentRows documents={documents.slice((page - 1) * 12, page * 12)} route={route} /><Pagination page={page} pageCount={pageCount} total={documents.length} onChange={next => location.hash = href({...route, page: next})} /></>
|
||||
}
|
||||
|
||||
function Pagination({page, pageCount, total, onChange}: {page: number; pageCount: number; total: number; onChange: (page: number) => void}) {
|
||||
return <div className="p-pagination" aria-label="Страницы"><span>{total} документов · страница {page} из {pageCount}</span><div className="p-pagination-actions"><button type="button" disabled={page <= 1} onClick={() => onChange(page - 1)}>Предыдущая</button><button type="button" disabled={page >= pageCount} onClick={() => onChange(page + 1)}>Следующая</button></div></div>
|
||||
}
|
||||
|
||||
function DocumentRows({documents, route}: {documents: LegalDocument[]; route?: Route}) {
|
||||
return <div className="p-document-list">{documents.map(document => <a className="p-document-row" key={document.id} href={docHref(document.id)}><span><strong>{document.subject || document.title}</strong><small>{document.number || 'Документ'} · {shortDate(document.act_date)}</small></span><span className="p-row-meta">{document.warnings?.length ? 'Требует сверки' : document.available ? 'Текст доступен' : 'Нет текста'}</span></a>)}{!documents.length && <p className="p-empty">Для этого типа пока нет материалов.</p>}</div>
|
||||
}
|
||||
|
||||
export function Contents({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
||||
const id = route.doc || route.id || documents[0]?.id || null
|
||||
const {data, loading, error} = useApi<ReaderData>(id ? `/reader?${new URLSearchParams({id, fragment: route.fragment || ''})}` : null)
|
||||
const documentId = id || ''
|
||||
const groups = useMemo(() => {
|
||||
const toc = data?.toc || []
|
||||
if (!documentId.endsWith('gk-rf')) return toc
|
||||
return toc.filter(fragment => /^Часть\s+/i.test(fragment.label))
|
||||
}, [data, documentId])
|
||||
if (loading) return <section className="p-contents"><p>Загружаем оглавление…</p></section>
|
||||
if (error || !data) return <section className="p-contents"><p className="p-empty">Оглавление пока недоступно.</p></section>
|
||||
return <section className="p-contents" aria-labelledby="contents-title"><p className="p-eyebrow">Оглавление</p><h1 id="contents-title">{data.document.subject || data.document.title}</h1><div className="p-contents-list">{groups.map((fragment, index) => <a key={fragment.id} href={docHref(data.document.id, fragment.id)}><span>{String(index + 1).padStart(2, '0')}</span><strong>{fragment.label}</strong></a>)}</div></section>
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import {Component, lazy, Suspense, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'
|
||||
import ForceGraph2D, {type ForceGraphMethods as Graph2D, type LinkObject} from 'react-force-graph-2d'
|
||||
import type {ForceGraphMethods as Graph3D} from 'react-force-graph-3d'
|
||||
import {api, docHref, href, kinds, safeURL, shortDate, type GraphEdge, type GraphNode, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import './connections.css'
|
||||
|
||||
type NetworkNode = GraphNode & {x?:number; y?:number; z?:number; aliases?:string[]; document_number?:string; document_date?:string}
|
||||
type LinkMeta = Omit<GraphEdge, 'source'|'target'> & {count?:number}
|
||||
type NetworkLink = LinkObject<NetworkNode, LinkMeta>
|
||||
type Level = 'documents'|'atoms'
|
||||
interface NetworkData {level?:Level; status?:string; note?:string; focus_id?:string; nodes:NetworkNode[]; edges:GraphEdge[]; total_nodes:number; total_edges:number; truncated?:boolean; stale?:boolean; loading?:boolean; warnings?:{problem?:string; output?:string}[]}
|
||||
const ForceGraph3D = lazy(() => import('react-force-graph-3d').then(module => ({default:module.default<NetworkNode, LinkMeta>})))
|
||||
const nodeLabel = (node:NetworkNode) => {
|
||||
const label=node.label&&!/^(doc:|legal-corpus:)/.test(node.label)?node.label:node.document_title||'Документ'
|
||||
if(node.kind!=='point')return label
|
||||
const point=label.match(/^(?:Пункт|п\.)\s*(\d+(?:\.\d+)*)/i)?.[1]
|
||||
const article=node.id.match(/:article:(\d+(?:\.\d+)*):/)?.[1]
|
||||
return point?'Пункт '+point+(article?' статьи '+article:''):label
|
||||
}
|
||||
const linkId = (value:NetworkLink['source']) => typeof value === 'object' ? value.id : value
|
||||
const graphStyle=getComputedStyle(document.documentElement)
|
||||
const graphColors={blue:graphStyle.getPropertyValue('--accent').trim(),red:graphStyle.getPropertyValue('--red').trim(),point:graphStyle.getPropertyValue('--graph-point').trim(),canvas:graphStyle.getPropertyValue('--graph-canvas').trim(),ink:graphStyle.getPropertyValue('--ink').trim()}
|
||||
const nodeColor = (node:NetworkNode) => node.document_kind === 'plenum' ? graphColors.red : node.kind === 'point' ? graphColors.point : graphColors.blue
|
||||
const tooltip = (node:NetworkNode) => {const span=document.createElement('span');span.textContent=nodeLabel(node)+(node.kind!=='document'?' · '+(node.document_title||''):'');return span.innerHTML}
|
||||
class WebGLBoundary extends Component<{children:ReactNode;onFallback:()=>void},{failed:boolean}> {
|
||||
state={failed:false}
|
||||
static getDerivedStateFromError(){return {failed:true}}
|
||||
render(){return this.state.failed ? <div className="p-connection-state" role="alert"><p>Объемный граф недоступен в этом браузере.</p><button className="p-button" onClick={this.props.onFallback}>Открыть 2D</button></div> : this.props.children}
|
||||
}
|
||||
|
||||
export function Connections({route}:{route:Route}) {
|
||||
const [query,setQuery]=useState(route.q||''), [mode,setMode]=useState<'graph'|'list'>('graph'), [threeD,setThreeD]=useState(false)
|
||||
const [selected,setSelected]=useState(route.node_id||''), [data,setData]=useState<NetworkData|null>(null), [error,setError]=useState(''), [retry,setRetry]=useState(0)
|
||||
const level:Level=route.level==='documents'?'documents':'atoms'
|
||||
const withStructure=route.include_contains!=='0'
|
||||
const path='/graph/network?'+new URLSearchParams({level,limit:'1000',include_contains:withStructure?'1':'0',...(route.fragment?{fragment:route.fragment}:{}),...(route.resource_id?{resource_id:route.resource_id}:{}),...(route.node_id?{node_id:route.node_id}:{}),...(route.q?{q:route.q}:{}),...(route.kind?{kind:route.kind}:{})})
|
||||
useEffect(()=>setQuery(route.q||''),[route.q])
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();let timer:ReturnType<typeof setTimeout>
|
||||
setData(null);setError('');setSelected(route.node_id||'')
|
||||
const fetchNetwork=()=>api<NetworkData>(path,{signal:controller.signal}).then(value=>{
|
||||
if(controller.signal.aborted)return
|
||||
if(value.loading&&!value.nodes.length){timer=setTimeout(fetchNetwork,700);return}
|
||||
setData(value);setSelected(value.focus_id||route.node_id||'')
|
||||
}).catch(reason=>{if(!controller.signal.aborted)setError(reason.message)})
|
||||
fetchNetwork();return()=>{controller.abort();clearTimeout(timer)}
|
||||
},[path,retry])
|
||||
const navigate=(next:Record<string,string|undefined>)=>{location.hash=href({view:'graph',level,fragment:route.fragment,include_contains:route.include_contains,...(route.resource_id?{resource_id:route.resource_id}:{}),...(route.node_id?{node_id:route.node_id}:{}),q:route.q,kind:route.kind,...next})}
|
||||
return <section className="p-connections" aria-labelledby="connections-title">
|
||||
<header className="p-connections-head"><div><p className="p-eyebrow">Статьи, пункты и точные ссылки</p><h1 id="connections-title">Граф знаний</h1><p>{level==='atoms'?'Каждая точка — отдельная статья или пункт. Найдите норму или откройте ее граф из текста.':'Сводный обзор документов. Для точных связей переключитесь на статьи и пункты.'}</p></div><div className="p-connection-actions" aria-label="Вид графа"><button className="p-button" aria-pressed={mode==='graph'&&!threeD} onClick={()=>{setMode('graph');setThreeD(false)}}>2D</button><button className="p-button" aria-pressed={mode==='graph'&&threeD} onClick={()=>{setMode('graph');setThreeD(true)}}>3D</button><button className="p-button" aria-pressed={mode==='list'} onClick={()=>setMode('list')}>Список</button></div></header>
|
||||
<form className="p-connection-filters" onSubmit={e=>{e.preventDefault();navigate({q:query||undefined,node_id:undefined,fragment:undefined,resource_id:undefined})}}><label className="p-field"><span>Поиск узлов</span><input value={query} onChange={e=>setQuery(e.target.value)} placeholder="Например, ст. 395 ГК или ст. 131 ГПК"/></label><label className="p-field"><span>Слой</span><select value={level} onChange={e=>navigate({level:e.target.value,node_id:undefined,fragment:undefined,resource_id:undefined})}><option value="atoms">Статьи и пункты</option><option value="documents">Обзор документов</option></select></label><label className="p-field"><span>Тип</span><select value={route.kind||''} onChange={e=>navigate({kind:e.target.value||undefined})}><option value="">Все типы</option>{Object.entries(kinds).map(([key,value])=><option key={key} value={key}>{value[0]}</option>)}</select></label><button className="p-button p-button-primary" type="submit"><Icon name="search"/>Найти</button></form>
|
||||
{level==='atoms'&&<label className="p-structure-toggle"><input type="checkbox" checked={withStructure} onChange={e=>navigate({include_contains:e.target.checked?'1':'0'})}/>Показывать состав статьи и вложенные пункты</label>}
|
||||
{(route.resource_id||route.node_id||route.fragment||route.q||route.kind)&&<div className="p-graph-scope"><span>{route.node_id||route.fragment?'Связи выбранной нормы':route.resource_id?'Статьи документа':'Результаты поиска норм'}</span><a href={href({view:'graph'})}>Общий граф</a></div>}
|
||||
{data?.stale&&<p className="p-connection-notice">После сборки исходные тексты изменились. Связи требуют сверки.</p>}
|
||||
{!!data?.warnings?.length&&<details className="p-connection-warnings"><summary>Проверка источников · {data.warnings.length}</summary>{data.warnings.map((warning,i)=><p key={i}>{warning.problem||warning.output||'Источник требует сверки.'}</p>)}</details>}
|
||||
{error?<div className="p-connection-state" role="alert"><strong>Граф недоступен</strong><p>{error}</p><button className="p-button" onClick={()=>setRetry(n=>n+1)}>Повторить</button></div>:!data?<p className="p-connection-state" role="status">Загружаем узлы и связи…</p>:!data.nodes.length?<p className="p-connection-state">{data.status==='focus_not_found'?'Этот фрагмент еще не выделен в графе. Связи всего документа вместо него не подставляются.':'Узлы не найдены. Измените запрос или фильтры.'}</p>:<NetworkContent key={path} data={data} mode={mode} threeD={threeD} selected={selected} onSelect={setSelected} onFallback={()=>setThreeD(false)}/>}
|
||||
</section>
|
||||
}
|
||||
|
||||
function NetworkContent({data,mode,threeD,selected,onSelect,onFallback}:{data:NetworkData;mode:'graph'|'list';threeD:boolean;selected:string;onSelect:(id:string)=>void;onFallback:()=>void}) {
|
||||
const [hover,setHover]=useState(''), [reduced,setReduced]=useState(()=>matchMedia('(prefers-reduced-motion: reduce)').matches)
|
||||
const [paused,setPaused]=useState(reduced), [settled,setSettled]=useState(false), [size,setSize]=useState({width:640,height:540})
|
||||
const [showIsolated,setShowIsolated]=useState(false)
|
||||
const labelRects=useRef<{x:number;y:number;width:number;height:number}[]>([])
|
||||
const canvasRef=useRef<HTMLDivElement>(null), ref2=useRef<Graph2D<NetworkNode,LinkMeta>|undefined>(undefined), ref3=useRef<Graph3D<NetworkNode,LinkMeta>|undefined>(undefined), fitted=useRef(false)
|
||||
// Force libraries mutate their data. Preserve the API snapshot when switching dimensions.
|
||||
const degree=useMemo(()=>{const result=new Map<string,number>();data.edges.forEach(link=>{result.set(link.source,(result.get(link.source)||0)+1);result.set(link.target,(result.get(link.target)||0)+1)});return result},[data])
|
||||
const isolated=data.nodes.filter(node=>!degree.has(node.id)).length
|
||||
const graphData=useMemo(()=>({nodes:data.nodes.filter(node=>node.id===data.focus_id||showIsolated||!data.edges.length||degree.has(node.id)).map(node=>({...node})),links:data.edges.map(link=>({...link})) as NetworkLink[]}),[data,threeD,showIsolated,degree])
|
||||
const focus=hover||selected
|
||||
const focusFamily=useMemo(()=>new Set(data.nodes.filter(node=>node.id===focus||(data.nodes.find(item=>item.id===focus)?.kind==='article'&&node.id.startsWith(focus+':'))).map(node=>node.id)),[data,focus])
|
||||
const neighbors=useMemo(()=>{const result=new Set(focusFamily);data.edges.forEach(link=>{if(focusFamily.has(link.source))result.add(link.target);if(focusFamily.has(link.target))result.add(link.source)});return result},[data,focusFamily])
|
||||
const selectedNode=data.nodes.find(node=>node.id===selected), duration=reduced?0:240
|
||||
const fit=()=>{(threeD?ref3.current:ref2.current)?.zoomToFit(duration,36)}
|
||||
useEffect(()=>{const media=matchMedia('(prefers-reduced-motion: reduce)');const change=()=>{setReduced(media.matches);if(media.matches)setPaused(true)};media.addEventListener('change',change);return()=>media.removeEventListener('change',change)},[])
|
||||
useEffect(()=>{const element=canvasRef.current;if(!element)return;const observer=new ResizeObserver(([entry])=>{setSize({width:Math.max(1,Math.floor(entry.contentRect.width)),height:Math.max(1,Math.floor(entry.contentRect.height))})});observer.observe(element);return()=>observer.disconnect()},[mode,threeD])
|
||||
useEffect(()=>{fitted.current=false;setSettled(false);setHover('')},[graphData,mode,threeD])
|
||||
useEffect(()=>{if(!fitted.current)return;const timer=setTimeout(fit,50);return()=>clearTimeout(timer)},[size.width,size.height])
|
||||
const onStop=()=>{setSettled(true);if(!fitted.current){fitted.current=true;fit()}}
|
||||
const togglePhysics=()=>{if(paused||settled){setPaused(false);setSettled(false);(threeD?ref3.current:ref2.current)?.d3ReheatSimulation()}else setPaused(true)}
|
||||
const zoom=(factor:number)=>{
|
||||
if(!threeD){const graph=ref2.current;if(graph)graph.zoom(Math.max(.05,Math.min(20,graph.zoom()*factor)),duration);return}
|
||||
const graph=ref3.current;if(!graph)return
|
||||
const camera=graph.camera(), controls=graph.controls() as {target?:{x:number;y:number;z:number}}, target=controls.target||{x:0,y:0,z:0}
|
||||
graph.cameraPosition({x:target.x+(camera.position.x-target.x)/factor,y:target.y+(camera.position.y-target.y)/factor,z:target.z+(camera.position.z-target.z)/factor},target,duration)
|
||||
}
|
||||
const colored=(node:NetworkNode)=>focus&&!neighbors.has(node.id)?'#d4dfed':node.id===focus?graphColors.blue:nodeColor(node)
|
||||
const paintLabel=(node:NetworkNode,ctx:CanvasRenderingContext2D,scale:number)=>{
|
||||
const radius=1.6*Math.sqrt(3+Math.sqrt(degree.get(node.id)||0)*2)
|
||||
ctx.beginPath();ctx.arc(node.x||0,node.y||0,radius,0,Math.PI*2)
|
||||
ctx.strokeStyle=node.id===focus?graphColors.red:graphColors.blue;ctx.lineWidth=(node.id===focus?2:1)/scale;ctx.stroke()
|
||||
if(node.id!==focus&&graphData.nodes.length>70&&scale<2)return
|
||||
const label=compactLabel(node), text=label.length>52?label.slice(0,49)+'…':label
|
||||
ctx.font=`${node.id===focus?500:400} ${11/scale}px Golos Text`
|
||||
const width=ctx.measureText(text).width+8/scale, height=15/scale
|
||||
const box={x:(node.x||0)-width/2,y:(node.y||0)+radius+5/scale,width,height}
|
||||
if(node.id!==focus&&labelRects.current.some(other=>box.x<other.x+other.width&&box.x+box.width>other.x&&box.y<other.y+other.height&&box.y+box.height>other.y))return
|
||||
labelRects.current.push(box);ctx.fillStyle=graphColors.canvas;ctx.fillRect(box.x,box.y,box.width,box.height)
|
||||
ctx.fillStyle=graphColors.ink;ctx.textAlign='center';ctx.fillText(text,node.x||0,box.y+11/scale)
|
||||
}
|
||||
const linked=(link:NetworkLink)=>focus&&(focusFamily.has(String(linkId(link.source)))||focusFamily.has(String(linkId(link.target))))
|
||||
const common={graphData,width:size.width,height:size.height,backgroundColor:graphColors.canvas,nodeLabel:tooltip,nodeColor:colored,nodeVal:(node:NetworkNode)=>3+Math.sqrt(degree.get(node.id)||0)*2,linkColor:(link:NetworkLink)=>linked(link)?graphColors.blue:focus?'#d4dfed':link.relation==='contains'?'#99abc2':'#6e95bd',linkDirectionalArrowLength:(link:NetworkLink)=>link.relation==='contains'?0:3,linkDirectionalArrowRelPos:1,linkWidth:(link:NetworkLink)=>linked(link)?1.8:.6,onNodeClick:(node:NetworkNode)=>onSelect(node.id),onNodeHover:(node:NetworkNode|null)=>setHover(node?.id||''),onBackgroundClick:()=>onSelect(''),warmupTicks:120,cooldownTicks:paused?0:180,cooldownTime:5000,onEngineStop:onStop,onEngineTick:()=>{if(!fitted.current){fitted.current=true;fit()}},enableNodeDrag:true}
|
||||
return <div className="p-network-layout"><div className="p-network-main">
|
||||
<div className="p-network-toolbar"><span>{mode==='graph'?graphData.nodes.length:data.nodes.length} узлов · {data.edges.length} связей</span>{mode==='graph'&&<div className="p-network-controls"><button className="p-button" aria-label="Приблизить карту" onClick={()=>zoom(1.3)}>+</button><button className="p-button" aria-label="Отдалить карту" onClick={()=>zoom(1/1.3)}>−</button><button className="p-button" onClick={fit}>По размеру</button><button className="p-button" aria-pressed={paused||settled} onClick={togglePhysics}>{paused||settled?'Оживить':'Пауза'}</button></div>}</div>
|
||||
{mode==='graph'&&isolated>0&&data.edges.length>0&&<label className="p-isolated-toggle"><input type="checkbox" checked={showIsolated} onChange={e=>setShowIsolated(e.target.checked)}/>Показать также узлы без связей · {isolated}</label>}
|
||||
{data.truncated&&<p className="p-connection-notice">Показано {data.nodes.length} из {data.total_nodes} узлов и {data.edges.length} из {data.total_edges} связей. Уточните документ или запрос.</p>}
|
||||
{mode==='graph'?<div className="p-force-canvas" ref={canvasRef} onPointerLeave={()=>setHover('')} role="region" aria-label={threeD?'Объемный граф знаний':'Граф знаний: перетаскивание и масштабирование'}>{threeD?<WebGLBoundary onFallback={onFallback}><Suspense fallback={<p role="status" className="p-connection-state">Загружаем объемный граф…</p>}><ForceGraph3D {...common} ref={ref3} controlType="orbit" showNavInfo={false} nodeResolution={12} linkOpacity={.55}/></Suspense></WebGLBoundary>:<ForceGraph2D<NetworkNode,LinkMeta> {...common} ref={ref2} nodeRelSize={1.6} minZoom={.05} maxZoom={20} linkLineDash={(link)=>link.relation==='contains'?[3,3]:null} nodeCanvasObjectMode={()=>'after'} onRenderFramePre={()=>{labelRects.current=[]}} nodeCanvasObject={paintLabel}/>}</div>:<div className="p-network-list" aria-label="Список узлов">{data.nodes.map(node=><button key={node.id} className="p-network-list-row" aria-pressed={node.id===selected} onClick={()=>onSelect(node.id)}><span className="p-network-dot" style={{background:nodeColor(node)}}/><span><strong>{nodeLabel(node)}</strong><small>{node.document_title} · {degree.get(node.id)||0} связей</small></span><Icon name="arrow"/></button>)}</div>}
|
||||
<div className="p-network-legend"><span><i style={{background:graphColors.blue}}/>Статьи</span><span><i style={{background:graphColors.red}}/>Пункты Пленумов</span><span><i style={{background:graphColors.point}}/>Другие пункты</span></div>
|
||||
</div><aside className="p-network-panel" aria-label="Выбранный узел">{selectedNode?<NodePanel node={selectedNode} data={data} onSelect={onSelect}/>:<div className="p-connection-state"><Icon name="graph"/><h2>Связи конкретной нормы</h2><p>Выберите статью или пункт. Здесь появятся точные входящие и исходящие ссылки с фрагментами источников.</p><p>Стрелка — прямая ссылка. Линия без стрелки — состав статьи.</p></div>}</aside></div>
|
||||
}
|
||||
|
||||
function compactLabel(node:NetworkNode) {
|
||||
if(node.kind==='document')return nodeLabel(node)
|
||||
const number=node.label.match(/^(?:Статья|Пункт|п\.)\s*(\d+(?:\.\d+)*)/i)?.[1]
|
||||
const alias=node.aliases?.filter(value=>value.length<=12).sort((a,b)=>a.length-b.length)[0]?.toLocaleUpperCase('ru')
|
||||
const plenum=node.document_number||node.document_title?.match(/(?:N|№)\s*([\d-]+)/)?.[1]
|
||||
const documentName=alias||(node.document_kind==='plenum'?'Пленум'+(plenum?' №'+plenum:''):(node.document_title||'').slice(0,28))
|
||||
const parent=node.kind==='point'?node.id.match(/:article:(\d+(?:\.\d+)*):/)?.[1]:undefined
|
||||
return number?(node.kind==='article'?'ст.':'п.')+' '+number+(parent?' ст. '+parent:'')+' · '+documentName:nodeLabel(node)
|
||||
}
|
||||
function NodePanel({node,data,onSelect}:{node:NetworkNode;data:NetworkData;onSelect:(id:string)=>void}) {
|
||||
const family=new Set(data.nodes.filter(item=>item.id===node.id||(node.kind==='article'&&item.id.startsWith(node.id+':'))).map(item=>item.id))
|
||||
const links=data.edges.filter(link=>family.has(link.source)||family.has(link.target))
|
||||
const references=links.filter(link=>link.relation!=='contains'), structural=links.filter(link=>link.relation==='contains')
|
||||
return <div className="p-selected-node"><div className="p-panel-heading"><p className="p-eyebrow">{node.kind==='document'?'Документ':'Конкретная норма'}</p><button className="p-icon-button" aria-label="Снять выбор" onClick={()=>onSelect('')}><Icon name="close"/></button></div><h2>{nodeLabel(node)}</h2>{node.document_title!==nodeLabel(node)&&<p>{node.document_title}</p>}<a className="p-button p-button-primary" href={docHref(node.resource_id,node.reader_id)}>{node.kind==='document'?'Читать документ':'Читать точное место'}</a><a className="p-local-graph-link" href={href({view:'graph',level:'atoms',resource_id:node.resource_id,node_id:node.kind==='document'?undefined:node.id})}>{node.kind==='document'?'Статьи этого документа':'В центре — эта норма'}<Icon name="graph"/></a><h3>Прямые ссылки · {references.length}</h3>{!references.length&&<p className="p-muted">Прямые ссылки для этой нормы в сохраненном графе не найдены. Это не означает отсутствия правовой связи.</p>}{[...references,...structural].map((link,index)=>{
|
||||
const outgoing=family.has(link.source), other=data.nodes.find(item=>item.id===(outgoing?link.target:link.source))
|
||||
if(!other)return null
|
||||
const origin=data.nodes.find(item=>item.id===(outgoing?link.source:link.target))
|
||||
const attribution=origin&&origin.id!==node.id?nodeLabel(origin)+' · ':''
|
||||
const relation=link.relation==='contains'?(outgoing?'Содержит':'Входит в'):attribution+(outgoing?'Ссылается на':'Ссылка из')
|
||||
return <section className="p-atomic-relation" key={link.source+'-'+link.target+'-'+index}><p className="p-eyebrow">{relation}</p><button className="p-related-node" onClick={()=>onSelect(other.id)}><span>{nodeLabel(other)}<small>{other.document_title}</small></span><Icon name="arrow"/></button>{link.relation!=='contains'&&<details className="p-network-evidence"><summary>Основание этой связи</summary><blockquote>{link.evidence?.excerpt||'Подтверждающий фрагмент не сохранен.'}</blockquote>{link.evidence?.revision&&<small>Редакция: {shortDate(link.evidence.revision)}</small>}{link.evidence?.source_url&&<a href={safeURL(link.evidence.source_url)} target="_blank" rel="noreferrer">Источник ↗</a>}</details>}<a className="p-atomic-read" href={docHref(other.resource_id,other.reader_id)}>Читать {compactLabel(other)}</a></section>
|
||||
})}</div>
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import {useCallback, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'
|
||||
import {api, docHref, href, kinds, normalized, safeURL, shortDate, useApi, type Anchor, type Fragment, type GraphEdge, type ReaderData, type RelatedData, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import {NormPractice} from './Practice'
|
||||
import {Sheet, SheetContent, SheetDescription, SheetTitle} from '@/components/ui/sheet'
|
||||
import './document.css'
|
||||
|
||||
type Props = {route: Route; onNotify: (message: string) => void; onRecent?: (id: string, fragment?: string) => void}
|
||||
type FullData = {fragments?: Fragment[]; body?: string}
|
||||
|
||||
function renderText(text: string, anchors: Anchor[] = [], query = ''): ReactNode[] {
|
||||
const pattern = query.trim() ? new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'ig') : null
|
||||
const ordered = anchors.slice().sort((a, b) => a.offset - b.offset)
|
||||
const parts: ReactNode[] = []
|
||||
let cursor = 0
|
||||
const add = (value: string, key: string) => {
|
||||
if (!value) return
|
||||
if (!pattern) { parts.push(<span key={key}>{value}</span>); return }
|
||||
parts.push(...value.split(pattern).map((part, index) => part.toLocaleLowerCase('ru') === query.toLocaleLowerCase('ru') ? <mark key={`${key}-mark-${index}`}>{part}</mark> : <span key={`${key}-${index}`}>{part}</span>))
|
||||
}
|
||||
ordered.forEach((anchor, index) => {
|
||||
const offset = Math.max(cursor, Math.min(text.length, anchor.offset))
|
||||
add(text.slice(cursor, offset), `text-${index}`)
|
||||
parts.push(<span className="p-anchor" id={anchor.id} key={`anchor-${anchor.id}`} aria-hidden="true" />)
|
||||
cursor = offset
|
||||
})
|
||||
add(text.slice(cursor), 'text-tail')
|
||||
return parts
|
||||
}
|
||||
|
||||
function bodyWithoutHeading(fragment: Fragment, query: string) {
|
||||
const raw = String(fragment.text || '')
|
||||
const first = raw.split(/\r?\n/, 1)[0].replace(/^\s*#+\s*/, '').trim()
|
||||
if (!first || normalized(first) !== normalized(fragment.label)) return renderText(raw, fragment.anchors, query)
|
||||
const match = raw.match(/\r?\n/)
|
||||
if (!match || match.index === undefined) return null
|
||||
const headingEnd = match.index + match[0].length
|
||||
const removed = headingEnd + (raw.slice(headingEnd).match(/^[\r\n]+/)?.[0].length || 0)
|
||||
const anchors = (fragment.anchors || []).filter(anchor => anchor.offset >= removed).map(anchor => ({...anchor, offset: anchor.offset - removed}))
|
||||
return renderText(raw.slice(removed), anchors, query)
|
||||
}
|
||||
|
||||
function shortTitle(title: string) {
|
||||
return title.replace(/\s*\(?Российской Федерации\)?\s*/gi, ' ').replace(/\s+РФ\s*$/i, '').trim() || title
|
||||
}
|
||||
|
||||
function Toc({items, activeId, documentId, filter, onFilter, onSelect}: {items: Fragment[]; activeId: string; documentId: string; filter: string; onFilter: (value: string) => void; onSelect: (id: string) => void}) {
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
const list=listRef.current, active=list?.querySelector('.is-active')
|
||||
if (list && active) list.scrollTop += active.getBoundingClientRect().top - list.getBoundingClientRect().top - 64
|
||||
}, [activeId, filter, items])
|
||||
const rows = useMemo(() => items.filter(item => !filter || normalized(`${item.label} ${item.text || ''}`).includes(normalized(filter))), [items, filter])
|
||||
const chapters = rows.filter(item => !['article', 'point', 'paragraph'].includes(item.kind))
|
||||
const chapterRows = useMemo(() => chapters.map((chapter, index) => {
|
||||
const start = items.indexOf(chapter)
|
||||
const end = index + 1 < chapters.length ? items.indexOf(chapters[index + 1]) : Infinity
|
||||
return {chapter, children: rows.filter(item => item.id !== chapter.id && !chapters.some(other => other.id === item.id) && items.indexOf(item) > start && items.indexOf(item) < end)}
|
||||
}), [chapters, items, rows])
|
||||
return <nav className="p-toc" aria-label="Оглавление"><div className="p-panel-title"><h2>Оглавление</h2></div><label className="p-field"><span>Статья или раздел</span><input type="search" value={filter} onChange={event => onFilter(event.target.value)} placeholder="Например, 395" /></label><div className="p-toc-list" ref={listRef}>
|
||||
{chapterRows.map(({chapter, children}) => <details key={chapter.id} open={Boolean(filter) || activeId === chapter.id || children.some(item => item.id === activeId)}><summary>{chapter.label}</summary><a className={activeId === chapter.id ? 'p-toc-link is-active' : 'p-toc-link'} aria-label={`Читать раздел ${chapter.label}`} href={docHref(documentId, chapter.id)} onClick={() => onSelect(chapter.id)}>Читать раздел</a>{children.map(item => <a className={activeId === item.id ? 'p-toc-link is-active' : 'p-toc-link'} href={docHref(documentId, item.id)} key={item.id} onClick={() => onSelect(item.id)}>{item.label}</a>)}</details>)}
|
||||
{!chapters.length && rows.map(item => <a className={activeId === item.id ? 'p-toc-link is-active' : 'p-toc-link'} href={docHref(documentId, item.id)} key={item.id} onClick={() => onSelect(item.id)}>{item.label}</a>)}
|
||||
</div></nav>
|
||||
}
|
||||
|
||||
const linkCount = (n: number) => n ? `${n} ${n % 10 === 1 && n % 100 !== 11 ? 'связь' : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? 'связи' : 'связей'}` : 'Связей нет'
|
||||
function Related({data, documentId, fragmentId}: {data: RelatedData; documentId: string; fragmentId:string}) {
|
||||
const nodeId = data.node_id
|
||||
return <aside className="p-context" aria-label="Контекст и связи"><div className="p-panel-title"><h2>Контекст</h2><span>{linkCount(data.related?.length || 0)}</span></div><p className="p-context-intro">Основания связи с выбранным фрагментом. Проверяйте каждый переход по источнику.</p><div className="p-related-list">{(data.related || []).map((edge: GraphEdge, index) => {
|
||||
const source = edge.source_node
|
||||
const target = edge.target_node
|
||||
const other = nodeId && source?.id === nodeId ? target : nodeId && target?.id === nodeId ? source : source?.resource_id === documentId ? target : source
|
||||
if (!other) return null
|
||||
return <details className="p-relation" key={`${edge.source}-${edge.target}-${index}`}><summary>{other.label || 'Связанный фрагмент'}</summary><div><span className="p-chip">{edge.relation === 'references' ? 'Прямая ссылка' : edge.relation === 'thematic' ? 'Тематическая связь' : 'Связь из графа'}</span>{edge.evidence?.excerpt ? <p>«{edge.evidence.excerpt}»</p> : <p className="p-muted">Доказательный фрагмент не сохранен.</p>}{edge.evidence?.revision && <p className="p-muted">Редакция: {shortDate(edge.evidence.revision)}</p>}{edge.evidence?.source_url && <a href={safeURL(edge.evidence.source_url)} target="_blank" rel="noopener noreferrer">Источник связи ↗</a>}<a className="p-button p-button-quiet" href={docHref(other.resource_id, other.reader_id)}>{other.reader_id ? 'Открыть фрагмент' : 'Открыть документ'} <Icon name="arrow" /></a></div></details>
|
||||
})}</div><a className="p-context-graph" href={href({view:'graph',level:'atoms',node_id:nodeId||undefined,resource_id:documentId,fragment:nodeId?undefined:fragmentId})}>Граф выбранной нормы →</a></aside>
|
||||
}
|
||||
|
||||
export default function Document({route, onNotify, onRecent}: Props) {
|
||||
const documentId = route.doc || route.id || ''
|
||||
const fragmentId = route.fragment || ''
|
||||
const readerPath = documentId ? `/reader?${new URLSearchParams({id: documentId, ...(fragmentId ? {fragment: fragmentId} : {})})}` : null
|
||||
const reader = useApi<ReaderData>(readerPath)
|
||||
const [allFragments, setAllFragments] = useState<Fragment[]>([])
|
||||
const [wholeLoading, setWholeLoading] = useState(false)
|
||||
const [wholeError, setWholeError] = useState('')
|
||||
const [find, setFind] = useState('')
|
||||
const [findOpen, setFindOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [fontSize, setFontSize] = useState(20)
|
||||
const [readingFocus, setReadingFocus] = useState(false)
|
||||
const [tocFilter, setTocFilter] = useState('')
|
||||
const [panel, setPanel] = useState<'toc' | 'context' | null>(null)
|
||||
const [related, setRelated] = useState<RelatedData>({related: []})
|
||||
const [relatedLoading, setRelatedLoading] = useState(false)
|
||||
const [matchIndex, setMatchIndex] = useState(-1)
|
||||
const [matchCount, setMatchCount] = useState(0)
|
||||
const findRef = useRef<HTMLInputElement>(null)
|
||||
const fullController = useRef<AbortController | null>(null)
|
||||
const fullGeneration = useRef(0)
|
||||
const documentData = reader.data?.document
|
||||
const toc = reader.data?.toc || []
|
||||
const fragments = allFragments.length ? allFragments : reader.data?.fragment ? [reader.data.fragment] : []
|
||||
const activeId = reader.data?.selected_id || fragmentId || fragments[0]?.id || ''
|
||||
const visible = query ? allFragments : fragments
|
||||
|
||||
useEffect(() => { setAllFragments([]); setQuery(''); setFind(''); setWholeError(''); setWholeLoading(false); fullGeneration.current += 1; fullController.current?.abort(); window.scrollTo(0,0) }, [documentId, fragmentId])
|
||||
useEffect(() => { if (reader.data?.document && activeId) onRecent?.(documentId, activeId) }, [reader.data?.document.id, activeId, documentId, onRecent])
|
||||
useEffect(() => { if (findOpen) findRef.current?.focus() }, [findOpen])
|
||||
useEffect(() => { document.body.classList.toggle('p-reading-focus', readingFocus); return () => document.body.classList.remove('p-reading-focus') }, [readingFocus])
|
||||
useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && readingFocus) setReadingFocus(false) }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey) }, [readingFocus])
|
||||
useEffect(() => () => { fullGeneration.current += 1; fullController.current?.abort() }, [])
|
||||
|
||||
const loadWhole = useCallback(async () => {
|
||||
if (!documentId || allFragments.length || wholeLoading) return allFragments
|
||||
fullController.current?.abort()
|
||||
const controller = new AbortController(); fullController.current = controller; const generation = ++fullGeneration.current
|
||||
setWholeLoading(true); setWholeError('')
|
||||
try {
|
||||
const data = await api<FullData>(`/document?${new URLSearchParams({id: documentId})}`, {signal: controller.signal})
|
||||
if (controller.signal.aborted || generation !== fullGeneration.current) return []
|
||||
const next = data.fragments || (data.body ? [{id: documentId, label: 'Документ', kind: 'document', text: data.body}] : [])
|
||||
setAllFragments(next); return next
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || generation !== fullGeneration.current) return []
|
||||
const message = error instanceof Error ? error.message : 'Полный текст недоступен.'; setWholeError(message); onNotify(message); return []
|
||||
} finally { if (generation === fullGeneration.current) { setWholeLoading(false); fullController.current = null } }
|
||||
}, [allFragments, documentId, onNotify, wholeLoading])
|
||||
|
||||
useEffect(() => {
|
||||
if (!find.trim()) { setQuery(''); return }
|
||||
const timer = window.setTimeout(() => { if (allFragments.length) {setQuery(find.trim());setMatchIndex(-1)} else if (!wholeLoading && !wholeError) void loadWhole() }, 260)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [find, allFragments, wholeLoading, wholeError, loadWhole])
|
||||
|
||||
useEffect(() => {
|
||||
if (!documentId) return
|
||||
const controller = new AbortController(); let timer: number | undefined; let attempts = 0; let live = true
|
||||
setRelatedLoading(true)
|
||||
const load = async () => { try { const data = await api<RelatedData>(`/related?${new URLSearchParams({id: documentId, ...(activeId ? {fragment: activeId} : {})})}`, {signal: controller.signal}); if (!live || controller.signal.aborted) return; setRelated(data); setRelatedLoading(Boolean(data.loading)); if (data.loading && attempts++ < 4) timer = window.setTimeout(load, 1500) } catch (error) { if (live && !(error instanceof Error && error.name === 'AbortError')) setRelated({related: []}) } }
|
||||
void load(); return () => { live = false; controller.abort(); if (timer !== undefined) window.clearTimeout(timer) }
|
||||
}, [documentId, activeId])
|
||||
|
||||
useEffect(() => { const frame = window.requestAnimationFrame(() => { setMatchCount(document.querySelectorAll('.p-reading mark').length); if (!query && !allFragments.length && activeId === reader.data?.fragment?.id) return; const node = activeId ? document.getElementById(activeId) : null; if (node) window.scrollTo({top: Math.max(0, node.getBoundingClientRect().top + window.scrollY - 110), behavior: 'auto'}) }); return () => window.cancelAnimationFrame(frame) }, [activeId, query, allFragments, reader.data])
|
||||
|
||||
const select = (id: string) => { window.location.hash = docHref(documentId, id).slice(1); onRecent?.(documentId, id) }
|
||||
const articleRows = toc.filter(item => item.kind === 'article')
|
||||
const articleIndex = articleRows.findIndex(item => item.id === reader.data?.fragment?.id)
|
||||
const adjacent = (direction: -1 | 1) => { const next = articleRows[articleIndex + direction]; if (next) select(next.id) }
|
||||
const navigateMatch = (direction: -1 | 1) => { const marks = Array.from(document.querySelectorAll<HTMLElement>('.p-reading mark')); if (!marks.length) return; const index = (matchIndex + direction + marks.length) % marks.length; setMatchIndex(index); marks[index].scrollIntoView({block: 'center', behavior: 'auto'}) }
|
||||
const copyLink = async () => { try { await navigator.clipboard.writeText(`${location.origin}${location.pathname}${docHref(documentId, activeId)}`); onNotify('Ссылка скопирована') } catch { onNotify('Копирование недоступно в этом браузере.') } }
|
||||
|
||||
if (reader.loading && !documentData) return <div className="p-document"><p className="p-status">Открываем документ…</p></div>
|
||||
if (reader.error || !documentData) return <div className="p-document"><p className="p-warning">{reader.error || 'Документ не найден.'}</p></div>
|
||||
const title = documentData.subject || documentData.title
|
||||
const longRevision = (documentData.revision?.length || 0) > 35
|
||||
return <div className="p-document">
|
||||
<header className="p-document-header">
|
||||
<div><span className="p-kicker">{kinds[documentData.kind]?.[0] || 'Документ'}</span><h1>{shortTitle(title)}</h1>
|
||||
<details><summary>Название, редакция и реквизиты</summary><p>{documentData.title}</p><dl><div><dt>Номер</dt><dd>{documentData.number || 'не указан'}</dd></div><div><dt>Дата акта</dt><dd>{shortDate(documentData.act_date)}</dd></div></dl><p>Редакция: {shortDate(documentData.revision)}</p><p>Получено: {shortDate(documentData.retrieved_at)} · Проверено: {shortDate(documentData.last_checked)}</p><p>{documentData.integrity ? 'Целостность сохраненного текста подтверждена' : 'Целостность текста не подтверждена'}</p></details>
|
||||
</div>
|
||||
<div className="p-header-actions"><a className="p-button" href={href({view:'history',id:documentId})}><Icon name="history"/>Редакции</a>{safeURL(documentData.source_url)!=='#'&&<a className="p-button" href={safeURL(documentData.source_url)} target="_blank" rel="noopener noreferrer">Источник<Icon name="source"/></a>}</div>
|
||||
</header>
|
||||
<div className="p-document-meta"><span>{longRevision ? 'Редакции четырех частей — в реквизитах' : `Редакция: ${shortDate(documentData.revision)}`}</span>{!!documentData.warnings?.length&&<details className="p-reader-warning"><summary>Требует сверки · {documentData.warnings.length}</summary>{documentData.warnings.map((text,i)=><p key={i}>{text}</p>)}</details>}</div>
|
||||
<div className="p-mobile-actions"><button className="p-button p-toc-trigger" onClick={()=>setPanel('toc')}><Icon name="menu"/>Оглавление</button><button className="p-button" onClick={()=>setPanel('context')}><Icon name="graph"/>Контекст</button></div>
|
||||
<div className="p-layout">
|
||||
<div className="p-side"><Toc items={toc} activeId={reader.data?.fragment?.id || activeId} documentId={documentId} filter={tocFilter} onFilter={setTocFilter} onSelect={select}/></div>
|
||||
<div className="p-reader-main">
|
||||
<div className="p-reader-tools">
|
||||
<div className="p-toolbar" role="toolbar" aria-label="Инструменты чтения">
|
||||
<button className="p-button" onClick={()=>setFindOpen(v=>!v)} aria-expanded={findOpen}><Icon name="search"/>Найти</button>
|
||||
<span className="p-tool-divider"/>
|
||||
<button className="p-icon-button" aria-label="Уменьшить шрифт" title="Уменьшить шрифт" disabled={fontSize<=16} onClick={()=>setFontSize(n=>n-1)}>A−</button>
|
||||
<button className="p-icon-button" aria-label="Увеличить шрифт" title="Увеличить шрифт" disabled={fontSize>=30} onClick={()=>setFontSize(n=>n+1)}>A+</button>
|
||||
<button className="p-icon-button" aria-label="Копировать ссылку" title="Копировать ссылку" onClick={()=>void copyLink()}><Icon name="copy"/></button>
|
||||
<button className="p-icon-button" aria-label={readingFocus?'Выйти из режима чтения':'Режим чтения'} title="Режим чтения · Escape для выхода" aria-pressed={readingFocus} onClick={()=>setReadingFocus(v=>!v)}><Icon name="expand"/></button>
|
||||
</div>
|
||||
{findOpen&&<div className="p-find-row"><label className="p-field p-find"><span className="sr-only">Найти в тексте</span><input ref={findRef} aria-label="Найти в тексте" type="search" value={find} onChange={e=>setFind(e.target.value)} placeholder="Слово или фраза"/></label><span className="p-counter" role="status">{wholeLoading?'Загрузка…':query?`${matchIndex>=0?matchIndex+1:0} / ${matchCount}`:''}</span><button className="p-icon-button" disabled={!matchCount} aria-label="Предыдущее совпадение" onClick={()=>navigateMatch(-1)}>↑</button><button className="p-icon-button" disabled={!matchCount} aria-label="Следующее совпадение" onClick={()=>navigateMatch(1)}>↓</button></div>}
|
||||
</div>
|
||||
{wholeError&&<p className="p-warning" role="alert">{wholeError}</p>}
|
||||
{!query&&<NormPractice documentId={documentId} fragmentId={reader.data?.fragment?.id || activeId}/>}
|
||||
<div className="p-reading" style={{fontSize}}>{visible.length?visible.map(fragment=><section className="p-fragment" id={fragment.id} key={fragment.id}><h2>{fragment.label}</h2><a className="p-fragment-graph" href={href({view:'graph',level:'atoms',resource_id:documentId,fragment:fragment.id})}><Icon name="graph"/>Граф этой нормы</a><div>{bodyWithoutHeading(fragment,query)}</div></section>):<p className="p-muted">Текст пока не загружен.</p>}</div>
|
||||
{articleIndex>=0&&<div className="p-adjacent"><button className="p-button" disabled={articleIndex<=0} onClick={()=>adjacent(-1)}>← Предыдущая статья</button><button className="p-button" disabled={articleIndex>=articleRows.length-1} onClick={()=>adjacent(1)}>Следующая статья →</button></div>}
|
||||
{!allFragments.length&&<button className="p-button p-whole-text" disabled={wholeLoading} onClick={()=>void loadWhole()}>{wholeLoading?'Загружаем…':'Открыть весь документ'}</button>}
|
||||
</div>
|
||||
<div className="p-side"><Related data={{...related,loading:relatedLoading}} documentId={documentId} fragmentId={activeId}/></div>
|
||||
</div>
|
||||
<Sheet open={panel!==null} onOpenChange={open=>{if(!open)setPanel(null)}}><SheetContent side={panel==='toc'?'left':'right'} className="p-sheet"><SheetTitle>{panel==='toc'?'Оглавление':'Контекст'}</SheetTitle><SheetDescription className="sr-only">Навигация и проверяемые связи документа</SheetDescription>{panel==='toc'?<Toc items={toc} activeId={reader.data?.fragment?.id || activeId} documentId={documentId} filter={tocFilter} onFilter={setTocFilter} onSelect={id=>{select(id);setPanel(null)}}/>:<Related data={{...related,loading:relatedLoading}} documentId={documentId} fragmentId={activeId}/>}</SheetContent></Sheet>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import {useEffect, useMemo, useState} from 'react'
|
||||
import {api, href, normalized, shortDate, useApi, type LegalDocument, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import './editions.css'
|
||||
|
||||
interface Version {id: string; revision?: string | null; retrieved_at?: string | null; observed_at?: string | null; effective_date?: string | null; current?: boolean}
|
||||
interface HistoryData {versions: Version[]; note: string}
|
||||
interface DiffChange {id: string; label: string; kind: 'added' | 'removed' | 'changed'; before: string; after: string; lines?: string[]}
|
||||
interface DiffData {changes: DiffChange[]; before: Version; after: Version; formatting_only?: boolean; note: string}
|
||||
|
||||
function shortTitle(value?: string | null) {
|
||||
return (value || 'Редакции документа')
|
||||
.replace(/\s*\(?Российской Федерации\)?\s*/gi, ' ')
|
||||
.replace(/\s+РФ\s*$/i, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function observedDate(version: Version) {
|
||||
return shortDate(version.observed_at || version.retrieved_at || version.revision)
|
||||
}
|
||||
|
||||
function copyLabel(version: Version, index: number) {
|
||||
return `Копия ${index + 1} · ${observedDate(version)}${version.current ? ' · текущая' : ''}`
|
||||
}
|
||||
|
||||
export function Editions({documents, route}: {documents: LegalDocument[]; route: Route}) {
|
||||
const [search, setSearch] = useState('')
|
||||
const [before, setBefore] = useState('')
|
||||
const [after, setAfter] = useState('')
|
||||
const [comparison, setComparison] = useState<string | null>(null)
|
||||
const documentId = route.id || route.doc || ''
|
||||
const document = documents.find(item => item.id === documentId)
|
||||
const history = useApi<HistoryData>(documentId ? `/history?${new URLSearchParams({id: documentId})}` : null)
|
||||
const diff = useApi<DiffData>(comparison)
|
||||
const versions = history.data?.versions || []
|
||||
const choices = useMemo(() => documents.filter(item => normalized(`${item.title} ${item.subject || ''} ${item.number || ''}`).includes(normalized(search))).slice(0, 16), [documents, search])
|
||||
|
||||
useEffect(() => {
|
||||
setComparison(null)
|
||||
if (versions.length >= 2) { setBefore(versions[0].id); setAfter(versions[versions.length - 1].id) } else { setBefore(''); setAfter('') }
|
||||
}, [documentId, history.data])
|
||||
|
||||
const compare = (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
if (!documentId || !before || !after || before === after) return
|
||||
setComparison(`/diff?${new URLSearchParams({id: documentId, before, after})}`)
|
||||
}
|
||||
|
||||
if (!documentId) return <div className="p-editions"><header className="p-editions-head"><span className="p-kicker">ИСТОРИЯ ТЕКСТА</span><h1>Редакции документов</h1><p>Выберите документ, чтобы увидеть только сохраненные копии и сравнить их.</p></header><label className="p-field"><span>Найти документ</span><input type="search" value={search} onChange={event => setSearch(event.target.value)} placeholder="Название или номер" /></label><div className="p-edition-picker">{choices.map(item => <a className="p-edition-choice" href={href({view: 'history', id: item.id})} key={item.id}><strong>{item.subject || item.title}</strong><span>{item.number || 'Номер не указан'}</span></a>)}{!choices.length && <p className="p-muted">Документы не найдены.</p>}</div></div>
|
||||
return <div className="p-editions"><header className="p-editions-head"><div><span className="p-kicker">ИСТОРИЯ ТЕКСТА</span><h1>{shortTitle(document?.subject || document?.title)}</h1><p className="p-editions-full-title">{document?.title || 'Сохраненные копии документа'}</p></div><a className="p-button p-button-quiet" href={href({doc: documentId})}><Icon name="back" /> К тексту</a></header>{history.loading && <p className="p-status">Загружаем сохраненные копии…</p>}{history.error && <p className="p-warning">{history.error}</p>}{history.data && <><p className="p-edition-note">{history.data.note}</p><div className="p-edition-list"><h2>Доступные копии</h2>{versions.map((version, index) => <div className="p-edition-row" key={version.id}><div><strong>Копия {index + 1}</strong><span>Наблюдалась: {observedDate(version)}</span><span className="p-edition-detail">Редакция: {shortDate(version.revision)}</span>{version.effective_date && <span className="p-edition-detail">Вступила в силу: {shortDate(version.effective_date)}</span>}</div>{version.current && <span className="p-chip">Текущая копия</span>}</div>)}{!versions.length && <p className="p-muted">Сохраненных копий пока нет.</p>}</div>{versions.length >= 2 ? <form className="p-compare" onSubmit={compare}><h2>Сравнить копии</h2><p>Дата наблюдения показывает, когда Эвномия получила копию. Она не подтверждает дату вступления изменений в силу.</p><div className="p-compare-fields"><label className="p-field"><span>Исходная</span><select value={before} onChange={event => setBefore(event.target.value)}>{versions.map((version, index) => <option value={version.id} key={version.id}>{copyLabel(version, index)}</option>)}</select></label><label className="p-field"><span>Сравниваемая</span><select value={after} onChange={event => setAfter(event.target.value)}>{versions.map((version, index) => <option value={version.id} key={version.id}>{copyLabel(version, index)}</option>)}</select></label><button className="p-button p-button-primary" disabled={before === after}>Сравнить</button></div></form> : <p className="p-empty">Для сравнения нужна еще одна сохраненная копия.</p>}{comparison && <DiffView state={diff} />}</>}</div>
|
||||
}
|
||||
|
||||
function DiffView({state}: {state: ReturnType<typeof useApi<DiffData>>}) {
|
||||
if (state.loading) return <p className="p-status">Сравниваем тексты…</p>
|
||||
if (state.error) return <p className="p-warning">{state.error}</p>
|
||||
const data = state.data
|
||||
if (!data) return null
|
||||
return <section className="p-diff"><h2>Результат сравнения</h2><p className="p-edition-note">{data.note}</p>{!data.changes.length ? <p className="p-empty">{data.formatting_only ? 'Изменилось только оформление текста.' : 'Тексты совпадают.'}</p> : data.changes.map(change => <article className="p-diff-change" key={change.id}><h3>{change.label}</h3><div><section><h4>Исходная копия</h4><pre>{change.before || 'Фрагмент отсутствовал'}</pre></section><section><h4>Сравниваемая копия</h4><pre>{change.after || 'Фрагмент отсутствовал'}</pre></section></div></article>)}</section>
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import type {CSSProperties} from 'react'
|
||||
|
||||
const names = ['library', 'search', 'history', 'graph', 'updates', 'back', 'arrow', 'menu', 'close', 'copy', 'source', 'minus', 'plus', 'expand', 'chevron', 'document']
|
||||
const aliases: Record<string, string> = {home:'library', code:'library', plenum:'document', bylaw:'document', review:'document', 'federal-law':'document', focus:'expand', recent:'history'}
|
||||
export function Icon({name, className = ''}: {name: string; className?: string}) {
|
||||
const index = Math.max(0, names.indexOf(aliases[name] || name))
|
||||
return <span aria-hidden="true" className={`p-icon ${className}`} style={{'--ix': `${index % 4 * 100 / 3}%`, '--iy': `${Math.floor(index / 4) * 100 / 3}%`} as CSSProperties} />
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import {useEffect, useState, type FormEvent, type ReactNode} from 'react'
|
||||
import {docHref, href, safeURL, shortDate, useApi, type PracticeActData, type PracticeAreaGraph, type PracticeArticle, type PracticeCard, type PracticeFacets, type PracticeLink, type PracticeList, type PracticeNorm, type PracticeStatus, type PracticeTree, type Route} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import './practice.css'
|
||||
|
||||
const MONTHS = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']
|
||||
const FILTERS = ['q', 'area', 'month', 'kind', 'category', 'court', 'code', 'article', 'sort'] as const
|
||||
const PRODUCTION: Record<string, string> = {'Гражданское': 'Гражданские', 'Административное': 'Административные', 'Уголовное': 'Уголовные'}
|
||||
type Link = (patch: Record<string, string | undefined>) => string
|
||||
export const plural = (n: number, one: string, few: string, many: string) => n % 10 === 1 && n % 100 !== 11 ? one : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? few : many
|
||||
export const actsWord = (n: number) => `${n.toLocaleString('ru-RU')} ${plural(n, 'акт', 'акта', 'актов')}`
|
||||
const monthLabel = (value: string) => { const [year, month] = value.split('-'); return `${MONTHS[Number(month) - 1] || value} ${year}` }
|
||||
const moment = (value?: string | null) => { const date = new Date(value || ''); return value && !Number.isNaN(+date) ? date.toLocaleString('ru-RU', {dateStyle: 'long', timeStyle: 'short'}) : 'не указано' }
|
||||
const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
|
||||
function highlight(text: string, terms: string[]): ReactNode {
|
||||
const stems = terms.filter(term => term.length > 1).map(escape)
|
||||
if (!stems.length) return text
|
||||
const pattern = new RegExp(`(?<![\\p{L}\\d])((?:${stems.join('|')})[\\p{L}\\d]*)`, 'giu')
|
||||
return text.split(pattern).map((part, index) => index % 2 ? <mark key={index}>{part}</mark> : part)
|
||||
}
|
||||
|
||||
function Select({label, value = '', options = [], all, onChange}: {label: string; value?: string; options?: [string, string][]; all: string; onChange: (value?: string) => void}) {
|
||||
return <label><span>{label}</span><select value={value} onChange={event => onChange(event.target.value || undefined)}>
|
||||
<option value="">{all}</option>
|
||||
{options.map(([option, text]) => <option key={option} value={option}>{text}</option>)}
|
||||
{value && !options.some(([option]) => option === value) && <option value={value}>{value}</option>}
|
||||
</select></label>
|
||||
}
|
||||
|
||||
function Row({item, terms}: {item: PracticeCard; terms: string[]}) {
|
||||
const quote = item.excerpt || item.subject || ''
|
||||
return <article className="p-result p-practice-row">
|
||||
<div className="p-result-kind">{item.category || 'Судебный акт'}</div>
|
||||
<h2><a href={href({view: 'act', act: item.doc})}>{item.kind}{item.number ? ` № ${item.number}` : ''}<Icon name="arrow" /></a></h2>
|
||||
<p className="p-result-document">{[shortDate(item.act_date), item.court].filter(Boolean).join(' · ')}</p>
|
||||
{quote && <p className="p-result-excerpt">{highlight(quote, terms)}</p>}
|
||||
</article>
|
||||
}
|
||||
|
||||
function lines(title: string, width = 16): string[] {
|
||||
if (title.length <= width) return [title]
|
||||
const spaces = [...title.matchAll(/ /g)].map(match => match.index || 0)
|
||||
const cut = spaces.reduce((best, index) => Math.abs(index - title.length / 2) < Math.abs(best - title.length / 2) ? index : best, spaces[0] ?? title.length)
|
||||
return [title.slice(0, cut), title.slice(cut + 1)].filter(Boolean)
|
||||
}
|
||||
|
||||
function Divisions({tree, route, link}: {tree: PracticeTree; route: Route; link: Link}) {
|
||||
const total = tree.total
|
||||
const hub = tree.areas.find(area => (route.area || '').split(',').some(id => id === area.id || area.children.some(child => child.id === id)))
|
||||
return <nav className="p-practice-divisions" aria-label="Деление практики">
|
||||
<div className="p-division-row"><span className="p-division-label">Производство</span>
|
||||
<a href={link({category: undefined})} aria-current={!route.category ? 'true' : undefined}>Все<span>{total.toLocaleString('ru-RU')}</span></a>
|
||||
{tree.productions.map(item => <a key={item.value} href={link({category: item.value})} aria-current={route.category === item.value ? 'true' : undefined}>{PRODUCTION[item.value] || item.value}<span>{item.count.toLocaleString('ru-RU')}</span></a>)}
|
||||
</div>
|
||||
<div className="p-division-row"><span className="p-division-label">Отрасли</span>
|
||||
<a href={link({area: undefined})} aria-current={!route.area ? 'true' : undefined}>Все отрасли</a>
|
||||
{tree.areas.map(area => <a key={area.id} href={link({area: area.id})} aria-current={hub?.id === area.id ? 'true' : undefined}>{area.title}<span>{area.count.toLocaleString('ru-RU')}</span></a>)}
|
||||
</div>
|
||||
</nav>
|
||||
}
|
||||
|
||||
function AreaGraph({data, selected, link}: {data: PracticeAreaGraph; selected: string[]; link: Link}) {
|
||||
const cx = 410, cy = 235, max = Math.max(1, ...data.children.map(child => child.count))
|
||||
const maxPair = Math.max(1, ...data.intersections.map(item => item.count))
|
||||
const place = new Map(data.children.map((child, index) => {
|
||||
const angle = -Math.PI / 2 + index * 2 * Math.PI / data.children.length
|
||||
return [child.id, {x: cx + 230 * Math.cos(angle), y: cy + 150 * Math.sin(angle), cos: Math.cos(angle), sin: Math.sin(angle), r: 20 + 18 * Math.sqrt(child.count / max)}]
|
||||
}))
|
||||
return <svg className="p-area-graph" viewBox="0 0 820 470" aria-hidden="true" focusable="false">
|
||||
{data.children.map(child => { const at = place.get(child.id)!; return <line key={child.id} className="p-area-spoke" x1={cx} y1={cy} x2={at.x} y2={at.y} /> })}
|
||||
{data.intersections.map(item => {
|
||||
const a = place.get(item.a), b = place.get(item.b)
|
||||
if (!a || !b) return null
|
||||
// Дуга выгибается наружу от центра; почти противоположные узлы - вбок, чтобы не идти сквозь центр.
|
||||
const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2, far = Math.hypot(mx - cx, my - cy) > 80
|
||||
const ux = far ? (mx - cx) / Math.hypot(mx - cx, my - cy) : (a.y - b.y) / Math.hypot(b.x - a.x, b.y - a.y)
|
||||
const uy = far ? (my - cy) / Math.hypot(mx - cx, my - cy) : (b.x - a.x) / Math.hypot(b.x - a.x, b.y - a.y)
|
||||
const qx = mx + ux * (far ? 60 : 150), qy = my + uy * (far ? 60 : 150)
|
||||
const on = selected.includes(item.a) && selected.includes(item.b)
|
||||
return <a key={item.a + item.b} href={link({area: `${item.a},${item.b}`})} tabIndex={-1}>
|
||||
<path className={`p-area-cross-edge${on ? ' is-on' : ''}`} d={`M${a.x},${a.y} Q${qx},${qy} ${b.x},${b.y}`} strokeWidth={1.5 + 4 * item.count / maxPair} />
|
||||
<circle className="p-area-badge" cx={(a.x + 2 * qx + b.x) / 4} cy={(a.y + 2 * qy + b.y) / 4} r="12" />
|
||||
<text className="p-area-badge-text" x={(a.x + 2 * qx + b.x) / 4} y={(a.y + 2 * qy + b.y) / 4 + 4}>{item.count}</text>
|
||||
</a>
|
||||
})}
|
||||
<a href={link({area: data.area.id})} tabIndex={-1}><circle className={`p-area-hub${selected.includes(data.area.id) ? ' is-on' : ''}`} cx={cx} cy={cy} r="62" />
|
||||
{lines(data.area.title, 10).map((line, index, all) => <text key={line} className="p-area-hub-text" x={cx} y={cy - 8 - (all.length - 1) * 9 + index * 18}>{line}</text>)}
|
||||
<text className="p-area-hub-count" x={cx} y={cy + 24}>{data.area.count}</text></a>
|
||||
{data.children.map(child => {
|
||||
const at = place.get(child.id)!, side = Math.abs(at.cos) > 0.3, words = lines(child.title)
|
||||
const anchor = side ? (at.cos > 0 ? 'start' : 'end') : 'middle'
|
||||
const x = side ? at.x + (at.r + 12) * Math.sign(at.cos) : at.x
|
||||
const y = side ? at.y - (words.length - 1) * 8 + 5 : at.sin < 0 ? at.y - at.r - 12 - (words.length - 1) * 16 : at.y + at.r + 22
|
||||
return <a key={child.id} href={link({area: child.id})} tabIndex={-1}>
|
||||
<circle className={`p-area-node${selected.includes(child.id) ? ' is-on' : ''}`} cx={at.x} cy={at.y} r={at.r} />
|
||||
<text className="p-area-node-count" x={at.x} y={at.y + 5}>{child.count}</text>
|
||||
{words.map((word, index) => <text key={word} className="p-area-node-text" textAnchor={anchor} x={x} y={y + index * 16}>{word}</text>)}
|
||||
</a>
|
||||
})}
|
||||
</svg>
|
||||
}
|
||||
|
||||
function AreaPanel({hub, route, link}: {hub: string; route: Route; link: Link}) {
|
||||
const {data} = useApi<PracticeAreaGraph>('/practice/area?' + new URLSearchParams({id: hub}))
|
||||
if (!data?.ready) return null
|
||||
const selected = (route.area || '').split(',')
|
||||
const title = (id: string) => data.children.find(child => child.id === id)?.title || id
|
||||
const atoms = data.articles.filter(item => selected.includes(item.node) || selected.includes(data.area.id))
|
||||
return <section className="p-area" aria-labelledby="area-title">
|
||||
<div className="p-area-head"><h2 id="area-title">{data.area.title}</h2>
|
||||
<p>{actsWord(data.area.count)}{data.productions.length ? ' · ' + data.productions.map(item => `${PRODUCTION[item.value] || item.value} ${item.count}`).join(' · ') : ''}</p></div>
|
||||
<AreaGraph data={data} selected={selected} link={link} />
|
||||
<nav className="p-area-children" aria-label="Подкатегории">
|
||||
<a href={link({area: data.area.id})} aria-current={route.area === data.area.id ? 'true' : undefined}>Все {data.area.title.toLocaleLowerCase('ru')}<span>{data.area.count}</span></a>
|
||||
{data.children.map(child => <a key={child.id} href={link({area: child.id})} aria-current={route.area === child.id ? 'true' : undefined}>{child.title}<span>{child.count}</span></a>)}
|
||||
</nav>
|
||||
{!!data.intersections.length && <div className="p-area-cross"><h3>Пересечения подкатегорий</h3>
|
||||
{data.intersections.map(item => <a key={item.a + item.b} href={link({area: `${item.a},${item.b}`})} aria-current={route.area === `${item.a},${item.b}` ? 'true' : undefined}>{title(item.a)} и {title(item.b)}<span>{actsWord(item.count)}</span></a>)}</div>}
|
||||
{!!atoms.length && <div className="p-area-cross"><h3>Чаще всего цитируют</h3>
|
||||
{atoms.map(item => <a key={item.node + item.article} href={link({area: item.node, code: item.code, article: item.article})}>{item.label}<small>{title(item.node)}</small><span>{item.count}</span></a>)}</div>}
|
||||
<p className="p-area-note">Акты отнесены машиной, без модели: по предмету требования в начале акта или по нескольким статьям главы СК. Причина видна в каждом акте.</p>
|
||||
</section>
|
||||
}
|
||||
|
||||
function NotLoaded() {
|
||||
return <p className="p-practice-note">Практика еще не загружена. Задача обновления каждый час забирает акты из Lynceuz и строит связи со статьями. Ее состояние — на странице «Состояние базы».</p>
|
||||
}
|
||||
|
||||
export function PracticeView({route}: {route: Route}) {
|
||||
const params = new URLSearchParams([...FILTERS.flatMap(key => route[key] ? [[key, route[key]]] : []), ...(route.page ? [['page', route.page]] : [])])
|
||||
const list = useApi<PracticeList>('/practice?' + params)
|
||||
const facets = useApi<PracticeFacets>('/practice/facets')
|
||||
const [query, setQuery] = useState(route.q || '')
|
||||
useEffect(() => setQuery(route.q || ''), [route.q])
|
||||
const tree = useApi<PracticeTree>('/practice/tree')
|
||||
const link: Link = patch => href({view: 'practice', ...Object.fromEntries(FILTERS.map(key => [key, route[key]])), ...patch, page: patch.page})
|
||||
const go = (patch: Record<string, string | undefined>) => { location.hash = link(patch) }
|
||||
const hub = tree.data?.areas.find(area => (route.area || '').split(',').some(id => id === area.id || area.children.some(child => child.id === id)))
|
||||
const node = route.area && !route.area.includes(',') ? [hub, ...(hub?.children || [])].find(item => item?.id === route.area) : undefined
|
||||
const submit = (event: FormEvent) => { event.preventDefault(); go({q: query.trim() || undefined}) }
|
||||
const data = list.data
|
||||
const byArticle = route.code && route.article ? data?.articles.find(item => item.code === route.code && item.article === route.article) : undefined
|
||||
const facet = (name: 'months' | 'kinds' | 'categories' | 'courts') => facets.data?.[name].map(({value, count}) => [value, `${name === 'months' ? monthLabel(value) : value} · ${count}`] as [string, string])
|
||||
return <section className="p-research p-practice" aria-labelledby="practice-title">
|
||||
<div className="p-page-head"><p className="p-eyebrow">Судебная практика · СудАкт</p><h1 id="practice-title">{byArticle ? `Практика по ${byArticle.label}` : route.q ? `«${route.q}»` : node?.title || 'Судебная практика'}</h1>
|
||||
<p>Акты судов 2026 года с полным текстом. Ищите словами или статьей: «неустойка», «ст. 333 ГК».</p></div>
|
||||
{tree.data?.ready && <Divisions tree={tree.data} route={route} link={link} />}
|
||||
{hub && <AreaPanel key={hub.id} hub={hub.id} route={route} link={link} />}
|
||||
<form className="p-practice-search" role="search" aria-label="Поиск по практике" onSubmit={submit}>
|
||||
<label className="p-field"><span>Слова или статья</span><input type="search" value={query} maxLength={300} onChange={event => setQuery(event.target.value)} placeholder="неустойка, ст. 333 ГК" /></label>
|
||||
<button className="p-button p-primary" type="submit"><Icon name="search" />Найти</button>
|
||||
</form>
|
||||
<div className="p-filterbar p-practice-filters">
|
||||
<Select label="Месяц" value={route.month} options={facet('months')} all="Все месяцы" onChange={month => go({month})} />
|
||||
<Select label="Вид акта" value={route.kind} options={facet('kinds')} all="Все виды" onChange={kind => go({kind})} />
|
||||
<Select label="Суд" value={route.court} options={facet('courts')} all="Все суды" onChange={court => go({court})} />
|
||||
<Select label="Порядок" value={route.sort} options={[['old', 'Сначала ранние']]} all="Сначала новые" onChange={sort => go({sort})} />
|
||||
</div>
|
||||
{!!data?.articles.length && <div className="p-practice-articles" aria-label="Статьи в запросе">{data.articles.map(item => <span className="p-chip" key={item.code + item.article}>{item.label}{item.reader && <a href={docHref(item.reader.id, item.reader.fragment)}>текст статьи</a>}</span>)}
|
||||
{route.code && <a className="p-practice-reset" href={href({view: 'practice'})}>Сбросить статью</a>}</div>}
|
||||
<div className="p-results-tools"><span role="status">{list.loading ? 'Ищем…' : data?.ready ? actsWord(data.total) : ''}</span></div>
|
||||
{list.error ? <p role="alert" className="p-notice">{list.error}</p>
|
||||
: !data ? <p className="p-loading" role="status">Открываем практику…</p>
|
||||
: !data.ready ? <NotLoaded />
|
||||
: !data.items.length ? <p className="p-empty">Актов по запросу нет. Уберите фильтр или измените слова.</p>
|
||||
: <><div className="p-results">{data.items.map(item => <Row key={item.doc} item={item} terms={data.terms} />)}</div>
|
||||
<div className="p-pagination" aria-label="Страницы"><span>Страница {data.page} из {data.pages}</span><div className="p-pagination-actions">
|
||||
<button type="button" disabled={data.page <= 1} onClick={() => go({page: String(data.page - 1)})}>Предыдущая</button>
|
||||
<button type="button" disabled={data.page >= data.pages} onClick={() => go({page: String(data.page + 1)})}>Следующая</button>
|
||||
</div></div></>}
|
||||
</section>
|
||||
}
|
||||
|
||||
function paragraphs(text: string, links: PracticeLink[], articles: PracticeArticle[]): ReactNode[] {
|
||||
const byKey = new Map(articles.map(item => [`${item.code}:${item.article}`, item]))
|
||||
const result: ReactNode[] = []
|
||||
let offset = 0
|
||||
for (const line of text.split('\n')) {
|
||||
const start = offset, end = offset + line.length
|
||||
offset = end + 1
|
||||
if (!line.trim()) continue
|
||||
const parts: ReactNode[] = []
|
||||
let cursor = start
|
||||
for (const link of links) {
|
||||
const from = Math.max(link.start, cursor), to = Math.min(link.end, end)
|
||||
if (from >= to) continue
|
||||
if (from > cursor) parts.push(text.slice(cursor, from))
|
||||
const article = byKey.get(`${link.code}:${link.article}`)
|
||||
parts.push(article?.reader
|
||||
? <a key={from} href={docHref(article.reader.id, article.reader.fragment)} title={`Открыть ${article.label}`}>{text.slice(from, to)}</a>
|
||||
: <span key={from} className="p-act-cite" title={article?.label}>{text.slice(from, to)}</span>)
|
||||
cursor = to
|
||||
}
|
||||
parts.push(text.slice(cursor, end))
|
||||
result.push(<p key={start}>{parts}</p>)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function PracticeAct({route}: {route: Route}) {
|
||||
const {data, error, loading} = useApi<PracticeActData>(route.act ? '/practice/act?' + new URLSearchParams({id: route.act}) : null)
|
||||
if (loading) return <section className="p-practice-act"><p className="p-loading" role="status">Открываем акт…</p></section>
|
||||
if (error || !data) return <section className="p-practice-act"><p className="p-notice" role="alert">{error || 'Акт не найден.'}</p></section>
|
||||
const {act} = data
|
||||
return <article className="p-practice-act" aria-labelledby="act-title">
|
||||
<header className="p-document-header"><div>
|
||||
<a className="p-practice-back" href={href({view: 'practice'})}><Icon name="back" />Судебная практика</a>
|
||||
<span className="p-kicker">{[act.category, act.kind].filter(Boolean).join(' · ')}</span>
|
||||
<h1 id="act-title">{data.heading || act.title}</h1>
|
||||
<p className="p-practice-court">{[act.court, act.area && `(${act.area})`].filter(Boolean).join(' ')}</p>
|
||||
</div></header>
|
||||
{act.removed_at && <p className="p-notice" role="status">Источник удалил акт {shortDate(act.removed_at)}{act.removed_code ? ` (${act.removed_code})` : ''}. Показана копия, сохраненная до удаления.</p>}
|
||||
<div className="p-act-layout">
|
||||
<div className="p-act-main">{data.text === null
|
||||
? <p className="p-notice" role="alert">Сохраненный текст не прошел сверку SHA-256 и не показан. Повторите импорт практики.</p>
|
||||
: <div className="p-reading p-act-text">{paragraphs(data.text, data.links, data.articles)}</div>}</div>
|
||||
<aside className="p-act-aside" aria-label="Источник и статьи акта">
|
||||
<section className="p-act-card" aria-labelledby="act-source"><h2 id="act-source">Источник</h2><dl>
|
||||
<div><dt>Адрес</dt><dd><a href={safeURL(act.url)} target="_blank" rel="noreferrer">{act.url.replace('https://', '').replace(/\/$/, '')}</a></dd></div>
|
||||
<div><dt>Загружено</dt><dd>{moment(act.fetched_at)}</dd></div>
|
||||
<div><dt>SHA-256</dt><dd><code className="p-hash">{act.sha256}</code><span className={act.verified ? 'p-chip' : 'p-chip p-chip-bad'}>{act.verified ? 'Хеш совпал' : 'Хеш не совпал'}</span></dd></div>
|
||||
</dl></section>
|
||||
{!!data.areas.length && <section className="p-act-card" aria-labelledby="act-areas"><h2 id="act-areas">Отрасль</h2><ul className="p-act-areas">
|
||||
{data.areas.map(item => <li key={item.id}><a href={href({view: 'practice', area: item.id})}>{item.parent_title ? `${item.parent_title} → ` : ''}{item.title}</a><small>{item.reason}</small></li>)}
|
||||
</ul></section>}
|
||||
<section className="p-act-card" aria-labelledby="act-articles"><h2 id="act-articles">Статьи в акте · {data.articles.length}</h2>
|
||||
{data.articles.length ? <ul>{data.articles.map(item => <li key={item.code + item.article}>
|
||||
{item.reader ? <a href={docHref(item.reader.id, item.reader.fragment)}>{item.label}</a> : <span>{item.label}</span>}
|
||||
<a className="p-act-more" href={href({view: 'practice', code: item.code, article: item.article})}>{actsWord(item.total || 0)} по статье</a>
|
||||
</li>)}</ul> : <p>Ссылок на статьи кодексов не найдено.</p>}
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</article>
|
||||
}
|
||||
|
||||
export function NormPractice({documentId, fragmentId}: {documentId: string; fragmentId: string}) {
|
||||
const applies = documentId.includes(':code:') && fragmentId.includes('_article_')
|
||||
const {data} = useApi<PracticeNorm>(applies ? '/practice/norm?' + new URLSearchParams({id: documentId, fragment: fragmentId}) : null)
|
||||
if (!data?.total || !data.code || !data.article) return null
|
||||
return <a className="p-norm-practice" href={href({view: 'practice', code: data.code, article: data.article})}>
|
||||
<Icon name="document" /><span className="p-norm-practice-text"><strong>Судебная практика по {data.label}</strong><small>{actsWord(data.total)} 2026 года цитируют статью</small></span><Icon name="arrow" />
|
||||
</a>
|
||||
}
|
||||
|
||||
export function PracticeTeaser({status}: {status?: PracticeStatus}) {
|
||||
const acts = status?.acts || 0
|
||||
return <section className="p-practice-teaser" aria-labelledby="practice-teaser-title">
|
||||
<div><p className="p-eyebrow">Судебная практика</p><h2 id="practice-teaser-title">Акты судов 2026 года</h2>
|
||||
<p>{status?.ready && acts ? `${actsWord(acts)} с полным текстом, источником и ссылками на статьи кодексов. Новые акты приходят сами.` : 'Акты появятся после первого импорта из Lynceuz.'}</p></div>
|
||||
<a className="p-button p-primary" href={href({view: 'practice'})}>Открыть практику<Icon name="arrow" /></a>
|
||||
</section>
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import {useState} from 'react'
|
||||
import {docHref, href, kinds, shortDate, useApi, usePoll, type Action, type Bootstrap, type LegalDocument, type Route, type SearchData, type StatusData} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import type {Recent} from './storage'
|
||||
import {ActsCard, LawCard} from './Updates'
|
||||
export {Editions} from './Editions'
|
||||
|
||||
function Empty({title,children}:{title:string;children?:React.ReactNode}) {
|
||||
return <div className="p-empty-scene"><div><h2>{title}</h2><p>{children}</p><a className="p-button" href={href({view:'home'})}>Открыть библиотеку <Icon name="arrow"/></a></div><img src="/assets/pantheon/eunomia-marble.webp" alt="" onError={event => { event.currentTarget.hidden = true }}/></div>
|
||||
}
|
||||
export function Results({route}:{route:Route}) {
|
||||
const {data,error,loading}=useApi<SearchData>(route.q?'/search?'+new URLSearchParams({q:route.q,kind:route.kind||''}):null)
|
||||
const rows=data?.results||[]
|
||||
const pages=Math.max(1,Math.ceil(rows.length/12))
|
||||
const page=Math.min(pages,Math.max(1,Number(route.page)||1))
|
||||
const terms=(route.q||'').trim().split(/\s+/).filter(x=>x.length>1).map(x=>x.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'))
|
||||
const pattern=terms.length?new RegExp('('+terms.join('|')+')','gi'):null
|
||||
return <section className="p-research"><div className="p-page-head"><p className="p-eyebrow">Поиск по текстам</p><h1>{route.q?`«${route.q}»`:'Что найти в библиотеке?'}</h1><p>{route.q?'Статьи и фрагменты из сохраненных документов.':'Введите номер статьи, название или фразу в строке поиска.'}</p></div>
|
||||
<div className="p-results-tools"><span role="status">{loading?'Ищем…':`${data?.total||0} фрагментов`}</span><label className="p-field"><span>Тип документа</span><select value={route.kind||''} onChange={e=>{location.hash=href({...route,kind:e.target.value,page:1})}}><option value="">Все документы</option>{Object.entries(kinds).map(([key,[title]])=><option key={key} value={key}>{title}</option>)}</select></label></div>
|
||||
{error?<p role="alert" className="p-notice">{error}</p>:loading?<p role="status" className="p-loading">Открываем результаты…</p>:!rows.length?<Empty title={route.q?'Совпадений нет':'Начните с поиска'}>Попробуйте точное название или сокращение: например, «статья 395 ГК».</Empty>:<><div className="p-results">{rows.slice((page-1)*12,page*12).map(row=><article className="p-result" key={row.id}><div className="p-result-kind">{kinds[row.kind]?.[0]||'Документ'}</div><h2><a href={docHref(row.resource_id,row.id)}>{row.label||row.title}<Icon name="arrow"/></a></h2><p className="p-result-document">{row.document||row.title}</p><p className="p-result-excerpt">{pattern?row.snippet.split(pattern).map((s,i)=>i%2?<mark key={i}>{s}</mark>:s):row.snippet}</p><div className="p-result-meta"><span>Редакция: {shortDate(row.revision)}</span>{!!row.warnings?.length&&<span className="p-chip p-warning">Требует сверки</span>}</div></article>)}</div>{data && data.total>rows.length&&<p className="p-muted">Показаны первые {rows.length} совпадений. Уточните запрос, чтобы сузить результаты.</p>}{pages>1&&<nav className="p-pager" aria-label="Страницы результатов"><a className="p-button" aria-disabled={page===1} href={page>1?href({...route,page:page-1}):undefined}>Назад</a><span>{page} / {pages}</span><a className="p-button" aria-disabled={page===pages} href={page<pages?href({...route,page:page+1}):undefined}>Далее</a></nav>}</>}
|
||||
</section>
|
||||
}
|
||||
export function RecentView({documents,recent,onClear}:{documents:LegalDocument[];recent:Recent[];onClear:()=>void}) {
|
||||
const rows=recent.flatMap(item=>{const doc=documents.find(d=>d.id===item.id);return doc?[{...item,doc}]:[]})
|
||||
return <section className="p-research"><div className="p-page-head p-head-action"><div><p className="p-eyebrow">Продолжить работу</p><h1>Недавнее</h1><p>Последние открытые документы. История хранится в этом браузере.</p></div>{recent.length>0&&<button className="p-button" onClick={onClear}>Очистить историю</button>}</div>{rows.length?<div className="p-recent-list">{rows.map(row=><a key={row.id} href={docHref(row.id,row.fragment)}><Icon name="document"/><span><strong>{row.doc.subject||row.doc.title}</strong><small>{row.fragment?'Вернуться к открытому фрагменту':'Открыть документ'}</small></span><time dateTime={new Date(row.at).toISOString()}>{shortDate(new Date(row.at).toISOString())}</time><Icon name="arrow"/></a>)}</div>:<Empty title="Здесь продолжится ваша работа">Откройте документ из библиотеки или поиска — он появится здесь вместе с последним прочитанным фрагментом.</Empty>}</section>
|
||||
}
|
||||
const states:Record<string,string>={queued:'В очереди',running:'Обновляется',current:'Проверен',updated:'Обновлен',deferred:'Повтор позже',blocked:'Источник недоступен',failed:'Ошибка обновления',error:'Ошибка обновления'}
|
||||
const plainPath=(text:string)=>text.replace(/\/(?:Users|home)\/[^/\s'"]+/g,'~')
|
||||
const jobReason=(job:{state:string;detail?:string|null})=>{
|
||||
const d=job.detail||''
|
||||
if(/Errno 2|No such file or directory/.test(d))return 'Обновление остановилось: пропал рабочий файл задания. Сохранённый текст на месте. Нажмите «Обновить законодательство», чтобы начать заново.'
|
||||
if(/fetch failed|timed out|timeout|URLError|ConnectionError|HTTP Error|getaddrinfo/i.test(d))return 'Источник не отдал страницу. Сохранённый текст на месте. Проверка повторится сама, а запустить её сейчас можно кнопкой «Обновить законодательство».'
|
||||
if(/source check failed|refresh not activated/.test(d))return 'Источник не прошёл проверку, текст не заменён. Сохранённая редакция на месте, проверка повторится по расписанию.'
|
||||
if(/body too short|content container absent/.test(d))return 'Источник прислал пустую страницу, текст не заменён. Проверка повторится по расписанию. Если ошибка держится, у документа мог смениться адрес.'
|
||||
if(/candidate failed|ValueError/.test(d))return 'Новую редакцию не удалось разобрать, текст не заменён. Проверка повторится по расписанию.'
|
||||
if(/не запустился|превысил/.test(d))return 'Задание не уложилось во время и отложено. Проверка повторится сама, а запустить её сейчас можно кнопкой «Обновить законодательство».'
|
||||
if(/parser_not_verified/.test(d))return 'Разбор этого источника ещё не проверен, поэтому обновление приостановлено. Сохранённый текст доступен.'
|
||||
if(job.state==='current')return 'Источник проверен, текст в библиотеке актуален.'
|
||||
if(job.state==='updated'){const m=/source date (\d{2}\.\d{2}\.\d{4})/.exec(d);return 'Текст обновлён по источнику'+(m?' от '+m[1]:'')+'.'}
|
||||
if(job.state==='queued')return 'Задание ждёт своей очереди.'
|
||||
if(job.state==='running')return 'Задание выполняется.'
|
||||
return 'Задание остановилось с ошибкой, текст не заменён. Нажмите «Обновить законодательство», чтобы повторить.'
|
||||
}
|
||||
export function Service({data,onAction}:{data:Bootstrap;onAction:(kind:Action)=>Promise<void>}) {
|
||||
const [busy,setBusy]=useState(false)
|
||||
const [error,setError]=useState('')
|
||||
const [shown,setShown]=useState('attention')
|
||||
const [page,setPage]=useState(1)
|
||||
const live=usePoll<StatusData>('/status',15000)
|
||||
const status=live.data||data.status
|
||||
const rebuild=async()=>{setBusy(true);setError('');try{await onAction('graph');live.reload()}catch(e){setError((e as Error).message)}finally{setBusy(false)}}
|
||||
const warnings=data.documents.filter(d=>!d.available||d.warnings?.length)
|
||||
const jobs=status.jobs||[]
|
||||
const attention=(s:string)=>['deferred','blocked','failed','error'].includes(s)
|
||||
const counts=(f:(s:string)=>boolean)=>jobs.filter(j=>f(j.state)).length
|
||||
const filtered=shown==='attention'?jobs.filter(j=>attention(j.state)):shown==='failed'?jobs.filter(j=>j.state==='failed'||j.state==='error'):shown==='all'?jobs:jobs.filter(j=>j.state===shown)
|
||||
const pages=Math.max(1,Math.ceil(filtered.length/20))
|
||||
const cur=Math.min(Math.max(1,page),pages)
|
||||
const rows=filtered.slice((cur-1)*20,cur*20)
|
||||
return <section className="p-research"><div className="p-page-head"><p className="p-eyebrow">Состояние базы</p><h1>Библиотека под контролем</h1><p>Сохраненные тексты доступны, пока проверяются источники.</p></div>{(error||live.error)&&<p className="p-notice" role="alert">{error||live.error}</p>}<div className="p-service-grid"><ActsCard onAction={onAction}/><LawCard onAction={onAction}/><section className="p-service-card"><h2>Связи документов</h2><p>{status.graph?.available?`Сборка от ${shortDate(status.graph.built_at)}`:'Сохраненная карта пока недоступна.'}</p><p>Пересоберите карту после изменения текстов, чтобы обновить перекрестные ссылки.</p><button className="p-button" disabled={busy} onClick={rebuild}>{busy?'Запускаем…':'Пересобрать связи'}<Icon name="graph"/></button></section></div><section className="p-jobs"><div className="p-results-tools"><h2>Очередь заданий</h2><label className="p-field"><span>Показать</span><select value={shown} onChange={e=>{setShown(e.target.value);setPage(1)}}><option value="attention">Требуют внимания · {counts(attention)}</option>{['deferred','blocked','failed','queued','running','current','updated'].map(s=><option key={s} value={s}>{states[s]} · {s==='failed'?counts(x=>x==='failed'||x==='error'):counts(x=>x===s)}</option>)}<option value="all">Все задания · {jobs.length}</option></select></label></div>{jobs.length?rows.length?rows.map((job,i)=><div className="p-job" key={job.id+i}><div><strong>{data.documents.find(d=>d.id===job.id)?.title||'Каталог источников'}</strong>{job.detail&&<details><summary>Подробности</summary><p>{jobReason(job)}</p><details><summary>Техническая подробность</summary><pre className="whitespace-pre-wrap break-all"><code>{plainPath(job.detail)}</code></pre></details></details>}</div><span className="p-chip">{states[job.state]||job.state}</span></div>):<p className="p-muted">{shown==='attention'?'Заданий, требующих внимания, нет. Выберите «Все задания», чтобы увидеть всю очередь.':'Заданий в этом состоянии нет.'}</p>:<p className="p-muted">Очередь пуста. Задания появятся после запроса обновления.</p>}{pages>1&&<nav className="p-pager" aria-label="Страницы очереди"><button type="button" className="p-button" disabled={cur<=1} onClick={()=>setPage(cur-1)}>Назад</button><span>{cur} / {pages}</span><button type="button" className="p-button" disabled={cur>=pages} onClick={()=>setPage(cur+1)}>Далее</button></nav>}</section>{warnings.length>0&&<details className="p-source-warnings"><summary>Документы, требующие сверки · {warnings.length}</summary>{warnings.map(d=><a href={docHref(d.id)} key={d.id}>{d.subject||d.title}<Icon name="arrow"/></a>)}</details>}</section>
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {useEffect, useLayoutEffect, useRef, useState} from 'react'
|
||||
import {Command as CommandPrimitive} from 'cmdk'
|
||||
import {Command, CommandItem, CommandList} from '@/components/ui/command'
|
||||
import {api, docHref, href, type SearchData} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
|
||||
export function SearchBox({large = false, initialQuery = ''}: {large?: boolean; initialQuery?: string}) {
|
||||
const [query, setQuery] = useState(initialQuery)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [data, setData] = useState<SearchData | null>(null)
|
||||
const [pending, setPending] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const box = useRef<HTMLDivElement>(null)
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
const selectedByKeyboard = useRef(false)
|
||||
const listId = useRef('')
|
||||
const showList = open && query.trim().length > 0
|
||||
useEffect(() => {setQuery(initialQuery);setOpen(false);selectedByKeyboard.current=false},[initialQuery])
|
||||
const go = (url: string) => {setOpen(false); input.current?.blur(); location.hash = url.slice(1)}
|
||||
const search = () => {if (query.trim()) go(href({view:'search',q:query.trim()}))}
|
||||
useEffect(() => {
|
||||
const key = (event: KeyboardEvent) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') {
|
||||
event.preventDefault(); input.current?.focus(); setOpen(true)
|
||||
}
|
||||
}
|
||||
const outside = (event: PointerEvent) => {if (!box.current?.contains(event.target as Node)) setOpen(false)}
|
||||
document.addEventListener('keydown', key)
|
||||
document.addEventListener('pointerdown', outside)
|
||||
return () => {document.removeEventListener('keydown',key); document.removeEventListener('pointerdown',outside)}
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
if (!query.trim()) {setData(null);setPending(false);setError('');return}
|
||||
const controller = new AbortController()
|
||||
setPending(true); setError('')
|
||||
const timer = setTimeout(() => {
|
||||
api<SearchData>('/search?'+new URLSearchParams({q:query}), {signal:controller.signal})
|
||||
.then(value => {if (!controller.signal.aborted) setData(value)})
|
||||
.catch(e => {if (!controller.signal.aborted) setError(e.message)})
|
||||
.finally(() => {if (!controller.signal.aborted) setPending(false)})
|
||||
}, 200)
|
||||
return () => {controller.abort();clearTimeout(timer)}
|
||||
}, [query])
|
||||
// cmdk hardcodes aria-expanded/aria-controls on Command.Input (spread order beats our props),
|
||||
// so the popup contract is patched on the DOM node directly: no popup, no aria-controls.
|
||||
useLayoutEffect(() => {
|
||||
const el = input.current
|
||||
if (!el) return
|
||||
if (!listId.current) listId.current = el.getAttribute('aria-controls') || ''
|
||||
el.setAttribute('aria-expanded', String(showList))
|
||||
if (showList) el.setAttribute('aria-controls', listId.current)
|
||||
else el.removeAttribute('aria-controls')
|
||||
}, [showList])
|
||||
return <div className={`p-search ${large ? 'p-search-large' : ''}`} ref={box}>
|
||||
<Command shouldFilter={false} label="Поиск по библиотеке">
|
||||
<div className="p-search-field">
|
||||
<Icon name="search" />
|
||||
<CommandPrimitive.Input
|
||||
ref={input} value={query} aria-label="Поиск по библиотеке" enterKeyHint="search"
|
||||
placeholder={large ? 'Статья, номер документа или вопрос права' : 'Поиск по библиотеке'}
|
||||
onValueChange={value => {setQuery(value);setOpen(true);selectedByKeyboard.current=false}}
|
||||
onFocus={() => setOpen(true)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Escape') {setOpen(false);event.stopPropagation()}
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') selectedByKeyboard.current=true
|
||||
if (event.key === 'Enter' && !selectedByKeyboard.current) {event.preventDefault();event.stopPropagation();search()}
|
||||
}}
|
||||
/>
|
||||
{query && <button className="p-search-clear" aria-label="Очистить поиск" onClick={() => {setQuery('');input.current?.focus()}}><Icon name="close" /></button>}
|
||||
{large ? <button className="p-button p-primary" onClick={search}>Найти <Icon name="arrow" /></button> : <kbd aria-label="Command или Control K">⌘ K</kbd>}
|
||||
</div>
|
||||
{showList && <CommandList className="p-suggestions">
|
||||
<CommandItem value="all-results" onSelect={search}><Icon name="search" /><span>Все результаты по запросу «{query}»</span><kbd>↵</kbd></CommandItem>
|
||||
{pending ? <p className="p-search-note" role="status">Ищем в текстах…</p> : error ? <p className="p-search-note" role="alert">{error}</p> : data?.results.length ? data.results.slice(0,5).map(row =>
|
||||
<CommandItem key={row.id} value={row.id} onSelect={() => go(docHref(row.resource_id,row.id))}>
|
||||
<Icon name="document" /><span><strong>{row.label}</strong><small>{row.document || row.title}</small></span><Icon name="arrow" />
|
||||
</CommandItem>
|
||||
) : <p className="p-search-note">Совпадений нет. Уточните название или номер статьи.</p>}
|
||||
</CommandList>}
|
||||
</Command>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import {useState, type ReactNode} from 'react'
|
||||
import {href, usePoll, type Action, type LawFreshness, type LawProgress, type Load, type PracticeProgress} from '@/lib/api'
|
||||
import {Icon} from './Icon'
|
||||
import {plural} from './Practice'
|
||||
import './updates.css'
|
||||
|
||||
// Полосы «Состояния базы». Смысл и тексты - со страницы загрузки СудАкта (eunomia/status/index.html),
|
||||
// одобренной владельцем 02.10.2026: одна полоса от 0 до 100 %, скорость, остаток, «нет свежих данных».
|
||||
const POLL_MS = 5000
|
||||
const STALE_MS = 3 * 60 * 1000
|
||||
const SHOWN = 5 // пунктов недостачи на карточке, остальное - числом
|
||||
const num = (n: number) => n.toLocaleString('ru-RU')
|
||||
const of = (n: number, one: string, many: string) => n % 10 === 1 && n % 100 !== 11 ? one : many // «из 96 101 акта»
|
||||
const minutes = (m: number) => m < 60 ? `${m} мин` : `${Math.floor(m / 60)} ч ${m % 60} мин`
|
||||
const day = (value: string) => new Date(value).toLocaleString('ru-RU', {day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit'})
|
||||
const pace = (p: Load) => `${p.per_min >= 1 ? `${num(Math.round(p.per_min))} в минуту` : `${num(Math.round(p.per_min * 60))} в час`}, осталось около ${minutes(p.eta_min ?? 0)}`
|
||||
const OUTCOMES: [string, string][] = [['current', 'без изменений'], ['updated', 'обновлены'], ['deferred', 'повтор позже'], ['blocked', 'источник недоступен'], ['failed', 'ошибка']]
|
||||
|
||||
// Отметка свежести - первой строкой под заголовком: результат виден до процентов и кнопок.
|
||||
function Mark({ok, label, missing}: {ok: boolean; label: string; missing?: LawFreshness['missing']}) {
|
||||
const rest = (missing?.length ?? 0) - SHOWN
|
||||
return <>
|
||||
<p className={ok ? 'p-load-mark' : 'p-load-mark p-load-incomplete'}>{label}</p>
|
||||
{!!missing?.length && <ul className="p-load-missing" aria-label="Что не готово">
|
||||
{missing.slice(0, SHOWN).map(item => <li key={item.id}>{item.title} — {item.reason}</li>)}
|
||||
{rest > 0 && <li>И еще {num(rest)}</li>}
|
||||
</ul>}
|
||||
</>
|
||||
}
|
||||
|
||||
function Meter({id, title, label, load, count, mark, children}: {id: string; title: string; label: string; load: Load | null; count: string; mark?: ReactNode; children: ReactNode}) {
|
||||
const share = load?.total ? Math.min(load.done / load.total, 1) : 0
|
||||
return <section className="p-service-card p-load" aria-labelledby={id}>
|
||||
<h2 id={id} className="p-load-title">{title}</h2>
|
||||
{mark}
|
||||
<p className="p-load-pct">{load ? `${(share * 100).toLocaleString('ru-RU', {minimumFractionDigits: 1, maximumFractionDigits: 1})} %` : '—'}</p>
|
||||
<progress max={100} value={share * 100} aria-label={label}/>
|
||||
<p className="p-load-count">{count}</p>
|
||||
{children}
|
||||
</section>
|
||||
}
|
||||
|
||||
function Fresh({at, next}: {at?: string; next?: string | null}) {
|
||||
if (!at) return null
|
||||
const moment = new Date(at)
|
||||
if (Date.now() - +moment >= STALE_MS) return <p className="p-load-meta p-load-stale">Нет свежих данных. Последнее обновление: {day(at)}</p>
|
||||
return <p className="p-load-meta">Обновлено в {moment.toLocaleTimeString('ru-RU', {hour: '2-digit', minute: '2-digit'})}{next ? ` · следующий обход ${day(next)}` : ''}</p>
|
||||
}
|
||||
|
||||
// Во время работы кнопка остается в фокусе и в порядке Tab (aria-disabled), но вторую работу не запускает.
|
||||
function Run({idle, label, onRun}: {idle: boolean; label: string; onRun: () => void}) {
|
||||
return <button type="button" className={idle ? 'p-button p-primary' : 'p-button p-load-wait'} aria-disabled={!idle} onClick={idle ? onRun : undefined}><Icon name="updates"/>{label}</button>
|
||||
}
|
||||
|
||||
function useRun(onAction: (kind: Action) => Promise<void>, kind: Action, reload: () => void) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const run = async () => {
|
||||
setBusy(true); setError('')
|
||||
try { await onAction(kind); reload() } catch (e) { setError((e as Error).message) } finally { setBusy(false) }
|
||||
}
|
||||
return {busy, error, run}
|
||||
}
|
||||
|
||||
export function ActsCard({onAction}: {onAction: (kind: Action) => Promise<void>}) {
|
||||
const poll = usePoll<PracticeProgress>('/practice/progress', POLL_MS)
|
||||
const {busy, error, run} = useRun(onAction, 'refresh', poll.reload)
|
||||
const p = poll.data, walk = p?.walk
|
||||
const waiting = walk?.requested_at && !walk.running ? Date.now() - +new Date(walk.requested_at) : null
|
||||
const found = walk?.found
|
||||
const state = !p ? poll.error || 'Считаем скачанное…' : p.error ? p.error
|
||||
: waiting !== null ? (waiting < STALE_MS ? 'Обход начнется в течение минуты' : 'Обход не начался за 3 минуты: задача частей не ответила')
|
||||
: p.per_min > 0 && p.done < p.total ? pace(p)
|
||||
: walk?.running ? (p.per_min > 0 ? 'Идет обход СудАкта, новые акты скачиваются' : 'Идет обход СудАкта, новых актов пока нет')
|
||||
: p.total && p.done >= p.total ? (found ? `Последний обход: ${num(found)} ${plural(found, 'новый акт', 'новых акта', 'новых актов')}` : found === 0 ? 'Последний обход: новых актов нет' : 'Загрузка завершена')
|
||||
: 'Сейчас загрузка стоит'
|
||||
const label = walk?.stopped ? 'Обход остановлен' : busy ? 'Запускаем…' : walk?.running ? 'Обход идет…' : walk?.requested_at ? 'Обход начнется…' : 'Обновить судебные акты'
|
||||
return <Meter id="load-acts" title="Судебные акты" label="Судебные акты: скачано, процентов" load={p}
|
||||
mark={p?.freshness && <Mark ok={p.freshness.fresh} label={p.freshness.label}/>}
|
||||
count={p ? `Скачано ${num(p.done)} из ${num(p.total)} ${of(p.total, 'акта', 'актов')}` : 'Загружаем данные'}>
|
||||
{walk?.stopped
|
||||
? <p className="p-notice" role="alert">Докачка остановлена: {walk.stopped}. Обход не начнется, пока остановку не снимут: удалите parts/state.json.</p>
|
||||
: <p className="p-load-pace">{state}</p>}
|
||||
{error && <p className="p-notice" role="alert">{error}</p>}
|
||||
<Fresh at={p?.updated_at} next={walk?.running || walk?.requested_at ? null : walk?.next_due}/>
|
||||
<div className="p-load-actions">
|
||||
<Run idle={!!p && !busy && !walk?.running && !walk?.requested_at && !walk?.stopped} label={label} onRun={run}/>
|
||||
<a className="p-button" href={href({view: 'practice'})}>Открыть практику<Icon name="arrow"/></a>
|
||||
</div>
|
||||
</Meter>
|
||||
}
|
||||
|
||||
export function LawCard({onAction}: {onAction: (kind: Action) => Promise<void>}) {
|
||||
const poll = usePoll<LawProgress>('/update/progress', POLL_MS)
|
||||
const {busy, error, run} = useRun(onAction, 'update', poll.reload)
|
||||
const p = poll.data, left = p ? p.total - p.done : 0
|
||||
const counts: Record<string, number> = p ? {...p.states, failed: (p.states.failed || 0) + (p.states.error || 0)} : {}
|
||||
const outcome = OUTCOMES.filter(([key]) => counts[key]).map(([key, title]) => `${title}: ${num(counts[key])}`).join(' · ')
|
||||
const state = !p ? poll.error || 'Считаем очередь…' : !p.total ? 'Очередь пуста. Кнопка поставит в нее все документы библиотеки.'
|
||||
: !left ? 'Очередь пройдена'
|
||||
: !p.running ? 'Очередь стоит 10 минут: обработчик не берет задания. Кнопка запустит проверку снова.'
|
||||
: p.per_min > 0 ? pace(p) : 'Проверка идет'
|
||||
return <Meter id="load-law" title="Законодательство" label="Законодательство: готово, процентов" load={p}
|
||||
mark={p?.freshness && <Mark ok={p.freshness.full} label={p.freshness.label} missing={p.freshness.missing}/>}
|
||||
count={p ? `Готово ${num(p.done)} из ${num(p.total)} ${of(p.total, 'документа', 'документов')}` : 'Загружаем данные'}>
|
||||
<p className="p-load-pace">{state}</p>
|
||||
{outcome && <p className="p-load-meta">{outcome.charAt(0).toUpperCase() + outcome.slice(1)}</p>}
|
||||
{error && <p className="p-notice" role="alert">{error}</p>}
|
||||
<Fresh at={p?.updated_at}/>
|
||||
<div className="p-load-actions">
|
||||
<Run idle={!!p && !busy && !p.running} label={busy ? 'Ставим в очередь…' : p?.running ? 'Идет обновление…' : 'Обновить законодательство'} onRun={run}/>
|
||||
</div>
|
||||
</Meter>
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/* The sculpture shares the page's ground and light, without an image card. */
|
||||
.p-hero{min-height:460px;margin:0 -20px 36px;display:flex;align-items:center}
|
||||
.p-hero-copy{width:55%;max-width:640px;padding:40px 20px 64px}
|
||||
.p-hero-figure{inset:-28px -12px -12px;overflow:visible;border-radius:0;background:none;pointer-events:none}
|
||||
.p-hero-figure:after{display:none}
|
||||
.p-hero-figure img{position:absolute;inset:0;width:100%;max-width:none;height:100%;object-fit:contain;object-position:right center;opacity:1;mix-blend-mode:multiply;mask-image:linear-gradient(90deg,transparent,#000 12%,#000 94%,transparent),linear-gradient(0deg,transparent,#000 9%,#000 91%,transparent);mask-composite:intersect}
|
||||
.p-empty-scene{display:flex;min-height:460px;overflow:visible;isolation:isolate}
|
||||
.p-empty-scene>div{width:52%;max-width:560px;z-index:1}
|
||||
.p-empty-scene img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;object-position:right center;opacity:1;z-index:-1;mix-blend-mode:multiply;mask-image:linear-gradient(90deg,transparent,#000 15%,#000 94%,transparent),linear-gradient(0deg,transparent,#000 9%,#000 91%,transparent);mask-composite:intersect}
|
||||
.p-main-graph{max-width:none}
|
||||
.p-main-graph .p-connections{max-width:none;padding:0;margin:0}
|
||||
.p-stone-image{background:none;border-radius:0;overflow:visible}
|
||||
.p-stone-image img{mask-image:linear-gradient(90deg,transparent,#000 7%,#000 93%,transparent),linear-gradient(0deg,transparent,#000 12%,#000 88%,transparent);mask-composite:intersect}
|
||||
@media(min-width:1600px){.p-hero{min-height:530px}.p-hero-copy{padding-bottom:90px}}
|
||||
@media(max-width:1100px){
|
||||
.p-hero{display:block;min-height:0;margin:0 0 24px;padding-bottom:220px}
|
||||
.p-hero-copy{width:100%;max-width:none;padding:16px 0 0}
|
||||
.p-hero h1{font-size:36px}
|
||||
.p-hero-copy>p:not(.p-eyebrow){max-width:40ch}
|
||||
.p-hero-figure{inset:auto -16px -8px;height:240px;overflow:hidden}
|
||||
.p-hero-figure img{inset:0;right:0;left:auto;width:auto;height:100%;object-fit:contain;opacity:1;mask-image:linear-gradient(90deg,transparent,#000 10%,#000 95%,transparent),linear-gradient(0deg,transparent,#000 10%,#000 91%,transparent);mask-composite:intersect}
|
||||
.p-empty-scene{display:block;min-height:0;padding-bottom:260px}
|
||||
.p-empty-scene>div{width:100%;max-width:none}
|
||||
.p-empty-scene img{inset:auto -16px 0 auto;width:auto;height:250px;max-width:none;opacity:1}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.p-structure-toggle{display:flex;align-items:center;gap:8px;min-height:44px;color:var(--muted);font-size:12px}
|
||||
.p-structure-toggle input{accent-color:var(--accent);width:16px;height:16px;flex:none}
|
||||
.p-atomic-relation{padding:20px 0;border-bottom:1px solid var(--line)}
|
||||
.p-atomic-relation>.p-eyebrow{margin-bottom:6px}
|
||||
.p-atomic-relation .p-related-node{border:0;padding:4px 0;align-items:flex-start}
|
||||
.p-atomic-relation .p-related-node small{display:block;font-size:11px;font-weight:400;color:var(--muted);line-height:1.5;margin-top:6px}
|
||||
.p-atomic-relation .p-network-evidence{margin:12px 0}
|
||||
.p-atomic-read{display:block;margin-top:12px;font-size:12px;color:var(--accent);line-height:1.5;text-decoration:underline;text-underline-offset:3px}
|
||||
.p-fragment-graph{display:inline-flex;align-items:center;gap:8px;min-height:44px;margin:-4px 0 16px;color:var(--accent);font:500 13px/1.4 var(--font-ui);text-decoration:none;border-bottom:1px solid var(--line)}
|
||||
.p-fragment-graph:hover{border-color:var(--accent)}
|
||||
.p-fragment-graph:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.p-atomic-relation .p-network-evidence blockquote{max-height:220px;overflow:auto}
|
||||
@media(min-width:1201px){.p-network-layout{grid-template-columns:minmax(0,1fr) 320px}}
|
||||
@@ -0,0 +1,4 @@
|
||||
.p-catalog{max-width:1320px;margin:auto;color:var(--ink)}.p-hero{position:relative;min-height:420px;isolation:isolate;margin-bottom:48px}.p-hero-copy{position:relative;z-index:2;width:61%;padding:44px 32px}.p-eyebrow{margin:0 0 12px;color:var(--accent);font-size:11px;font-weight:600;letter-spacing:.1em;text-transform:uppercase}.p-hero h1{font-size:clamp(36px,3.4vw,50px);font-weight:500;line-height:1.12;letter-spacing:-.035em;margin:0 0 20px}.p-hero-copy>p:not(.p-eyebrow){max-width:44ch;color:var(--muted);font-size:15px;line-height:1.65}.p-hero-figure{position:absolute;inset:0;z-index:0;border-radius:20px;overflow:hidden;background:var(--paper)}.p-hero-figure:after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,var(--paper) 0%,#fffffff2 25%,#ffffff75 48%,transparent 63%)}.p-hero-figure img{width:100%;height:100%;object-fit:cover;object-position:center 37%;mix-blend-mode:multiply}.p-catalog-head{display:flex;justify-content:space-between;align-items:center;gap:20px;margin:0 0 24px}.p-catalog-head h2{margin:0;font-size:26px;font-weight:500}.p-catalog-head .p-eyebrow{margin-bottom:8px}.p-catalog-total{font-size:13px;color:var(--muted);white-space:nowrap}.p-tabs{display:flex;align-items:stretch;gap:16px;overflow:auto;border-bottom:1px solid var(--line);scrollbar-width:thin}.p-tabs a{display:inline-flex;align-items:center;gap:8px;min-height:52px;padding:0 4px;color:var(--muted);font-size:13px;text-decoration:none;white-space:nowrap;border-bottom:2px solid transparent}.p-tabs a[aria-current=page]{color:var(--ink);border-color:var(--accent);font-weight:500}.p-tabs span{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:22px;padding:0 6px;border-radius:5px;background:var(--tint);color:var(--muted);font-size:11px;line-height:22px}.p-tabs a[aria-current=page] span{background:var(--tint);color:var(--accent)}.p-stone-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:32px 24px;padding:24px 0 32px}.p-stone{display:flex;flex-direction:column;min-width:0;color:var(--ink);text-decoration:none;border-radius:12px;transition:transform 180ms}.p-stone:hover{transform:translateY(-2px)}.p-stone-image{aspect-ratio:3/2;overflow:hidden;border-radius:12px;background:var(--paper)}.p-stone-image img{display:block;width:100%;height:100%;object-fit:contain;mix-blend-mode:multiply}.p-stone-face{display:flex;flex-direction:column;flex:1;padding:16px 4px 0}.p-stone-face strong{font-size:17px;font-weight:500;line-height:1.35;min-height:46px}.p-stone-face span{color:var(--muted);font-size:12px;line-height:1.5;margin-top:8px}.p-stone-face small{display:block;color:var(--muted);font-size:11px;line-height:1.55;margin-top:8px}.p-topic-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;padding:24px 0 8px}.p-topic{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;min-height:66px;padding:12px;text-align:left;background:#fff;border:1px solid var(--line);border-radius:10px;color:var(--ink);font-size:12px;line-height:1.4}.p-topic strong{font-weight:500}.p-topic span{color:var(--muted);font-size:11px}.p-topic:hover,.p-topic.is-active{border-color:var(--accent);background:var(--tint)}.p-filterbar{display:flex;gap:16px;align-items:end;padding:24px 0}.p-filterbar label{display:grid;gap:6px;color:var(--muted);font-size:12px}.p-filterbar select{min-height:44px;padding:0 12px;color:var(--ink);background:#fff;border:1px solid var(--line);border-radius:10px;font-size:13px}.p-document-list{border-top:1px solid var(--line)}.p-document-row{display:flex;align-items:center;justify-content:space-between;gap:24px;padding:22px 0;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line)}.p-document-row:hover strong{color:var(--accent)}.p-document-row strong{display:block;font-size:15px;font-weight:500;line-height:1.5}.p-document-row small{display:block;margin-top:8px;color:var(--muted);font-size:12px}.p-row-meta{color:var(--muted);font-size:11px;white-space:nowrap}.p-pagination{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:24px 0;color:var(--muted);font-size:12px}.p-pagination-actions{display:flex;gap:8px}.p-pagination button{min-height:44px;padding:8px 14px;color:var(--ink);background:#fff;border:1px solid var(--line);border-radius:10px;font-size:13px}.p-empty{padding:32px 0;color:var(--muted)}.p-contents{max-width:900px;margin:0 auto;padding:24px 0 48px}.p-contents h1{max-width:30ch;font-size:36px;line-height:1.2}.p-contents-list{margin-top:32px;border-top:1px solid var(--line)}.p-contents-list a{display:grid;grid-template-columns:48px 1fr;align-items:baseline;gap:16px;padding:22px 0;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line)}.p-contents-list a:hover{color:var(--accent)}.p-contents-list strong{font-weight:500}.p-contents-list span{font-size:13px;color:var(--muted)}
|
||||
@media(max-width:1100px){.p-hero-copy{padding:32px 24px;width:65%}.p-hero h1{font-size:40px}.p-hero{min-height:400px}.p-stone-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.p-topic-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.p-tabs{gap:14px}}
|
||||
@media(max-width:767px){.p-hero{min-height:370px;margin-bottom:36px}.p-hero-copy{width:100%;padding:28px 16px}.p-hero h1{font-size:38px}.p-hero-copy>p:not(.p-eyebrow){max-width:31ch}.p-hero-figure img{opacity:.35;object-position:64% center}.p-hero-figure:after{background:linear-gradient(90deg,#ffffffef,#ffffff5a)}.p-catalog-head h2{font-size:23px}.p-catalog-total{font-size:11px}.p-tabs{gap:14px}.p-tabs a{font-size:12px}.p-topic-grid{gap:8px}.p-filterbar{flex-wrap:wrap}.p-document-row{display:block}.p-row-meta{display:block;margin-top:12px}.p-pagination{flex-wrap:wrap}.p-contents h1{font-size:30px}}
|
||||
@media(max-width:500px){.p-stone-grid{grid-template-columns:1fr;gap:28px}.p-stone-face strong{min-height:0}.p-stone-image{aspect-ratio:1.8}.p-stone-image img{object-fit:cover}.p-catalog-head{gap:8px}.p-hero-copy{padding-inline:12px}.p-hero h1{font-size:35px}.p-topic-grid{grid-template-columns:1fr 1fr}}
|
||||
@@ -0,0 +1,55 @@
|
||||
|
||||
.p-main-graph .p-connections{max-width:none;padding:0;color:var(--ink);font-variant-numeric:lining-nums tabular-nums}
|
||||
.p-connections-head{display:flex;justify-content:space-between;align-items:center;gap:24px;margin:0 0 24px}
|
||||
.p-connections-head h1{font-size:40px;font-weight:500;line-height:1.15;margin:0}
|
||||
.p-connections-head p:last-child{color:var(--muted);font-size:13px;max-width:66ch;margin:12px 0 0}
|
||||
.p-connection-actions{display:flex;gap:4px;padding:4px;background:var(--tint);border-radius:12px;flex:none}
|
||||
.p-connection-actions .p-button{background:transparent;border-color:transparent;min-width:46px}
|
||||
.p-connection-actions .p-button[aria-pressed=true]{color:var(--ink);background:white;border-color:var(--line)}
|
||||
.p-connections .p-button-primary{color:white;background:var(--accent);border-color:var(--accent)}
|
||||
.p-connection-filters{display:grid;grid-template-columns:minmax(180px,1fr) minmax(130px,180px) minmax(130px,180px) auto;gap:12px;align-items:end;padding-bottom:20px;border-bottom:1px solid var(--line)}
|
||||
.p-connections .p-field{display:flex;flex-direction:column;align-items:stretch;gap:6px;font-size:12px;min-width:0}
|
||||
.p-connections .p-field input,.p-connections .p-field select{width:100%;min-width:0;min-height:44px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;color:var(--ink);background:#fff;font:inherit}
|
||||
.p-graph-scope{display:flex;gap:16px;font-size:13px;margin-top:14px;color:var(--muted)}
|
||||
.p-graph-scope a,.p-local-graph-link{color:var(--accent)}
|
||||
.p-connection-warnings{font-size:12px;color:var(--muted);margin-top:12px}
|
||||
.p-connection-warnings p{overflow-wrap:anywhere}
|
||||
.p-connection-notice{color:var(--muted);font-size:12px;margin:12px 0;line-height:1.5}
|
||||
.p-network-layout{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:20px;margin-top:20px;align-items:start}
|
||||
.p-network-main{min-width:0}
|
||||
.p-network-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;font-size:12px;color:var(--muted);min-height:44px;flex-wrap:wrap}
|
||||
.p-network-controls{display:flex;gap:6px;flex-wrap:wrap}
|
||||
.p-network-controls .p-button{font-size:12px;min-width:44px;padding:8px 12px;min-height:44px}
|
||||
.p-force-canvas{width:100%;height:calc(100svh - 520px);min-height:400px;overflow:hidden;border:1px solid var(--line);border-radius:12px;background:var(--paper);touch-action:none}
|
||||
.p-force-canvas canvas{display:block;max-width:100%}
|
||||
.p-network-panel{min-width:0;max-height:calc(100svh - 280px);min-height:300px;overflow:auto;padding:20px 0 20px 20px;border-left:1px solid var(--line);background:transparent}
|
||||
.p-network-panel .p-connection-state{padding:24px 8px}
|
||||
.p-connection-state{padding:48px 20px;text-align:center;color:var(--muted);font-size:14px}
|
||||
.p-connection-state h2,.p-connection-state strong{color:var(--ink);font-size:20px;font-weight:500}
|
||||
.p-connection-state .p-icon{margin:0 auto 16px}
|
||||
.p-connection-state p{line-height:1.65}
|
||||
.p-panel-heading{display:flex;align-items:center;justify-content:space-between;gap:10px}
|
||||
.p-panel-heading .p-eyebrow{margin:0}
|
||||
.p-selected-node h2{font-size:22px;font-weight:500;line-height:1.35;margin:12px 0 20px;overflow-wrap:anywhere}
|
||||
.p-selected-node>p{font-size:13px;color:var(--muted)}
|
||||
.p-selected-node h3{font-size:14px;font-weight:500;margin:28px 0 10px}
|
||||
.p-local-graph-link{display:flex;gap:8px;align-items:center;margin-top:16px;font-size:13px;line-height:1.5;text-decoration:none}
|
||||
.p-related-node{display:flex;align-items:center;justify-content:space-between;width:100%;gap:8px;padding:12px 0;border:0;border-bottom:1px solid var(--line);background:none;color:var(--accent);font:inherit;font-size:13px;line-height:1.5;text-align:left;cursor:pointer}
|
||||
.p-network-evidence{font-size:12px;margin-top:16px;line-height:1.6}
|
||||
.p-network-evidence blockquote{margin:10px 0;padding-left:12px;border-left:2px solid var(--red)}
|
||||
.p-network-evidence a{display:block;color:var(--accent);margin-top:8px}
|
||||
.p-network-legend{display:flex;gap:16px;flex-wrap:wrap;margin-top:14px;font-size:11px;color:var(--muted)}
|
||||
.p-network-legend span{display:flex;align-items:center;gap:6px}
|
||||
.p-network-legend i,.p-network-dot{width:8px;height:8px;border-radius:50%;flex:none;display:inline-block}
|
||||
.p-network-list{height:calc(100svh - 520px);min-height:400px;overflow:auto;border-block:1px solid var(--line)}
|
||||
.p-network-list-row{display:flex;align-items:center;gap:12px;width:100%;padding:14px 12px;background:none;border:0;border-bottom:1px solid var(--line);color:var(--ink);text-align:left;font:inherit;font-size:13px;cursor:pointer}
|
||||
.p-network-list-row[aria-pressed=true]{background:var(--tint)}
|
||||
.p-network-list-row>span:nth-child(2){flex:1;min-width:0}
|
||||
.p-network-list-row strong{display:block;font-weight:500;overflow-wrap:anywhere}
|
||||
.p-network-list-row small{display:block;color:var(--muted);font-size:11px;margin-top:6px}
|
||||
.p-connections button:focus-visible,.p-connections a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
@media(max-width:1200px){.p-network-layout{grid-template-columns:minmax(0,1fr) 240px}.p-connection-filters{grid-template-columns:1fr 1fr auto}.p-connection-filters .p-field:first-child{grid-column:1/-1}.p-connections-head{align-items:flex-start}.p-connections-head h1{font-size:34px}}
|
||||
@media(max-width:1000px){.p-network-layout{grid-template-columns:1fr}.p-network-panel{border-left:0;border-top:1px solid var(--line);padding:20px 0;max-height:440px;min-height:0}.p-network-panel:has(.p-connection-state){display:none}.p-force-canvas,.p-network-list{height:55svh;min-height:400px}.p-connections-head{flex-wrap:wrap}}
|
||||
@media(max-width:500px){.p-connection-filters{grid-template-columns:1fr 1fr}.p-connection-filters>.p-button{grid-column:1/-1}.p-connections-head{gap:16px}.p-network-controls{gap:4px}.p-network-controls .p-button{padding:8px 10px}.p-network-legend{gap:10px}.p-force-canvas,.p-network-list{min-height:370px}}
|
||||
|
||||
.p-isolated-toggle{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--muted);min-height:32px;margin-bottom:8px}.p-isolated-toggle input{accent-color:var(--accent);width:16px;height:16px}.p-connections .p-button-primary .p-icon{filter:brightness(0) invert(1)}
|
||||
@@ -0,0 +1,10 @@
|
||||
|
||||
.p-document{min-width:0;color:var(--ink)}
|
||||
.p-document-header{display:flex;align-items:start;justify-content:space-between;gap:24px;padding:12px 0 16px}.p-document-header>div:first-child{min-width:0}.p-document-header h1{font:500 30px/1.2 var(--font-sans);letter-spacing:-.025em;margin:8px 0}.p-kicker{color:var(--accent);font-size:11px;font-weight:500;letter-spacing:.08em;text-transform:uppercase}.p-document-header details{max-width:750px;color:var(--muted);font-size:13px}.p-document-header summary{font-weight:400;color:var(--accent);padding:6px 0;min-height:36px}.p-document-header details p{margin:8px 0}.p-document-header dl{display:flex;gap:24px;flex-wrap:wrap;margin:12px 0}.p-document-header dt{font-size:11px;color:var(--muted)}.p-document-header dd{margin:4px 0;color:var(--ink)}.p-header-actions{display:flex;gap:8px;flex-shrink:0}.p-document-meta{display:flex;align-items:baseline;flex-wrap:wrap;gap:8px 24px;padding:12px 0;border-block:1px solid var(--line);font-size:12px;color:var(--muted)}.p-reader-warning{color:var(--red-ink)}.p-reader-warning summary{padding:0;min-height:24px}.p-reader-warning p{max-width:90ch;margin:8px 0;color:var(--muted)}
|
||||
.p-layout{display:grid;grid-template-columns:200px minmax(0,1fr) 240px;align-items:start;gap:24px;padding:24px 0 48px;max-width:1540px;margin:auto}.p-side,.p-reader-main{min-width:0}.p-toc,.p-context{position:sticky;top:96px}.p-panel-title{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}.p-panel-title h2{font-size:16px;font-weight:500;margin:0}.p-panel-title>span{font-size:11px;color:var(--muted)}.p-toc .p-field{font-size:11px}.p-toc .p-field input{font-size:12px}.p-toc-list{margin-top:16px;max-height:calc(100svh - 260px);overflow:auto;scrollbar-width:thin}.p-toc-list details{border-bottom:1px solid var(--line)}.p-toc-list summary{padding:12px 4px;min-height:44px;font-size:12px;font-weight:500;line-height:1.5}.p-toc-link{display:block;min-height:44px;padding:10px 8px 10px 12px;border-left:2px solid transparent;color:var(--muted);text-decoration:none;font-size:12px;line-height:1.5}.p-toc-link:hover,.p-toc-link.is-active{border-left-color:var(--accent);color:var(--accent);background:var(--tint)}
|
||||
.p-reader-tools{position:sticky;top:72px;z-index:10;background:var(--paper);border-bottom:1px solid var(--line);padding-bottom:12px}.p-toolbar{display:flex;align-items:center;gap:4px;min-height:44px}.p-toolbar .p-button{font-size:13px;min-width:96px}.p-toolbar .p-icon-button{font-size:14px}.p-toolbar .p-icon-button[aria-pressed=true]{background:var(--tint);border-color:var(--accent)}.p-tool-divider{height:22px;width:1px;background:var(--line);margin:0 6px}.p-find-row{display:flex;align-items:center;gap:4px;margin-top:12px}.p-find-row .p-find{flex:1;min-width:0}.p-find-row input{font-size:13px}.p-counter{font-size:11px;color:var(--muted);white-space:nowrap;margin:0 4px}.p-reading{max-width:70ch;margin:24px auto 0;font:20px/1.75 var(--font-serif);overflow-wrap:break-word}.p-fragment{scroll-margin-top:148px;margin-bottom:36px}.p-fragment h2{font:500 24px/1.35 var(--font-sans);letter-spacing:-.02em;margin:0 0 24px}.p-fragment>div{white-space:pre-wrap}.p-anchor{display:block;scroll-margin-top:148px}.p-adjacent{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-top:32px}.p-adjacent .p-button{font-size:12px;padding-inline:12px}.p-whole-text{margin-top:24px}
|
||||
.p-context-intro{font-size:12px;line-height:1.6;color:var(--muted)}.p-related-list{max-height:calc(100svh - 300px);overflow:auto;scrollbar-width:thin}.p-relation{border-top:1px solid var(--line)}.p-relation summary{font-size:12px;font-weight:500;padding:12px 4px;color:var(--ink);line-height:1.6;min-height:44px}.p-relation>div{font-size:12px;line-height:1.6;padding:0 4px 16px}.p-relation p{margin:12px 0}.p-relation a{display:inline-flex;align-items:center;gap:4px;color:var(--accent);font-size:12px;margin-top:8px}.p-relation .p-button{white-space:normal}.p-context-graph{display:inline-flex;align-items:center;min-height:44px;margin-top:12px;color:var(--accent);font-size:12px}.p-mobile-actions{display:none}.p-sheet{overflow:auto;padding:24px;gap:12px}.p-sheet>.p-toc,.p-sheet>.p-context{position:static;margin-top:20px}.p-sheet .p-toc-list,.p-sheet .p-related-list{max-height:none;overflow:visible}
|
||||
.p-reading-focus .p-document-header,.p-reading-focus .p-document-meta,.p-reading-focus .p-layout>.p-side,.p-reading-focus .p-mobile-actions{display:none!important}.p-reading-focus .p-layout{display:block;max-width:840px;padding-top:0}.p-reading-focus .p-reader-main{max-width:840px;margin:auto}
|
||||
@media(min-width:1001px) and (max-width:1439px){.p-layout{grid-template-columns:200px minmax(0,1fr)}.p-layout>.p-side:last-child{display:none}.p-mobile-actions{display:flex;margin-top:16px;gap:8px}.p-mobile-actions>.p-toc-trigger{display:none}}
|
||||
@media(max-width:1000px){.p-layout{display:block;max-width:820px}.p-layout>.p-side{display:none}.p-mobile-actions{display:flex;gap:8px;margin-top:16px}.p-document-header h1{font-size:28px}.p-document-header{flex-wrap:wrap}.p-header-actions .p-button{font-size:12px}.p-reader-tools{top:72px}}
|
||||
@media(max-width:767px){.p-document-header h1{font-size:26px}.p-header-actions{gap:8px}.p-document-header{gap:8px}.p-document-meta{font-size:11px}.p-reading{margin-top:24px}.p-fragment h2{font-size:22px}.p-reader-tools{top:68px}.p-toolbar{gap:0}.p-toolbar .p-button{min-width:84px;padding-inline:10px}.p-toolbar .p-icon-button{width:40px;flex-basis:40px}.p-tool-divider{margin-inline:4px}.p-find-row{flex-wrap:wrap}.p-find-row .p-find{min-width:130px}.p-find-row>.p-icon-button{width:36px;flex-basis:36px}.p-adjacent{display:grid;grid-template-columns:1fr}.p-sheet{max-width:calc(100vw - 32px)}}
|
||||
@@ -0,0 +1,7 @@
|
||||
.p-editions { min-height: 100%; padding: 40px clamp(20px, 5vw, 72px) 72px; color: var(--ink); background: var(--paper); font-variant-numeric: lining-nums tabular-nums; }
|
||||
.p-editions *, .p-editions *::before, .p-editions *::after { box-sizing: border-box; }.p-editions-head { display: flex; align-items: start; justify-content: space-between; gap: 24px; max-width: 920px; margin-bottom: 30px; }.p-editions-head h1 { margin: 6px 0 8px; font: 500 34px/1.16 var(--font-sans, sans-serif); letter-spacing: -.02em; }.p-editions-full-title { max-width: 70ch; margin: 0; color: var(--muted); font-size: 14px; line-height: 1.45; }.p-editions-head p { max-width: 62ch; margin: 0; color: var(--muted); line-height: 1.6; }.p-kicker { color: var(--accent); font-size: 12px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }
|
||||
.p-button { min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 9px 13px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: #fff; cursor: pointer; font: inherit; font-size: 14px; font-weight: 700; text-decoration: none; }.p-button:hover { color: var(--accent); border-color: var(--accent); }.p-button:focus-visible,.p-field input:focus-visible,.p-field select:focus-visible { outline: 3px solid color-mix(in srgb, var(--accent) 35%, transparent); outline-offset: 2px; }.p-button-primary { color: white; border-color: var(--accent); background: var(--accent); }.p-button-quiet { background: transparent; }
|
||||
.p-field { display: grid; gap: 6px; max-width: 620px; color: var(--muted); font-size: 12px; font-weight: 750; }.p-field input,.p-field select { min-height: 44px; width: 100%; padding: 9px 11px; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); background: #fff; font: inherit; font-size: 14px; }.p-edition-picker { max-width: 920px; margin-top: 20px; }.p-edition-choice { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 60px; padding: 14px 0; border-bottom: 1px solid var(--line); color: var(--ink); text-decoration: none; }.p-edition-choice:hover strong { color: var(--accent); }.p-edition-choice span,.p-edition-row span { color: var(--muted); font-size: 13px; }
|
||||
.p-edition-note,.p-status,.p-empty,.p-muted { max-width: 920px; color: var(--muted); line-height: 1.6; }.p-status { padding: 14px 0; }.p-warning { max-width: 920px; padding: 12px 14px; border: 1px solid var(--red); border-radius: 10px; color: var(--red-ink); background: var(--red-tint); }.p-edition-list,.p-compare,.p-diff { max-width: 1120px; margin-top: 30px; }.p-edition-list h2,.p-compare h2,.p-diff h2 { margin: 0 0 14px; font-size: 20px; }.p-edition-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 72px; padding: 14px 0; border-top: 1px solid var(--line); }.p-edition-row > div { display: flex; flex-wrap: wrap; gap: 8px 20px; align-items: baseline; }.p-edition-row strong { min-width: 110px; }.p-edition-row .p-edition-detail { font-size: 12px; }.p-chip { display: inline-flex; padding: 5px 9px; border-radius: 999px; color: var(--accent); background: var(--tint); font-size: 12px; font-weight: 800; }.p-compare { padding-top: 26px; border-top: 1px solid var(--line); }.p-compare p { color: var(--muted); font-size: 14px; }.p-compare-fields { display: grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr) auto; gap: 12px; align-items: end; }.p-diff-change { margin-top: 22px; }.p-diff-change h3 { margin: 0 0 8px; font-size: 16px; }.p-diff-change > div { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 14px; }.p-diff-change section { min-width: 0; padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: #fff; }.p-diff-change h4 { margin: 0 0 8px; color: var(--muted); font-size: 12px; }.p-diff-change pre { max-height: 420px; margin: 0; overflow: auto; white-space: pre-wrap; color: var(--ink); font: 15px/1.55 Georgia, 'Source Serif 4', serif; }
|
||||
@media (max-width: 700px) { .p-editions { padding: 24px 16px 48px; }.p-editions-head { display: block; }.p-editions-head .p-button { margin-top: 18px; }.p-edition-choice,.p-edition-row { align-items: start; flex-direction: column; }.p-compare-fields,.p-diff-change > div { grid-template-columns: 1fr; }.p-compare-fields .p-button { width: 100%; } }
|
||||
@media (prefers-reduced-motion: reduce) { .p-button { transition: none; } }
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2019 The Golos Text Project Authors (https://github.com/googlefonts/golos-text)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2014 The Source Serif 4 Project Authors (https://github.com/adobe-fonts/source-serif)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
@@ -0,0 +1,33 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "./catalog.css";
|
||||
@import "./document.css";
|
||||
@import "./editions.css";
|
||||
@font-face{font-family:'Golos Text';src:url('./fonts/golos.woff2') format('woff2');font-weight:400 900;font-display:swap}
|
||||
@font-face{font-family:'Source Serif 4';src:url('./fonts/source-serif.woff2') format('woff2');font-weight:200 900;font-display:swap}
|
||||
@theme inline{
|
||||
--color-background:var(--background);--color-foreground:var(--ink);--color-card:var(--card);--color-card-foreground:var(--ink);--color-popover:var(--popover);--color-popover-foreground:var(--ink);--color-primary:var(--accent);--color-primary-foreground:#fff;--color-secondary:var(--tint);--color-secondary-foreground:var(--ink);--color-muted:var(--tint);--color-muted-foreground:var(--muted);--color-accent:var(--tint);--color-accent-foreground:var(--accent);--color-destructive:var(--red);--color-border:var(--line);--color-input:var(--line);--color-ring:var(--accent);--color-sidebar:var(--sidebar);--color-sidebar-foreground:var(--ink);--color-sidebar-primary:var(--accent);--color-sidebar-primary-foreground:#fff;--color-sidebar-accent:var(--tint);--color-sidebar-accent-foreground:var(--accent);--color-sidebar-border:var(--line);--color-sidebar-ring:var(--accent);--font-sans:'Golos Text',system-ui,sans-serif;--font-serif:'Source Serif 4',Georgia,serif;--radius-sm:6px;--radius-md:8px;--radius-lg:10px;--radius-xl:20px;
|
||||
}
|
||||
:root{--flag-white:#ffffff;--flag-blue:#0067b9;--flag-red:#e32620;--paper:var(--flag-white);--ink:#17243d;--muted:#586579;--line:#dce4ef;--control-border:#8292a8;--accent:var(--flag-blue);--accent-hover:#005397;--red:var(--flag-red);--red-ink:#ae201c;--red-tint:#fff2f1;--tint:#edf5ff;--graph-canvas:#f6f9ff;--graph-point:#ffffff;--background:var(--paper);--card:#fff;--popover:#fff;--sidebar:#f5f8fd;--radius:10px;--font-serif:'Source Serif 4',Georgia,serif;--font-sans:'Golos Text',system-ui,sans-serif}
|
||||
*{box-sizing:border-box}html{min-width:320px;scroll-behavior:auto}body{margin:0;min-width:320px;background:var(--paper);color:var(--ink);font-family:var(--font-sans);font-size:16px;line-height:1.5;font-variant-numeric:lining-nums tabular-nums}button,input,select,textarea{font:inherit}button,a,input,select{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled,[aria-disabled=true]{opacity:.45;cursor:default;pointer-events:none}a{text-underline-offset:4px}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,[tabindex]:focus-visible{outline:3px solid var(--accent);outline-offset:3px}h1,h2,h3,p{margin-top:0}h1{font-size:40px;line-height:1.15;font-weight:500;letter-spacing:-.035em}h2{font-size:24px;line-height:1.3;font-weight:500;letter-spacing:-.02em}h3{font-size:18px;font-weight:500}img{max-width:100%}mark{background:var(--tint);color:var(--ink);border-radius:2px}summary{cursor:pointer;min-height:44px;padding:10px 0}.p-muted{color:var(--muted)}
|
||||
.p-app{min-height:100svh}.p-icon{width:28px;height:28px;flex:0 0 28px;display:inline-block;vertical-align:middle;background-image:url('/assets/pantheon/icons.webp');background-size:400% 400%;background-position:var(--ix) var(--iy);background-repeat:no-repeat}.p-button,.p-icon-button{display:inline-flex;min-height:44px;align-items:center;justify-content:center;gap:8px;border:1px solid var(--line);background:#fff;border-radius:10px;padding:9px 16px;color:var(--ink);font-size:14px;font-weight:500;line-height:24px;text-decoration:none;white-space:nowrap;transition:background-color 150ms,border-color 150ms}.p-button:hover,.p-icon-button:hover{border-color:var(--accent);background:var(--tint)}.p-primary{background:var(--accent);border-color:var(--accent);color:white}.p-primary:hover{background:var(--accent-hover);color:white;border-color:var(--accent-hover)}.p-primary .p-icon{filter:brightness(0) invert(1)}.p-icon-button{width:44px;flex:0 0 44px;padding:7px;background:transparent;border-color:transparent}.p-chip{display:inline-flex;align-items:center;gap:4px;min-height:26px;padding:2px 8px;border-radius:6px;background:var(--tint);color:var(--accent);font-size:12px;line-height:20px}.p-warning{color:var(--red-ink);background:var(--red-tint)}.p-field{display:flex;flex-direction:column;gap:6px;color:var(--muted);font-size:13px}.p-field input,.p-field select{min-width:0;min-height:44px;border:1px solid var(--line);border-radius:10px;background:#fff;padding:10px 12px;color:var(--ink)}.p-notice{padding:16px 20px;border-left:3px solid var(--red);background:var(--red-tint);color:var(--red-ink);border-radius:0 8px 8px 0}.p-loading{padding:48px 0;color:var(--muted)}
|
||||
.p-skip{position:fixed;top:12px;left:12px;z-index:100;transform:translateY(-200%);padding:12px 20px;background:var(--accent);color:#fff;border-radius:8px}.p-skip:focus{transform:none}.p-surface{flex:1;min-width:0}.p-topbar{position:sticky;top:0;z-index:30;display:flex;align-items:center;gap:16px;min-height:72px;padding:12px 32px;border-bottom:1px solid var(--line);background:color-mix(in srgb,var(--paper) 97%,transparent)}.p-breadcrumb{display:flex;align-items:center;gap:12px;color:var(--muted);font-size:13px;white-space:nowrap}.p-breadcrumb a{color:var(--ink);text-decoration:none}.p-breadcrumb>span:last-child{max-width:220px;overflow:hidden;text-overflow:ellipsis}.p-local-note{display:flex;align-items:center;gap:8px;margin-left:auto;color:var(--muted);font-size:12px}.p-local-note>span,.p-sidebar-note>span{width:6px;height:6px;flex:0 0 6px;border-radius:50%;background:var(--accent)}.p-main{max-width:1384px;padding:32px;margin:auto;outline:none}.p-main-reading{max-width:none;padding:24px 32px}.p-main>.p-catalog{padding:0}.p-monogram{display:grid;place-items:center;width:36px;height:40px;flex:0 0 36px;border:1px solid var(--accent);border-radius:8px;color:var(--accent);font-family:var(--font-serif);font-size:29px;line-height:1;background:var(--paper)}.p-brand{display:flex;align-items:center;gap:12px;min-height:72px;color:var(--ink);text-decoration:none}.p-brand-name{display:flex;flex-direction:column}.p-brand strong{font-size:20px;font-weight:500;letter-spacing:-.04em}.p-brand small{font-size:9px;letter-spacing:.12em;color:var(--muted);margin-top:1px}.p-sidebar [data-sidebar=header]{padding:0 20px;border-bottom:1px solid var(--line)}.p-sidebar [data-sidebar=content]{padding:28px 12px}.p-sidebar [data-sidebar=footer]{padding:12px 12px 20px}.p-sidebar [data-sidebar=menu]{gap:6px}.p-sidebar [data-sidebar=menu-button]{min-height:46px;height:auto;gap:10px;padding:9px 10px;font-size:13px;border-radius:10px;color:var(--muted)}.p-sidebar [data-sidebar=menu-button]:hover,.p-sidebar [data-sidebar=menu-button][data-active=true]{background:var(--tint);color:var(--accent)}.p-sidebar [data-sidebar=menu-button][data-active=true]{font-weight:500}.p-sidebar-note{display:flex;align-items:center;gap:8px;margin:20px 10px 0;font-size:10px;color:var(--muted);white-space:nowrap}.p-sidebar[data-state=collapsed] .p-brand-name,.p-sidebar[data-state=collapsed] .p-sidebar-note{display:none}.p-sidebar[data-state=collapsed] [data-sidebar=header]{padding:0 18px}.p-sidebar[data-state=collapsed] [data-sidebar=content],.p-sidebar[data-state=collapsed] [data-sidebar=footer]{padding-left:12px;padding-right:12px}.p-sidebar[data-state=collapsed] [data-sidebar=menu-button]{width:48px!important;min-width:48px;padding:10px!important;justify-content:center}
|
||||
.p-search{position:relative;width:min(480px,100%);margin-left:auto}.p-search>[cmdk-root]{overflow:visible;background:transparent;color:var(--ink)}.p-search-field{display:flex;align-items:center;gap:8px;height:46px;padding:4px 8px;background:#fff;border:1px solid var(--line);border-radius:10px}.p-search-field:focus-within{border-color:var(--accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--accent) 10%,transparent)}.p-search-field input{min-width:0;flex:1;width:100%;height:40px;border:0;background:transparent;outline:none;font-size:14px}.p-search-field input::placeholder{color:var(--muted)}.p-search-field kbd{flex:0 0 auto;border:1px solid var(--line);border-radius:5px;padding:2px 5px;font:11px/18px var(--font-sans);color:var(--muted)}.p-search-clear{display:grid;place-items:center;min-width:36px;min-height:40px;background:none;border:0}.p-search-large{width:100%;max-width:580px;margin:28px 0 0}.p-search-large .p-search-field{height:64px;padding:7px 8px 7px 16px;box-shadow:0 8px 24px #17243d06}.p-search-large input{height:48px;font-size:15px}.p-search-large .p-primary{height:48px;padding-inline:18px}.p-suggestions{position:absolute;z-index:60;top:calc(100% + 8px);left:0;right:0;max-height:390px!important;border:1px solid var(--line);border-radius:12px;background:#fff;padding:6px;box-shadow:0 16px 40px #17243d20}.p-suggestions [cmdk-item]{display:flex;align-items:center;min-height:52px;gap:8px;padding:10px;border-radius:7px;color:var(--ink);font-size:13px}.p-suggestions [cmdk-item][data-selected=true]{background:var(--tint);color:var(--ink)}.p-suggestions [cmdk-item]>span:not(.p-icon){min-width:0;flex:1}.p-suggestions strong,.p-suggestions small{display:block}.p-suggestions strong{font-weight:500}.p-suggestions small{margin-top:3px;color:var(--muted);font-size:11px;max-height:34px;overflow:hidden}.p-search-note{padding:14px 12px;margin:0;font-size:13px;color:var(--muted)}
|
||||
.p-page-head{margin:12px 0 32px}.p-page-head h1{margin-bottom:12px}.p-page-head p:last-child{color:var(--muted);max-width:65ch;margin-bottom:0}.p-head-action{display:flex;align-items:center;justify-content:space-between;gap:24px}.p-research{max-width:1100px;margin:0 auto;padding:12px 0 40px}.p-results-tools{display:flex;justify-content:space-between;align-items:center;gap:16px;padding-bottom:24px;border-bottom:1px solid var(--line);font-size:14px;color:var(--muted)}.p-results-tools .p-field{flex-direction:row;align-items:center;gap:12px}.p-result{padding:28px 0;border-bottom:1px solid var(--line)}.p-result-kind{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--accent);margin-bottom:10px}.p-result h2{font-size:22px;margin:0 0 8px}.p-result h2 a{display:flex;align-items:center;gap:12px;color:var(--ink);text-decoration:none}.p-result h2 a:hover{color:var(--accent)}.p-result h2 .p-icon{margin-left:auto}.p-result-document{font-size:13px;color:var(--muted);margin-bottom:14px}.p-result-excerpt{max-width:85ch;line-height:1.7;margin-bottom:14px}.p-result-meta{display:flex;align-items:center;gap:16px;font-size:12px;color:var(--muted)}.p-pager{display:flex;justify-content:space-between;align-items:center;gap:16px;padding:28px 0;color:var(--muted);font-size:13px}.p-empty-scene{position:relative;display:grid;grid-template-columns:1fr 1fr;align-items:center;min-height:350px;gap:24px;overflow:hidden}.p-empty-scene>div{position:relative;z-index:1}.p-empty-scene p{color:var(--muted);max-width:45ch}.p-empty-scene img{width:100%;mix-blend-mode:multiply}.p-recent-list>a{display:flex;align-items:center;gap:16px;min-height:100px;padding:20px 0;border-bottom:1px solid var(--line);text-decoration:none;color:var(--ink)}.p-recent-list>a>span:not(.p-icon){flex:1}.p-recent-list strong,.p-recent-list small{display:block}.p-recent-list strong{font-weight:500}.p-recent-list small{font-size:13px;color:var(--muted);margin-top:6px}.p-recent-list time{font-size:12px;color:var(--muted);white-space:nowrap}.p-service-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px;margin:32px 0 48px}.p-service-card{padding:28px;background:white;border:1px solid var(--line);border-radius:16px}.p-service-card h2{font-size:22px;margin-bottom:24px}.p-service-card dl{margin:0 0 20px}.p-service-card dl>div{display:flex;justify-content:space-between;align-items:baseline;gap:16px;padding:9px 0;border-bottom:1px solid #f0f0ec}.p-service-card dt,.p-service-card p{color:var(--muted);font-size:13px}.p-service-card dd{margin:0;font-size:14px;text-align:right}.p-job{display:flex;align-items:start;justify-content:space-between;gap:24px;padding:20px 0;border-bottom:1px solid var(--line)}.p-job strong{font-size:14px;font-weight:500}.p-job details{font-size:12px;color:var(--muted)}.p-job>.p-chip{white-space:nowrap}.p-source-warnings{margin-top:40px}.p-source-warnings>a{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:60px;padding:12px 0;border-top:1px solid var(--line);font-size:14px;color:var(--ink);text-decoration:none}.p-start-state{margin:auto;padding:48px;text-align:center}.p-start-state .p-monogram{margin:0 auto 24px}.p-start-state h1{font-size:30px}.p-toast{position:fixed;z-index:80;left:50%;bottom:24px;max-width:calc(100vw - 32px);padding:12px 20px;background:var(--ink);color:white;border-radius:10px;font-size:14px;transform:translate(-50%,120px);opacity:0;transition:transform 180ms,opacity 180ms;pointer-events:none}.p-toast.is-visible{transform:translate(-50%,0);opacity:1}
|
||||
@media(min-width:768px){.p-topbar>.p-icon-button{display:none}}
|
||||
@media(max-width:1100px){.p-topbar{padding-inline:24px}.p-main{padding:24px}.p-breadcrumb>a,.p-breadcrumb>span[aria-hidden]{display:none}.p-local-note{font-size:11px}}
|
||||
@media(max-width:767px){.p-main,.p-main-reading{padding:20px 16px}.p-topbar{min-height:68px;padding:10px 12px;gap:8px}.p-topbar:has(.p-search) .p-breadcrumb{display:none}.p-topbar .p-search{width:100%}.p-local-note{display:none}.p-breadcrumb{font-size:14px}.p-head-action{align-items:flex-start;flex-direction:column}.p-page-head{margin-top:12px}.p-page-head h1{font-size:32px}.p-service-grid{grid-template-columns:1fr;gap:16px}.p-service-card{padding:20px}.p-results-tools{align-items:flex-start;flex-direction:column}.p-results-tools .p-field{width:100%;justify-content:space-between}.p-empty-scene{grid-template-columns:1fr;min-height:320px}.p-empty-scene img{position:absolute;right:-20%;width:75%;opacity:.22}.p-empty-scene>div{max-width:90%}.p-recent-list time{display:none}.p-job{flex-direction:column;gap:10px}.p-search-large input{font-size:13px}.p-search-large .p-search-field{padding-left:8px;gap:3px}.p-search-large .p-primary{padding:8px 12px}.p-search-large .p-primary .p-icon{display:none}.p-search-large .p-search-field>.p-icon{width:24px;flex-basis:24px;height:24px}.p-result h2{font-size:20px}}
|
||||
@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;animation-duration:.01ms!important;transition-duration:.01ms!important}}
|
||||
/* Shared primitives are owned here; screen styles only supply layout. */
|
||||
.p-field{font-weight:400;max-width:none}.p-field input,.p-field select{font-weight:400}.p-chip{margin:0;font-weight:500;line-height:20px}.p-eyebrow{font-size:11px;font-weight:500;letter-spacing:.09em}.p-connections,.p-editions{padding:12px 0 40px;max-width:1100px;margin:auto}.p-connections h1,.p-editions-head h1{font-weight:500;font-size:40px;line-height:1.15}.p-hero-figure img{position:absolute;right:0;width:auto;max-width:none;height:100%;object-fit:contain;object-position:right center}.p-search-large input::placeholder{font-size:14px}.p-search-clear{min-width:44px;min-height:44px}.p-search-large .p-search-field{gap:8px}.p-search-field input{font-weight:400}.p-reading{font-family:var(--font-serif)}
|
||||
@media(max-width:900px){.p-hero-copy{width:100%;max-width:600px}.p-hero-figure img{opacity:.33}.p-hero-figure:after{background:linear-gradient(90deg,#fffffff0,#ffffff80)}.p-connections h1,.p-editions-head h1{font-size:32px}}
|
||||
@media(max-width:500px){.p-search-large input::placeholder{font-size:12px}.p-search-large .p-search-field{gap:3px}.p-hero-figure img{right:-90px}.p-search-large .p-search-clear{min-width:36px}.p-stone-face span{margin-top:6px}}
|
||||
|
||||
.p-hero-figure img{mask-image:linear-gradient(90deg,transparent,#000 22%)}.p-kicker{font-size:11px;font-weight:500}.p-evidence-route a{font-weight:500}.p-connection-notice{font-size:13px;margin-bottom:12px}.p-evidence-summary{font-size:13px}.p-evidence-summary strong{font-weight:500}
|
||||
|
||||
.p-toolbar .p-icon-button,.p-find-row>.p-icon-button{width:44px;flex-basis:44px;min-height:44px}.p-search-large .p-search-clear{min-width:44px;min-height:44px}.p-toolbar{flex-wrap:wrap}.p-relation summary{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:3;overflow:hidden}.p-relation[open] summary{display:list-item;-webkit-line-clamp:unset}
|
||||
|
||||
.p-stone-face strong{min-height:69px}.p-reading{font-variant-numeric:lining-nums tabular-nums}.p-sidebar[data-mobile=true] .p-brand{padding-right:44px}.p-sidebar[data-mobile=true] [data-sidebar=content]{padding-top:24px}
|
||||
@media(max-width:500px){.p-stone-face strong{min-height:0}}
|
||||
|
||||
.p-icon{clip-path:inset(2px)}.p-sheet .p-panel-title{display:none}.p-relation summary{display:list-item;-webkit-line-clamp:unset}
|
||||
@@ -0,0 +1,79 @@
|
||||
.p-practice .p-page-head p:last-child{max-width:62ch}
|
||||
.p-practice-search{display:flex;gap:12px;align-items:end;margin:0}
|
||||
.p-practice-search .p-field{flex:1}
|
||||
.p-practice-search .p-field input{font-size:16px}
|
||||
.p-filterbar.p-practice-filters{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px 16px;padding:20px 0 24px}
|
||||
.p-practice-filters select{width:100%;min-width:0;text-overflow:ellipsis}
|
||||
.p-practice-articles{display:flex;flex-wrap:wrap;align-items:center;gap:8px 16px;margin:0 0 20px}
|
||||
.p-practice-articles .p-chip a{margin-left:10px;color:var(--accent)}
|
||||
.p-practice-reset{color:var(--muted);font-size:13px}
|
||||
.p-practice-note{padding:20px 24px;border:1px solid var(--line);border-radius:12px;background:var(--sidebar);color:var(--muted);max-width:70ch}
|
||||
.p-practice-row h2 a{font-weight:500}
|
||||
.p-result-excerpt mark{background:#fff1a8;color:inherit;border-radius:2px;padding:0 1px}
|
||||
.p-practice-teaser{display:flex;align-items:center;justify-content:space-between;gap:24px;margin:0 0 48px;padding:28px 32px;border:1px solid var(--line);border-radius:16px;background:var(--sidebar)}
|
||||
.p-practice-teaser h2{margin:0 0 8px;font-size:24px;font-weight:500;letter-spacing:-.01em}
|
||||
.p-practice-teaser p:last-child{margin:0;color:var(--muted);max-width:60ch}
|
||||
.p-practice-teaser .p-button{flex-shrink:0}
|
||||
.p-norm-practice{display:flex;align-items:center;gap:14px;max-width:70ch;margin:20px auto 0;padding:14px 18px;border:1px solid var(--line);border-radius:12px;color:var(--ink);background:#fff;text-decoration:none}
|
||||
.p-norm-practice:hover{border-color:var(--accent)}
|
||||
.p-norm-practice-text{display:grid;gap:2px;flex:1}
|
||||
.p-norm-practice small{color:var(--muted);font-size:13px}
|
||||
.p-practice-act{max-width:1180px;margin:0 auto;padding:4px 0 48px}
|
||||
.p-practice-act .p-kicker{display:block;margin-top:4px}
|
||||
.p-practice-back{display:flex;width:max-content;align-items:center;gap:8px;min-height:44px;color:var(--accent);font-size:13px;text-decoration:none}
|
||||
.p-practice-court{margin:4px 0 0;color:var(--muted);font-size:14px}
|
||||
.p-act-layout{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:48px;align-items:start;padding-top:8px;border-top:1px solid var(--line)}
|
||||
.p-act-text{margin-top:24px}
|
||||
.p-act-text p{margin:0 0 .9em}
|
||||
.p-act-text a{color:var(--accent);text-decoration-thickness:1px}
|
||||
.p-act-cite{border-bottom:1px dotted var(--muted)}
|
||||
.p-act-aside{position:sticky;top:96px;display:grid;gap:16px;padding-top:24px}
|
||||
.p-act-card{padding:20px;border:1px solid var(--line);border-radius:14px;background:#fff}
|
||||
.p-act-card h2{margin:0 0 12px;font-size:16px;font-weight:600}
|
||||
.p-act-card dl{display:grid;gap:12px;margin:0}
|
||||
.p-act-card dt{color:var(--muted);font-size:12px}
|
||||
.p-act-card dd{margin:2px 0 0;font-size:14px;overflow-wrap:anywhere}
|
||||
.p-act-card p{margin:0;color:var(--muted);font-size:14px}
|
||||
.p-hash{display:block;margin-bottom:6px;color:var(--ink);font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all}
|
||||
.p-chip-bad{background:var(--red-tint);color:var(--red-ink)}
|
||||
.p-act-card ul{display:grid;gap:4px;max-height:60vh;margin:0;padding:0;overflow:auto;list-style:none}
|
||||
.p-act-card li{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:0 12px;font-size:14px}
|
||||
.p-act-card li>a,.p-act-card li>span{display:inline-flex;align-items:center;min-height:32px}
|
||||
.p-act-more{color:var(--muted);font-size:12px}
|
||||
@media(max-width:1000px){.p-act-layout{grid-template-columns:minmax(0,1fr);gap:8px}.p-act-aside{position:static}}
|
||||
@media(max-width:767px){.p-practice-search{flex-direction:column;align-items:stretch}.p-filterbar.p-practice-filters{grid-template-columns:1fr 1fr}.p-practice-teaser{flex-direction:column;align-items:stretch;padding:20px;margin-bottom:32px}}
|
||||
.p-practice-divisions{display:grid;gap:10px;margin:0 0 24px}
|
||||
.p-division-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
.p-division-label{min-width:116px;color:var(--muted);font-size:12px;letter-spacing:.06em;text-transform:uppercase}
|
||||
.p-division-row a,.p-area-children a,.p-area-cross a{display:inline-flex;align-items:center;gap:8px;min-height:40px;padding:6px 14px;border:1px solid var(--line);border-radius:999px;color:var(--ink);background:#fff;font-size:14px;text-decoration:none}
|
||||
.p-division-row a span,.p-area-children a span,.p-area-cross a span{color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}
|
||||
.p-division-row a:hover,.p-area-children a:hover,.p-area-cross a:hover{border-color:var(--accent)}
|
||||
.p-division-row a[aria-current],.p-area-children a[aria-current],.p-area-cross a[aria-current]{border-color:var(--accent);background:var(--tint);color:var(--accent)}
|
||||
.p-area{margin:0 0 28px;padding:24px 28px;border:1px solid var(--line);border-radius:16px;background:var(--sidebar)}
|
||||
.p-area-head{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:4px 16px}
|
||||
.p-area-head h2{margin:0;font-size:22px;font-weight:500}
|
||||
.p-area-head p{margin:0;color:var(--muted);font-size:14px}
|
||||
.p-area-graph{display:block;width:100%;max-width:860px;height:auto;margin:8px auto 4px}
|
||||
.p-area-spoke{stroke:var(--line);stroke-width:1.5}
|
||||
.p-area-cross-edge{fill:none;stroke:var(--accent);stroke-opacity:.35}
|
||||
.p-area-cross-edge.is-on{stroke:var(--red);stroke-opacity:.85}
|
||||
.p-area-badge{fill:#fff;stroke:var(--accent);stroke-width:1}
|
||||
.p-area-badge-text{fill:var(--accent);font:600 12px var(--font-sans);text-anchor:middle}
|
||||
.p-area-hub{fill:var(--tint);stroke:var(--accent);stroke-width:2}
|
||||
.p-area-hub.is-on{fill:#d9e9ff}
|
||||
.p-area-hub-text{fill:var(--ink);font:600 15px var(--font-sans);text-anchor:middle}
|
||||
.p-area-hub-count{fill:var(--accent);font:600 14px var(--font-sans);text-anchor:middle}
|
||||
.p-area-node{fill:#fff;stroke:var(--accent);stroke-width:1.5}
|
||||
.p-area-node.is-on{fill:var(--accent)}
|
||||
.p-area-node-count{fill:var(--accent);font:600 13px var(--font-sans);text-anchor:middle;pointer-events:none}
|
||||
.p-area-node.is-on+.p-area-node-count{fill:#fff}
|
||||
.p-area-node-text{fill:var(--ink);font:500 14px var(--font-sans)}
|
||||
.p-area-graph a:hover .p-area-node,.p-area-graph a:hover .p-area-hub{stroke-width:3}
|
||||
.p-area-children{display:flex;flex-wrap:wrap;gap:8px;margin:12px 0 0}
|
||||
.p-area-cross{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:16px 0 0}
|
||||
.p-area-cross h3{flex-basis:100%;margin:0;color:var(--muted);font-size:12px;font-weight:500;letter-spacing:.06em;text-transform:uppercase}
|
||||
.p-area-cross a small{color:var(--muted);font-size:12px}
|
||||
.p-area-note{margin:16px 0 0;color:var(--muted);font-size:13px;max-width:80ch}
|
||||
.p-act-areas li{display:grid;gap:2px;padding:4px 0}
|
||||
.p-act-areas small{color:var(--muted);font-size:12px;line-height:1.45}
|
||||
@media(max-width:767px){.p-area{padding:18px 16px}.p-area-graph{display:none}.p-division-label{flex-basis:100%;min-width:0}}
|
||||
@@ -0,0 +1,14 @@
|
||||
export interface Recent {id: string; fragment?: string; at: number}
|
||||
const key = 'eunomia:recent:v1'
|
||||
export function recentItems(): Recent[] {
|
||||
try {
|
||||
const data: unknown = JSON.parse(localStorage.getItem(key) || '[]')
|
||||
return Array.isArray(data) ? data.filter((x): x is Recent => x && typeof x.id === 'string' && typeof x.at === 'number' && (!x.fragment || typeof x.fragment === 'string')).slice(0, 12) : []
|
||||
} catch { return [] }
|
||||
}
|
||||
export function remember(id: string, fragment?: string) {
|
||||
const items = [{id, fragment, at: Date.now()}, ...recentItems().filter(x => x.id !== id)].slice(0, 12)
|
||||
try {localStorage.setItem(key, JSON.stringify(items))} catch { /* Reading also works when browser storage is unavailable. */ }
|
||||
return items
|
||||
}
|
||||
export function clearRecent() {try {localStorage.removeItem(key)} catch { /* Memory state can still be cleared. */ }}
|
||||
@@ -0,0 +1,12 @@
|
||||
/* Screen palette inspired by Art. Lebedev Studio's Flag of Russia project. */
|
||||
.p-monogram{box-shadow:0 3px 0 var(--red)}
|
||||
.p-hero-figure img,.p-empty-scene img{width:auto;left:auto;right:0}
|
||||
.p-sidebar [data-sidebar=menu-button][data-active=true]{box-shadow:inset 3px 0 0 var(--red)}
|
||||
.p-hero-copy>.p-eyebrow,.p-catalog-head .p-eyebrow{color:var(--red-ink)}
|
||||
.p-tabs a[aria-current=page]{color:var(--accent);border-bottom-color:var(--red)}
|
||||
.p-primary:hover,.p-button-primary:hover,.p-connections .p-button-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:var(--flag-white)}
|
||||
.p-search-field,.p-field input,.p-field select,.p-filterbar select,.p-main-graph .p-connections .p-field input,.p-main-graph .p-connections .p-field select{border-color:var(--control-border)}
|
||||
.p-search-field:focus-within{border-color:var(--accent)}
|
||||
.p-network-legend i,.p-network-dot{border:1px solid var(--accent)}
|
||||
.p-main-graph .p-connection-actions .p-button[aria-pressed=true]{color:var(--accent);box-shadow:inset 0 -2px 0 var(--red)}
|
||||
@media(min-width:1201px){.p-main-graph .p-network-layout{grid-template-columns:minmax(0,1fr) 320px}}
|
||||
@@ -0,0 +1,20 @@
|
||||
/* Полосы «Состояния базы»: пропорции страницы загрузки СудАкта — крупный процент, полоса, строки под ней.
|
||||
Стили идут в сборке раньше pantheon.css, поэтому селекторы на класс сильнее «.p-service-card p». */
|
||||
.p-load{display:flex;flex-direction:column}
|
||||
.p-load .p-load-title{margin-bottom:8px}
|
||||
.p-load .p-load-mark{align-self:flex-start;margin:0 0 12px;padding:2px 10px;border-radius:6px;background:var(--tint);color:var(--accent);font-size:13px;font-weight:600;line-height:22px}
|
||||
.p-load .p-load-incomplete{background:#fff4e5;color:#8a4b00}
|
||||
.p-load .p-load-missing{margin:-4px 0 12px;padding-left:18px;color:var(--muted);font-size:13px;line-height:1.5}
|
||||
.p-load .p-load-pct{margin:0 0 16px;color:var(--ink);font:400 clamp(40px,5vw,56px)/1 var(--font-serif);letter-spacing:-.02em;font-variant-numeric:tabular-nums}
|
||||
.p-load progress{display:block;width:100%;height:12px;border:0;border-radius:6px;overflow:hidden;background:var(--tint);-webkit-appearance:none;appearance:none}
|
||||
.p-load progress::-webkit-progress-bar{background:var(--tint)}
|
||||
.p-load progress::-webkit-progress-value{background:var(--accent);transition:width 240ms ease-out}
|
||||
.p-load progress::-moz-progress-bar{background:var(--accent)}
|
||||
.p-load .p-load-count{margin:16px 0 4px;color:var(--ink);font-size:15px}
|
||||
.p-load .p-load-pace{margin:0 0 4px;font-size:14px}
|
||||
.p-load .p-load-meta{margin:0 0 4px}
|
||||
.p-load .p-load-stale{color:#8a4b00}
|
||||
.p-load .p-notice{margin:12px 0 0;font-size:13px;line-height:1.5}
|
||||
.p-load-actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:auto;padding-top:20px}
|
||||
.p-load-actions .p-load-wait{opacity:1;color:var(--muted);cursor:default}
|
||||
@media (prefers-reduced-motion:reduce){.p-load progress::-webkit-progress-value{transition:none}}
|
||||
@@ -0,0 +1,269 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--font-sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--font-serif: Georgia, "Times New Roman", serif;
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: #ffffff;
|
||||
--foreground: #202824;
|
||||
--card: #ffffff;
|
||||
--card-foreground: #202824;
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: #202824;
|
||||
--primary: #244b40;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #f6f7f8;
|
||||
--secondary-foreground: #47534e;
|
||||
--muted: #f6f7f8;
|
||||
--muted-foreground: #6b756f;
|
||||
--accent: #edf4f0;
|
||||
--accent-foreground: #244b40;
|
||||
--destructive: #a23d35;
|
||||
--border: #dce4df;
|
||||
--input: #dce4df;
|
||||
--ring: #244b40;
|
||||
--sidebar-width: 15rem;
|
||||
--sidebar-width-icon: 3rem;
|
||||
--sidebar: #f6f7f8;
|
||||
--sidebar-foreground: #47534e;
|
||||
--sidebar-primary: #244b40;
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: #edf4f0;
|
||||
--sidebar-accent-foreground: #244b40;
|
||||
--sidebar-border: #dce4df;
|
||||
--sidebar-ring: #244b40;
|
||||
--ease-out: cubic-bezier(.23, 1, .32, 1);
|
||||
--ease-drawer: cubic-bezier(.32, .72, 0, 1);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { min-width: 320px; scroll-behavior: auto; }
|
||||
body { min-width: 320px; margin: 0; color: var(--foreground); background: var(--background); font-family: var(--font-sans); font-size: 16px; line-height: 1.5; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
a { color: var(--primary); text-underline-offset: 3px; }
|
||||
:focus-visible { outline: 3px solid var(--ring); outline-offset: 3px; }
|
||||
.sr-only, .visually-hidden { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0, 0, 0, 0) !important; white-space: nowrap !important; border: 0 !important; }
|
||||
|
||||
.eunomia-shell { min-height: 100vh; background: var(--background); --sidebar-width: 15rem !important; }
|
||||
.eunomia-main { min-width: 0; background: var(--background); }
|
||||
.skip-link { position: fixed; z-index: 100; top: 12px; left: 12px; padding: 12px 20px; color: white; background: var(--primary); border-radius: 8px; transform: translateY(-180%); }
|
||||
.skip-link:focus { transform: none; }
|
||||
.topbar { position: sticky; top: 0; z-index: 20; display: flex; min-height: 76px; align-items: center; gap: 1rem; padding: .75rem clamp(1rem, 4vw, 4rem); background: color-mix(in srgb, var(--background) 97%, transparent); border-bottom: 1px solid var(--border); }
|
||||
.topbar .menu-toggle { display: none; }
|
||||
.breadcrumb { display: flex; min-width: 0; align-items: center; gap: .5rem; color: var(--muted-foreground); font-size: .8125rem; white-space: nowrap; }
|
||||
.breadcrumb > :last-child { overflow: hidden; text-overflow: ellipsis; }
|
||||
.breadcrumb-link { color: var(--secondary-foreground); text-decoration: none; }
|
||||
.global-search { width: min(30rem, 100%); margin-left: auto; }
|
||||
.search-field { display: flex; height: 2.75rem; align-items: center; gap: .5rem; padding: 0 .5rem 0 .75rem; background: var(--secondary); border: 1px solid var(--border); border-radius: var(--radius-lg); }
|
||||
.search-field:focus-within { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent); }
|
||||
.search-field input { min-width: 0; flex: 1; height: 2.5rem; color: var(--foreground); background: transparent; border: 0; outline: 0; }
|
||||
.search-field button { min-height: 2rem; padding: .25rem .75rem; color: var(--primary-foreground); background: var(--primary); border: 0; border-radius: var(--radius-sm); cursor: pointer; font-size: .8125rem; font-weight: 700; }
|
||||
.refresh-button, .menu-toggle { display: grid; width: 2.75rem; height: 2.75rem; flex: 0 0 2.75rem; place-items: center; color: var(--primary); background: var(--background); border: 1px solid var(--border); border-radius: var(--radius-md); cursor: pointer; }
|
||||
|
||||
.content { width: 100%; margin: 0 auto; padding: 3.5rem clamp(1.5rem, 3vw, 3rem) 5.5rem; }
|
||||
.page { width: 100%; max-width: 1280px; margin: 0 auto; }
|
||||
.wide-page { width: 100%; max-width: 1440px; margin: 0 auto; }
|
||||
.page-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem; margin-bottom: 2.125rem; }
|
||||
.page-heading h1, .page-title { margin: 0; color: var(--foreground); font: 400 clamp(2rem, 4vw, 3.125rem)/1.08 var(--font-serif); letter-spacing: -.035em; }
|
||||
.page-heading p { max-width: 62ch; margin: .625rem 0 0; color: var(--muted-foreground); }
|
||||
.heading-actions, .inline-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
|
||||
.button { display: inline-flex; min-height: 2.75rem; align-items: center; justify-content: center; gap: .4375rem; padding: .5625rem .875rem; color: var(--primary); background: var(--background); border: 1px solid var(--border); border-radius: var(--radius-md); cursor: pointer; font-size: .875rem; font-weight: 700; text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), border-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.button:hover { background: var(--accent); border-color: #b6cdc3; }
|
||||
.button:active { transform: scale(.98); }
|
||||
.button.primary { color: var(--primary-foreground); background: var(--primary); border-color: var(--primary); }
|
||||
.button.primary:hover { background: #17382f; border-color: #17382f; }
|
||||
|
||||
.home-intro { display: grid; grid-template-columns: minmax(0, 1fr) 18.75rem; gap: 3rem; min-height: 18.75rem; max-height: 20rem; align-items: center; margin-bottom: 3rem; }
|
||||
.home-intro-copy { min-width: 0; }
|
||||
.home-label { display: block; margin-bottom: 1.25rem; color: var(--primary); font-size: .75rem; font-weight: 800; letter-spacing: .13em; text-transform: uppercase; }
|
||||
.home-intro h1 { margin: 0; font: 400 clamp(3rem, 6vw, 3.75rem)/.98 var(--font-serif); letter-spacing: -.045em; }
|
||||
.home-intro-copy > p { margin: 1.125rem 0 0; color: var(--secondary-foreground); font-size: 1.125rem; }
|
||||
.home-search { display: flex; max-width: 42.5rem; margin-top: 1.875rem; }
|
||||
.home-search input { min-width: 0; height: 3.5rem; flex: 1; padding: 0 1.0625rem; color: var(--foreground); background: var(--background); border: 1px solid var(--border); border-right: 0; border-radius: 10px 0 0 10px; outline: 0; font-size: 1rem; }
|
||||
.home-search input:focus { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent); }
|
||||
.home-search .button { height: 3.5rem; padding-inline: 1.375rem; border-radius: 0 10px 10px 0; }
|
||||
.home-examples { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem .875rem; margin-top: .75rem; color: var(--muted-foreground); font-size: .875rem; }
|
||||
.home-art { display: grid; gap: .5625rem; }
|
||||
.goddess-art { display: block; width: 18.75rem; max-width: 100%; aspect-ratio: 1; object-fit: cover; background: #f5f7f6; border-radius: 20px; }
|
||||
.home-art figcaption { color: var(--muted-foreground); font-size: .75rem; }
|
||||
.collection-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: .625rem; }
|
||||
.collection-link { display: grid; min-width: 0; min-height: 10.625rem; align-content: start; gap: .75rem; padding: 1.125rem; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-xl); text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), border-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.collection-link:hover { background: var(--accent); border-color: #b6cdc3; transform: translateY(-2px); }
|
||||
.collection-icon { display: grid; width: 2.125rem; height: 2.125rem; place-items: center; color: var(--primary); background: var(--accent); border-radius: .5rem; font-weight: 800; }
|
||||
.collection-copy { display: grid; min-width: 0; gap: .3125rem; }
|
||||
.collection-copy strong { font-size: .9375rem; line-height: 1.25; }
|
||||
.collection-copy span { color: var(--muted-foreground); font-size: .8125rem; line-height: 1.35; }
|
||||
.collection-count { color: var(--muted-foreground); font-size: .75rem; }
|
||||
.collection-arrow { align-self: end; color: var(--primary); font-size: 1.125rem; }
|
||||
.home-shelf { margin-top: 3.625rem; }
|
||||
.section-heading { display: flex; align-items: baseline; justify-content: space-between; gap: 1.25rem; margin: 2.125rem 0 1rem; }
|
||||
.section-heading h2 { margin: 0; font: 400 1.6875rem/1.2 var(--font-serif); }
|
||||
.book-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1.5rem; }
|
||||
.book-card { display: flex; min-width: 0; flex-direction: column; overflow: hidden; color: var(--foreground); background: var(--card); border-radius: var(--radius-xl); text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.book-card:hover { background: var(--accent); transform: translateY(-3px); }
|
||||
.book-card-image { display: grid; width: 100%; aspect-ratio: 1; place-items: center; overflow: hidden; background: #f5f7f6; border-radius: var(--radius-xl); }
|
||||
.book-card-image img { display: block; width: 100%; height: 100%; object-fit: contain; mix-blend-mode: multiply; }
|
||||
.book-title { margin: .9375rem 0 0; font-size: 1.125rem; line-height: 1.25; }
|
||||
.book-caption { margin: .375rem 0 0; color: var(--muted-foreground); font-size: .875rem; }
|
||||
.book-open { display: inline-flex; min-height: 2.75rem; align-items: center; gap: .4375rem; margin-top: auto; color: var(--primary); font-size: .875rem; font-weight: 700; }
|
||||
|
||||
.category-tools, .history-controls { display: flex; align-items: end; gap: .75rem; margin-bottom: 2rem; padding: 1.125rem 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
.field { display: grid; min-width: 10.625rem; gap: .375rem; }
|
||||
.field.grow, .field:first-child { flex: 1; }
|
||||
.field > span, .field label { color: var(--muted-foreground); font-size: .8125rem; font-weight: 700; }
|
||||
.field input, .field select { width: 100%; height: 2.75rem; min-width: 0; padding: 0 .75rem; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-md); outline: 0; }
|
||||
.field input:focus, .field select:focus { border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent); }
|
||||
.topic-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem; }
|
||||
.topic-card, .part-card { display: block; padding: 1.125rem; color: var(--foreground); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-lg); text-decoration: none; transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), border-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
.topic-card { min-height: 7.5rem; }.topic-card:hover,.part-card:hover { background: var(--accent); border-color: #b6cdc3; transform: translateY(-2px); }
|
||||
.topic-heading { display: flex; align-items: baseline; justify-content: space-between; gap: .75rem; }.topic-heading h3 { margin: 0; font-size: 1rem; }.topic-count { color: var(--muted-foreground); font-size: .8125rem; font-weight: 700; }.topic-card p { margin: .4375rem 0 0; color: var(--muted-foreground); font-size: .875rem; }
|
||||
.list-heading,.document-details { display: flex; flex-wrap: wrap; gap: .5rem 1.125rem; color: var(--muted-foreground); font-size: .875rem; }.list-heading { justify-content: space-between; margin-bottom: .625rem; }.document-list,.version-list { border-top: 1px solid var(--border); }.document-row { display: flex; min-height: 5.625rem; align-items: center; gap: 1.375rem; padding: 1rem 0; border-bottom: 1px solid var(--border); }.document-main { min-width: 0; flex: 1; }.document-title { display: block; color: var(--primary); font-size: 1rem; font-weight: 750; line-height: 1.35; text-decoration: none; }.document-title:hover { text-decoration: underline; }.document-subject { margin-top: .25rem; color: var(--secondary-foreground); font-size: .875rem; }.document-details { margin-top: .375rem; }.document-meta { display: flex; flex: 0 0 auto; align-items: center; gap: 1.125rem; }.document-date { color: var(--muted-foreground); white-space: nowrap; font-variant-numeric: tabular-nums; }.document-open { display: inline-flex; min-height: 2.75rem; align-items: center; padding: .5rem .8125rem; color: var(--primary); border: 1px solid var(--border); border-radius: var(--radius-md); font-size: .875rem; font-weight: 700; text-decoration: none; }.document-open:hover { background: var(--accent); border-color: #b6cdc3; }
|
||||
.status-tag { padding: .1875rem .5rem; color: var(--success, #2f684d); background: var(--accent); border-radius: .3125rem; font-size: .75rem; font-weight: 700; }.status-tag.warning { color: #80581d; background: #fbf2df; }.muted,.help-note { color: var(--muted-foreground); }.text-link { color: var(--primary); font-size: .875rem; font-weight: 700; }.empty-state { padding: 3.5rem 1.25rem; color: var(--muted-foreground); text-align: center; border: 1px dashed #b8c8c0; border-radius: var(--radius-lg); }.empty-state strong { display: block; margin-bottom: .4375rem; color: var(--foreground); font: 400 1.375rem var(--font-serif); }.notice,.error-state { padding: .875rem 1rem; color: var(--secondary-foreground); background: var(--accent); border: 1px solid #c7d9d0; border-radius: var(--radius-lg); font-size: .875rem; }.notice.warning { color: #80581d; background: #fbf2df; border-color: #e6c98e; }.error-state { color: #a23d35; background: #fff1ef; border-color: #e6b8b1; }.pagination { display: flex; justify-content: center; gap: .5rem; margin-top: 1.75rem; }
|
||||
|
||||
.reader-document-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem; margin-bottom: 1.625rem; }.reader-document-head .eyebrow { margin: 0 0 .625rem; color: var(--primary); font-size: .75rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; }.reader-document-head h1 { max-width: 28ch; margin: 0; color: var(--foreground); font: 400 clamp(1.875rem,4vw,2.875rem)/1.1 var(--font-serif); letter-spacing: -.03em; }.reader-shell { display: grid; grid-template-columns: 15rem minmax(0,1fr); gap: 2rem; align-items: start; }.reader-desktop-panel { min-width: 0; }.reader-desktop-panel:first-child { grid-column: 1; }.reader-desktop-panel:last-child { grid-column: 3; }.reader-toc { position: sticky; top: 6.25rem; min-width: 0; }.reader-center { min-width: 0; grid-column: 2; }.reader-related { position: static; grid-column: auto; }.reader-panel-content > h2,.reader-toc h2 { margin: 0 0 .75rem; font: 400 1.25rem var(--font-serif); }.toc-scroll { max-height: calc(100vh - 15rem); overflow: auto; padding-right: .3125rem; }.toc-link { display: block; width: 100%; padding: .5rem .625rem; color: var(--muted-foreground); border-left: 2px solid transparent; text-decoration: none; font-size: .875rem; text-align: left; }.toc-link:hover,.toc-link.is-active { color: var(--primary); background: var(--accent); border-left-color: var(--primary); }.toc-link[data-level="2"] { padding-left: 1.25rem; }.document-toolbar { position: sticky; top: 4.75rem; z-index: 4; display: flex; align-items: center; gap: .625rem; margin-bottom: 1.25rem; padding: .75rem 0; background: color-mix(in srgb, var(--background) 97%, transparent); border-bottom: 1px solid var(--line-soft, #edf1ef); }.document-toolbar .inline-actions { flex: 1; }.reader-find { display: flex; align-items: end; gap: .5rem; margin-bottom: 1rem; }.reader-find .field { flex: 1; }.reader-find button,.size-controls button { width: 2.75rem; height: 2.75rem; padding: 0; color: var(--primary); background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-md); cursor: pointer; }.size-controls { display: flex; gap: .3125rem; }.reader-meta { display: flex; flex-wrap: wrap; gap: .375rem 1.5rem; padding: .8125rem 0 1.375rem; color: var(--muted-foreground); border-bottom: 1px solid var(--border); font-size: .875rem; }.reading-text { max-width: 72ch; margin-top: 1.875rem; color: var(--foreground); font: 20px/1.8 var(--font-serif); }.text-fragment { margin-bottom: 2.25rem; scroll-margin-top: 9.375rem; }.fragment-heading { margin: 0 0 .75rem; color: var(--foreground); font: 400 1.625rem/1.25 var(--font-serif); }.fragment-body { white-space: pre-wrap; }.point-anchor { scroll-margin-top: 9.375rem; }.reader-panel-toggle { display: none; }.relation-item { margin-bottom: .5625rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-md); }.relation-item summary { min-height: 2.75rem; padding: .625rem .75rem; color: var(--primary); cursor: pointer; font-size: .875rem; font-weight: 700; }.relation-detail { padding: 0 .75rem .8125rem; color: var(--muted-foreground); font-size: .8125rem; line-height: 1.55; }.relation-detail p { margin: 0 0 .5rem; }.contents-list { max-width: 56.25rem; margin-top: 1.5rem; }.contents-list .toc-link { padding: .875rem 1rem; font-size: 1.0625rem; }.contents-list .toc-group { margin: .625rem 0; border: 1px solid var(--border); border-radius: var(--radius-lg); }.contents-list summary { padding: 1rem; cursor: pointer; font: 400 1.125rem var(--font-serif); }.part-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .875rem; }.part-card { min-height: 9.375rem; }.part-number { color: var(--primary); font: 400 2.125rem var(--font-serif); }.part-card h2 { margin: .625rem 0; font: 400 1.375rem var(--font-serif); }
|
||||
.updates-summary { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 1.125rem; }.schedule-details { padding: 1.25rem 0; border-top: 2px solid var(--primary); }.schedule-details h2 { margin: 0 0 1.125rem; font: 400 1.375rem var(--font-serif); }.schedule-details dl { display: grid; grid-template-columns: 1fr auto; gap: .75rem 1.5rem; margin: 0; }.schedule-details dt { color: var(--muted-foreground); }.schedule-details dd { margin: 0; font-weight: 700; }.graph-workspace { display: grid; grid-template-columns: minmax(0,1fr) 18.75rem; min-height: 38.75rem; overflow: hidden; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius-xl); }.graph-stage { min-width: 0; background: #f7faf8; }.graph-mount,.graph-mount svg { min-height: 36.25rem; }.graph-mount { overflow: hidden; background: var(--card); }.graph-mount svg { display: block; width: 100%; height: 36.25rem; }.graph-sidebar { padding: 1.25rem; border-left: 1px solid var(--border); }.graph-node-list { display: grid; max-height: 26.25rem; gap: .1875rem; margin-top: 1.125rem; overflow: auto; }.graph-node-button { min-height: 2.75rem; padding: .5625rem; color: var(--secondary-foreground); background: transparent; border: 0; border-radius: var(--radius-sm); cursor: pointer; text-align: left; }.graph-node-button:hover { color: var(--primary); background: var(--accent); }
|
||||
|
||||
.ui-icon { display: inline-block; width: 1.75rem; height: 1.75rem; flex: 0 0 1.75rem; background: url("/assets/icons.webp") no-repeat var(--icon-x,0%) var(--icon-y,0%); background-size: 400% 400%; }
|
||||
.eunomia-sidebar [data-sidebar="header"] { padding: 1.5rem; }.brand-link { display: flex; align-items: center; gap: .6875rem; color: var(--foreground); text-decoration: none; }.brand-mark { display: grid; width: 2.125rem; height: 2.125rem; place-items: center; color: #fff; background: var(--primary); border-radius: 999px; font: 1.25rem/1 var(--font-serif); }.brand-copy { display: grid; gap: .0625rem; }.brand-copy strong { font: 1.125rem/1.1 var(--font-serif); letter-spacing: -.02em; }.brand-copy small { color: var(--muted-foreground); font-size: .6875rem; }
|
||||
.sidebar-status { display: flex; min-height: 2.75rem; align-items: center; gap: .5rem; padding: .5rem .625rem; color: var(--muted-foreground); font-size: .75rem; }
|
||||
.connection-dot { width: .4375rem; height: .4375rem; flex: 0 0 .4375rem; background: #80581d; border-radius: 999px; }.connection-dot.ready { background: #2f684d; }
|
||||
.sidebar-brand-note { display: block; padding: .375rem .625rem 0; color: var(--muted-foreground); font-size: .6875rem; }
|
||||
.search-launcher { display: flex; width: 22.5rem; min-width: 0; height: 2.75rem; flex: 0 1 22.5rem; align-items: center; gap: .5rem; margin-left: auto; padding: 0 .625rem 0 .75rem; color: var(--muted-foreground); background: #f6f7f8; border: 1px solid var(--border); border-radius: 10px; cursor: pointer; text-align: left; }
|
||||
.search-launcher:hover { color: var(--primary); background: var(--accent); border-color: #b6cdc3; }.search-launcher > span:not(.ui-icon) { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.search-launcher kbd { padding: .125rem .375rem; color: var(--muted-foreground); background: var(--background); border: 1px solid var(--border); border-radius: .25rem; font-size: .6875rem; }
|
||||
.command-status { padding: 1rem; color: var(--muted-foreground); font-size: .875rem; text-align: center; }.command-footer { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: .75rem 1rem; padding: .625rem .75rem; color: var(--muted-foreground); border-top: 1px solid var(--border); font-size: .6875rem; }
|
||||
.command-footer span { white-space: nowrap; }
|
||||
[cmdk-item] strong,[cmdk-item] small { display: block; }[cmdk-item] > span:last-child { display: grid; min-width: 0; gap: .2rem; }[cmdk-item] small { overflow: hidden; color: var(--muted-foreground); font-size: .75rem; text-overflow: ellipsis; white-space: nowrap; }.command-status + [cmdk-group] small { color: var(--muted-foreground); font-size: .75rem; }
|
||||
[data-sidebar="sidebar"] { color: var(--sidebar-foreground); background: var(--sidebar); }
|
||||
[data-sidebar="menu-button"] { min-height: 2.75rem; color: var(--sidebar-foreground); border-radius: var(--radius-md); transition: color 180ms var(--ease-out), background-color 180ms var(--ease-out), transform 120ms var(--ease-out); }
|
||||
[data-sidebar="menu-button"]:hover,[data-sidebar="menu-button"][data-active="true"] { color: var(--sidebar-accent-foreground); background: var(--sidebar-accent); }
|
||||
[data-sidebar="footer"] { color: var(--muted-foreground); }
|
||||
.eunomia-sidebar .brand-copy,.eunomia-sidebar [data-sidebar="group-label"],.eunomia-sidebar [data-sidebar="menu-badge"] { transition: opacity 180ms var(--ease-out); }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar .brand-copy,.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="group-label"],.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-badge"],.group[data-collapsible="icon"] .eunomia-sidebar .sidebar-footer-copy { display: none; }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-button"] { min-height: 2.75rem; justify-content: center; }
|
||||
body.reading-focus .eunomia-shell .group.peer:has(.eunomia-sidebar) { display: none; }
|
||||
body.reading-focus .eunomia-main { margin-left: 0; }
|
||||
.reader-mobile-actions { display: none; }
|
||||
.reader-mobile-overlay { display: none; }
|
||||
|
||||
@media (min-width:1600px) { .reader-shell { grid-template-columns: 15rem minmax(37.5rem,1fr) 17.5rem; gap: 2rem; }.reader-related { grid-column: 3; position: sticky; top: 6.25rem; }.reader-related .reader-panel-toggle { display: none; }.reader-related .reader-panel-content { display: block; } }
|
||||
@media (min-width:761px) and (max-width:1599px) { .reader-related.is-open { position: fixed; z-index: 40; top: 4.75rem; right: 0; bottom: 0; width: min(23.75rem,calc(100vw - 2rem)); padding: 1.5rem; overflow: auto; background: var(--card); border-left: 1px solid var(--border); box-shadow: -1rem 0 2rem #19382c20; animation: drawer-in 220ms var(--ease-drawer); }.reader-related.is-open .reader-panel-content { display: block; }.reader-related.is-open .reader-panel-toggle { display: flex; width: 100%; margin-bottom: .875rem; }.reader-related.is-open .reader-panel-toggle::after { margin-left: auto; content: "×"; font-size: 1.4375rem; } }
|
||||
@keyframes drawer-in { from { opacity: 0; transform: translateX(1.25rem); } to { opacity: 1; transform: none; } }
|
||||
@media (max-width:1100px) { .content { padding-inline: 1.75rem; }.topbar { padding-inline: 1.75rem; }.collection-grid { grid-template-columns: repeat(3,minmax(0,1fr)); }.book-grid { grid-template-columns: repeat(3,minmax(0,1fr)); } }
|
||||
@media (max-width:760px) { .topbar { flex-wrap: wrap; height: auto; min-height: 4.75rem; padding: .75rem 1rem; }.topbar .menu-toggle { display: grid; }.breadcrumb { order: 2; flex: 1; min-width: 0; }.refresh-button { order: 1; }.global-search { order: 3; flex-basis: 100%; width: auto; margin: 0; }.content { padding: 2.25rem 1.125rem 4rem; }.page-heading { display: block; }.heading-actions { margin-top: 1.125rem; }.page-heading h1 { font-size: 2.125rem; }.home-intro { display: block; margin-bottom: 2.875rem; }.home-intro h1 { font-size: 3.125rem; }.home-intro-copy > p { font-size: 1.0625rem; }.home-search { width: 100%; }.home-search input,.home-search .button { height: 3.25rem; }.home-art { margin-top: 1.875rem; }.goddess-art { max-width: none; }.collection-grid,.topic-grid,.updates-summary { grid-template-columns: repeat(2,minmax(0,1fr)); }.collection-grid { gap: .5rem; }.collection-link { min-height: 9.375rem; padding: .875rem; }.book-grid { grid-template-columns: repeat(2,minmax(0,1fr)); gap: 1.125rem .75rem; }.book-title { font-size: 1rem; }.category-tools,.history-controls { display: grid; grid-template-columns: 1fr; align-items: stretch; }.document-row { display: block; padding: 1.0625rem 0; }.document-meta { justify-content: space-between; margin-top: .625rem; }.document-open { width: 100%; margin-top: .4375rem; }.section-heading { align-items: flex-start; flex-direction: column; gap: .375rem; }.part-grid,.diff-grid { grid-template-columns: 1fr; }.reader-document-head { display: block; }.reader-document-head .heading-actions { margin-top: 1rem; }.reader-shell { display: block; }.reader-toc,.reader-related { position: static; margin-bottom: .875rem; }.reader-panel-toggle { display: flex; width: 100%; align-items: center; justify-content: space-between; }.reader-panel-toggle::after { content: "+"; font-size: 1.25rem; }.reader-panel-toggle[aria-expanded="true"]::after { content: "−"; }.reader-panel-content { display: none; padding-top: .75rem; }.reader-panel-content.is-open { display: block; }.toc-scroll { max-height: 18.75rem; padding: 0; }.document-toolbar { position: static; display: block; margin-bottom: 1.125rem; }.document-toolbar .inline-actions { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); }.document-toolbar .inline-actions .button { width: 100%; }.size-controls { margin-top: .5625rem; }.reader-find { display: grid; grid-template-columns: 1fr 2.75rem 2.75rem; }.reader-find .field { grid-column: 1/-1; }.reading-text { font-size: 20px; line-height: 1.8; }.graph-workspace { display: block; }.graph-sidebar { border-top: 1px solid var(--border); border-left: 0; }.graph-mount,.graph-mount svg { min-height: 27.5rem; height: 27.5rem; }.version-item { display: grid; gap: .25rem; } }
|
||||
@media (max-width:430px) { .collection-grid { grid-template-columns: 1fr 1fr; }.collection-link { min-height: 8.875rem; }.home-intro h1 { font-size: 2.875rem; }.book-grid { gap: 1.125rem .625rem; }.book-caption { font-size: .8125rem; } }
|
||||
@media (forced-colors:active) { .button,.collection-link,.topic-card,.part-card,.field input,.field select { border: 1px solid ButtonText; }.brand-mark { border: 1px solid ButtonText; }.status-tag { border: 1px solid currentColor; } }
|
||||
@media (prefers-reduced-motion:reduce) { *,*::before,*::after { scroll-behavior: auto !important; animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; } }
|
||||
|
||||
@media (min-width:761px) {
|
||||
.reader-mobile-actions,.reader-mobile-overlay { display: none; }
|
||||
}
|
||||
@media (max-width:760px) {
|
||||
.reader-mobile-actions { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .5rem; margin-bottom: 1rem; }
|
||||
.reader-mobile-actions .button { width: 100%; }
|
||||
.reader-desktop-panel { display: none; }
|
||||
.reader-mobile-overlay { position: fixed; inset: 0; z-index: 60; display: grid; align-items: end; background: #17382f66; }
|
||||
.reader-mobile-overlay > div { max-height: 86vh; overflow: auto; padding: 1.25rem; background: var(--card); border-top: 1px solid var(--border); border-radius: 1rem 1rem 0 0; box-shadow: 0 -1rem 2rem #19382c20; animation: drawer-up 220ms var(--ease-drawer); }
|
||||
.reader-mobile-overlay .reader-toc,.reader-mobile-overlay .reader-related { display: block; margin: 0 0 1rem; }
|
||||
.reader-mobile-overlay .reader-panel-content { display: block; }
|
||||
.reader-mobile-overlay .toc-scroll { max-height: 45vh; }
|
||||
}
|
||||
@keyframes drawer-up { from { opacity: 0; transform: translateY(1.25rem); } to { opacity: 1; transform: none; } }
|
||||
|
||||
/* shadcn collapsible=icon keeps controls usable at touch size. */
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-button"] { width: 2.75rem !important; min-width: 2.75rem; min-height: 2.75rem; padding: .375rem !important; }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="menu-button"] > span:last-child { display: none; }
|
||||
.group[data-collapsible="icon"] .eunomia-sidebar [data-sidebar="header"] { padding: .5rem; }
|
||||
|
||||
@media (min-width:1101px) and (max-width:1599px) {
|
||||
.reader-shell { grid-template-columns: 15rem minmax(0,1fr); }
|
||||
.reader-desktop-panel:last-child { display: none; }
|
||||
.reader-mobile-actions { display: flex; justify-content: flex-end; margin-bottom: 1rem; }
|
||||
.reader-mobile-actions .button:first-child { display: none; }
|
||||
}
|
||||
@media (max-width:1100px) {
|
||||
.reader-desktop-panel { display: none; }
|
||||
.reader-shell { display: block; }
|
||||
.reader-mobile-actions { display: flex; gap: .5rem; margin-bottom: 1rem; }
|
||||
.reader-mobile-actions .button { flex: 1; }
|
||||
}
|
||||
@media (max-width:760px) {
|
||||
.search-launcher { min-width: 0; flex: 1; margin-left: 0; }
|
||||
.search-launcher > span:not(.ui-icon) { font-size: 0; }.search-launcher > span:not(.ui-icon)::before { content: "Поиск"; font-size: .875rem; }.search-launcher kbd { display: none; }
|
||||
.home-intro { max-height: none; }
|
||||
.reader-document-head h1 { max-width: none; font-size: 2rem; }
|
||||
}
|
||||
|
||||
.reader-mobile-sheet { max-height: 100dvh; overflow-y: auto; }
|
||||
.reader-mobile-sheet .reader-toc,.reader-mobile-sheet .reader-related,.reader-mobile-sheet .reader-panel-content { display: block; position: static; max-height: none; overflow: visible; }
|
||||
.reader-mobile-sheet .toc-scroll { max-height: min(55vh, 34rem); overflow-y: auto; }
|
||||
.reader-mobile-sheet .reader-panel-content > h2 { font-size: 1.375rem; }
|
||||
|
||||
body.reading-focus .reader-desktop-panel { display: none; }
|
||||
body.reading-focus .reader-shell { display: block; }
|
||||
body.reading-focus .reader-center { max-width: 52rem; margin-inline: auto; }
|
||||
body.reading-focus .reader-document-head .inline-actions { display: flex; }
|
||||
|
||||
.graph-scroll { width: 100%; overflow: auto; overscroll-behavior: contain; }
|
||||
.legal-graph { display: block; width: 100%; min-width: 42.5rem; height: auto; }
|
||||
.graph-node-label { color: var(--foreground); font-family: var(--font-sans); line-height: 1.25; }
|
||||
.graph-node-label strong,.graph-node-label small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.graph-node-label strong { font-size: .875rem; font-weight: 750; }.graph-node-label small { margin-top: .25rem; color: var(--muted-foreground); font-size: .6875rem; }
|
||||
.graph-accessible-list { padding: .75rem 1rem; border-top: 1px solid var(--border); }.graph-accessible-list summary { cursor: pointer; color: var(--primary); font-size: .875rem; font-weight: 700; }
|
||||
.diff-columns { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 1px; overflow: hidden; background: var(--border); border: 1px solid var(--border); border-radius: var(--radius-md); }.diff-columns > div { min-width: 0; padding: 1rem; background: var(--card); }.diff-columns h3 { margin: 0 0 .5rem; color: var(--muted-foreground); font-size: .8125rem; }.diff-columns pre { margin: 0; overflow: auto; white-space: pre-wrap; font: .875rem/1.7 var(--font-sans); }
|
||||
@media (max-width:600px) { .diff-columns { grid-template-columns: 1fr; }.legal-graph { min-width: 36rem; } }
|
||||
|
||||
/* The icon is part of the search field, not a separate column. */
|
||||
.home-search { position: relative; }
|
||||
.home-search > .ui-icon { position: absolute; left: .65rem; top: .875rem; pointer-events: none; }
|
||||
.home-search input { padding-left: 2.75rem; }
|
||||
.home-art a { text-decoration: none; }
|
||||
.home-art figcaption { display: flex; align-items: center; gap: .5rem; margin-top: .4rem; }
|
||||
.graph-entry { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-top: 2.5rem; padding: 1.25rem 0; border-top: 1px solid var(--border); border-bottom: 1px solid var(--border); text-decoration: none; }
|
||||
.graph-entry > span { display: inline-flex; align-items: center; gap: .5rem; }
|
||||
.graph-entry:hover { color: var(--primary); background: var(--accent); }
|
||||
.home-page > .help-note { margin-top: 1rem; }
|
||||
.collection-link > .ui-icon:last-child { margin-top: auto; }
|
||||
[data-sidebar="menu-button"] { font-size: .9375rem; }
|
||||
@media(max-width:760px) { .graph-entry { align-items: flex-start; flex-direction: column; } .home-search > .ui-icon { top: .75rem; } }
|
||||
|
||||
.legal-graph { touch-action: none; cursor: grab; user-select: none; }
|
||||
.legal-graph.is-panning { cursor: grabbing; }
|
||||
|
||||
.reader-find button:not([aria-label]) { width: auto; min-width: 4.75rem; padding-inline: .875rem; }
|
||||
.reader-find-count { white-space: nowrap; align-self: center; }
|
||||
@media (min-width: 641px) and (max-width: 1100px) { .reader-document-head { display: block; } .reader-document-head .heading-actions { margin-top: 1rem; } }
|
||||
@@ -0,0 +1,159 @@
|
||||
import {useMemo, useState} from 'react'
|
||||
import {Icon} from '../components/Icon'
|
||||
import {docCount, docHref, href, kinds, normalized, shortDate, useApi, type LegalDocument, type Route} from '../lib/api'
|
||||
|
||||
const CODE_SUFFIXES = ['gk-rf', 'gpk-rf', 'apk-rf', 'sk-rf', 'kas-rf', 'koap-rf', 'nk-rf-gosposhlina', 'tk-rf', 'zhk-rf', 'zk-rf', 'uk-rf', 'upk-rf']
|
||||
const TOPICS = [
|
||||
['civil', 'Гражданское право', 'Договоры, собственность, обязательства', /договор|собственност|обязательств|гражданск.{0,12}кодекс|наслед|сдел[ок]|жилищ|вещн|вред|потребител/i],
|
||||
['process', 'Судебный процесс', 'Иски, доказательства, обжалование', /процесс|производств|судебн.{0,14}решени|подсудност|апелляц|кассац|доказательств|расход|судебн.{0,12}приказ|арбитражн/i],
|
||||
['criminal', 'Уголовное право', 'Преступления и назначение наказания', /уголовн|преступлен|наказани|осужден|приговор|хищени|взяточ|убийств|мошеннич|наркот/i],
|
||||
['admin', 'Административное право', 'Правонарушения и публичные споры', /административн|правонарушени|публичн|государственн.{0,8}служб|избирательн/i],
|
||||
['work', 'Труд и социальные права', 'Работа, пенсии, социальные выплаты', /трудов|работник|работодател|пенси|социальн|заработн|забастов/i],
|
||||
['family', 'Семья и дети', 'Брак, алименты, защита прав детей', /семейн|брачн|алимент|родител|детей|ребенк|усыновл|расторжени.{0,8}брак/i],
|
||||
['business', 'Экономические споры', 'Банкротство, налоги, деятельность компаний', /банкрот|несостоятельн|налог|таможен|экономическ|корпоративн|акционер|предпринимател|конкуренц/i],
|
||||
['other', 'Другие вопросы', 'Документы вне выбранных направлений', null],
|
||||
] as const
|
||||
|
||||
const idSuffix = (doc: LegalDocument) => doc.id.split(':').at(-1) || doc.id
|
||||
const shortName = (doc: LegalDocument) => (doc.subject || doc.title)
|
||||
.replace(/\s+Российской Федерации/g, '')
|
||||
.replace(/\s+от\s+\d{2}\.\d{2}\.\d{4}.*$/, '')
|
||||
.replace(/[«»]/g, '')
|
||||
const exactTitle = (doc: LegalDocument) => doc.subject || doc.title
|
||||
const isCode = (doc: LegalDocument) => doc.kind === 'code' && CODE_SUFFIXES.includes(idSuffix(doc))
|
||||
const kindLabel = (kind: LegalDocument['kind']) => kinds[kind]?.[0] || 'Документы'
|
||||
const titleDate = (doc: LegalDocument) => doc.act_date || doc.effective_date || doc.revision
|
||||
|
||||
function coverageCaption(doc: LegalDocument) {
|
||||
if (!doc.available) return 'Текст пока не загружен'
|
||||
if (doc.coverage?.status === 'partial') return 'Доступна часть текста'
|
||||
if (doc.warnings?.length) return 'Требует сверки'
|
||||
if (idSuffix(doc) === 'gk-rf') return 'Четыре части'
|
||||
if (doc.coverage?.status === 'full') return 'Текст загружен'
|
||||
return 'Полнота требует проверки'
|
||||
}
|
||||
|
||||
export function BookCard({doc}: {doc: LegalDocument}) {
|
||||
const cover = isCode(doc) ? `/assets/books/${idSuffix(doc)}.webp` : null
|
||||
return <a className={`book-card ${cover ? '' : 'book-card-text'}`} href={href({view: 'contents', id: doc.id})} data-title={exactTitle(doc)}>
|
||||
{cover ? <div className="book-card-image"><img src={cover} alt={`Обложка: ${shortName(doc)}`} width="320" height="220" loading="lazy" /></div> : <span className="law-symbol"><Icon name={doc.kind} /></span>}
|
||||
<h2 className="book-title">{shortName(doc)}</h2>
|
||||
<p className="book-caption">{coverageCaption(doc)}</p>
|
||||
<span className="book-open">Открыть <Icon name="arrow" /></span>
|
||||
</a>
|
||||
}
|
||||
|
||||
function CollectionLink({kind, count}: {kind: LegalDocument['kind']; count: number}) {
|
||||
const [label, description] = kinds[kind]
|
||||
return <a className="collection-link" href={href({view: 'category', kind})}>
|
||||
<Icon name={kind} />
|
||||
<span className="collection-copy"><strong>{label}</strong><span>{description}</span></span>
|
||||
<span className="collection-count">{count}</span><Icon name="arrow" />
|
||||
</a>
|
||||
}
|
||||
|
||||
export function Home({docs}: {docs: LegalDocument[]}) {
|
||||
const [query, setQuery] = useState('')
|
||||
const count = (kind: LegalDocument['kind']) => docs.filter(doc => doc.kind === kind).length
|
||||
const shelf = ['gk-rf', 'gpk-rf', 'apk-rf', 'sk-rf'].map(suffix => docs.find(doc => idSuffix(doc) === suffix)).filter(Boolean) as LegalDocument[]
|
||||
return <div className="page home-page">
|
||||
<section className="home-intro">
|
||||
<div className="home-intro-copy">
|
||||
<span className="home-label">Эвномия · Themiz</span>
|
||||
<h1>Библиотека</h1>
|
||||
<p>Нормативные акты и судебная практика</p>
|
||||
<form className="home-search" onSubmit={event => {event.preventDefault(); const q = query.trim(); if (q) window.location.hash = href({view: 'search', q}).slice(1)}}>
|
||||
<label className="sr-only" htmlFor="home-query">Поиск по библиотеке</label>
|
||||
<Icon name="search" /><input id="home-query" type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="Название, статья или фраза" autoComplete="off" />
|
||||
<button className="button primary" type="submit">Найти</button>
|
||||
</form>
|
||||
<div className="home-examples"><span>Например:</span><a href={href({view: 'search', q: 'ст. 131 ГПК'})}>ст. 131 ГПК</a><a href={href({view: 'search', q: 'ст. 395 ГК'})}>ст. 395 ГК</a></div>
|
||||
</div>
|
||||
<figure className="home-art"><a href={href({view: 'contents', id: docs.find(doc => idSuffix(doc) === 'gk-rf')?.id})}><img className="goddess-art" src="/assets/books/gk-rf.webp" alt="Обложка Гражданского кодекса Российской Федерации" width="280" height="280" /><figcaption><span>Гражданский кодекс</span><Icon name="arrow" /></figcaption></a></figure>
|
||||
</section>
|
||||
<div className="section-heading"><h2>Разделы библиотеки</h2><span>{docCount(docs.length)}</span></div>
|
||||
<div className="collection-grid"><CollectionLink kind="code" count={count('code')} /><CollectionLink kind="federal-law" count={count('federal-law')} /><CollectionLink kind="bylaw" count={count('bylaw')} /><CollectionLink kind="plenum" count={count('plenum')} /><CollectionLink kind="review" count={count('review')} /></div>
|
||||
<section className="home-shelf"><div className="section-heading"><h2>Кодексы</h2><a className="text-link" href={href({view: 'category', kind: 'code'})}>Все кодексы <Icon name="arrow" /></a></div><div className="book-grid">{shelf.map(doc => <BookCard key={doc.id} doc={doc} />)}</div></section>
|
||||
<a className="graph-entry" href={href({view: 'graph'})}><strong>Связи статей и разъяснений</strong><span>Открыть граф связей <Icon name="arrow" /></span></a>
|
||||
<p className="help-note">Тексты хранятся на компьютере. Полнота и дата проверки указаны в документе.</p>
|
||||
</div>
|
||||
}
|
||||
|
||||
function matchesTopic(doc: LegalDocument, topic: string) {
|
||||
if (!topic || topic === 'all') return true
|
||||
const text = `${doc.subject || ''} ${doc.title}`
|
||||
if (topic === 'other') return !TOPICS.some(item => item[3] && item[3].test(text))
|
||||
return TOPICS.find(item => item[0] === topic)?.[3]?.test(text) || false
|
||||
}
|
||||
|
||||
function identity(doc: LegalDocument) {
|
||||
const text = [doc.act_date, doc.number, doc.title].filter(Boolean).join(' ')
|
||||
const match = text.match(/\b(\d{2})\.(\d{2})\.(\d{4})\b/)
|
||||
const key = match ? `${match[3]}-${match[2]}-${match[1]}` : ''
|
||||
return {date: match ? `${match[1]}.${match[2]}.${match[3]}` : null, key, year: match?.[3] || '', number: doc.number || ''}
|
||||
}
|
||||
|
||||
function DocumentRow({doc}: {doc: LegalDocument}) {
|
||||
const meta = identity(doc)
|
||||
const warning = !doc.available ? 'Текст пока не загружен' : doc.coverage?.status === 'partial' ? 'Неполный текст' : doc.warnings?.length ? 'Нужна сверка' : ''
|
||||
return <article className="document-row" data-act-date={meta.key}>
|
||||
<div className="document-main"><a className="document-title" href={docHref(doc.id)}>{exactTitle(doc)}</a><div className="document-details"><span>{kindLabel(doc.kind)}{meta.number ? ` № ${meta.number}` : ''}</span><span>Редакция: {shortDate(doc.revision)}</span>{warning && <span className="status-tag warning">{warning}</span>}</div></div>
|
||||
<div className="document-meta"><span className="document-date">{meta.date ? <time dateTime={meta.key}>{meta.date}</time> : 'Дата не указана'}</span><a className="document-open" href={docHref(doc.id)} aria-label={`Читать: ${exactTitle(doc)}`}>Читать <Icon name="arrow" /></a></div>
|
||||
</article>
|
||||
}
|
||||
|
||||
function Pagination({page, total, route}: {page: number; total: number; route: Route}) {
|
||||
const pages = Math.max(1, Math.ceil(total / 12))
|
||||
if (pages <= 1) return null
|
||||
return <nav className="pagination" aria-label="Страницы документов"><a className={`button quiet ${page === 1 ? 'is-disabled' : ''}`} aria-disabled={page === 1 || undefined} href={page === 1 ? undefined : href({...route, page: page - 1})}>Назад</a><span>Страница {page} из {pages}</span><a className={`button quiet ${page === pages ? 'is-disabled' : ''}`} aria-disabled={page === pages || undefined} href={page === pages ? undefined : href({...route, page: page + 1})}>Далее</a></nav>
|
||||
}
|
||||
|
||||
function YearGroups({docs}: {docs: LegalDocument[]}) {
|
||||
const groups = new Map<string, LegalDocument[]>()
|
||||
docs.forEach(doc => {const year = identity(doc).year || 'Дата не указана'; groups.set(year, [...(groups.get(year) || []), doc])})
|
||||
return <>{[...groups].map(([year, rows]) => <section className="year-group" key={year}><h2>{year}{/^\d/.test(year) ? ' год' : ''}</h2><div className="document-list">{rows.map(doc => <DocumentRow key={doc.id} doc={doc} />)}</div></section>)}</>
|
||||
}
|
||||
|
||||
export function Category({docs, route}: {docs: LegalDocument[]; route: Route}) {
|
||||
const kind = route.kind && route.kind in kinds ? route.kind as LegalDocument['kind'] : 'code'
|
||||
const all = docs.filter(doc => doc.kind === kind)
|
||||
const isBooks = kind === 'code' || kind === 'federal-law'
|
||||
const query = normalized(route.q)
|
||||
const books = all.filter(doc => normalized(`${doc.title} ${doc.subject || ''}`).includes(query))
|
||||
const hasTopics = ['plenum', 'review', 'bylaw'].includes(kind)
|
||||
const showTopics = hasTopics && !route.topic && !route.q && !route.year
|
||||
const years = [...new Set(all.map(doc => identity(doc).year).filter(Boolean))].sort()
|
||||
const sort = route.sort === 'new' ? 'new' : 'old'
|
||||
const filtered = all.filter(doc => matchesTopic(doc, route.topic || 'all') && (!route.year || identity(doc).year === route.year) && (!query || normalized(`${doc.title} ${doc.subject || ''} ${doc.number || ''} ${identity(doc).date || ''}`).includes(query))).sort((a, b) => {
|
||||
const aa = identity(a), bb = identity(b)
|
||||
if (!aa.key) return bb.key ? 1 : a.title.localeCompare(b.title, 'ru')
|
||||
if (!bb.key) return -1
|
||||
return (sort === 'new' ? -1 : 1) * aa.key.localeCompare(bb.key) || aa.number.localeCompare(bb.number, 'ru', {numeric: true})
|
||||
})
|
||||
const page = Math.min(Math.max(1, Number(route.page) || 1), Math.max(1, Math.ceil(filtered.length / 12)))
|
||||
if (isBooks) return <div className="page book-library"><div className="page-heading"><div><h1>{kindLabel(kind)}</h1><p>{kind === 'code' ? 'Откройте кодекс и выберите нужную статью.' : 'Законы по отдельным вопросам.'}</p></div></div><form id="book-filter" className="book-filter category-tools" onSubmit={event => {event.preventDefault(); const form = new FormData(event.currentTarget); window.location.hash = href({view: 'category', kind, q: String(form.get('q') || '')}).slice(1)}}><label className="field grow"><span>Найти {kind === 'code' ? 'кодекс' : 'закон'}</span><input name="q" type="search" defaultValue={route.q || ''} placeholder="Название или сокращение" /></label><button className="button primary" type="submit">Найти</button></form><div className="book-grid">{books.map(doc => <BookCard key={doc.id} doc={doc} />)}</div>{!books.length && <p className="empty-state"><strong>Ничего не найдено</strong><span>Попробуйте другое название или сокращение.</span></p>}</div>
|
||||
const topic = TOPICS.find(item => item[0] === route.topic)
|
||||
return <div className="page"><div className="page-heading"><div><h1>{topic?.[1] || kindLabel(kind)}</h1><p>{showTopics ? 'Выберите направление или найдите документ по названию, номеру и дате.' : `${docCount(filtered.length)} · Дата акта и редакция показаны отдельно.`}</p></div></div><form className="category-tools" onSubmit={event => {event.preventDefault(); const form = new FormData(event.currentTarget); const value = (name: string) => String(form.get(name) || ''); window.location.hash = href({view: 'category', kind, topic: value('topic'), q: value('q'), year: value('year'), sort: value('sort')}).slice(1)}}><label className="field grow"><span>Поиск в разделе</span><input name="q" type="search" defaultValue={route.q || ''} placeholder="Название, номер или дата" /></label>{hasTopics && <label className="field"><span>Направление</span><select name="topic" defaultValue={route.topic || ''}><option value="">Любое направление</option>{TOPICS.map(item => <option key={item[0]} value={item[0]}>{item[1]}</option>)}</select></label>}<label className="field"><span>Год акта</span><select name="year" defaultValue={route.year || ''}><option value="">Все годы</option>{years.map(year => <option key={year} value={year}>{year}</option>)}</select></label><label className="field"><span>По дате акта</span><select name="sort" defaultValue={sort}><option value="old">Сначала ранние</option><option value="new">Сначала новые</option></select></label><button className="button primary" type="submit">Найти</button></form>{showTopics ? <><div className="section-heading"><h2>По направлениям</h2><a className="text-link" href={href({view: 'category', kind, topic: 'all'})}>Все {docCount(all.length)} <Icon name="arrow" /></a></div><div className="topic-grid">{TOPICS.map(item => <a className="topic-card" key={item[0]} href={href({view: 'category', kind, topic: item[0]})}><div className="topic-heading"><h3>{item[1]}</h3><span className="topic-count">{all.filter(doc => matchesTopic(doc, item[0])).length}</span></div><p>{item[2]}</p></a>)}</div><p className="help-note">Направления определены по названиям документов. Один документ может относиться к нескольким направлениям.</p></> : <><div className="list-heading"><span>{docCount(filtered.length)}</span><span>{sort === 'new' ? 'От поздних дат к ранним' : 'От ранних дат к поздним'}</span></div>{filtered.length ? <YearGroups docs={filtered.slice((page - 1) * 12, page * 12)} /> : <p className="empty-state"><strong>Документы не найдены</strong><span>Попробуйте другое направление, год или название.</span></p>}<Pagination page={page} total={filtered.length} route={route} /></>}</div>
|
||||
}
|
||||
|
||||
function tocRows(rows: Array<{id: string; label: string; kind?: string}>, id: string, query: string) {
|
||||
const filtered = rows.filter(row => !query || normalized(row.label).includes(normalized(query)))
|
||||
return <div className="contents-list">{filtered.map(row => /^Глава\s/i.test(row.label) ? <details className="toc-group" key={row.id} open={Boolean(query)}><summary>{row.label}</summary><a className="toc-link" href={docHref(id, row.id)}>{row.label}</a></details> : <a className="toc-link" key={row.id} href={docHref(id, row.id)} data-level={row.kind === 'article' || row.kind === 'point' ? '2' : '1'}>{row.label}</a>)}</div>
|
||||
}
|
||||
|
||||
export function Contents({docs, route}: {docs: LegalDocument[]; route: Route}) {
|
||||
const doc = docs.find(item => item.id === route.id || item.id === route.doc)
|
||||
const id = doc?.id || route.id || route.doc || ''
|
||||
const {data, error, loading} = useApi<{toc: Array<{id: string; label: string; kind?: string}>}>(id ? `/reader?${new URLSearchParams({id})}` : null)
|
||||
const [query, setQuery] = useState('')
|
||||
const toc = data?.toc || []
|
||||
const parts = useMemo(() => toc.filter(row => /^Часть\s+(первая|вторая|третья|четвертая|четвёртая)/i.test(row.label)), [toc])
|
||||
if (!doc) return <div className="page"><p className="empty-state"><strong>Документ не найден</strong><span>Откройте библиотеку.</span></p></div>
|
||||
if (loading) return <div className="page"><h1>{shortName(doc)}</h1><p className="help-note">Открываем оглавление…</p></div>
|
||||
if (error) return <div className="page"><h1>{shortName(doc)}</h1><p className="empty-state"><strong>Оглавление пока недоступно</strong><span>{error}</span></p></div>
|
||||
const partStart = route.part ? toc.findIndex(row => row.id === route.part) : -1
|
||||
const nextPart = partStart >= 0 ? toc.findIndex((row, index) => index > partStart && parts.some(part => part.id === row.id)) : -1
|
||||
const rows = partStart >= 0 ? toc.slice(partStart, nextPart < 0 ? toc.length : nextPart) : toc
|
||||
const choosePart = parts.length > 1 && !route.part
|
||||
return <div className="page contents-page"><div className="page-heading"><div><h1>{shortName(doc)}</h1><p>{exactTitle(doc)}</p></div></div>{choosePart ? <><p className="contents-intro">Выберите часть кодекса</p><div className="part-grid">{parts.slice(0, 4).map((part, index) => <a className="part-card" key={part.id} href={href({view: 'contents', id: doc.id, part: part.id})}><span className="part-number">{['I', 'II', 'III', 'IV'][index]}</span><h2>{part.label}</h2><span>Разделы и статьи <Icon name="arrow" /></span></a>)}</div></> : <><div className="section-heading"><h2>{rows[0]?.label?.startsWith('Часть ') ? rows[0].label : 'Оглавление'}</h2><a className="button quiet" href={docHref(doc.id, rows[0]?.id)}>Читать с начала</a></div>{parts.length > 1 && <a className="text-link" href={href({view: 'contents', id: doc.id})}>← Все части кодекса</a>}<label className="field"><span>Статья, пункт или слово в заголовке</span><input type="search" value={query} onChange={event => setQuery(event.target.value)} placeholder="Например, 395" /></label>{tocRows(rows, doc.id, query)}</>}</div>
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import {useCallback, useEffect, useMemo, useRef, useState, type ReactNode} from 'react'
|
||||
import {api, docHref, href, normalized, safeURL, shortDate, useApi, type Anchor, type Fragment, type GraphEdge, type ReaderData, type RelatedData, type Route} from '../lib/api'
|
||||
import {Icon} from '../components/Icon'
|
||||
import {Sheet, SheetContent, SheetDescription, SheetTitle} from '../components/ui/sheet'
|
||||
|
||||
type DocumentData = ReaderData & {fragments?: Fragment[]; body?: string}
|
||||
type ReaderProps = {route: Route; onNotify: (message: string) => void; onUpdate: (id: string) => Promise<void>}
|
||||
|
||||
const emptyDocument: Fragment[] = []
|
||||
|
||||
function labelKind(kind: string) {
|
||||
return ({code: 'Кодекс', 'federal-law': 'Федеральный закон', bylaw: 'Подзаконный акт', plenum: 'Пленум', review: 'Обзор практики'} as Record<string, string>)[kind] || 'Правовой документ'
|
||||
}
|
||||
|
||||
function renderAnchoredText(text: string, anchors: Anchor[] = [], query = ''): ReactNode[] {
|
||||
const sorted = anchors.filter(anchor => Number.isFinite(anchor.offset) && anchor.offset >= 0).slice().sort((a, b) => a.offset - b.offset)
|
||||
const chunks: ReactNode[] = []
|
||||
let cursor = 0
|
||||
const addText = (value: string, key: string) => {
|
||||
if (!value) return
|
||||
if (!query) { chunks.push(<span key={key}>{value}</span>); return }
|
||||
const parts = value.split(new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'ig'))
|
||||
chunks.push(...parts.map((part, index) => part.toLocaleLowerCase('ru') === query.toLocaleLowerCase('ru') ? <mark key={`${key}-mark-${index}`}>{part}</mark> : <span key={`${key}-${index}`}>{part}</span>))
|
||||
}
|
||||
sorted.forEach((anchor, index) => {
|
||||
const offset = Math.min(text.length, Math.max(cursor, anchor.offset))
|
||||
addText(text.slice(cursor, offset), `text-${index}`)
|
||||
chunks.push(<span id={anchor.id} key={`anchor-${anchor.id}`} className="reader-anchor" aria-hidden="true" />)
|
||||
cursor = offset
|
||||
})
|
||||
addText(text.slice(cursor), 'text-tail')
|
||||
return chunks
|
||||
}
|
||||
|
||||
function fragmentText(fragment: Fragment, query = '') {
|
||||
return <div className="fragment-body">{renderAnchoredText(String(fragment.text || ''), fragment.anchors, query)}</div>
|
||||
}
|
||||
|
||||
function isHeadingDuplicated(fragment: Fragment) {
|
||||
const firstLine = String(fragment.text || '').split(/\r?\n/, 1)[0].replace(/^\s*#+\s*/, '').trim()
|
||||
return firstLine && normalized(firstLine) === normalized(fragment.label)
|
||||
}
|
||||
|
||||
function Toc({items, documentId, activeId, filter, onFilter, onSelect}: {items: Fragment[]; documentId: string; activeId: string; filter: string; onFilter: (value: string) => void; onSelect: (id: string) => void}) {
|
||||
const rows = useMemo(() => items.filter(item => !filter || normalized(`${item.label} ${item.text || ''}`).includes(normalized(filter))), [items, filter])
|
||||
const chapters = rows.filter(item => !['article', 'point', 'paragraph'].includes(item.kind))
|
||||
const chapterIds = new Set(chapters.map(item => item.id))
|
||||
const chapterRows = useMemo(() => chapters.map((chapter, index) => {
|
||||
const start = items.indexOf(chapter)
|
||||
const nextStart = index + 1 < chapters.length ? items.indexOf(chapters[index + 1]) : Infinity
|
||||
const children = rows.filter(item => item.id !== chapter.id && !chapterIds.has(item.id) && items.indexOf(item) > start && items.indexOf(item) < nextStart)
|
||||
return {chapter, children}
|
||||
}), [chapters, chapterIds, items, rows])
|
||||
return <aside className="reader-toc" aria-label="Оглавление">
|
||||
<div className="reader-panel-content">
|
||||
<div className="section-heading"><h2>Оглавление</h2><span className="muted">{rows.length} разделов</span></div>
|
||||
<label className="field"><span>Статья или пункт</span><input type="search" value={filter} onChange={event => onFilter(event.target.value)} placeholder="Например, 395" /></label>
|
||||
<div className="toc-scroll">
|
||||
{chapterRows.map(({chapter, children}) => <details key={chapter.id} open={Boolean(filter) || activeId === chapter.id || children.some(item => item.id === activeId)} className="toc-group">
|
||||
<summary>{chapter.label}</summary>
|
||||
<a aria-label={`Читать раздел ${chapter.label}`} className={activeId === chapter.id ? 'toc-link is-active' : 'toc-link'} href={docHref(documentId, chapter.id)} onClick={() => onSelect(chapter.id)}>Читать раздел</a>
|
||||
{children.map(item => <a key={item.id} className={activeId === item.id ? 'toc-link is-active' : 'toc-link'} href={docHref(documentId, item.id)} onClick={() => onSelect(item.id)}>{item.label}</a>)}
|
||||
</details>)}
|
||||
{!chapters.length && rows.map(item => <a key={item.id} className={activeId === item.id ? 'toc-link is-active' : 'toc-link'} href={docHref(documentId, item.id)} onClick={() => onSelect(item.id)}>{item.label}</a>)}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
|
||||
function Related({edges, loading, documentId, fragmentId, nodeId}: {edges: GraphEdge[]; loading: boolean; documentId: string; fragmentId: string; nodeId?: string}) {
|
||||
return <aside className="reader-related" aria-label="Связанные материалы">
|
||||
<div className="reader-panel-content"><h2>Связанные материалы</h2><p className="muted">{fragmentId ? 'К выбранной статье или пункту' : 'К документу целиком'}</p>
|
||||
{loading && <p className="help-note" role="status">Загружаем связи…</p>}
|
||||
{!loading && !edges.length && <p className="help-note">Подтвержденных связей пока нет. Текст можно читать.</p>}
|
||||
<div className="related-list">{edges.slice(0, 30).map((edge, index) => {
|
||||
const source = edge.source_node
|
||||
const target = edge.target_node
|
||||
const other = (nodeId && source?.id === nodeId ? target : nodeId && target?.id === nodeId ? source : undefined) || (source?.resource_id === documentId ? target : source)
|
||||
if (!other) return null
|
||||
return <details key={`${edge.source}-${edge.target}-${index}`} className="relation-item"><summary>{other.label || 'Связанный фрагмент'} · {other.document_title || ''}</summary><div className="relation-detail"><span className="status-tag">{edge.relation === 'references' ? 'Прямая ссылка' : edge.relation === 'thematic' ? 'Тематическая связь' : 'Связь из графа'}</span><p>{edge.evidence?.excerpt || 'Доказательство связи не предоставлено.'}</p><p>Редакция: {shortDate(edge.evidence?.revision)}</p>{edge.evidence?.source_url && <a className="text-link" href={safeURL(edge.evidence.source_url)} target="_blank" rel="noopener noreferrer">Источник связи ↗</a>}<a className="button quiet" href={docHref(other.resource_id, other.reader_id)}>{other.reader_id ? 'Открыть фрагмент' : 'Открыть документ'} →</a></div></details>
|
||||
})}</div>
|
||||
<a className="text-link" href={href({view: 'graph', ...(nodeId ? {node_id: nodeId} : {resource_id: documentId})})}>Показать на карте связей →</a>
|
||||
</div>
|
||||
</aside>
|
||||
}
|
||||
|
||||
export default function Reader({route, onNotify, onUpdate}: ReaderProps) {
|
||||
const documentId = route.doc || route.id || ''
|
||||
const fragmentId = route.fragment || ''
|
||||
const readerPath = documentId ? `/reader?${new URLSearchParams({id: documentId, ...(fragmentId ? {fragment: fragmentId} : {})})}` : null
|
||||
const reader = useApi<ReaderData>(readerPath)
|
||||
const [allFragments, setAllFragments] = useState<Fragment[]>([])
|
||||
const [wholeLoading, setWholeLoading] = useState(false)
|
||||
const [wholeError, setWholeError] = useState('')
|
||||
const [tocFilter, setTocFilter] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [fontSize, setFontSize] = useState(20)
|
||||
const [focusMode, setFocusMode] = useState(false)
|
||||
const [mobilePanel, setMobilePanel] = useState<'toc' | 'related' | null>(null)
|
||||
const [matchIndex, setMatchIndex] = useState(-1)
|
||||
const [matchCount, setMatchCount] = useState(0)
|
||||
const [related, setRelated] = useState<RelatedData>({related: []})
|
||||
const [relatedLoading, setRelatedLoading] = useState(false)
|
||||
const findRef = useRef<HTMLInputElement>(null)
|
||||
const requestRef = useRef(0)
|
||||
const wholeControllerRef = useRef<AbortController | null>(null)
|
||||
const wholeGenerationRef = useRef(0)
|
||||
const legalDocument = reader.data?.document
|
||||
const toc = reader.data?.toc || emptyDocument
|
||||
const fragments = allFragments.length ? allFragments : reader.data?.fragment ? [reader.data.fragment] : emptyDocument
|
||||
const activeId = reader.data?.selected_id || fragmentId || fragments[0]?.id || ''
|
||||
|
||||
useEffect(() => { document.body.classList.toggle('reading-focus', focusMode); return () => document.body.classList.remove('reading-focus') }, [focusMode])
|
||||
useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && focusMode) setFocusMode(false) }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey) }, [focusMode])
|
||||
useEffect(() => { setAllFragments([]); setQuery(''); setSearchQuery(''); setWholeError(''); wholeGenerationRef.current += 1; wholeControllerRef.current?.abort(); wholeControllerRef.current = null }, [documentId, fragmentId])
|
||||
useEffect(() => () => { wholeGenerationRef.current += 1; wholeControllerRef.current?.abort() }, [])
|
||||
|
||||
const loadWhole = useCallback(async () => {
|
||||
if (!documentId || wholeLoading || allFragments.length) return allFragments
|
||||
wholeControllerRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
wholeControllerRef.current = controller
|
||||
const generation = ++wholeGenerationRef.current
|
||||
setWholeLoading(true); setWholeError('')
|
||||
try {
|
||||
const data = await api<{fragments?: Fragment[]; body?: string}>(`/document?${new URLSearchParams({id: documentId})}`, {signal: controller.signal})
|
||||
if (controller.signal.aborted || generation !== wholeGenerationRef.current) return []
|
||||
const next = data.fragments || (data.body ? [{id: documentId, label: 'Документ', kind: 'document', text: data.body}] : [])
|
||||
setAllFragments(next); return next
|
||||
} catch (error) { if (controller.signal.aborted || generation !== wholeGenerationRef.current) return []; const message = error instanceof Error ? error.message : 'Не удалось загрузить полный текст.'; setWholeError(message); onNotify(message); return []
|
||||
} finally { if (generation === wholeGenerationRef.current) { setWholeLoading(false); wholeControllerRef.current = null } }
|
||||
}, [allFragments, documentId, onNotify, wholeLoading])
|
||||
|
||||
const runSearch = useCallback(async (value = query) => {
|
||||
const clean = value.trim(); setSearchQuery(clean)
|
||||
if (!clean) return
|
||||
const loaded = await loadWhole()
|
||||
if (loaded.length) setTimeout(() => document.querySelector('.reader-find mark')?.scrollIntoView({block: 'center'}), 0)
|
||||
}, [loadWhole, query])
|
||||
|
||||
useEffect(() => {
|
||||
if (!documentId) return
|
||||
const controller = new AbortController(); const request = ++requestRef.current
|
||||
setRelatedLoading(true)
|
||||
let attempts = 0
|
||||
let timer: number | undefined
|
||||
const load = async () => {
|
||||
try { const data = await api<RelatedData>(`/related?${new URLSearchParams({id: documentId, ...(activeId ? {fragment: activeId} : {})})}`, {signal: controller.signal}); if (request !== requestRef.current || controller.signal.aborted) return; setRelated(data); setRelatedLoading(Boolean(data.loading)); if (data.loading && attempts++ < 4) timer = window.setTimeout(load, 1500) }
|
||||
catch (error) { if (error instanceof Error && error.name === 'AbortError') return; if (request === requestRef.current) { setRelated({related: []}); setRelatedLoading(false) } }
|
||||
}
|
||||
void load(); return () => { controller.abort(); if (timer !== undefined) window.clearTimeout(timer) }
|
||||
}, [documentId, activeId])
|
||||
|
||||
const selectFragment = (id: string) => { window.location.hash = docHref(documentId, id).slice(1) }
|
||||
const copy = async (value: string, message: string) => { try { await navigator.clipboard.writeText(value); onNotify(message) } catch { onNotify('Копирование недоступно в этом браузере.') } }
|
||||
const navigateMatch = (direction: 1 | -1) => {
|
||||
const marks = Array.from(document.querySelectorAll<HTMLElement>('.reading-text mark'))
|
||||
if (!marks.length) return
|
||||
const next = (matchIndex + direction + marks.length) % marks.length
|
||||
setMatchIndex(next)
|
||||
marks[next]?.scrollIntoView({block: 'center', behavior: 'auto'})
|
||||
}
|
||||
const visibleFragments = searchQuery ? allFragments : fragments
|
||||
|
||||
useEffect(() => {
|
||||
setMatchIndex(-1)
|
||||
if (!query.trim()) { setSearchQuery(''); return }
|
||||
const timer = window.setTimeout(() => { void runSearch(query) }, 280)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [query])
|
||||
|
||||
useEffect(() => {
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
const node = activeId ? document.getElementById(activeId) : null
|
||||
if (!node) return
|
||||
const topbar = document.querySelector<HTMLElement>('.topbar')?.getBoundingClientRect().height || 0
|
||||
const toolbar = document.querySelector<HTMLElement>('.document-toolbar')?.getBoundingClientRect().height || 0
|
||||
const top = node.getBoundingClientRect().top + window.scrollY - topbar - toolbar - 20
|
||||
window.scrollTo({top: Math.max(0, top), behavior: 'auto'})
|
||||
})
|
||||
return () => window.cancelAnimationFrame(frame)
|
||||
}, [activeId, allFragments, reader.data])
|
||||
|
||||
useEffect(() => {
|
||||
const frame = window.requestAnimationFrame(() => setMatchCount(document.querySelectorAll('.reading-text mark').length))
|
||||
return () => window.cancelAnimationFrame(frame)
|
||||
}, [searchQuery, allFragments])
|
||||
|
||||
if (reader.loading && !legalDocument) return <div className="wide-page reader-shell"><p className="help-note" role="status">Открываем документ…</p></div>
|
||||
if (reader.error || !legalDocument) return <div className="wide-page reader-shell"><p className="notice warning">{reader.error || 'Документ не найден.'}</p></div>
|
||||
const title = legalDocument.subject || legalDocument.title
|
||||
const warnings = legalDocument.warnings || []
|
||||
const findText = (fragment: Fragment) => {
|
||||
const raw = String(fragment.text || '')
|
||||
if (!isHeadingDuplicated(fragment)) return fragmentText(fragment, searchQuery)
|
||||
const newline = raw.search(/\r?\n/)
|
||||
if (newline < 0) return null
|
||||
const removed = newline + (raw[newline] === '\r' && raw[newline + 1] === '\n' ? 2 : 1)
|
||||
return <div className="fragment-body">{renderAnchoredText(raw.slice(removed), (fragment.anchors || []).filter(anchor => anchor.offset >= removed).map(anchor => ({...anchor, offset: anchor.offset - removed})), searchQuery)}</div>
|
||||
}
|
||||
return <main className="wide-page reader-page">
|
||||
<div className="reader-document-head"><div><p className="eyebrow">{labelKind(legalDocument.kind)}{legalDocument.number ? ` · № ${legalDocument.number}` : ''}</p><h1>{title}</h1><p className="muted">{legalDocument.title !== title ? legalDocument.title : ''}</p></div><div className="inline-actions"><button className="button quiet" onClick={() => setFocusMode(value => !value)} aria-pressed={focusMode}><Icon name="focus" /> {focusMode ? 'Выйти из режима чтения' : 'Сосредоточенное чтение'}</button><a className="button quiet" href={href({view: 'history', id: legalDocument.id})}>История редакций</a><button className="button quiet" onClick={() => void onUpdate(legalDocument.id).catch(error => onNotify(error instanceof Error ? error.message : 'Не удалось обновить документ.'))}>Обновить</button></div></div>
|
||||
{warnings.length > 0 && <details className="notice warning"><summary>{warnings[0]} <span>Подробнее</span></summary><ul>{warnings.map(warning => <li key={warning}>{warning}</li>)}</ul></details>}
|
||||
<div className="reader-mobile-actions"><button className="button quiet" onClick={() => setMobilePanel('toc')}><Icon name="menu" /> Оглавление</button><button className="button quiet" onClick={() => setMobilePanel('related')}>Связи</button></div>
|
||||
<div className="reader-shell">
|
||||
<div className={`reader-desktop-panel ${mobilePanel === 'toc' ? 'is-mobile-open' : ''}`}><Toc items={toc} documentId={legalDocument.id} activeId={activeId} filter={tocFilter} onFilter={setTocFilter} onSelect={selectFragment} /></div>
|
||||
<article className="reader-center">
|
||||
<div className="document-toolbar"><div className="inline-actions"><button className="button quiet" onClick={() => copy(visibleFragments.map(item => item.text || '').join('\n\n'), 'Текст скопирован')}><Icon name="copy" /> Копировать текст</button><button className="button quiet" onClick={() => copy(`${location.origin}${location.pathname}${docHref(legalDocument.id, activeId)}`, 'Ссылка скопирована')}>Копировать ссылку</button>{legalDocument.source_url && <a className="button quiet" href={safeURL(legalDocument.source_url)} target="_blank" rel="noopener noreferrer">Источник ↗</a>}</div><div className="size-controls" aria-label="Размер текста"><button onClick={() => setFontSize(value => Math.max(16, value - 2))} aria-label="Уменьшить текст">А−</button><span>{fontSize}</span><button onClick={() => setFontSize(value => Math.min(30, value + 2))} aria-label="Увеличить текст">А+</button></div></div>
|
||||
<div className="reader-find"><label className="field grow"><span>Найти в документе</span><input ref={findRef} type="search" value={query} onChange={event => setQuery(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') void runSearch() }} placeholder="Слово или фраза" /></label><button className="button quiet" onClick={() => void runSearch()} disabled={wholeLoading}>Найти</button><button className="button quiet" onClick={() => navigateMatch(-1)} aria-label="Предыдущее совпадение">↑</button><button className="button quiet" onClick={() => navigateMatch(1)} aria-label="Следующее совпадение">↓</button><span className="reader-find-count" role="status" aria-live="polite">{matchCount ? (matchIndex >= 0 ? `${matchIndex + 1} из ${matchCount}` : `Совпадений: ${matchCount}`) : query ? 'Совпадений нет' : ''}</span>{wholeError && <span className="status-tag">{wholeError}</span>}</div>
|
||||
<div className="reader-meta"><span>Редакция: <strong>{shortDate(legalDocument.revision)}</strong></span><span>Копия получена: {shortDate(legalDocument.retrieved_at)}</span><span>Проверка: {shortDate(legalDocument.last_checked)}</span>{legalDocument.effective_date && <span>Вступление в силу: {shortDate(legalDocument.effective_date)}</span>}</div>
|
||||
{!allFragments.length && <button className="button primary" onClick={() => void loadWhole()} disabled={wholeLoading}>{wholeLoading ? 'Загружаем…' : 'Открыть весь документ'}</button>}
|
||||
<div className="reading-text" style={{fontSize}}>{visibleFragments.length ? visibleFragments.map(fragment => <section className="text-fragment" id={fragment.id} key={fragment.id}><h2 className="fragment-heading">{fragment.label}</h2>{findText(fragment)}</section>) : <p className="help-note">Текст пока не загружен.</p>}</div>
|
||||
</article>
|
||||
<div className={`reader-desktop-panel ${mobilePanel === 'related' ? 'is-mobile-open' : ''}`}><Related edges={related.related || []} loading={relatedLoading} documentId={legalDocument.id} fragmentId={activeId} nodeId={related.node_id} /></div>
|
||||
</div>
|
||||
<Sheet open={mobilePanel !== null} onOpenChange={open => { if (!open) setMobilePanel(null) }}>
|
||||
<SheetContent side={mobilePanel === 'toc' ? 'left' : 'right'} className="reader-mobile-sheet">
|
||||
<SheetTitle>{mobilePanel === 'toc' ? 'Оглавление' : 'Связанные материалы'}</SheetTitle>
|
||||
<SheetDescription className="sr-only">Навигационная панель документа</SheetDescription>
|
||||
{mobilePanel === 'toc' ? <Toc items={toc} documentId={legalDocument.id} activeId={activeId} filter={tocFilter} onFilter={setTocFilter} onSelect={id => { selectFragment(id); setMobilePanel(null) }} /> : <Related edges={related.related || []} loading={relatedLoading} documentId={legalDocument.id} fragmentId={activeId} nodeId={related.node_id} />}
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</main>
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext", "moduleResolution": "bundler",
|
||||
"jsx": "react-jsx", "strict": true, "skipLibCheck": true,
|
||||
"esModuleInterop": true, "resolveJsonModule": true,
|
||||
"noEmit": true, "allowImportingTsExtensions": true,
|
||||
"paths": {"@/*": ["./src/*"]}
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
|
||||
publicDir: false,
|
||||
build: { outDir: '../web/dist', emptyOutDir: true },
|
||||
server: { proxy: { '/api': 'http://127.0.0.1:18765', '/assets/books': 'http://127.0.0.1:18765', '/assets/icons.webp': 'http://127.0.0.1:18765' } },
|
||||
})
|
||||
@@ -0,0 +1,332 @@
|
||||
"""Read-only bounded adapter for Themiz legal graph snapshots."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from pathlib import Path
|
||||
from threading import Lock, Thread
|
||||
|
||||
|
||||
def _clean(n):
|
||||
return {k: n.get(k) for k in ("id", "label", "resource_id", "kind",
|
||||
"source_location", "revision", "aliases") if k in n}
|
||||
|
||||
|
||||
class GraphView:
|
||||
def __init__(self, data):
|
||||
self.snapshot, self.stale = data.get("snapshot"), bool(data.get("stale"))
|
||||
self.report, self.warnings = data.get("report") or {}, list(data.get("warnings") or [])
|
||||
fields = ("id", "label", "resource_id", "kind", "document_kind",
|
||||
"source_location", "revision", "aliases")
|
||||
raw = [{key: n[key] for key in fields if key in n}
|
||||
for n in data.get("nodes", []) if n.get("id")]
|
||||
self.nodes = {n["id"]: n for n in raw}
|
||||
self.resource_nodes = defaultdict(list)
|
||||
self.document_nodes = {}
|
||||
for n in raw:
|
||||
self.resource_nodes[n.get("resource_id")].append(n)
|
||||
if n.get("kind") == "document": self.document_nodes[n.get("resource_id")] = n
|
||||
self.edges, self.adjacency = [], defaultdict(list)
|
||||
for e in data.get("edges", []):
|
||||
if e.get("source") in self.nodes and e.get("target") in self.nodes:
|
||||
self.edges.append(e); self.adjacency[e["source"]].append(e); self.adjacency[e["target"]].append(e)
|
||||
|
||||
def _env(self, **kw):
|
||||
return {"snapshot": self.snapshot, "stale": self.stale, "warnings": self.warnings,
|
||||
"report": self.report, **kw}
|
||||
|
||||
def find_node(self, resource_id, kind=None, label=None, number=None):
|
||||
for n in self.resource_nodes.get(resource_id, []):
|
||||
if kind and n.get("kind") != kind: continue
|
||||
if label and label.casefold() not in n.get("label", "").casefold(): continue
|
||||
if number and number not in n.get("label", ""): continue
|
||||
return _clean(n)
|
||||
return None
|
||||
|
||||
def clustered(self, kind=None, query=None, limit=100, offset=0, resource_id=None):
|
||||
docs = list(self.document_nodes.values())
|
||||
if resource_id: docs = [n for n in docs if n.get("resource_id") == resource_id]
|
||||
if kind: docs = [n for n in docs if n.get("document_kind") == kind or n.get("resource_id", "").split(":")[1:2] == [kind]]
|
||||
if query:
|
||||
q = query.casefold().split()
|
||||
fragments = []
|
||||
for n in self.nodes.values():
|
||||
hay = (n.get("label", "") + " " + " ".join(n.get("aliases") or [])).casefold()
|
||||
if all(token in hay for token in q): fragments.append(n)
|
||||
page = fragments[offset:offset + limit]
|
||||
return self._env(nodes=[_clean(n) for n in page], edges=[], total=len(fragments), offset=offset,
|
||||
has_more=offset + len(page) < len(fragments), status="ok")
|
||||
page = docs[offset:offset + limit]; resources = {n.get("resource_id") for n in page}; out, seen = [], set()
|
||||
for e in self.edges:
|
||||
if e.get("relation") == "contains": continue
|
||||
a, b = self.nodes[e["source"]].get("resource_id"), self.nodes[e["target"]].get("resource_id")
|
||||
if a in resources and b in resources and (a, b, e.get("relation")) not in seen:
|
||||
seen.add((a, b, e.get("relation"))); out.append({**e, "source": self.document_nodes[a]["id"], "target": self.document_nodes[b]["id"]})
|
||||
return self._env(nodes=[_clean(n) for n in page], edges=out, total=len(docs), offset=offset,
|
||||
has_more=offset + len(page) < len(docs), status="ok")
|
||||
|
||||
@staticmethod
|
||||
def _matches(node, query='', kind=''):
|
||||
resource_kind = node.get('resource_id', '').split(':')[1:2]
|
||||
if kind and node.get('kind') != kind and node.get('document_kind') != kind and resource_kind != [kind]:
|
||||
return False
|
||||
if query:
|
||||
tokens = [({'ст': 'статья', 'п': 'пункт'}.get(token.rstrip('.'), token.rstrip('.')))
|
||||
for token in re.findall(r'[\w.]+', query.casefold()) if token.rstrip('.')]
|
||||
hay = ' '.join([node.get('label', ''), *[str(a) for a in node.get('aliases') or []]]).casefold()
|
||||
if not all((re.search(rf'(?<!\d){re.escape(token)}(?!\d)', hay) if token.isdigit()
|
||||
else token in hay) for token in tokens):
|
||||
return False
|
||||
return True
|
||||
|
||||
def network(self, level='documents', query='', kind='', resource_id='', node_id='',
|
||||
include_contains=True, max_nodes=1000, max_edges=5000):
|
||||
"""Return a deterministic, bounded network for the interactive graph.
|
||||
|
||||
The overview collapses atom edges to document pairs. The atom view
|
||||
keeps only actual contains/references edges and never includes bodies.
|
||||
"""
|
||||
max_nodes = max(1, min(1000, int(max_nodes)))
|
||||
max_edges = max(1, min(5000, int(max_edges)))
|
||||
docs = sorted(self.document_nodes.values(), key=lambda n: (n.get('label', '').casefold(), n.get('id', '')))
|
||||
if query:
|
||||
docs = [n for n in docs if self._matches(n, query)]
|
||||
if kind:
|
||||
docs = [n for n in docs if self._matches(n, kind=kind)]
|
||||
if resource_id:
|
||||
docs = [n for n in docs if n.get('resource_id') == resource_id]
|
||||
if node_id and node_id in self.nodes:
|
||||
anchor_resource = self.nodes[node_id].get('resource_id')
|
||||
docs = [n for n in docs if n.get('resource_id') == anchor_resource]
|
||||
if level == 'documents':
|
||||
selected_docs = docs[:max_nodes]
|
||||
doc_ids = {n.get('resource_id') for n in selected_docs}
|
||||
grouped = {}
|
||||
for edge in self.edges:
|
||||
if edge.get('relation') == 'contains':
|
||||
continue
|
||||
source = self.nodes.get(edge.get('source'))
|
||||
target = self.nodes.get(edge.get('target'))
|
||||
left, right = (source or {}).get('resource_id'), (target or {}).get('resource_id')
|
||||
if left not in doc_ids or right not in doc_ids or left == right:
|
||||
continue
|
||||
key = (self.document_nodes[left]['id'], self.document_nodes[right]['id'], edge.get('relation', 'related'))
|
||||
entry = grouped.setdefault(key, {'source': key[0], 'target': key[1], 'relation': key[2], 'count': 0, 'evidence': None})
|
||||
entry['count'] += 1
|
||||
if edge.get('evidence') and not entry['evidence']:
|
||||
entry['evidence'] = edge['evidence']
|
||||
all_edges = sorted(grouped.values(), key=lambda e: (e['source'], e['target'], e['relation']))
|
||||
out_edges = all_edges[:max_edges]
|
||||
return self._env(level='documents', nodes=[_clean(n) for n in selected_docs], edges=out_edges,
|
||||
focus_id=(self.document_nodes.get(self.nodes[node_id].get('resource_id'), {}).get('id', '')
|
||||
if node_id in self.nodes else ''),
|
||||
total_nodes=len(docs), total_edges=len(all_edges), displayed_nodes=len(selected_docs),
|
||||
displayed_edges=len(out_edges), truncated=len(selected_docs) < len(docs) or len(out_edges) < len(all_edges),
|
||||
status='ok')
|
||||
|
||||
return self.atomic_network(query, kind, resource_id, node_id, include_contains,
|
||||
max_nodes, max_edges)
|
||||
|
||||
def atomic_network(self, query='', kind='', resource_id='', node_id='',
|
||||
include_contains=True, max_nodes=1000, max_edges=5000):
|
||||
atom_ids = {i for i, n in self.nodes.items()
|
||||
if n.get('kind') in {'article', 'point', 'paragraph', 'heading'}}
|
||||
if node_id and node_id not in atom_ids:
|
||||
return self._env(level='atoms', nodes=[], edges=[], focus_id=node_id,
|
||||
total_nodes=0, total_edges=0, displayed_nodes=0, displayed_edges=0,
|
||||
truncated=False, status='focus_not_found')
|
||||
seeds = ({node_id} if node_id else
|
||||
{i for i in atom_ids if self._matches(self.nodes[i], query, kind)
|
||||
and (not resource_id or self.nodes[i].get('resource_id') == resource_id)})
|
||||
# Only structural descendants belong to the seed family. A reference
|
||||
# neighbor must never become a new seed during this traversal.
|
||||
family = set(seeds)
|
||||
queue = deque(seeds)
|
||||
while queue:
|
||||
current = queue.popleft()
|
||||
for edge in self.adjacency[current]:
|
||||
child = edge.get('target')
|
||||
if (edge.get('relation') == 'contains' and edge.get('source') == current
|
||||
and child in atom_ids and child not in family):
|
||||
family.add(child)
|
||||
queue.append(child)
|
||||
|
||||
# Prefer the precise child source only for the same evidenced mention.
|
||||
# The original snapshot and all legacy API views remain unchanged.
|
||||
if not hasattr(self, '_atomic_edges'):
|
||||
parents = defaultdict(set)
|
||||
for edge in self.edges:
|
||||
if edge.get('relation') == 'contains':
|
||||
parents[edge.get('target')].add(edge.get('source'))
|
||||
child_mentions = defaultdict(list)
|
||||
for edge in self.edges:
|
||||
if edge.get('relation') == 'references':
|
||||
for parent in parents[edge.get('source')]:
|
||||
child_mentions[(parent, edge.get('target'))].append(edge)
|
||||
def same_mention(left, right):
|
||||
if not left.get('source_file') or left.get('source_file') != right.get('source_file'):
|
||||
return False
|
||||
if left.get('source_location') and right.get('source_location'):
|
||||
return left['source_location'] == right['source_location']
|
||||
a = ' '.join((left.get('evidence') or {}).get('excerpt', '').split())
|
||||
b = ' '.join((right.get('evidence') or {}).get('excerpt', '').split())
|
||||
return len(a) >= 20 and a == b
|
||||
unique = {}
|
||||
for edge in self.edges:
|
||||
source, target, relation = edge.get('source'), edge.get('target'), edge.get('relation')
|
||||
if source not in atom_ids or target not in atom_ids or relation not in {'references', 'contains'}:
|
||||
continue
|
||||
if relation == 'references' and any(same_mention(edge, child)
|
||||
for child in child_mentions[(source, target)]):
|
||||
continue
|
||||
key = (source, target, relation)
|
||||
if key not in unique or (not unique[key].get('evidence') and edge.get('evidence')):
|
||||
unique[key] = edge
|
||||
self._atomic_edges = list(unique.values())
|
||||
|
||||
relevant = [e for e in self._atomic_edges
|
||||
if (e['source'] in family or e['target'] in family)
|
||||
and (include_contains or e['relation'] != 'contains')]
|
||||
expanded = seeds | {i for e in relevant for i in (e['source'], e['target'])}
|
||||
focus = node_id or (next(iter(seeds)) if len(seeds) == 1 else '')
|
||||
degree = defaultdict(int)
|
||||
adjacency = defaultdict(list)
|
||||
for edge in relevant:
|
||||
source, target = edge['source'], edge['target']
|
||||
priority = 0 if edge['relation'] == 'references' else 1
|
||||
adjacency[source].append((priority, target))
|
||||
adjacency[target].append((priority, source))
|
||||
if priority == 0:
|
||||
degree[source] += 1
|
||||
degree[target] += 1
|
||||
rank = lambda i: (-degree[i], self.nodes[i].get('resource_id', ''), i)
|
||||
# Connected traversal keeps the overview's exact counterpart atoms in
|
||||
# the bounded result instead of filling it with article seeds alone.
|
||||
roots = ([focus] if focus else []) + sorted(expanded - {focus}, key=rank)
|
||||
selected_ids, seen = [], set()
|
||||
for root in roots:
|
||||
if root in seen:
|
||||
continue
|
||||
queue = deque([root])
|
||||
seen.add(root)
|
||||
while queue and len(selected_ids) < max_nodes:
|
||||
current = queue.popleft()
|
||||
selected_ids.append(current)
|
||||
for _, other in sorted(adjacency[current], key=lambda pair: (pair[0], rank(pair[1]))):
|
||||
if other not in seen:
|
||||
seen.add(other)
|
||||
queue.append(other)
|
||||
if len(selected_ids) >= max_nodes:
|
||||
break
|
||||
selected = set(selected_ids)
|
||||
out_edges = sorted((e for e in relevant if e['source'] in selected and e['target'] in selected),
|
||||
key=lambda e: (e['source'], e['target'], e['relation']))[:max_edges]
|
||||
return self._env(level='atoms', nodes=[_clean(self.nodes[i]) for i in selected_ids],
|
||||
edges=out_edges, focus_id=focus, matched_nodes=len(seeds),
|
||||
total_nodes=len(expanded), total_edges=len(relevant),
|
||||
displayed_nodes=len(selected_ids), displayed_edges=len(out_edges),
|
||||
truncated=len(selected_ids) < len(expanded) or len(out_edges) < len(relevant),
|
||||
status='ok')
|
||||
|
||||
def ego(self, node_id, depth=1, limit=200, offset=0, include_contains=False):
|
||||
if node_id not in self.nodes: return self._env(focus_id=node_id, nodes=[], edges=[], total=0, offset=0, has_more=False, status="not_found")
|
||||
seen, queue, edges = {node_id}, deque([(node_id, 0)]), []
|
||||
while queue and len(seen) < limit:
|
||||
cur, level = queue.popleft()
|
||||
if level >= depth: continue
|
||||
def rank(e):
|
||||
if e.get("relation") == "contains": return 3
|
||||
other = e["target"] if e["source"] == cur else e["source"]
|
||||
return 0 if self.nodes[other].get("resource_id") != self.nodes[cur].get("resource_id") else 1
|
||||
for e in sorted(self.adjacency[cur], key=lambda item: (rank(item), item.get("source", ""), item.get("target", ""))):
|
||||
if not include_contains and e.get("relation") == "contains": continue
|
||||
edges.append(e); other = e["target"] if e["source"] == cur else e["source"]
|
||||
if other not in seen and len(seen) < limit: seen.add(other); queue.append((other, level + 1))
|
||||
unique = {(e["source"], e["target"], e.get("relation")): e for e in edges}
|
||||
all_edges = list(unique.values())
|
||||
page_edges = all_edges[offset:offset + limit]
|
||||
page_ids = {node_id} | {e["source"] for e in page_edges} | {e["target"] for e in page_edges}
|
||||
return self._env(focus_id=node_id, nodes=[_clean(self.nodes[i]) for i in page_ids], edges=page_edges,
|
||||
total=len(all_edges), offset=offset, has_more=offset + len(page_edges) < len(all_edges), status="ok")
|
||||
|
||||
def related(self, resource_id, node_id=""):
|
||||
ids = {node_id} if node_id else {n["id"] for n in self.resource_nodes.get(resource_id, [])}; edges = []
|
||||
for i in ids: edges += [e for e in self.adjacency[i] if e.get("relation") != "contains"]
|
||||
unique = {(e["source"], e["target"], e.get("relation")): e for e in edges}; edges = list(unique.values())
|
||||
ids |= {e["target"] if e["source"] in ids else e["source"] for e in edges}
|
||||
enriched = [{**e, "source_node": _clean(self.nodes[e["source"]]),
|
||||
"target_node": _clean(self.nodes[e["target"]])} for e in edges]
|
||||
return self._env(focus_id=node_id or resource_id, related=enriched,
|
||||
nodes=[_clean(self.nodes[i]) for i in ids], edges=edges,
|
||||
total=len(ids), offset=0, has_more=False, status="ok")
|
||||
|
||||
def edge(self, source_id, target_id):
|
||||
es = [e for e in self.adjacency.get(source_id, []) if e.get("source") == source_id and e.get("target") == target_id]
|
||||
return self._env(source=_clean(self.nodes[source_id]) if source_id in self.nodes else None,
|
||||
target=_clean(self.nodes[target_id]) if target_id in self.nodes else None, edges=es,
|
||||
status="ok" if es else "not_found")
|
||||
|
||||
|
||||
class GraphViewCache:
|
||||
TTL = 30.0
|
||||
def __init__(self, root):
|
||||
self.root, self._view, self._fingerprint = Path(root), None, None
|
||||
self._corpus_fingerprint, self._checked = None, 0.0
|
||||
self._loading, self._lock = False, Lock()
|
||||
def get(self):
|
||||
with self._lock: return self._view
|
||||
def _fp(self):
|
||||
p = self.root / ".agent/maintenance/legal-graph/current.json"
|
||||
try: s = p.stat(); return (s.st_mtime_ns, s.st_size)
|
||||
except OSError: return None
|
||||
def _corpus_fp(self, snapshot):
|
||||
if not snapshot: return None
|
||||
manifest = self.root / ".agent/maintenance/legal-graph/snapshots" / snapshot / "source-manifest.json"
|
||||
try: documents = json.loads(manifest.read_text(encoding="utf-8")).get("documents", [])
|
||||
except (OSError, ValueError, TypeError): return None
|
||||
result = []
|
||||
for item in documents:
|
||||
relative = item.get("relative_path")
|
||||
if not relative: continue
|
||||
try:
|
||||
stat = (self.root / relative).stat()
|
||||
result.append((relative, stat.st_mtime_ns, stat.st_size))
|
||||
except OSError: result.append((relative, None, None))
|
||||
return tuple(result)
|
||||
def ensure(self):
|
||||
now, fp = time.monotonic(), self._fp()
|
||||
with self._lock:
|
||||
if (self._view and fp == self._fingerprint
|
||||
and now - self._checked < self.TTL):
|
||||
return {"loading": False, "ready": True, "snapshot": self._view.snapshot, "stale": self._view.stale}
|
||||
cached_view = self._view if self._view and fp == self._fingerprint else None
|
||||
if cached_view is not None:
|
||||
corpus_fp = self._corpus_fp(cached_view.snapshot)
|
||||
with self._lock:
|
||||
if self._view is cached_view and fp == self._fingerprint:
|
||||
if corpus_fp != self._corpus_fingerprint:
|
||||
self._view.stale = True
|
||||
self._corpus_fingerprint = corpus_fp
|
||||
self._checked = now
|
||||
return {"loading": False, "ready": True, "snapshot": self._view.snapshot, "stale": self._view.stale}
|
||||
with self._lock:
|
||||
self._checked = now
|
||||
if self._loading: return {"loading": True, "ready": self._view is not None, "snapshot": self._view.snapshot if self._view else None}
|
||||
self._loading = True
|
||||
Thread(target=self._load, daemon=True, name="eunomia-graph-view").start()
|
||||
return {"loading": True, "ready": self._view is not None, "snapshot": self._view.snapshot if self._view else None}
|
||||
def _load(self):
|
||||
try:
|
||||
try: from scripts import legal_graph
|
||||
except ImportError: import legal_graph
|
||||
# Capture the publication pointer before parsing the snapshot.
|
||||
# If it is replaced during the parse, the next ensure() sees the
|
||||
# new fingerprint and reloads instead of accepting an old view.
|
||||
fp = self._fp()
|
||||
view = GraphView(legal_graph.graph_data(self.root))
|
||||
with self._lock:
|
||||
self._view, self._fingerprint = view, fp
|
||||
self._corpus_fingerprint, self._loading = self._corpus_fp(view.snapshot), False
|
||||
except Exception:
|
||||
with self._lock: self._loading = False
|
||||
@@ -0,0 +1,433 @@
|
||||
"""Read models and disposable local search index over the Themiz registry.
|
||||
|
||||
Only registered public corpus paths enter this database. Search queries are
|
||||
never recorded. Published in-memory views stay readable during indexing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from bisect import bisect_left
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import background_corpus
|
||||
import corpus_registry
|
||||
import legal_graph
|
||||
from cite import CODE_SLUGS
|
||||
|
||||
|
||||
def stamp():
|
||||
return datetime.now(UTC).isoformat().replace('+00:00', 'Z')
|
||||
|
||||
|
||||
def normalized(text):
|
||||
return re.sub(r'\s+', ' ', re.sub(r'(?m)^#{1,6}\s+', '', text)).strip()
|
||||
|
||||
|
||||
def fragments(resource_id, body):
|
||||
"""Stable graph-compatible anchors, with complete non-overlapping text."""
|
||||
base = legal_graph._graph_id(resource_id)
|
||||
headings = [{'start': match.start(), 'end': match.end(), 'label': match.group(2)}
|
||||
for match in legal_graph.HEADING_RE.finditer(body)]
|
||||
# Synthetic and legacy sources often use plain ``Статья N.`` lines. Keep
|
||||
# them as real fragments so reader/diff selectors do not fall back to the
|
||||
# whole document. Markdown headings remain authoritative on overlap.
|
||||
if not headings:
|
||||
for match in legal_graph.ARTICLE_RE.finditer(body):
|
||||
tail = match.group(2).strip()
|
||||
headings.append({'start': match.start(), 'end': match.end(),
|
||||
'label': f'Статья {match.group(1)}{(". " + tail) if tail else "."}'})
|
||||
headings.sort(key=lambda item: item['start'])
|
||||
result = []
|
||||
for ordinal, match in enumerate(headings, 1):
|
||||
label = match['label']
|
||||
article = re.match(r'Статья\s+(\d+(?:\.\d+)*(?:-\d+)?)', label, re.I)
|
||||
point = re.match(r'(?:Пункт|п\.)\s*(\d+(?:\.\d+)*)', label, re.I)
|
||||
ident = (f"{base}_article_{article[1].replace('.', '_').replace('-', '_')}" if article else
|
||||
f"{base}_point_{point[1].replace('.', '_')}" if point else f'{base}_heading_{ordinal}')
|
||||
end = headings[ordinal]['start'] if ordinal < len(headings) else len(body)
|
||||
text = body[match['start']:end].strip()
|
||||
anchors = []
|
||||
if article:
|
||||
for p in legal_graph.POINT_RE.finditer(text):
|
||||
anchor = f"{ident}_point_{p[1].replace('.', '_')}"
|
||||
suffix = 1
|
||||
while any(a['id'] == anchor for a in anchors):
|
||||
suffix += 1
|
||||
anchor = f"{ident}_point_{p[1].replace('.', '_')}_{suffix}"
|
||||
anchors.append({'id': anchor, 'number': p[1], 'label': f"{p[1]}.",
|
||||
'offset': p.start(), 'body_offset': match['start'] + p.start()})
|
||||
elif len(resource_id.split(':')) > 1 and resource_id.split(':')[1] in {'plenum', 'review'}:
|
||||
for p in legal_graph.POINT_RE.finditer(text):
|
||||
anchor = f"{ident}_point_{p[1].replace('.', '_')}"
|
||||
suffix = 1
|
||||
while any(a['id'] == anchor for a in anchors):
|
||||
suffix += 1
|
||||
anchor = f"{ident}_point_{p[1].replace('.', '_')}_{suffix}"
|
||||
anchors.append({'id': anchor, 'number': p[1], 'label': f"{p[1]}.",
|
||||
'offset': p.start(), 'body_offset': match['start'] + p.start()})
|
||||
result.append({'id': ident, 'label': label, 'kind': 'article' if article else 'point' if point else 'heading',
|
||||
'text': text, 'anchors': anchors})
|
||||
if not result:
|
||||
result = [{'id': base, 'label': 'Текст документа', 'kind': 'document', 'text': body}]
|
||||
elif headings[0]['start'] > 0 and body[:headings[0]['start']].strip():
|
||||
result.insert(0, {'id': base, 'label': 'Преамбула', 'kind': 'document', 'text': body[:headings[0]['start']]})
|
||||
return result
|
||||
|
||||
|
||||
class Library:
|
||||
def __init__(self, root):
|
||||
self.root = Path(root).resolve()
|
||||
self.state = self.root / '.agent/maintenance/eunomia'
|
||||
self.state.mkdir(parents=True, exist_ok=True)
|
||||
self.db = self.state / 'library.sqlite3'
|
||||
self.lock = threading.Lock()
|
||||
self.documents = {}
|
||||
self.error = None
|
||||
self.indexed_at = None
|
||||
self.signature = None
|
||||
with self.connect() as conn:
|
||||
conn.execute('PRAGMA journal_mode=WAL')
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS versions (id TEXT PRIMARY KEY, resource_id TEXT, raw BLOB, meta TEXT, observed_at TEXT)')
|
||||
conn.execute('CREATE INDEX IF NOT EXISTS versions_resource ON versions(resource_id)')
|
||||
conn.execute('CREATE VIRTUAL TABLE IF NOT EXISTS search USING fts5(resource_id UNINDEXED, fragment_id UNINDEXED, title, label, body, aliases, tokenize="unicode61")')
|
||||
|
||||
def connect(self):
|
||||
conn = sqlite3.connect(self.db, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
def _read(self, resource, raw=None):
|
||||
path = legal_graph._source_path(self.root, resource['output'])
|
||||
if raw is None:
|
||||
if path.stat().st_size > legal_graph.MAX_DOCUMENT_BYTES:
|
||||
raise ValueError('Текст превышает допустимый размер')
|
||||
raw = path.read_bytes()
|
||||
meta, body = legal_graph._frontmatter(raw)[:2]
|
||||
declared = meta.get('sha256', '').removeprefix('sha256:')
|
||||
digest = hashlib.sha256(body.encode()).hexdigest()
|
||||
integrity = declared == digest
|
||||
return raw, meta, body, integrity
|
||||
|
||||
def _summary(self, resource, meta, body, integrity):
|
||||
headings = fragments(resource['id'], body) if body else []
|
||||
title = next((x['label'] for x in headings if x['text'].startswith('# ')), None)
|
||||
title = title or resource.get('title') or resource.get('label') or resource.get('entry', {}).get('title') or resource['id']
|
||||
# Act identity comes from the title/identity line, never the revision date.
|
||||
identity = ' '.join(str(v or '') for v in (resource.get('date'), meta.get('дата_акта'), meta.get('закон'), title))
|
||||
date_match = re.search(r'\b(\d{2}\.\d{2}\.\d{4})\b', identity)
|
||||
act_date = None
|
||||
if date_match:
|
||||
try:
|
||||
act_date = datetime.strptime(date_match[1], '%d.%m.%Y').strftime('%d.%m.%Y')
|
||||
except ValueError:
|
||||
pass
|
||||
number_match = re.search(r'(?:№|\bN)\s*([\d]+(?:[-/][\w\d]+)*)', identity)
|
||||
number = resource.get('number') or (number_match[1] if number_match else None)
|
||||
paragraphs = [p.strip() for p in body.split('\n\n') if p.strip()]
|
||||
subject = ''
|
||||
if resource['kind'] in {'plenum', 'review'}:
|
||||
for para in paragraphs[1:5]:
|
||||
subject_match = re.search(r'(?:^|\s)(О\s+|Об\s+|По вопросам\s+)(.+)', para)
|
||||
if subject_match and len(para) < 1500:
|
||||
subject = re.sub(r'\s+', ' ', subject_match[0]).strip(' "«»')
|
||||
if subject.isupper():
|
||||
subject = subject.capitalize()
|
||||
break
|
||||
missing = bool(re.search(r'(?i)НЕ СКАЧАН|не удалось (?:скачать|загрузить)|текст статьи отсутствует', body))
|
||||
scope = resource.get('entry', {}).get('chapter_scope')
|
||||
coverage = meta.get('coverage', '')
|
||||
full = coverage in {'full', 'complete'} and not missing and integrity
|
||||
status = 'full' if full else 'partial' if missing or scope or coverage in {'partial', 'headings_complete'} else 'unknown'
|
||||
warnings = []
|
||||
if not integrity and body:
|
||||
warnings.append('Контрольная сумма не подтверждена: требуется сверка')
|
||||
if status == 'partial':
|
||||
warnings.append('Частичный корпус: полнота документа не подтверждена')
|
||||
if status == 'unknown' and body:
|
||||
warnings.append('Полнота текста не подтверждена')
|
||||
checked = meta.get('last_checked')
|
||||
parsed = legal_graph._parse_time(checked)
|
||||
if not parsed or datetime.now(UTC) - parsed > timedelta(days=7) or parsed > datetime.now(UTC):
|
||||
warnings.append('Нет успешной проверки за последние семь дней')
|
||||
if meta.get('source_freshness') == 'mixed_legacy_cache':
|
||||
warnings.append('Смешанная выгрузка: редакции фрагментов могут различаться')
|
||||
kind = resource['kind']
|
||||
if kind == 'code' and (resource.get('entry', {}).get('slug', '').startswith('fz-') or resource.get('entry', {}).get('slug') == 'zozpp'):
|
||||
kind = 'federal-law'
|
||||
units = [x for x in headings if x['kind'] in {'article', 'point'}]
|
||||
loaded = sum(not re.search(r'(?i)НЕ СКАЧАН|текст статьи отсутствует', x['text']) for x in units)
|
||||
return {'id': resource['id'], 'title': title, 'subject': subject, 'kind': kind, 'source_url': resource['url'],
|
||||
'revision': meta.get('дата_редакции'), 'act_date': act_date,
|
||||
'number': number, 'last_checked': checked,
|
||||
'retrieved_at': meta.get('дата_выгрузки') or meta.get('retrieved_at'),
|
||||
'effective_date': None, 'available': bool(body), 'integrity': integrity,
|
||||
'coverage': {'status': status if body else 'missing', 'loaded': loaded, 'total': len(units) or None,
|
||||
'scope': f'Только глава {scope}' if scope else None}, 'warnings': warnings, 'update': {}}
|
||||
|
||||
def _save_version(self, conn, resource, raw, *, current=False):
|
||||
try:
|
||||
_, meta, body, integrity = self._read(resource, raw)
|
||||
except (ValueError, UnicodeError, OSError):
|
||||
return
|
||||
# Keep snapshots even when old integrity metadata is absent; disclose it.
|
||||
# A snapshot id must retain whitespace-only revisions: diff() reports
|
||||
# those as formatting changes instead of silently deduplicating them.
|
||||
version_id = hashlib.sha256((resource['id'] + '\n' + body + '\n' + str(meta.get('дата_редакции', ''))).encode()).hexdigest()
|
||||
details = {'id': version_id, 'revision': meta.get('дата_редакции'),
|
||||
'retrieved_at': meta.get('дата_выгрузки') or meta.get('retrieved_at'),
|
||||
'effective_date': None, 'source_url': resource['url'], 'integrity': integrity}
|
||||
conn.execute('INSERT OR IGNORE INTO versions VALUES(?,?,?,?,?)',
|
||||
(version_id, resource['id'], zlib.compress(raw), json.dumps(details, ensure_ascii=False), stamp()))
|
||||
return version_id
|
||||
|
||||
def refresh(self):
|
||||
if not self.lock.acquire(blocking=False):
|
||||
return False
|
||||
try:
|
||||
resources = [r for r in corpus_registry.registry(self.root) if r['kind'] != 'catalog']
|
||||
stats = []
|
||||
for r in resources:
|
||||
try:
|
||||
p = legal_graph._source_path(self.root, r['output'])
|
||||
st = p.stat()
|
||||
stats.append((r, st.st_size, st.st_mtime_ns))
|
||||
except OSError:
|
||||
stats.append((r, None))
|
||||
signature = hashlib.sha256(json.dumps(stats, sort_keys=True).encode()).hexdigest()
|
||||
if signature == self.signature:
|
||||
return False
|
||||
view = {}
|
||||
with self.connect() as conn:
|
||||
conn.execute('DELETE FROM search')
|
||||
for resource in resources:
|
||||
raw, meta, body, integrity = b'', {}, '', False
|
||||
try:
|
||||
raw, meta, body, integrity = self._read(resource)
|
||||
except (OSError, ValueError, UnicodeError) as exc:
|
||||
problem = str(exc) if not isinstance(exc, FileNotFoundError) else 'Рабочая копия пока отсутствует'
|
||||
else:
|
||||
problem = None
|
||||
summary = self._summary(resource, meta, body, integrity)
|
||||
if problem:
|
||||
summary['warnings'].append(problem)
|
||||
parts = fragments(resource['id'], body) if body else []
|
||||
version_id = self._save_version(conn, resource, raw, current=True) if raw else None
|
||||
# Import only backups for this exact registered output; never cases/.
|
||||
output = Path(resource['output'])
|
||||
job = self.root / '.agent/maintenance/background/jobs' / hashlib.sha256(resource['id'].encode()).hexdigest()
|
||||
archives = list((job / 'backups' / output.stem).glob('*.md'))
|
||||
archives += list((self.root / 'knowledge/_corpus_archive').glob('*/' + output.name))
|
||||
for archive in archives:
|
||||
if archive.is_symlink() or archive.stat().st_size > legal_graph.MAX_DOCUMENT_BYTES:
|
||||
continue
|
||||
self._save_version(conn, resource, archive.read_bytes())
|
||||
aliases = ' '.join(k for k, v in CODE_SLUGS.items() if v == output.stem)
|
||||
search_title = ' '.join(str(x or '') for x in (summary['title'], summary['number'], summary['act_date']))
|
||||
if not parts:
|
||||
parts_for_index = [{'id': legal_graph._graph_id(resource['id']), 'label': summary['title'], 'text': ''}]
|
||||
else:
|
||||
parts_for_index = parts
|
||||
conn.executemany('INSERT INTO search VALUES(?,?,?,?,?,?)',
|
||||
[(resource['id'], p['id'], search_title, p['label'], p['text'], aliases) for p in parts_for_index])
|
||||
view[resource['id']] = {'document': summary, 'body': body, 'fragments': parts,
|
||||
'resource': resource, 'version_id': version_id}
|
||||
self.documents = view
|
||||
self.signature = signature
|
||||
self.indexed_at = stamp()
|
||||
self.error = None
|
||||
return True
|
||||
except Exception as exc:
|
||||
self.error = f'Индекс: {type(exc).__name__}: {exc}'
|
||||
return False
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
def summaries(self):
|
||||
try:
|
||||
jobs = {j['id']: j for j in background_corpus.status(self.root)['jobs']}
|
||||
except Exception:
|
||||
jobs = {}
|
||||
return [{**v['document'], 'update': jobs.get(k, {})} for k, v in self.documents.items()]
|
||||
|
||||
def document(self, resource_id):
|
||||
item = self.documents.get(resource_id)
|
||||
if not item:
|
||||
raise KeyError('Документ не зарегистрирован')
|
||||
return {k: v for k, v in item.items() if k in {'document', 'body', 'fragments'}}
|
||||
|
||||
def resolve_fragment(self, resource_id, location=''):
|
||||
"""Resolve an opaque part/anchor ID to its containing fragment."""
|
||||
item = self.documents.get(resource_id)
|
||||
if not item:
|
||||
raise KeyError('Документ не зарегистрирован')
|
||||
if not location:
|
||||
return None, None
|
||||
for part in item['fragments']:
|
||||
if part['id'] == location:
|
||||
return part, part['id']
|
||||
if any(anchor.get('id') == location for anchor in part.get('anchors', [])):
|
||||
return part, location
|
||||
return None, None
|
||||
|
||||
def reader_location(self, resource_id, label, source_location=''):
|
||||
"""Resolve a graph label to one exact part or numbered anchor.
|
||||
|
||||
A bare duplicated point number is intentionally rejected. ``L123``
|
||||
refers to the source line and is used only to disambiguate candidates.
|
||||
"""
|
||||
item = self.documents.get(resource_id)
|
||||
if not item:
|
||||
raise KeyError('Документ не зарегистрирован')
|
||||
wanted = str(label or '').strip()
|
||||
article_match = re.fullmatch(r'(?i)\s*(?:статья|ст\.)\s*(\d+(?:\.\d+)*)\.?\s*.*', wanted)
|
||||
if article_match:
|
||||
number = article_match[1].replace('.', '_')
|
||||
candidates = [p for p in item['fragments'] if p['id'].endswith(f'_article_{number}')]
|
||||
return candidates[0]['id'] if len(candidates) == 1 else None
|
||||
point_match = re.fullmatch(r'(?i)\s*(?:пункт|п\.)?\s*(\d+(?:\.\d+)*)\.?\s*.*', wanted)
|
||||
if not point_match:
|
||||
return None
|
||||
number = point_match[1].replace('.', '_')
|
||||
part_candidates = [p for p in item['fragments']
|
||||
if p['kind'] == 'point' and re.search(
|
||||
rf'(?i)^(?:пункт|п\.)\s*{re.escape(point_match[1])}(?:\.|\s|$)', p['label'])]
|
||||
if len(part_candidates) == 1:
|
||||
return part_candidates[0]['id']
|
||||
candidates = [
|
||||
(part, anchor) for part in item['fragments']
|
||||
for anchor in part.get('anchors', [])
|
||||
if anchor.get('number', '').replace('.', '_') == number
|
||||
]
|
||||
if len(candidates) == 1:
|
||||
return candidates[0][1]['id']
|
||||
if source_location:
|
||||
line_match = re.search(r'(?i)L(\d+)', str(source_location))
|
||||
if not line_match:
|
||||
return None
|
||||
line = int(line_match[1])
|
||||
newline_offsets = item.get('_newline_offsets')
|
||||
if newline_offsets is None:
|
||||
newline_offsets = [match.start() for match in re.finditer('\\n', item['body'])]
|
||||
item['_newline_offsets'] = newline_offsets
|
||||
candidates = [(part, anchor) for part, anchor in candidates
|
||||
if bisect_left(newline_offsets, anchor.get('body_offset', anchor['offset'])) + 1 == line]
|
||||
if len(candidates) != 1:
|
||||
return None
|
||||
return candidates[0][1]['id']
|
||||
|
||||
def reader(self, resource_id, fragment=''):
|
||||
"""Компактный reader payload: оглавление и один фрагмент по запросу.
|
||||
|
||||
``document`` сохраняет прежний payload для совместимости. Reader нужен
|
||||
UI для больших кодексов: повторная выдача всего текста не требуется при
|
||||
переходе к статье.
|
||||
"""
|
||||
item = self.documents.get(resource_id)
|
||||
if not item:
|
||||
raise KeyError('Документ не зарегистрирован')
|
||||
parts = item['fragments']
|
||||
toc = []
|
||||
for part in parts:
|
||||
entry = {k: part[k] for k in ('id', 'label', 'kind') if k in part}
|
||||
entry['anchors'] = [
|
||||
{k: anchor[k] for k in ('id', 'label') if k in anchor}
|
||||
for anchor in part.get('anchors', [])
|
||||
]
|
||||
toc.append(entry)
|
||||
selected, selected_id = self.resolve_fragment(resource_id, fragment)
|
||||
if not fragment and parts:
|
||||
selected, selected_id = parts[0], parts[0]['id']
|
||||
return {'document': item['document'], 'toc': toc,
|
||||
'fragment': selected, 'selected_id': selected_id}
|
||||
|
||||
def search(self, query, kind='', limit=80):
|
||||
if len(query) > 500:
|
||||
raise ValueError('Запрос длиннее 500 символов')
|
||||
# Quoted phrases stay phrases. Everything else is a literal token, never FTS syntax.
|
||||
terms = re.findall(r'"([^"]+)"|([\w.-]+)', query.lower().replace('ё', 'е'))
|
||||
tokens = [a or b for a, b in terms]
|
||||
tokens = [{'ст.': 'статья', 'ст': 'статья', 'п.': 'пункт', 'п': 'пункт'}.get(t, t) for t in tokens]
|
||||
tokens = [t for t in tokens if t not in {'рф', 'от', '№', 'n'}]
|
||||
if not tokens:
|
||||
return {'results': [], 'total': 0}
|
||||
expression = ' AND '.join('"' + t.replace('"', '""') + '"' for t in tokens)
|
||||
with self.connect() as conn:
|
||||
rows = conn.execute('SELECT resource_id,fragment_id,title,label,body,bm25(search,0,0,5,8,1,6) AS rank FROM search WHERE search MATCH ? ORDER BY rank LIMIT 1500', (expression,)).fetchall()
|
||||
results = []
|
||||
for row in rows:
|
||||
item = self.documents.get(row['resource_id'])
|
||||
if not item or (kind and item['document']['kind'] != kind):
|
||||
continue
|
||||
doc = item['document']
|
||||
body = row['body']
|
||||
body_lower = body.lower()
|
||||
positions = [body_lower.find(t) for t in tokens if body_lower.find(t) >= 0]
|
||||
start = max(0, min(positions or [0]) - 90)
|
||||
excerpt = body[start:start + 380]
|
||||
results.append({'resource_id': doc['id'], 'document': doc['title'], 'title': doc['title'],
|
||||
'id': row['fragment_id'], 'label': row['label'], 'kind': doc['kind'],
|
||||
'text': excerpt, 'snippet': excerpt, 'revision': doc['revision'],
|
||||
'warnings': doc['warnings'], 'source_url': doc['source_url']})
|
||||
return {'results': results[:limit], 'total': len(results)}
|
||||
|
||||
def history(self, resource_id):
|
||||
item = self.documents.get(resource_id)
|
||||
if not item:
|
||||
raise KeyError('Документ не зарегистрирован')
|
||||
with self.connect() as conn:
|
||||
rows = conn.execute('SELECT id,meta,observed_at FROM versions WHERE resource_id=? ORDER BY observed_at,id', (resource_id,)).fetchall()
|
||||
versions = [{**json.loads(r['meta']), 'observed_at': r['observed_at'], 'current': r['id'] == item['version_id']} for r in rows]
|
||||
def date_key(v):
|
||||
value = v.get('retrieved_at') or v['observed_at']
|
||||
try:
|
||||
return datetime.strptime(value, '%d.%m.%Y').isoformat()
|
||||
except ValueError:
|
||||
return value
|
||||
versions.sort(key=date_key)
|
||||
return {'versions': versions, 'observation_started': min((v['observed_at'] for v in versions), default=None),
|
||||
'note': 'Показаны только доступные копии. Дата получения не означает вступление изменений в силу. Разница текстов сама по себе не подтверждает изменение закона.'}
|
||||
|
||||
def diff(self, resource_id, before, after, fragment=''):
|
||||
item = self.documents.get(resource_id)
|
||||
if not item:
|
||||
raise KeyError('Документ не зарегистрирован')
|
||||
with self.connect() as conn:
|
||||
rows = [conn.execute('SELECT raw,meta FROM versions WHERE resource_id=? AND id=?', (resource_id, v)).fetchone() for v in (before, after)]
|
||||
if not all(rows):
|
||||
raise KeyError('Снимок не найден')
|
||||
bodies = [legal_graph._frontmatter(zlib.decompress(r['raw']))[1] for r in rows]
|
||||
parts = [{p['id']: p for p in fragments(resource_id, b)} for b in bodies]
|
||||
changes = []
|
||||
for key in dict.fromkeys([*parts[0], *parts[1]]):
|
||||
old, new = parts[0].get(key), parts[1].get(key)
|
||||
if fragment:
|
||||
selector = fragment.lower()
|
||||
label = (new or old)['label'].lower()
|
||||
selector_match = selector in key.lower() or selector in label
|
||||
match = re.fullmatch(r'(article|point|heading):([\d._-]+)', selector)
|
||||
if match:
|
||||
number = match[2].replace('.', '_').replace('-', '_')
|
||||
selector_match = selector_match or bool(re.search(rf'_{match[1]}_{re.escape(number)}(?:_|$)', key.lower()))
|
||||
if match[1] == 'article':
|
||||
selector_match = selector_match or bool(re.search(rf'(?i)\bСтатья\s+{re.escape(match[2])}(?:\.|\s|$)', (old or {}).get('text', '') + '\n' + (new or {}).get('text', '')))
|
||||
elif match[1] == 'point':
|
||||
selector_match = selector_match or bool(re.search(rf'(?i)\b(?:Пункт|п\.)\s*{re.escape(match[2])}(?:\.|\s|$)', (old or {}).get('text', '') + '\n' + (new or {}).get('text', '')))
|
||||
if not selector_match:
|
||||
continue
|
||||
a, b = old['text'] if old else '', new['text'] if new else ''
|
||||
if normalized(a) == normalized(b):
|
||||
continue
|
||||
changes.append({'id': key, 'label': (new or old)['label'], 'kind': 'added' if not old else 'removed' if not new else 'changed',
|
||||
'before': a, 'after': b,
|
||||
'lines': list(difflib.unified_diff(a.splitlines(), b.splitlines(), lineterm=''))})
|
||||
return {'changes': changes, 'before': json.loads(rows[0]['meta']), 'after': json.loads(rows[1]['meta']),
|
||||
'formatting_only': bodies[0] != bodies[1] and normalized(bodies[0]) == normalized(bodies[1]),
|
||||
'note': 'Сравнение локальных копий. Дата, когда происходит вступление изменений в силу, и сам текст требуют сверки с актом, который внёс изменения.'}
|
||||
@@ -0,0 +1,100 @@
|
||||
{
|
||||
"version": 1,
|
||||
"about": "Отрасли судебной практики Эвномии. Подкатегория: предмет требования (claims ищутся в 300 знаках после слов «иск», «с заявлением», «по заявлению», «обратился в суд» в первых 6000 знаках акта; фон («после расторжения брака», «свидетельство об установлении отцовства») требованием не считается) или не меньше min_articles статей перечисленных глав кодекса при не меньше min_code_articles статьях этого кодекса в акте. Главы и их статьи читаются из текста кодекса в корпусе. Отрасль собирает акты своих подкатегорий любого производства. Решение владельца 01.10.2026: деление по отраслям, граф отрасли малый, подкатегории дают пересечения.",
|
||||
"areas": [
|
||||
{
|
||||
"id": "family",
|
||||
"title": "Семейные споры",
|
||||
"code": "sk-rf",
|
||||
"min_code_articles": 4,
|
||||
"min_articles": 2,
|
||||
"children": [
|
||||
{
|
||||
"id": "family-children",
|
||||
"title": "Споры о детях",
|
||||
"chapters": [
|
||||
"Глава 11",
|
||||
"Глава 12"
|
||||
],
|
||||
"claims": [
|
||||
"\\bоб?\\s+определении\\s+(?:места\\s+жительства|порядка\\s+(?:общения|участия))",
|
||||
"\\bо\\s+(?:лишении|ограничении)\\s+родительск",
|
||||
"\\bо\\s+восстановлении\\s+в\\s+родительск",
|
||||
"\\bоб?\\s+(?:отобрании|возврате|передаче)\\s+(?:\\w+\\s+){0,2}(?:ребен|детей|несовершеннолетн|малолетн)",
|
||||
"\\bоб?\\s+устранении\\s+препятствий\\s+в\\s+общении"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "family-alimony",
|
||||
"title": "Алименты",
|
||||
"chapters": [
|
||||
"Глава 13",
|
||||
"Глава 14",
|
||||
"Глава 15",
|
||||
"Глава 16",
|
||||
"Глава 17"
|
||||
],
|
||||
"claims": [
|
||||
"\\bоб?\\s+(?:взыскании|изменении|уменьшении|увеличении|освобождении|прекращении|расчете|перерасчете|определении|снижении)\\s+(?:\\w+\\s+){0,4}алимент",
|
||||
"задолженност\\w+\\s+по\\s+алимент",
|
||||
"взыска\\w+\\s+алимент"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "family-property",
|
||||
"title": "Раздел имущества супругов",
|
||||
"chapters": [
|
||||
"Глава 7",
|
||||
"Глава 8",
|
||||
"Глава 9"
|
||||
],
|
||||
"claims": [
|
||||
"\\bо\\s+(?:разделе|выделе)\\s+(?:\\w+\\s+){0,2}(?:совместно\\s+нажит|общ\\w+|супружеск|имуществ\\w+\\s+супруг)",
|
||||
"\\bо\\s+признании\\s+(?:\\w+\\s+){0,2}(?:совместно\\s+нажит|общ\\w+\\s+совместн\\w+\\s+собственност)",
|
||||
"\\bо\\s+(?:\\w+\\s+){0,2}брачн\\w+\\s+договор"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "family-marriage",
|
||||
"title": "Расторжение и недействительность брака",
|
||||
"chapters": [
|
||||
"Глава 3",
|
||||
"Глава 4",
|
||||
"Глава 5"
|
||||
],
|
||||
"claims": [
|
||||
"\\bо\\s+расторжении\\s+брака",
|
||||
"\\bо\\s+признании\\s+брака\\s+недействительн"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "family-origin",
|
||||
"title": "Отцовство и материнство",
|
||||
"chapters": [
|
||||
"Глава 10"
|
||||
],
|
||||
"claims": [
|
||||
"(?<!свидетельству )(?<!свидетельства )(?<!свидетельство )(?<!суда )\\bоб?\\s+(?:установлении|оспаривании)\\s+(?:факта\\s+признания\\s+)?(?:отцовства|материнства)",
|
||||
"\\bоб?\\s+исключении\\s+сведений\\s+об\\s+отце"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "family-guardianship",
|
||||
"title": "Усыновление, опека, приемная семья",
|
||||
"chapters": [
|
||||
"Глава 18",
|
||||
"Глава 19",
|
||||
"Глава 20",
|
||||
"Глава 21",
|
||||
"Глава 22"
|
||||
],
|
||||
"claims": [
|
||||
"\\bоб?\\s+(?:отмене\\s+)?(?:усыновлени|удочерени)",
|
||||
"(?:установлени|прекращени)\\w*\\s+опек\\w*\\s+(?:и\\s+попечительства\\s+)?над\\s+(?:\\w+\\s+){0,2}(?:ребен|детьми|детей|несовершеннолетн|малолетн)",
|
||||
"(?:назначени|освобождени|отстранени)\\w*\\s+(?:\\w+\\s+)?опекун\\w*\\s+(?:\\w+\\s+){0,3}(?:ребен|детей|несовершеннолетн|малолетн)"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Индекс права: норма -> акты, норма -> соседи, тема -> нормы. Только stdlib sqlite3.
|
||||
|
||||
build() предрассчитывает таблицы из СудАкта, снимка legal_graph и practice_taxonomy.json.
|
||||
Материалы дел в индекс не идут. query() держит соединение и соседей в памяти процесса.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import cite # noqa: E402
|
||||
|
||||
DEFAULT_INDEX = ROOT / ".agent/maintenance/pravo-index/pravo.sqlite3"
|
||||
PRACTICE = ROOT / ".agent/maintenance/practice/practice.sqlite3"
|
||||
SNAPSHOTS = ROOT / ".agent/maintenance/legal-graph/snapshots"
|
||||
TAXONOMY = ROOT / "eunomia/practice_taxonomy.json"
|
||||
|
||||
RECENT_SQL = ("SELECT act_date, number, court, title, act_id FROM norm_acts "
|
||||
"WHERE code=? AND article=? ORDER BY act_date DESC LIMIT ?")
|
||||
RECENT_SQL_EXPLAIN = "EXPLAIN QUERY PLAN " + RECENT_SQL
|
||||
|
||||
|
||||
def latest_snapshot(snaps: Path = SNAPSHOTS) -> Path:
|
||||
return max((p for p in snaps.iterdir() if (p / "search.sqlite3").exists()), key=lambda p: p.name)
|
||||
|
||||
|
||||
def build(practice: Path = PRACTICE, snapshot: Path | None = None,
|
||||
taxonomy: Path = TAXONOMY, out: Path = DEFAULT_INDEX) -> Path:
|
||||
snapshot = snapshot or latest_snapshot()
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = out.with_suffix(".tmp")
|
||||
tmp.unlink(missing_ok=True)
|
||||
db = sqlite3.connect(tmp, uri=True)
|
||||
db.executescript("""
|
||||
CREATE TABLE norm_acts (code TEXT, article TEXT, act_date TEXT, act_id INTEGER,
|
||||
number TEXT, court TEXT, title TEXT);
|
||||
CREATE TABLE norm_links (src TEXT, dst TEXT, label TEXT);
|
||||
CREATE TABLE topic_norms (topic TEXT, code TEXT, chapter TEXT);
|
||||
""")
|
||||
db.execute("ATTACH DATABASE ? AS p", (practice.resolve().as_uri() + "?mode=ro",))
|
||||
db.execute("""INSERT INTO norm_acts SELECT r.code, r.article, a.act_date, a.id, a.number,
|
||||
a.court, a.title FROM p.refs r JOIN p.acts a ON a.id = r.act
|
||||
WHERE a.removed_at IS NULL""")
|
||||
db.commit()
|
||||
db.execute("DETACH DATABASE p")
|
||||
db.execute("ATTACH DATABASE ? AS g", ((snapshot / "search.sqlite3").resolve().as_uri() + "?mode=ro",))
|
||||
# ребра references идут и от пунктов: сворачиваем источник до статьи
|
||||
db.execute("""INSERT INTO norm_links
|
||||
SELECT CASE WHEN instr(e.source, ':point:') > 0
|
||||
THEN substr(e.source, 1, instr(e.source, ':point:') - 1) ELSE e.source END,
|
||||
e.target, n.label
|
||||
FROM g.edges e JOIN g.nodes n ON n.id = e.target WHERE e.relation = 'references'""")
|
||||
db.commit()
|
||||
db.execute("DETACH DATABASE g")
|
||||
for area in json.loads(taxonomy.read_text(encoding="utf-8")).get("areas", []):
|
||||
for ch in area.get("children", []):
|
||||
db.executemany("INSERT INTO topic_norms VALUES (?,?,?)",
|
||||
[(ch["id"], area["code"], c) for c in ch.get("chapters", [])])
|
||||
db.executescript("""
|
||||
CREATE INDEX norm_acts_idx ON norm_acts(code, article, act_date);
|
||||
CREATE INDEX norm_links_src ON norm_links(src);
|
||||
CREATE INDEX topic_norms_topic ON topic_norms(topic);
|
||||
ANALYZE;
|
||||
""")
|
||||
db.commit()
|
||||
db.close()
|
||||
tmp.replace(out)
|
||||
return out
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def _open(index: str) -> tuple[sqlite3.Connection, dict]:
|
||||
db = sqlite3.connect(Path(index).resolve().as_uri() + "?mode=ro", uri=True, check_same_thread=False)
|
||||
links: dict[str, list[str]] = {}
|
||||
for src, label in db.execute("SELECT src, label FROM norm_links"):
|
||||
links.setdefault(src, []).append(label)
|
||||
return db, links
|
||||
|
||||
|
||||
def query(norm: str, limit: int = 10, index: Path = DEFAULT_INDEX) -> dict:
|
||||
"""Текст нормы (cite.resolve), свежие акты по статье, соседние нормы."""
|
||||
res = cite.resolve(norm)
|
||||
out = {"query": norm, "found": bool(res.get("found")), "text": res.get("text"),
|
||||
"cite_tag": res.get("cite_tag"), "acts": [], "neighbors": []}
|
||||
m = cite.ARTICLE_QUERY_RE.search(norm)
|
||||
if not (out["found"] and m and res.get("file")):
|
||||
return out
|
||||
code, article = Path(res["file"]).stem, m.group(1)
|
||||
db, links = _open(str(index))
|
||||
out["acts"] = [dict(zip(("date", "number", "court", "title", "id"), r))
|
||||
for r in db.execute(RECENT_SQL, (code, article, limit))]
|
||||
out["neighbors"] = [{"label": lb} for lb in
|
||||
links.get(f"doc:legal-corpus:code:{code}:article:{article}", [])]
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(build())
|
||||
@@ -0,0 +1,506 @@
|
||||
"""Loopback-only HTTP surface. Network updates belong to background_corpus."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import secrets
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import background_corpus
|
||||
import legal_graph
|
||||
from eunomia.library import Library, stamp
|
||||
from eunomia.graph_view import GraphViewCache
|
||||
from eunomia.practice import Practice, PracticeError, progress, request_walk, walk
|
||||
|
||||
CODE_ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = Path(__file__).parent / 'web'
|
||||
# Карточки «Состояние базы» опрашивают полосы раз в 5 с; подсчет СудАкта по диску идет до 0,5 с.
|
||||
CACHE_SECONDS = 5
|
||||
SPEED_WINDOW = 600 # скорость очереди законов - за 10 минут, как у СудАкта
|
||||
# Расписание сверено с кодом 03.10.2026: background_corpus повторно проверяет документ, когда его last_checked
|
||||
# старше 7 суток (_enqueue_validated), задача частей обходит СудАкт раз в сутки (practice.next_day).
|
||||
LAW_DAYS, PRACTICE_DAYS = 7, 1
|
||||
SHOWN = 5 # пунктов недостачи на карточке: остальное - числом
|
||||
REASONS = (('job превысил', 'проверка не уложилась в срок задания, повтор позже'),
|
||||
('deadline exhausted', 'не хватило времени проверки, повтор позже'),
|
||||
('generic candidate failed', 'разбор документа не прошел, повтор позже'),
|
||||
('source body too short', 'источник отдал пустую страницу, повтор позже'),
|
||||
('review_parser_not_verified', 'разборщик обзоров не принят'),
|
||||
('worker не запустился', 'обработчик не запустился, повтор позже'))
|
||||
STATES = {'queued': 'ждет очереди', 'running': 'проверяется сейчас', 'deferred': 'повтор позже',
|
||||
'blocked': 'источник недоступен', 'failed': 'ошибка проверки'}
|
||||
|
||||
|
||||
def _moment(value):
|
||||
try:
|
||||
moment = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
return None
|
||||
return moment if moment.tzinfo else moment.replace(tzinfo=UTC)
|
||||
|
||||
|
||||
def _day(moment):
|
||||
return moment.astimezone().strftime('%d.%m.%Y')
|
||||
|
||||
|
||||
def _plural(n, one, few, many):
|
||||
return one if n % 10 == 1 and n % 100 != 11 else few if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14 else many
|
||||
|
||||
|
||||
def law_freshness(jobs, titles, now=None):
|
||||
"""Отметка законов (решение владельца 03.10.2026): «Корпус полный · актуально на ДД.ММ.ГГГГ», если каждый
|
||||
документ очереди в состоянии current или updated и проверен не раньше 7 суток назад; дата - самой старой
|
||||
проверки. Иначе - сколько и какие не готовы, с причиной."""
|
||||
now = now or datetime.now(UTC)
|
||||
missing, oldest = [], None
|
||||
for job in jobs:
|
||||
checked = _moment(job.get('last_checked')) if job.get('last_checked') else None
|
||||
if (job.get('state') in ('current', 'updated') and checked
|
||||
and now - timedelta(days=LAW_DAYS) <= checked <= now + timedelta(minutes=5)):
|
||||
oldest = min(oldest or checked, checked)
|
||||
continue
|
||||
detail = str(job.get('detail') or '')
|
||||
reason = next((text for mark, text in REASONS if mark in detail), None)
|
||||
if reason is None and job.get('state') in ('current', 'updated'):
|
||||
reason = f'проверен {_day(checked)}, больше недели назад' if checked else 'дата проверки неизвестна'
|
||||
reason = reason or STATES.get(job.get('state'), str(job.get('state'))) + (f': {detail[:80]}' if detail else '')
|
||||
missing.append({'id': job['id'], 'title': titles.get(job['id']) or job['id'].rsplit(':', 1)[-1],
|
||||
'reason': reason})
|
||||
if jobs and not missing:
|
||||
return {'full': True, 'label': f'Корпус полный · актуально на {_day(oldest)}', 'as_of': _day(oldest),
|
||||
'missing': [], 'interval_days': LAW_DAYS}
|
||||
label = (f"Корпус неполный: не {_plural(len(missing), 'готов', 'готовы', 'готовы')} {len(missing)} "
|
||||
f"{_plural(len(missing), 'документ', 'документа', 'документов')} из {len(jobs)}"
|
||||
if jobs else 'Корпус пуст: очередь не заполнена')
|
||||
return {'full': False, 'label': label, 'as_of': None, 'missing': missing, 'interval_days': LAW_DAYS}
|
||||
|
||||
|
||||
def practice_freshness(value, now=None):
|
||||
"""Отметка практики (решение владельца 03.10.2026): «Актуально на сегодня», если ежедневный обход СудАкта
|
||||
закончился сегодня по часам Mac и новых актов к докачке нет. Иначе - почему нет."""
|
||||
walk, today = value.get('walk') or {}, (now or datetime.now(UTC)).astimezone().date()
|
||||
left, at = max(value.get('total', 0) - value.get('done', 0), 0), _moment(walk.get('at')) if walk.get('at') else None
|
||||
if walk.get('stopped'):
|
||||
label = f"Не актуально: обход остановлен ({walk['stopped']})"
|
||||
elif walk.get('running'):
|
||||
label = 'Не актуально: идет обход СудАкта'
|
||||
elif left:
|
||||
label = f"Не актуально: не {_plural(left, 'скачан', 'скачаны', 'скачаны')} {left:,} {_plural(left, 'акт', 'акта', 'актов')}".replace(',', ' ')
|
||||
elif at is None:
|
||||
label = 'Не актуально: обхода СудАкта еще не было'
|
||||
elif at.astimezone().date() != today:
|
||||
label = f'Не актуально: последний обход {_day(at)}, сегодняшний еще не прошел'
|
||||
else:
|
||||
return {'fresh': True, 'label': 'Актуально на сегодня', 'as_of': _day(at), 'interval_days': PRACTICE_DAYS}
|
||||
return {'fresh': False, 'label': label, 'as_of': _day(at) if at else None, 'interval_days': PRACTICE_DAYS}
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, root):
|
||||
self.root = Path(root).resolve()
|
||||
self.library = Library(root)
|
||||
self.csrf = secrets.token_urlsafe(32)
|
||||
self.actions_lock = threading.Lock()
|
||||
self.processes = {}
|
||||
self.action_results = {}
|
||||
self.graph_views = GraphViewCache(self.root)
|
||||
self.practice = Practice(self.root, self.library)
|
||||
self.cache, self.cache_lock = {}, threading.Lock()
|
||||
self.graph_views.ensure()
|
||||
|
||||
def cached(self, key, build):
|
||||
"""Один подсчет на CACHE_SECONDS, сколько бы вкладок ни опрашивало полосу."""
|
||||
with self.cache_lock:
|
||||
at, value = self.cache.get(key, (0.0, None))
|
||||
if value is None or time.monotonic() - at >= CACHE_SECONDS:
|
||||
value = build()
|
||||
self.cache[key] = (time.monotonic(), value)
|
||||
return value
|
||||
|
||||
def practice_progress(self):
|
||||
try:
|
||||
value = progress(self.root)
|
||||
except Exception: # карты или индекса Lynceuz еще нет: полоса честно пустая
|
||||
value = {'done': 0, 'total': 0, 'per_min': 0.0, 'eta_min': None, 'updated_at': stamp(),
|
||||
'error': 'Корпус СудАкта пока не скачан.'}
|
||||
value = {**value, 'walk': walk(self.root)}
|
||||
return {**value, 'freshness': practice_freshness(value)}
|
||||
|
||||
def law_progress(self):
|
||||
"""Полоса законов из очереди background_corpus.status(): готово - все, кроме queued и running.
|
||||
Отложенные и недоступные источники очередь не держат: их повторит обработчик, счет - в states."""
|
||||
queue, now = background_corpus.status(self.root), time.time()
|
||||
jobs = queue.get('jobs') or []
|
||||
left = sum(job.get('state') in ('queued', 'running') for job in jobs)
|
||||
recent = sum(isinstance(job.get('finished_at'), (int, float)) and now - job['finished_at'] <= SPEED_WINDOW
|
||||
for job in jobs)
|
||||
moved = max((job['updated_at'] for job in jobs if isinstance(job.get('updated_at'), (int, float))), default=0)
|
||||
per_min = recent * 60 / SPEED_WINDOW
|
||||
titles = {key: (item.get('document') or {}).get('title') for key, item in self.library.documents.items()}
|
||||
return {'done': len(jobs) - left, 'total': len(jobs), 'per_min': round(per_min, 1),
|
||||
'eta_min': 0 if not left else round(left / per_min) if per_min else None,
|
||||
'running': bool(left) and now - moved < SPEED_WINDOW, 'states': queue.get('queue') or {},
|
||||
'updated_at': stamp(), 'freshness': law_freshness(jobs, titles)}
|
||||
|
||||
def graph_page(self, params):
|
||||
status = self.graph_views.ensure()
|
||||
view = self.graph_views.get()
|
||||
if view is None:
|
||||
return {'nodes': [], 'edges': [], 'loading': status.get('loading', False), 'total': 0,
|
||||
'warnings': ['Снимок графа пока недоступен. Тексты и поиск продолжают работать.']}
|
||||
limit = max(1, min(60, int(params.get('limit', '40'))))
|
||||
if params.get('node_id'):
|
||||
value = view.ego(params['node_id'], limit=limit, offset=max(0, int(params.get('offset', '0'))))
|
||||
else:
|
||||
value = view.clustered(kind=params.get('kind'), query=params.get('q'),
|
||||
limit=limit, offset=max(0, int(params.get('offset', '0'))),
|
||||
resource_id=params.get('resource_id'))
|
||||
if not view.snapshot and not value.get('warnings'):
|
||||
value['warnings'] = ['Сохраненный снимок графа отсутствует. Тексты и поиск продолжают работать.']
|
||||
for node in value.get('nodes', []):
|
||||
doc = self.library.documents.get(node.get('resource_id'), {}).get('document', {})
|
||||
node['document_kind'] = doc.get('kind', node.get('document_kind'))
|
||||
node['document_title'] = doc.get('subject') or doc.get('title')
|
||||
node['document_number'] = doc.get('number')
|
||||
node['document_date'] = doc.get('act_date') or doc.get('date')
|
||||
node['reader_id'] = self.reader_id(node)
|
||||
return value
|
||||
|
||||
def graph_network(self, params):
|
||||
status = self.graph_views.ensure()
|
||||
view = self.graph_views.get()
|
||||
if view is None or (not self.library.documents and not self.library.indexed_at):
|
||||
return {'nodes': [], 'edges': [], 'loading': status.get('loading', False) or not self.library.indexed_at, 'total_nodes': 0,
|
||||
'total_edges': 0, 'displayed_nodes': 0, 'displayed_edges': 0, 'truncated': False,
|
||||
'warnings': ['Снимок графа пока недоступен.']}
|
||||
resource_id = params.get('resource_id', '')
|
||||
node_id = params.get('node_id', '')
|
||||
fragment = params.get('fragment', '')
|
||||
if not node_id and resource_id and fragment:
|
||||
if fragment in view.nodes and view.nodes[fragment].get('resource_id') == resource_id:
|
||||
node_id = fragment
|
||||
else:
|
||||
try:
|
||||
part, _ = self.library.resolve_fragment(resource_id, fragment)
|
||||
except (KeyError, TypeError):
|
||||
part = None
|
||||
if part:
|
||||
matches = [n for n in view.nodes.values()
|
||||
if n.get('resource_id') == resource_id and n.get('kind') == part.get('kind')
|
||||
and ((part.get('source_location') and n.get('source_location') == part.get('source_location'))
|
||||
or n.get('label') == part.get('label')
|
||||
or n.get('id', '').endswith(':' + part.get('id', '')))]
|
||||
if len(matches) == 1:
|
||||
node_id = matches[0]['id']
|
||||
if fragment != part.get('id'):
|
||||
points = [n for n in view.nodes.values()
|
||||
if n.get('resource_id') == resource_id
|
||||
and n.get('kind') == 'point'
|
||||
and n.get('id', '').startswith(node_id + ':')
|
||||
and self.reader_id(n) == fragment]
|
||||
node_id = points[0]['id'] if len(points) == 1 else '__unknown_fragment__'
|
||||
else:
|
||||
node_id = '__unknown_fragment__'
|
||||
else:
|
||||
node_id = '__unknown_fragment__'
|
||||
include_contains = str(params.get('include_contains', '1')).casefold() not in {'0', 'false', 'no'}
|
||||
try:
|
||||
limit = int(params.get('limit', '1000'))
|
||||
except (TypeError, ValueError):
|
||||
limit = 1000
|
||||
value = view.network(level=params.get('level', 'atoms'), query=params.get('q', ''),
|
||||
kind=params.get('kind', ''), resource_id=resource_id, node_id=node_id,
|
||||
include_contains=include_contains, max_nodes=limit, max_edges=5000)
|
||||
for node in value.get('nodes', []):
|
||||
doc = self.library.documents.get(node.get('resource_id'), {}).get('document', {})
|
||||
node['document_kind'] = doc.get('kind', node.get('document_kind'))
|
||||
node['document_title'] = doc.get('subject') or doc.get('title')
|
||||
node['document_number'] = doc.get('number')
|
||||
node['document_date'] = doc.get('act_date') or doc.get('date')
|
||||
node['reader_id'] = self.reader_id(node)
|
||||
return value
|
||||
|
||||
def reader_id(self, node):
|
||||
# Узел вне библиотеки (индекс практики practice:index) - без адреса для чтения, а не KeyError
|
||||
# и 404 на всю связь статьи (приемка практики 03.10.2026, ст. 333 ГК РФ).
|
||||
if node.get('kind') == 'document' or node.get('resource_id') not in self.library.documents:
|
||||
return ''
|
||||
nested = re.search(r':article:(\d+(?:\.\d+)*):point:(\d+(?:\.\d+)*)$', node.get('id', ''))
|
||||
if nested:
|
||||
item = self.library.documents.get(node.get('resource_id'), {})
|
||||
article_suffix = '_article_' + nested[1].replace('.', '_')
|
||||
anchors = [anchor for part in item.get('fragments', [])
|
||||
if part['id'].endswith(article_suffix)
|
||||
for anchor in part.get('anchors', [])
|
||||
if anchor.get('number') == nested[2]]
|
||||
if len(anchors) == 1:
|
||||
return anchors[0]['id']
|
||||
if anchors:
|
||||
# Articles can contain both 1. and 1). Match the stored text,
|
||||
# never guess between repeated numbers or a stale source line.
|
||||
label = re.sub(r'^(?:Пункт|п\.)\s*\d+(?:\.\d+)*[.\s]*', '', node.get('label', ''), flags=re.I)
|
||||
normalize = lambda text: ' '.join(text.split()).rstrip('. ')
|
||||
exact = []
|
||||
for part in item.get('fragments', []):
|
||||
if not part['id'].endswith(article_suffix):
|
||||
continue
|
||||
for anchor in anchors:
|
||||
line = part['text'][anchor['offset']:].lstrip().split('\n', 1)[0]
|
||||
text = re.sub(r'^\d+(?:\.\d+)*[.)]\s*', '', line)
|
||||
if normalize(text) == normalize(label):
|
||||
exact.append(anchor['id'])
|
||||
if len(exact) == 1:
|
||||
return exact[0]
|
||||
return self.library.reader_location(node.get('resource_id'), node.get('label', ''), node.get('source_location', ''))
|
||||
|
||||
def related_data(self, resource_id, fragment=''):
|
||||
status = self.graph_views.ensure()
|
||||
view = self.graph_views.get()
|
||||
if view is None:
|
||||
return {'related': [], 'loading': status.get('loading', False)}
|
||||
node_id = fragment if fragment in view.nodes else ''
|
||||
if fragment and not node_id:
|
||||
part, _ = self.library.resolve_fragment(resource_id, fragment)
|
||||
if part:
|
||||
label = part.get('label', '')
|
||||
if part.get('kind') == 'point':
|
||||
label = re.sub(r'^п\.\s*', 'Пункт ', label)
|
||||
found = view.find_node(resource_id, part.get('kind'), label)
|
||||
node_id = found.get('id', '') if found else ''
|
||||
if not node_id:
|
||||
return {'related': [], 'loading': False, 'note': 'Фрагмент отсутствует в графе.'}
|
||||
result = view.related(resource_id, node_id)
|
||||
for edge in result.get('related', []):
|
||||
for side in ('source_node', 'target_node'):
|
||||
node = edge.get(side, {})
|
||||
node['reader_id'] = self.reader_id(node)
|
||||
doc = self.library.documents.get(node.get('resource_id'), {}).get('document', {})
|
||||
node['document_title'] = doc.get('subject') or doc.get('title')
|
||||
result['loading'] = False
|
||||
result['node_id'] = node_id
|
||||
return result
|
||||
|
||||
def status(self):
|
||||
try:
|
||||
queue = background_corpus.status(self.root)
|
||||
except Exception as exc:
|
||||
queue = {'queue': {}, 'jobs': [], 'error': str(exc)}
|
||||
try:
|
||||
graph = legal_graph.status(self.root)
|
||||
except Exception as exc:
|
||||
graph = {'available': False, 'error': str(exc)}
|
||||
enabled = background_corpus.enabled(self.root)
|
||||
schedule_fn = getattr(background_corpus, 'schedule', None)
|
||||
try:
|
||||
schedule = schedule_fn(self.root) if schedule_fn else None
|
||||
except Exception:
|
||||
schedule = None
|
||||
schedule = schedule or {
|
||||
'enabled': enabled, 'interval_days': 7, 'next_run': None,
|
||||
'detail': 'Штатный обработчик Themiz проверяет очередь каждые 5 минут; каждый источник — раз в семь дней.' if enabled else 'Фоновое расписание Themiz не установлено. Ручные задания сохраняются в очереди.'}
|
||||
try:
|
||||
practice = self.practice.summary()
|
||||
except Exception as exc:
|
||||
practice = {'ready': False, 'error': type(exc).__name__}
|
||||
running = {}
|
||||
with self.actions_lock:
|
||||
for key, proc in self.processes.items():
|
||||
running[key] = {'running': proc.poll() is None, 'exit_code': proc.poll()}
|
||||
return {**queue, 'schedule': schedule, 'graph': graph, 'practice': practice, 'processes': running,
|
||||
'index': {'ready': bool(self.library.documents), 'indexing': self.library.lock.locked(),
|
||||
'indexed_at': self.library.indexed_at, 'error': self.library.error},
|
||||
'actions': self.action_results}
|
||||
|
||||
def _spawn(self, action):
|
||||
old = self.processes.get(action)
|
||||
if old and old.poll() is None:
|
||||
return False
|
||||
script, args = ('background_corpus.py', ['--tick']) if action == 'update' else ('legal_graph.py', ['--refresh', '--force', '--json'])
|
||||
# Detached from both HTTP worker and browser; original corpus lock arbitrates.
|
||||
log = self.library.state / (action + '.log')
|
||||
with log.open('ab') as output:
|
||||
proc = subprocess.Popen([sys.executable, str(CODE_ROOT / 'scripts' / script), '--root', str(self.root), *args],
|
||||
stdin=subprocess.DEVNULL, stdout=output, stderr=output,
|
||||
start_new_session=True, cwd=CODE_ROOT, close_fds=True)
|
||||
self.processes[action] = proc
|
||||
return True
|
||||
|
||||
def action(self, path, payload):
|
||||
with self.actions_lock:
|
||||
if path == '/api/update':
|
||||
resource_id = payload.get('id')
|
||||
if resource_id is not None and (not isinstance(resource_id, str) or resource_id not in self.library.documents):
|
||||
raise ValueError('Документ не зарегистрирован')
|
||||
if resource_id:
|
||||
jobs = [background_corpus.enqueue_id(self.root, resource_id, force=True)]
|
||||
else:
|
||||
jobs = background_corpus.enqueue_all(self.root, force=True)
|
||||
started = self._spawn('update')
|
||||
result = {'ok': True, 'jobs': jobs, 'started': started, 'detail': 'Задание сохранено в очереди Themiz.'}
|
||||
if not background_corpus.enabled(self.root):
|
||||
result['detail'] += ' Фоновый обработчик отключён: требуется штатная установка расписания.'
|
||||
with self.cache_lock: # подсчет, начатый до просьбы, не вернется в кеш
|
||||
self.cache.pop('law', None)
|
||||
elif path == '/api/practice/refresh': # сборку ведет задача частей, сервер только просит
|
||||
result = request_walk(self.root)
|
||||
result['detail'] = ('Обход СудАкта начнется в течение минуты.' if result['started']
|
||||
else 'Обход СудАкта уже идет.')
|
||||
with self.cache_lock: # подсчет, начатый до просьбы, не вернется в кеш
|
||||
self.cache.pop('practice', None)
|
||||
elif path == '/api/graph/rebuild':
|
||||
started = self._spawn('graph')
|
||||
result = {'ok': True, 'started': started, 'deduplicated': not started,
|
||||
'detail': 'Пересборка графа запущена.' if started else 'Граф уже собирается.'}
|
||||
else:
|
||||
raise KeyError('Маршрут не найден')
|
||||
self.action_results[path] = {'at': stamp(), 'detail': result['detail']}
|
||||
return result
|
||||
|
||||
|
||||
def handler(app):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = 'Eunomia'
|
||||
|
||||
def log_message(self, *_):
|
||||
pass # Queries and client questions must never enter access logs.
|
||||
|
||||
def allowed(self, write=False):
|
||||
expected = f'127.0.0.1:{self.server.server_port}'
|
||||
if self.headers.get('Host') != expected:
|
||||
return False
|
||||
origin = self.headers.get('Origin')
|
||||
if origin is not None and origin != 'http://' + expected:
|
||||
return False
|
||||
if self.headers.get('Sec-Fetch-Site') not in (None, 'none', 'same-origin'):
|
||||
return False
|
||||
if write:
|
||||
return (origin == 'http://' + expected
|
||||
and hmac.compare_digest(self.headers.get('X-Eunomia-CSRF', ''), app.csrf)
|
||||
and self.headers.get('Content-Type', '').split(';')[0] == 'application/json')
|
||||
return True
|
||||
|
||||
def respond(self, data, status=200, content_type='application/json; charset=utf-8'):
|
||||
raw = data if isinstance(data, bytes) else json.dumps(data, ensure_ascii=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', content_type)
|
||||
self.send_header('Content-Length', str(len(raw)))
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('X-Content-Type-Options', 'nosniff')
|
||||
self.send_header('Referrer-Policy', 'no-referrer')
|
||||
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'")
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def do_GET(self):
|
||||
if not self.allowed():
|
||||
return self.respond({'error': 'Недопустимый источник запроса'}, 403)
|
||||
parsed = urlsplit(self.path)
|
||||
params = {k: v[-1] for k, v in parse_qs(parsed.query).items()}
|
||||
try:
|
||||
if parsed.path == '/api/bootstrap':
|
||||
value = {'name': 'Eunomia', 'csrf': app.csrf, 'documents': app.library.summaries(), 'status': app.status()}
|
||||
elif parsed.path == '/api/status':
|
||||
value = app.status()
|
||||
elif parsed.path == '/api/document':
|
||||
value = app.library.document(params.get('id', ''))
|
||||
elif parsed.path == '/api/reader':
|
||||
value = app.library.reader(params.get('id', ''), params.get('fragment', ''))
|
||||
elif parsed.path == '/api/related':
|
||||
value = app.related_data(params.get('id', ''), params.get('fragment', ''))
|
||||
elif parsed.path == '/api/search':
|
||||
value = app.library.search(params.get('q', ''), params.get('kind', ''))
|
||||
elif parsed.path == '/api/practice':
|
||||
value = app.practice.browse(params)
|
||||
elif parsed.path == '/api/practice/facets':
|
||||
value = app.practice.facets()
|
||||
elif parsed.path == '/api/practice/act':
|
||||
value = app.practice.act(params.get('id', ''))
|
||||
elif parsed.path == '/api/practice/tree':
|
||||
value = app.practice.tree()
|
||||
elif parsed.path == '/api/practice/area':
|
||||
value = app.practice.area(params.get('id', ''))
|
||||
elif parsed.path == '/api/practice/norm':
|
||||
value = app.practice.norm(params.get('id', ''), params.get('fragment', ''))
|
||||
elif parsed.path == '/api/practice/progress':
|
||||
value = app.cached('practice', app.practice_progress)
|
||||
elif parsed.path == '/api/update/progress':
|
||||
value = app.cached('law', app.law_progress)
|
||||
elif parsed.path == '/api/graph':
|
||||
value = app.graph_page(params)
|
||||
elif parsed.path == '/api/graph/network':
|
||||
value = app.graph_network(params)
|
||||
elif parsed.path == '/api/history':
|
||||
value = app.library.history(params.get('id', ''))
|
||||
elif parsed.path == '/api/diff':
|
||||
value = app.library.diff(params.get('id', ''), params.get('before', ''), params.get('after', ''), params.get('fragment', ''))
|
||||
else:
|
||||
filename = {'/': 'index.html', '/index.html': 'index.html', '/app.js': 'app.js', '/graph.js': 'graph.js', '/codebook.png': 'codebook.png', '/styles.css': 'styles.css', '/polish.css': 'polish.css', '/favicon.svg': 'favicon.svg', '/eunomia-goddess.png': 'eunomia-goddess.png'}.get(parsed.path)
|
||||
if filename == 'index.html' and (WEB / 'dist/index.html').is_file():
|
||||
filename = 'dist/index.html'
|
||||
if re.fullmatch(r'/assets/(?:books/|pantheon/)?[A-Za-z0-9_-]+\.(?:png|webp|js|css|woff2)', parsed.path):
|
||||
relative = parsed.path.lstrip('/')
|
||||
filename = 'dist/' + relative if (WEB / 'dist' / relative).is_file() else relative
|
||||
target = (WEB / filename).resolve() if filename else None
|
||||
if target is None or not target.is_relative_to(WEB.resolve()) or not target.is_file():
|
||||
return self.respond({'error': 'Страница не найдена'}, 404)
|
||||
mime = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
if mime.startswith('text/') or mime in ('application/javascript', 'application/json'):
|
||||
mime += '; charset=utf-8'
|
||||
return self.respond(target.read_bytes(), content_type=mime)
|
||||
self.respond(value)
|
||||
except (KeyError, FileNotFoundError) as exc:
|
||||
self.respond({'error': str(exc)}, 404)
|
||||
except (ValueError, TypeError) as exc:
|
||||
self.respond({'error': str(exc)}, 400)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
pass
|
||||
except Exception:
|
||||
self.respond({'error': 'Компонент временно недоступен. Рабочие копии сохранены.'}, 503)
|
||||
|
||||
def do_POST(self):
|
||||
if not self.allowed(write=True):
|
||||
return self.respond({'error': 'Управляющий запрос отклонён'}, 403)
|
||||
try:
|
||||
length = int(self.headers.get('Content-Length', '0'))
|
||||
if not 0 < length <= 4096 or self.headers.get('Transfer-Encoding'):
|
||||
raise ValueError('Недопустимый размер запроса')
|
||||
self.connection.settimeout(5)
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
if not isinstance(payload, dict) or set(payload) - {'id'}:
|
||||
raise ValueError('Недопустимые параметры')
|
||||
self.respond(app.action(urlsplit(self.path).path, payload), 202)
|
||||
except PracticeError as exc: # части остановлены отказом СудАкта: просьба не поставлена
|
||||
self.respond({'error': str(exc)}, 409)
|
||||
except KeyError as exc:
|
||||
self.respond({'error': str(exc)}, 404)
|
||||
except (ValueError, TypeError) as exc:
|
||||
self.respond({'error': str(exc)}, 400)
|
||||
except Exception:
|
||||
self.respond({'error': 'Не удалось поставить задание. Рабочие копии сохранены.'}, 503)
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def serve(root, port=18765):
|
||||
app = App(root)
|
||||
server = ThreadingHTTPServer(('127.0.0.1', port), handler(app))
|
||||
server.daemon_threads = True
|
||||
|
||||
def indexing():
|
||||
while True:
|
||||
app.library.refresh()
|
||||
time.sleep(30)
|
||||
|
||||
threading.Thread(target=indexing, daemon=True, name='eunomia-index').start()
|
||||
print(f'http://127.0.0.1:{server.server_port}', flush=True)
|
||||
server.serve_forever()
|
||||
@@ -0,0 +1,82 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Загрузка практики СудАкта</title>
|
||||
<!-- Локальная страница загрузки: открывается как файл из .agent/maintenance/practice/status/.
|
||||
Каждые 5 с подгружает status.js рядом с собой; его раз в минуту пишет
|
||||
eunomia/practice.py publish. Скрипт, а не fetch: из file:// браузеры fetch запрещают. -->
|
||||
<style>
|
||||
:root { --text: #202824; --accent: #244B40; --track: #EDF4F0; --muted: #5B6660; --warn: #8A4B00; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: #fff;
|
||||
color: var(--text); font: 17px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
|
||||
main { width: 100%; max-width: 560px; }
|
||||
h1 { margin: 0; font-size: 17px; font-weight: 600; color: var(--muted); }
|
||||
#pct { margin: 8px 0 24px; font: 400 clamp(72px, 22vw, 128px)/1 Georgia, "Times New Roman", serif;
|
||||
letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||
progress { display: block; width: 100%; height: 16px; border: 0; border-radius: 8px; overflow: hidden;
|
||||
background: var(--track); -webkit-appearance: none; appearance: none; }
|
||||
progress::-webkit-progress-bar { background: var(--track); }
|
||||
progress::-webkit-progress-value { background: var(--accent); }
|
||||
progress::-moz-progress-bar { background: var(--accent); }
|
||||
p { margin: 16px 0 0; }
|
||||
.muted { color: var(--muted); }
|
||||
.stale { color: var(--warn); }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Загрузка практики СудАкта</h1>
|
||||
<p id="pct">—</p>
|
||||
<progress id="bar" max="100" value="0" aria-label="Скачано, процентов"></progress>
|
||||
<p id="count"></p>
|
||||
<p id="pace" class="muted"></p>
|
||||
<p id="time" class="stale">Нет свежих данных</p>
|
||||
</main>
|
||||
<script>
|
||||
const STALE_MS = 3 * 60 * 1000
|
||||
const $ = (id) => document.getElementById(id)
|
||||
const num = (n) => n.toLocaleString('ru-RU')
|
||||
const acts = (n) => (n % 10 === 1 && n % 100 !== 11 ? 'акта' : 'актов') // «из 96 101 акта», «из 96 097 актов»
|
||||
const left = (m) => (m < 60 ? `${m} мин` : `${Math.floor(m / 60)} ч ${m % 60} мин`)
|
||||
let last = null
|
||||
|
||||
function render() {
|
||||
if (!last) return
|
||||
const s = last
|
||||
const share = s.total ? Math.min(s.done / s.total, 1) : 0
|
||||
const pct = (share * 100).toLocaleString('ru-RU', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %'
|
||||
$('pct').textContent = pct
|
||||
document.title = `${pct} · загрузка практики СудАкта`
|
||||
$('bar').value = share * 100
|
||||
$('count').textContent = `Скачано ${num(s.done)} из ${num(s.total)} ${acts(s.total)}`
|
||||
$('pace').textContent = s.total && s.done >= s.total ? 'Загрузка завершена'
|
||||
: s.per_min > 0 ? `${num(Math.round(s.per_min))} в минуту, осталось около ${left(s.eta_min)}`
|
||||
: 'Сейчас загрузка стоит'
|
||||
const at = new Date(s.updated_at)
|
||||
const fresh = Date.now() - at < STALE_MS
|
||||
const clock = at.toLocaleString('ru-RU', fresh ? { hour: '2-digit', minute: '2-digit' }
|
||||
: { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' })
|
||||
$('time').textContent = fresh ? `Обновлено в ${clock}` : `Нет свежих данных. Последнее обновление: ${clock}`
|
||||
$('time').className = fresh ? 'muted' : 'stale'
|
||||
}
|
||||
|
||||
function showStatus(s) { last = s } // status.js: showStatus({...})
|
||||
|
||||
function load() { // файла нет - остаются прежние числа, через 3 минуты страница скажет, что они устарели
|
||||
document.getElementById('data')?.remove()
|
||||
const script = document.createElement('script')
|
||||
script.id = 'data'
|
||||
script.src = `status.js?${Date.now()}`
|
||||
script.onload = script.onerror = render
|
||||
document.body.append(script)
|
||||
}
|
||||
|
||||
load()
|
||||
setInterval(load, 5000)
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Acceptance checks for exact article/point knowledge graphs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.environ.get("EUNOMIA_URL", "http://127.0.0.1:18765")
|
||||
OUT = Path(__file__).parents[1] / "qa" / "atomic"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
GPK = "legal-corpus:code:gpk-rf"
|
||||
GPK131 = "doc:legal-corpus:code:gpk-rf:article:131"
|
||||
GK = "legal-corpus:code:gk-rf"
|
||||
GK395 = "doc:legal-corpus:code:gk-rf:article:395"
|
||||
|
||||
|
||||
def get_json(path: str) -> dict[str, Any]:
|
||||
last: Exception | None = None
|
||||
for _ in range(4):
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + "/api" + path, timeout=30) as response:
|
||||
return json.load(response)
|
||||
except urllib.error.HTTPError as error:
|
||||
last = error
|
||||
time.sleep(0.4)
|
||||
raise last or RuntimeError("API request failed")
|
||||
|
||||
|
||||
def graph(resource: str, fragment: str = "", **extra: str) -> dict[str, Any]:
|
||||
params = {"level": "atoms", "resource_id": resource, "limit": "1000", **extra}
|
||||
if fragment:
|
||||
params["fragment"] = fragment
|
||||
last: dict[str, Any] = {}
|
||||
for _ in range(120):
|
||||
last = get_json("/graph/network?" + urllib.parse.urlencode(params))
|
||||
if not last.get("loading") or last.get("nodes"):
|
||||
return last
|
||||
time.sleep(1)
|
||||
return last
|
||||
|
||||
|
||||
def check(report: dict[str, Any], name: str, ok: bool, detail: Any = "") -> None:
|
||||
report["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
|
||||
|
||||
|
||||
def ids_and_edges(data: dict[str, Any]) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
|
||||
return {node["id"]: node for node in data.get("nodes", [])}, data.get("edges", [])
|
||||
|
||||
|
||||
def assert_focus(report: dict[str, Any], data: dict[str, Any], focus: str, resource: str) -> None:
|
||||
nodes, edges = ids_and_edges(data)
|
||||
check(report, f"{focus} has exact focus id", data.get("focus_id") == focus, data.get("focus_id"))
|
||||
check(report, f"{focus} has no document nodes", not any(node.get("kind") == "document" for node in nodes.values()), [node.get("kind") for node in nodes.values() if node.get("kind") == "document"])
|
||||
check(report, f"{focus} is represented as an article/point", nodes.get(focus, {}).get("kind") in {"article", "point"}, nodes.get(focus, {}).get("kind"))
|
||||
check(report, f"{focus} graph is bounded", len(nodes) <= 1000 and len(edges) <= 1000, {"nodes": len(nodes), "edges": len(edges)})
|
||||
check(report, f"{focus} nodes stay in graph resources", all(node.get("resource_id") for node in nodes.values()), resource)
|
||||
|
||||
|
||||
def route(**params: str) -> str:
|
||||
return "#" + urllib.parse.urlencode({"view": "graph", **params})
|
||||
|
||||
|
||||
def reader_hash(resource: str, fragment: str) -> str:
|
||||
return "#" + urllib.parse.urlencode({"doc": resource, "fragment": fragment})
|
||||
|
||||
|
||||
def edge_set(data: dict[str, Any], relation: str = "references") -> set[tuple[str, str, str]]:
|
||||
return {(edge["source"], edge["target"], edge.get("relation", "")) for edge in data.get("edges", []) if edge.get("relation") == relation}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
report: dict[str, Any] = {"base": BASE, "checks": []}
|
||||
gpk0 = graph(GPK, GPK131, include_contains="0")
|
||||
gpk1 = graph(GPK, GPK131, include_contains="1")
|
||||
gk0 = graph(GK, GK395, include_contains="0")
|
||||
gk1 = graph(GK, GK395, include_contains="1")
|
||||
report["api"] = {"gpk131_no_structure": {"nodes": len(gpk0.get("nodes", [])), "edges": len(gpk0.get("edges", []))}, "gpk131_structure": {"nodes": len(gpk1.get("nodes", [])), "edges": len(gpk1.get("edges", []))}, "gk395_no_structure": {"nodes": len(gk0.get("nodes", [])), "edges": len(gk0.get("edges", []))}, "gk395_structure": {"nodes": len(gk1.get("nodes", [])), "edges": len(gk1.get("edges", []))}}
|
||||
for data, focus, resource in [(gpk0, GPK131, GPK), (gk0, GK395, GK)]:
|
||||
assert_focus(report, data, focus, resource)
|
||||
gpk_nodes, gpk_edges = ids_and_edges(gpk1)
|
||||
gpk_inc = [edge for edge in gpk_edges if edge["target"] == GPK131]
|
||||
gpk_out = [edge for edge in gpk_edges if edge["source"] == GPK131]
|
||||
check(report, "GPK 131 has incoming plenum point", any(gpk_nodes.get(edge["source"], {}).get("document_kind") == "plenum" and gpk_nodes.get(edge["source"], {}).get("kind") == "point" for edge in gpk_inc), [(gpk_nodes.get(edge["source"], {}).get("kind"), gpk_nodes.get(edge["source"], {}).get("document_kind")) for edge in gpk_inc])
|
||||
check(report, "GPK 131 has outbound article/point relation", any(gpk_nodes.get(edge["target"], {}).get("kind") in {"article", "point"} for edge in gpk_out), len(gpk_out))
|
||||
check(report, "structure toggle adds contains edges", len(gpk1.get("edges", [])) > len(gpk0.get("edges", [])) and any(edge.get("relation") == "contains" for edge in gpk1.get("edges", [])), report["api"])
|
||||
check(report, "structure toggle preserves exact citation edge set", edge_set(gpk0) == edge_set(gpk1), {"without": len(edge_set(gpk0)), "with": len(edge_set(gpk1))})
|
||||
gk_query = graph(GK, q="ст. 395 ГК")
|
||||
qnodes = {node["id"]: node for node in gk_query.get("nodes", [])}
|
||||
check(report, "query 395 returns exact article focus", any(node.get("label", "").startswith("Статья 395.") for node in qnodes.values()), [node.get("label") for node in qnodes.values() if node.get("kind") == "article"][:5])
|
||||
seed_1395 = [node for node in qnodes.values() if re.search(r"article:1395(?:$|_)", node.get("id", ""))]
|
||||
check(report, "query 395 does not seed article 1395", not seed_1395, [node.get("id") for node in seed_1395])
|
||||
check(report, "query graph stays bounded", len(qnodes) <= 1000 and len(gk_query.get("edges", [])) <= 1000, {"nodes": len(qnodes), "edges": len(gk_query.get("edges", []))})
|
||||
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 1000})
|
||||
page.goto(BASE + "/" + route(level="atoms", resource_id=GPK, fragment=GPK131, include_contains="1"), wait_until="domcontentloaded")
|
||||
page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
||||
try:
|
||||
page.get_by_role("button", name="Оживить").wait_for(timeout=120000)
|
||||
except Exception:
|
||||
pass
|
||||
body = page.locator("body").inner_text()
|
||||
check(report, "browser focus identifies article 131", "Статья 131" in body and "Связи выбранной нормы" in body, body[:1500])
|
||||
relations = page.locator(".p-atomic-relation")
|
||||
relation_text = " ".join(relations.all_inner_texts())
|
||||
relation_lower = relation_text.lower()
|
||||
check(report, "browser renders concrete atomic relation labels", all(label in relation_lower for label in ("ссылка из", "ссылается на", "содержит")), relation_text[:1200])
|
||||
check(report, "browser relations expose concrete reader links", relations.locator("a.p-atomic-read").count() > 0 and all((href := link.get_attribute("href")) and href.startswith("#doc=") for link in relations.locator("a.p-atomic-read").all()), relations.locator("a.p-atomic-read").count())
|
||||
center = page.get_by_role("link", name="В центре — эта норма")
|
||||
check(report, "recenter link preserves exact node", center.count() == 1 and "node_id=" in (center.get_attribute("href") or ""), center.get_attribute("href") if center.count() else "")
|
||||
first_relation = page.locator(".p-atomic-relation").first
|
||||
if first_relation.count():
|
||||
first_relation.locator(".p-related-node").click()
|
||||
page.wait_for_timeout(300)
|
||||
recenter = page.get_by_role("link", name="В центре — эта норма")
|
||||
recenter_href = recenter.get_attribute("href") if recenter.count() else ""
|
||||
recenter_params = urllib.parse.parse_qs(recenter_href.lstrip("#")) if recenter_href else {}
|
||||
expected_node = recenter_params.get("node_id", [""])[0]
|
||||
check(report, "related node offers exact recenter action", recenter.count() == 1 and bool(expected_node), recenter_href)
|
||||
if recenter.count():
|
||||
recenter.click(); page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
||||
route_params = urllib.parse.parse_qs(urllib.parse.urlparse(page.url).fragment)
|
||||
check(report, "recenter action navigates to selected exact node", route_params.get("node_id", [""])[0] == expected_node, {"url": page.url, "expected": expected_node})
|
||||
neighbor_graph = graph(GPK, "", node_id=expected_node, include_contains="1")
|
||||
check(report, "recentered related node becomes API focus", neighbor_graph.get("focus_id") == expected_node, neighbor_graph.get("focus_id"))
|
||||
page.screenshot(path=str(OUT / "atomic-gpk-131.png"), full_page=True)
|
||||
toggle = page.get_by_role("checkbox", name="Показывать состав статьи и вложенные пункты")
|
||||
check(report, "browser exposes structure toggle", toggle.count() == 1, toggle.count())
|
||||
if toggle.count():
|
||||
before = page.locator(".p-network-toolbar").inner_text()
|
||||
toggle.click(force=True); page.wait_for_timeout(1200)
|
||||
after = page.locator(".p-network-toolbar").inner_text()
|
||||
check(report, "structure toggle changes graph payload", before != after or page.url.find("include_contains=0") >= 0, {"before": before, "after": after, "url": page.url})
|
||||
page.goto(BASE + "/" + route(level="atoms", q="ст. 395 ГК"), wait_until="domcontentloaded")
|
||||
page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
||||
check(report, "browser query 395 excludes 1395 as seed", "Статья 1395." not in page.locator("body").inner_text().split("Граф знаний", 1)[-1], page.locator("body").inner_text()[-1000:])
|
||||
page.set_viewport_size({"width": 390, "height": 844}); page.wait_for_timeout(500)
|
||||
check(report, "atomic graph has no mobile overflow", page.evaluate("document.documentElement.scrollWidth - document.documentElement.clientWidth") == 0, page.evaluate("[document.documentElement.scrollWidth, document.documentElement.clientWidth]"))
|
||||
page.screenshot(path=str(OUT / "atomic-mobile.png"), full_page=True)
|
||||
|
||||
# Real user path: reader article -> exact graph, for both requested articles.
|
||||
for resource, reader_fragment, canonical in ((GPK, "doc:legal-corpus:code:gpk-rf_article_131", GPK131), (GK, "doc:legal-corpus:code:gk-rf_article_395", GK395)):
|
||||
page.set_viewport_size({"width": 1440, "height": 1000})
|
||||
page.goto(BASE + "/" + reader_hash(resource, reader_fragment), wait_until="domcontentloaded")
|
||||
page.locator(".p-document").wait_for(timeout=120000)
|
||||
page.locator(".p-fragment-graph").first.wait_for(timeout=120000)
|
||||
graph_link = None
|
||||
graph_href = ""
|
||||
for candidate in page.locator(".p-fragment-graph").all():
|
||||
candidate_href = candidate.get_attribute("href") or ""
|
||||
candidate_params = urllib.parse.parse_qs(candidate_href.lstrip("#"))
|
||||
if candidate_params.get("fragment", [""])[0] == reader_fragment:
|
||||
graph_link, graph_href = candidate, candidate_href
|
||||
break
|
||||
check(report, f"reader exposes exact graph link for {reader_fragment}", graph_link is not None, graph_href)
|
||||
if graph_link is not None:
|
||||
graph_link.click()
|
||||
page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
||||
parsed = urllib.parse.urlparse(page.url)
|
||||
route_params = urllib.parse.parse_qs(parsed.fragment)
|
||||
graph_data = graph(resource, reader_fragment, include_contains="1")
|
||||
check(report, f"reader graph link centers {canonical}", graph_data.get("focus_id") == canonical and route_params.get("fragment", [""])[0] == reader_fragment, {"focus_id": graph_data.get("focus_id"), "url": page.url})
|
||||
relation_link = page.locator(".p-atomic-read").first
|
||||
if relation_link.count():
|
||||
target_href = relation_link.get_attribute("href") or ""
|
||||
target_params = urllib.parse.parse_qs(target_href.lstrip("#"))
|
||||
relation_link.click()
|
||||
page.locator(".p-document").wait_for(timeout=120000)
|
||||
try:
|
||||
target_reader = get_json("/reader?" + urllib.parse.urlencode({"id": target_params.get("doc", [""])[0], "fragment": target_params.get("fragment", [""])[0]}))
|
||||
except Exception as error:
|
||||
target_reader = {}
|
||||
check(report, f"atomic relation opens exact reader for {canonical}", False, {"href": target_href, "error": str(error)})
|
||||
if target_reader:
|
||||
requested_fragment = target_params.get("fragment", [""])[0]
|
||||
check(report, f"atomic relation opens exact reader for {canonical}", bool(requested_fragment) and target_reader.get("selected_id") == requested_fragment, {"href": target_href, "selected_id": target_reader.get("selected_id")})
|
||||
|
||||
unknown = graph(GPK, "doc:legal-corpus:code:gpk-rf_article_999999", include_contains="1")
|
||||
check(report, "unknown fragment stays empty instead of falling back to document", unknown.get("status") == "focus_not_found" and not unknown.get("nodes"), {"status": unknown.get("status"), "nodes": len(unknown.get("nodes", []))})
|
||||
browser.close()
|
||||
(OUT / "atomic-check.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
failures = [item for item in report["checks"] if not item["ok"]]
|
||||
print(json.dumps({"checks": len(report["checks"]), "failures": failures}, ensure_ascii=False, indent=2))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Headed Chromium QA for the focused atomic graph; does not modify product code."""
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = 'http://127.0.0.1:18765/'
|
||||
OUT = Path(__file__).resolve().parents[1] / 'qa/atomic'
|
||||
NODE = 'doc:legal-corpus:code:gpk-rf:article:131'
|
||||
RUNTIME = """() => {
|
||||
const e = document.querySelector('.p-force-canvas');
|
||||
if (!e) throw Error('force canvas missing');
|
||||
let f = e[Object.keys(e).find(k => k.startsWith('__reactFiber$'))];
|
||||
for (; f; f = f.return) {
|
||||
let h = f.memoizedState, graph = null, data = null;
|
||||
while (h) {
|
||||
const v = h.memoizedState?.current, m = h.memoizedState;
|
||||
if (v && (typeof v.zoom === 'function' || typeof v.camera === 'function')) graph = v;
|
||||
if (Array.isArray(m) && m[0]?.nodes && m[0]?.links) data = m[0];
|
||||
h = h.next;
|
||||
}
|
||||
if (graph && data) return {graph, data};
|
||||
}
|
||||
throw Error('graph refs not found in React runtime');
|
||||
}"""
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
errors, console_errors, failed = [], [], []
|
||||
report = {}
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=False, args=['--use-angle=metal'])
|
||||
page = browser.new_page(viewport={'width': 1440, 'height': 1000})
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
page.on('console', lambda message: console_errors.append(message.text) if message.type == 'error' else None)
|
||||
page.on('requestfailed', lambda request: failed.append(f'{request.url}: {request.failure}'))
|
||||
page.on('response', lambda response: failed.append(f'{response.status} {response.url}') if response.status >= 400 else None)
|
||||
url = BASE + '#view=graph&level=atoms&resource_id=legal-corpus%3Acode%3Agpk-rf&fragment=' + NODE.replace(':', '%3A')
|
||||
page.goto(url, wait_until='networkidle', timeout=60000)
|
||||
page.get_by_role('button', name='Оживить', exact=True).wait_for(timeout=30000)
|
||||
page.wait_for_timeout(1200)
|
||||
page.evaluate('window.qaGraph = ' + RUNTIME)
|
||||
data = page.evaluate('qaGraph().data')
|
||||
assert any(node['id'] == NODE for node in data['nodes']), 'article 131 is absent from focused graph'
|
||||
initial_missing = page.evaluate("performance.getEntriesByType('resource').map(e => e.name).filter(n => n.endsWith('/favicon.ico'))")
|
||||
report['focus'] = {'node': NODE, 'nodes': len(data['nodes']), 'links': len(data['links'])}
|
||||
canvas = page.locator('.p-force-canvas canvas')
|
||||
box = canvas.bounding_box()
|
||||
assert box and box['width'] > 300 and box['height'] > 300
|
||||
before = page.evaluate('qaGraph().graph.zoom()')
|
||||
page.get_by_role('button', name='Приблизить карту').click()
|
||||
page.wait_for_timeout(800)
|
||||
after = page.evaluate('qaGraph().graph.zoom()')
|
||||
assert after > before, (before, after)
|
||||
report['2d_zoom'] = {'before': before, 'after': after}
|
||||
node = page.evaluate("""(id) => {
|
||||
const {graph, data} = qaGraph(); const n = data.nodes.find(x => x.id === id);
|
||||
const s = graph.graph2ScreenCoords(n.x, n.y); return {id, x:n.x, y:n.y, sx:s.x, sy:s.y};
|
||||
}""", NODE)
|
||||
x, y = box['x'] + node['sx'], box['y'] + node['sy']
|
||||
page.mouse.move(x, y); page.wait_for_timeout(100); page.mouse.down()
|
||||
page.mouse.move(x + 48, y + 24, steps=12); page.mouse.up(); page.wait_for_timeout(500)
|
||||
moved = page.evaluate('(id) => { const n=qaGraph().data.nodes.find(x=>x.id===id); return {x:n.x,y:n.y}; }', NODE)
|
||||
assert math.hypot(moved['x'] - node['x'], moved['y'] - node['y']) > 2, (node, moved)
|
||||
report['2d_drag'] = {'before': node, 'after': moved}
|
||||
page.get_by_role('button', name='3D', exact=True).click()
|
||||
page.wait_for_function("() => { try { return typeof qaGraph().graph.camera === 'function'; } catch { return false; } }", timeout=30000)
|
||||
page.wait_for_timeout(1000)
|
||||
box = page.locator('.p-force-canvas canvas').bounding_box(); assert box
|
||||
before = page.evaluate('() => { const p=qaGraph().graph.camera().position; return [p.x,p.y,p.z]; }')
|
||||
page.mouse.move(box['x'] + box['width']*.8, box['y'] + box['height']*.25)
|
||||
page.mouse.down(); page.mouse.move(box['x'] + box['width']*.6, box['y'] + box['height']*.4, steps=8); page.mouse.up()
|
||||
page.wait_for_timeout(1000)
|
||||
after = page.evaluate('() => { const p=qaGraph().graph.camera().position; return [p.x,p.y,p.z]; }')
|
||||
assert math.dist(before, after) > 1, (before, after)
|
||||
report['3d_orbit'] = {'before': before, 'after': after}
|
||||
before = page.evaluate('() => qaGraph().graph.camera().position.length()')
|
||||
page.get_by_role('button', name='Приблизить карту').click(); page.wait_for_timeout(1000)
|
||||
after = page.evaluate('() => qaGraph().graph.camera().position.length()')
|
||||
assert after < before, (before, after)
|
||||
report['3d_zoom'] = {'before': before, 'after': after}
|
||||
page.emulate_media(reduced_motion='reduce'); page.reload(wait_until='networkidle', timeout=60000)
|
||||
page.get_by_role('button', name='Оживить', exact=True).wait_for(timeout=30000)
|
||||
page.wait_for_timeout(1000); page.evaluate('window.qaGraph = ' + RUNTIME)
|
||||
before = page.evaluate('qaGraph().data.nodes.map(n => [n.x,n.y])'); page.wait_for_timeout(700)
|
||||
after = page.evaluate('qaGraph().data.nodes.map(n => [n.x,n.y])')
|
||||
assert before == after, 'reduced-motion graph kept moving'
|
||||
report['reduced_motion_stable'] = len(after)
|
||||
missing = sorted(set(initial_missing + page.evaluate("performance.getEntriesByType('resource').map(e => e.name).filter(n => n.endsWith('/favicon.ico'))")))
|
||||
report['javascript_errors'] = errors; report['console_errors'] = console_errors
|
||||
report['request_failures'] = failed; report['known_missing_assets'] = missing
|
||||
page.screenshot(path=str(OUT / 'runtime-atomic-131.png'), full_page=True)
|
||||
browser.close()
|
||||
(OUT / 'runtime-atomic-131.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
unexpected_console = [message for message in console_errors if 'Failed to load resource' not in message]
|
||||
assert not errors and not unexpected_console and not failed and len(missing) == 1, report
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Read-only browser acceptance against a running local Eunomia instance.
|
||||
|
||||
Run: python3 eunomia/tests/browser_check.py
|
||||
No source updates or graph builds are triggered by this check.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
|
||||
BASE = 'http://127.0.0.1:18765/'
|
||||
OUT = Path(__file__).resolve().parents[1] / 'qa'
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(exist_ok=True)
|
||||
checks = []
|
||||
errors = []
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={'width': 1440, 'height': 1000})
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
page.goto(BASE, wait_until='networkidle')
|
||||
page.wait_for_selector('.collection-link', timeout=60000)
|
||||
assert page.locator('.collection-link').count() == 5
|
||||
assert page.locator('.document-row').count() == 0
|
||||
assert page.locator('.goddess-art').evaluate('(i)=>i.complete && i.naturalWidth > 0')
|
||||
page.screenshot(path=str(OUT / 'home-final.png'), full_page=True)
|
||||
checks.append('Главная: пять разделов, без длинного списка, изображение загружено')
|
||||
|
||||
page.goto(BASE + '#view=category&kind=plenum', wait_until='networkidle')
|
||||
page.wait_for_selector('.topic-card')
|
||||
assert page.locator('.topic-card').count() == 8
|
||||
assert page.locator('.document-row').count() == 0
|
||||
page.screenshot(path=str(OUT / 'topics-final.png'), full_page=True)
|
||||
page.locator('.section-heading a').click()
|
||||
page.wait_for_selector('.document-row')
|
||||
dates = page.locator('.document-row').evaluate_all('(xs)=>xs.map(x=>x.dataset.actDate).filter(Boolean)')
|
||||
assert dates == sorted(dates)
|
||||
assert page.locator('.document-row').count() <= 12
|
||||
page.screenshot(path=str(OUT / 'chronology-final.png'), full_page=True)
|
||||
checks.append('Пленумы: направления, 12 документов на странице, ранние даты первыми')
|
||||
|
||||
page.select_option('[name=sort]', 'new')
|
||||
page.wait_for_function('location.hash.includes("sort=new")')
|
||||
dates = page.locator('.document-row').evaluate_all('(xs)=>xs.map(x=>x.dataset.actDate).filter(Boolean)')
|
||||
assert dates == sorted(dates, reverse=True)
|
||||
page.select_option('[name=year]', '2016')
|
||||
page.wait_for_function('location.hash.includes("year=2016")')
|
||||
assert all(x.startswith('2016') for x in page.locator('.document-row').evaluate_all('(xs)=>xs.map(x=>x.dataset.actDate)'))
|
||||
checks.append('Смена порядка сортировки и фильтр по году')
|
||||
|
||||
page.fill('#global-search', 'ст. 131 ГПК')
|
||||
page.press('#global-search', 'Enter')
|
||||
page.wait_for_selector('.result-row', timeout=30000)
|
||||
assert 'Статья 131' in page.locator('.result-row a').first.inner_text()
|
||||
page.locator('.result-row a').first.click()
|
||||
page.wait_for_selector('.reading-text', timeout=60000)
|
||||
assert 'fragment=' in page.url
|
||||
assert 'Исковое заявление' in page.locator('.reading-text').inner_text()
|
||||
target = page.locator('.toc-link.is-active')
|
||||
assert '131.' in target.inner_text()
|
||||
link = page.url
|
||||
page.reload(wait_until='networkidle')
|
||||
page.wait_for_selector('.reading-text', timeout=60000)
|
||||
assert page.url == link
|
||||
checks.append('Поиск статьи, полный текст, точная ссылка и повторное открытие')
|
||||
|
||||
size = page.locator('.reading-text').evaluate('(e)=>parseFloat(getComputedStyle(e).fontSize)')
|
||||
page.locator('[data-size="2"]').click()
|
||||
assert page.locator('.reading-text').evaluate('(e)=>parseFloat(getComputedStyle(e).fontSize)') > size
|
||||
page.fill('#reader-find', 'заявление')
|
||||
assert page.locator('.reading-text mark').count() > 0
|
||||
page.locator('[data-action="find-next"]').click()
|
||||
assert 'из' in page.locator('#find-count').inner_text()
|
||||
checks.append('Размер текста, подсветка и переход между совпадениями')
|
||||
|
||||
page.goto(link, wait_until='networkidle')
|
||||
page.wait_for_selector('.reading-text', timeout=60000)
|
||||
page.locator('[data-action="related"]').first.click()
|
||||
assert page.locator('.reader-related').is_visible()
|
||||
page.locator('.related-close').click()
|
||||
assert not page.locator('.reader-related').is_visible()
|
||||
checks.append('Панель связанных материалов доступна при чтении')
|
||||
|
||||
for width, height in [(1440, 1000), (1000, 900), (720, 900), (390, 844)]:
|
||||
page.set_viewport_size({'width': width, 'height': height})
|
||||
page.goto(link, wait_until='networkidle')
|
||||
page.reload(wait_until='networkidle')
|
||||
page.wait_for_selector('.reading-text', timeout=60000)
|
||||
page.wait_for_function('''() => {
|
||||
const id=new URLSearchParams(location.hash.slice(1)).get('fragment');
|
||||
const target=document.getElementById(id);
|
||||
if(!target)return false;
|
||||
const y=target.getBoundingClientRect().top;
|
||||
return y>=document.querySelector('.topbar').getBoundingClientRect().bottom && y<innerHeight-100;
|
||||
}''')
|
||||
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth'), width
|
||||
if width >= 1101:
|
||||
assert page.locator('.reading-text').bounding_box()['width'] >= 600
|
||||
page.screenshot(path=str(OUT / f'reader-{width}-final.png'))
|
||||
checks.append('Чтение на 1440, 1000, 720 и 390 пикселях без горизонтального переполнения')
|
||||
|
||||
page.click('#menu-toggle')
|
||||
assert page.locator('#sidebar').evaluate('(e)=>!e.inert')
|
||||
page.keyboard.press('Escape')
|
||||
assert page.locator('#sidebar').evaluate('(e)=>e.inert')
|
||||
checks.append('Мобильная навигация и закрытие с клавиатуры')
|
||||
assert not errors, errors
|
||||
browser.close()
|
||||
report = '\n'.join(f'PASS: {item}' for item in checks) + '\nОшибок JavaScript: 0\n'
|
||||
(OUT / 'browser-check.txt').write_text(report, encoding='utf-8')
|
||||
print(report)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Chromium для браузерных приемок Эвномии. Кеша браузеров Playwright на машине может не быть
|
||||
(03.10.2026 его нет вовсе: helioz-browser.mjs), поэтому берется любой Chromium с диска."""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
CHROMES = [os.environ.get('EUNOMIA_CHROME', ''),
|
||||
*sorted(glob.glob(str(Path.home() / '.cache/puppeteer/chrome-headless-shell/*/*/chrome-headless-shell')), reverse=True),
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome']
|
||||
|
||||
|
||||
def executable() -> str | None:
|
||||
"""Путь к Chromium с диска; None - Playwright возьмет свой из кеша."""
|
||||
return next((path for path in CHROMES if path and Path(path).is_file()), None)
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Browser acceptance for the Pantheon network view.
|
||||
|
||||
This checks observable graph behaviour against the real network endpoint. It deliberately
|
||||
does not treat a canvas existing as proof of interaction: hashes are compared around
|
||||
pointer gestures and the accessible list is exercised for keyboard navigation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, sync_playwright
|
||||
|
||||
|
||||
BASE = os.environ.get("EUNOMIA_URL", "http://127.0.0.1:18765")
|
||||
OUT = Path(__file__).parents[1] / "qa" / "marble-revision"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def digest(page, selector: str = "canvas") -> str:
|
||||
value = page.locator(selector).evaluate("el => el.toDataURL('image/png')")
|
||||
return hashlib.sha256(value.encode()).hexdigest()
|
||||
|
||||
|
||||
def check(report: dict[str, Any], name: str, ok: bool, detail: Any = "") -> None:
|
||||
report["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
|
||||
|
||||
|
||||
def main() -> int:
|
||||
report: dict[str, Any] = {"base": BASE, "checks": []}
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True, args=["--enable-unsafe-swiftshader"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 1000}, device_scale_factor=1)
|
||||
api: dict[str, Any] = {}
|
||||
for _ in range(30):
|
||||
api = page.request.get(f"{BASE}/api/graph/network?level=documents&limit=1000").json()
|
||||
if api.get("nodes"):
|
||||
break
|
||||
page.wait_for_timeout(700)
|
||||
nodes = api.get("nodes", [])
|
||||
links = api.get("edges", api.get("links", []))
|
||||
node_ids = {node.get("id") for node in nodes}
|
||||
valid_links = sum(link.get("source") in node_ids and link.get("target") in node_ids for link in links)
|
||||
report["network"] = {
|
||||
"nodes": len(nodes),
|
||||
"links": len(links),
|
||||
"total_nodes": api.get("total_nodes"),
|
||||
"total_edges": api.get("total_edges"),
|
||||
"valid_links": valid_links,
|
||||
"warnings": api.get("warnings", []),
|
||||
}
|
||||
check(report, "actual network has at least 350 nodes", len(nodes) >= 350, len(nodes))
|
||||
check(report, "actual network has at least 500 links", len(links) >= 500, len(links))
|
||||
check(report, "all displayed links resolve to displayed nodes", valid_links == len(links), f"{valid_links}/{len(links)}")
|
||||
|
||||
page.goto(f"{BASE}/#view=graph&level=documents", wait_until="domcontentloaded")
|
||||
page.locator('.p-connection-state[role="status"]').wait_for(state="detached", timeout=40000)
|
||||
page.locator(".p-network-toolbar").wait_for(timeout=40000)
|
||||
canvas = page.locator("canvas").first
|
||||
check(report, "desktop canvas is present", canvas.count() == 1)
|
||||
connected_toolbar = page.locator(".p-network-toolbar").inner_text()
|
||||
check(report, "desktop toolbar exposes actual link count", f"{len(links)} связей" in connected_toolbar, connected_toolbar)
|
||||
include_isolates = page.get_by_role("checkbox")
|
||||
check(report, "graph offers an explicit isolated-node control", include_isolates.count() == 1, include_isolates.count())
|
||||
if include_isolates.count():
|
||||
include_isolates.check()
|
||||
page.wait_for_timeout(500)
|
||||
toolbar = page.locator(".p-network-toolbar").inner_text()
|
||||
report["displayed"] = toolbar
|
||||
check(report, "including isolated nodes exposes the full API node count", f"{len(nodes)} узлов" in toolbar, toolbar)
|
||||
page.screenshot(path=str(OUT / "network-1440.png"), full_page=True)
|
||||
|
||||
box = canvas.bounding_box()
|
||||
settled_button = page.get_by_role("button", name="Оживить")
|
||||
try:
|
||||
settled_button.wait_for(timeout=15000)
|
||||
except PlaywrightTimeoutError:
|
||||
pass
|
||||
if box:
|
||||
before = digest(page)
|
||||
page.mouse.move(box["x"] + box["width"] * 0.7, box["y"] + box["height"] * 0.55)
|
||||
page.mouse.wheel(0, 700)
|
||||
page.wait_for_timeout(80)
|
||||
after_zoom = digest(page)
|
||||
check(report, "wheel gesture changes graph rendering", before != after_zoom, {"before": before, "after": after_zoom})
|
||||
page.mouse.move(box["x"] + box["width"] * 0.65, box["y"] + box["height"] * 0.5)
|
||||
page.mouse.down()
|
||||
page.mouse.move(box["x"] + 90, box["y"] + 34, steps=8)
|
||||
page.mouse.up()
|
||||
page.wait_for_timeout(80)
|
||||
after_pan = digest(page)
|
||||
check(report, "drag gesture changes graph rendering", after_zoom != after_pan, {"before": after_zoom, "after": after_pan})
|
||||
else:
|
||||
check(report, "wheel gesture changes graph rendering", False, "canvas has no box")
|
||||
check(report, "drag gesture changes graph rendering", False, "canvas has no box")
|
||||
|
||||
fit_buttons = page.get_by_role("button", name=__import__("re").compile("размер|впис|центр|сбросить вид|масштаб", __import__("re").I))
|
||||
pause_buttons = page.get_by_role("button", name=__import__("re").compile("пауз|оживить", __import__("re").I))
|
||||
check(report, "graph exposes an actual fit/reset view control", fit_buttons.count() > 0, page.get_by_role("button").all_inner_texts())
|
||||
if pause_buttons.count():
|
||||
if page.get_by_role("button", name="Оживить").count():
|
||||
page.get_by_role("button", name="Оживить").click()
|
||||
check(report, "resume control restarts physics", page.get_by_role("button", name="Пауза").count() > 0, page.get_by_role("button").all_inner_texts())
|
||||
page.get_by_role("button", name="Пауза").click()
|
||||
else:
|
||||
page.get_by_role("button", name="Пауза").click()
|
||||
check(report, "pause control exposes resume state", page.get_by_role("button", name="Оживить").count() > 0, page.get_by_role("button").all_inner_texts())
|
||||
|
||||
page.get_by_role("button", name="Список").click()
|
||||
rows = page.locator(".p-network-list-row")
|
||||
check(report, "accessible list contains the actual network nodes", rows.count() == len(nodes), rows.count())
|
||||
first = rows.first
|
||||
first.focus()
|
||||
first.press("Enter")
|
||||
page.wait_for_timeout(250)
|
||||
exact = page.locator(".p-selected-node a.p-button-primary")
|
||||
check(report, "keyboard selection opens a selected-node panel", page.locator(".p-selected-node").count() == 1, page.url)
|
||||
check(report, "selected node has an exact reader target", bool(exact.get_attribute("href")) if exact.count() else False, exact.get_attribute("href") if exact.count() else "")
|
||||
|
||||
page.get_by_role("button", name="2D").click()
|
||||
page.get_by_role("button", name="3D").click()
|
||||
page.wait_for_timeout(3500)
|
||||
report["three_d_canvas"] = page.locator("canvas").evaluate_all("els => els.map(el => ({width: el.width, height: el.height}))")
|
||||
check(report, "3D toggle renders a WebGL canvas", page.locator("canvas").count() >= 1 and page.locator("canvas").first.get_attribute("width") not in (None, "0"), report["three_d_canvas"])
|
||||
if page.locator("canvas").count():
|
||||
three_d_before = page.locator(".p-force-canvas").screenshot()
|
||||
three_d_box = page.locator("canvas").first.bounding_box()
|
||||
if three_d_box:
|
||||
page.mouse.move(three_d_box["x"] + three_d_box["width"] * .5, three_d_box["y"] + three_d_box["height"] * .5)
|
||||
page.mouse.down(); page.mouse.move(three_d_box["x"] + 90, three_d_box["y"] + 28, steps=8); page.mouse.up()
|
||||
page.wait_for_timeout(120)
|
||||
three_d_after = page.locator(".p-force-canvas").screenshot()
|
||||
check(report, "3D orbit gesture changes the rendered view", three_d_before != three_d_after, "container screenshot differs after orbit")
|
||||
page.screenshot(path=str(OUT / "network-3d.png"), full_page=True)
|
||||
|
||||
page.get_by_role("button", name="2D").click()
|
||||
kind = page.get_by_label("Тип")
|
||||
kind.select_option("plenum")
|
||||
page.get_by_role("button", name="Найти").click()
|
||||
page.wait_for_timeout(1500)
|
||||
filtered_api = page.request.get(f"{BASE}/api/graph/network?level=documents&kind=plenum&limit=1000").json()
|
||||
filtered_nodes = len(filtered_api.get("nodes", []))
|
||||
check(report, "kind filter narrows the real network", filtered_nodes < len(nodes) and filtered_nodes > 0, filtered_nodes)
|
||||
check(report, "kind filter is reflected in the URL", "kind=plenum" in page.url, page.url)
|
||||
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
page.goto(f"{BASE}/#view=graph&level=documents", wait_until="domcontentloaded")
|
||||
page.locator(".p-network-toolbar").wait_for(timeout=15000)
|
||||
page.wait_for_timeout(700)
|
||||
overflow = page.evaluate("document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
mobile_box = page.locator("canvas").first.bounding_box()
|
||||
report["mobile"] = {"overflow": overflow, "canvas": mobile_box}
|
||||
check(report, "mobile graph has no document overflow", overflow == 0, overflow)
|
||||
check(report, "mobile canvas fits its viewport", bool(mobile_box) and mobile_box["width"] <= 390, mobile_box)
|
||||
page.screenshot(path=str(OUT / "network-mobile.png"), full_page=True)
|
||||
browser.close()
|
||||
|
||||
(OUT / "network-check.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
failures = [item for item in report["checks"] if not item["ok"]]
|
||||
print(json.dumps({"checks": len(report["checks"]), "failures": failures}, ensure_ascii=False, indent=2))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Read-only browser checks of actual node/camera coordinates; no product test hooks."""
|
||||
import json, math, signal
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
OUT=Path(__file__).resolve().parents[1]/'qa/marble-revision'
|
||||
RUNTIME="""() => {
|
||||
let e=document.querySelector('.p-force-canvas'), f=e[Object.keys(e).find(k=>k.startsWith('__reactFiber$'))];
|
||||
for(;f;f=f.return){let h=f.memoizedState,graph=null,data=null;
|
||||
while(h){const v=h.memoizedState?.current,m=h.memoizedState;
|
||||
if(v&&(typeof v.zoom==='function'||typeof v.camera==='function'))graph=v;
|
||||
if(Array.isArray(m)&&m[0]?.nodes&&m[0]?.links)data=m[0];h=h.next;
|
||||
}if(graph&&data)return {graph,data};
|
||||
}throw Error('Graph refs not found in React runtime');
|
||||
}"""
|
||||
def main():
|
||||
signal.alarm(90)
|
||||
report={};errors=[]
|
||||
with sync_playwright() as p:
|
||||
browser=p.chromium.launch(headless=False,args=['--use-angle=metal'])
|
||||
page=browser.new_page(viewport={'width':1440,'height':1000})
|
||||
page.on('pageerror',lambda e:errors.append(str(e)))
|
||||
page.goto('http://127.0.0.1:18765/#view=graph&level=documents',wait_until='networkidle')
|
||||
page.get_by_role('button',name='Оживить',exact=True).wait_for(timeout=20000)
|
||||
page.evaluate('window.qaGraph='+RUNTIME)
|
||||
canvas=page.locator('.p-force-canvas canvas');canvas.scroll_into_view_if_needed()
|
||||
before=page.evaluate('qaGraph().graph.zoom()')
|
||||
page.get_by_role('button',name='Приблизить карту').click();page.wait_for_timeout(350)
|
||||
after=page.evaluate('qaGraph().graph.zoom()');assert after>before
|
||||
report['2d_button_zoom']={'before':before,'after':after}
|
||||
page.get_by_role('button',name='По размеру').click();page.wait_for_timeout(350)
|
||||
canvas.scroll_into_view_if_needed();box=canvas.bounding_box()
|
||||
point=page.evaluate("""() => {const {graph,data}=qaGraph();let n=data.nodes.find(n=>n.id==='doc:legal-corpus:code:gk-rf')||data.nodes[0];return {id:n.id,x:n.x,y:n.y,screen:graph.graph2ScreenCoords(n.x,n.y)}}""")
|
||||
x,y=box['x']+point['screen']['x'],box['y']+point['screen']['y']
|
||||
page.mouse.move(x,y);page.wait_for_timeout(100);page.mouse.down();page.mouse.move(x+45,y+28,steps=12);page.mouse.up();page.wait_for_timeout(200)
|
||||
moved=page.evaluate('(id)=>{const n=qaGraph().data.nodes.find(n=>n.id===id);return {x:n.x,y:n.y}}',point['id'])
|
||||
assert math.hypot(moved['x']-point['x'],moved['y']-point['y'])>2,(point,moved)
|
||||
report['2d_node_drag']={'before':point,'after':moved};print('PASS 2D node drag',flush=True)
|
||||
page.get_by_role('button',name='3D',exact=True).click()
|
||||
page.wait_for_function("() => {try{return typeof qaGraph().graph.camera==='function'}catch{return false}}",timeout=20000)
|
||||
page.get_by_role('button',name='Оживить',exact=True).wait_for(timeout=20000);page.wait_for_timeout(400)
|
||||
canvas=page.locator('.p-force-canvas canvas');canvas.scroll_into_view_if_needed();box=canvas.bounding_box()
|
||||
before=page.evaluate('()=>{const p=qaGraph().graph.camera().position;return [p.x,p.y,p.z]}')
|
||||
page.mouse.move(box['x']+box['width']*.85,box['y']+box['height']*.25);page.mouse.down();page.mouse.move(box['x']+box['width']*.65,box['y']+box['height']*.4,steps=1);page.mouse.up();page.wait_for_timeout(500)
|
||||
after=page.evaluate('()=>{const p=qaGraph().graph.camera().position;return [p.x,p.y,p.z]}')
|
||||
assert math.dist(before,after)>1,(before,after)
|
||||
report['3d_orbit_camera']={'before':before,'after':after};print('PASS 3D orbit',flush=True)
|
||||
before=page.evaluate('qaGraph().graph.camera().position.length()')
|
||||
page.get_by_role('button',name='Приблизить карту').click();page.wait_for_timeout(350)
|
||||
after=page.evaluate('qaGraph().graph.camera().position.length()');assert after<before
|
||||
report['3d_zoom_camera']={'before':before,'after':after}
|
||||
page.screenshot(path=str(OUT/'graph-final-3d.png'))
|
||||
page.emulate_media(reduced_motion='reduce');page.reload(wait_until='networkidle');page.get_by_role('button',name='Оживить',exact=True).wait_for(timeout=20000);page.evaluate('window.qaGraph='+RUNTIME)
|
||||
before=page.evaluate('qaGraph().data.nodes.map(n=>[n.x,n.y])');page.wait_for_timeout(500);after=page.evaluate('qaGraph().data.nodes.map(n=>[n.x,n.y])');assert before==after
|
||||
report['reduced_motion_stable_nodes']=len(after)
|
||||
before=page.evaluate('qaGraph().graph.zoom()');page.get_by_role('button',name='Приблизить карту').click();page.wait_for_timeout(100);after=page.evaluate('qaGraph().graph.zoom()');assert after>before
|
||||
report['paused_canvas_remains_interactive']=True
|
||||
report['javascript_errors']=errors;assert not errors
|
||||
browser.close()
|
||||
(OUT/'network-runtime.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS',json.dumps(report,ensure_ascii=False))
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, unquote, urlsplit
|
||||
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError, sync_playwright
|
||||
from chromium import executable
|
||||
|
||||
BASE = os.environ.get('EUNOMIA_URL', 'http://127.0.0.1:18765').rstrip('/')
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
QA = ROOT / 'qa'
|
||||
|
||||
class Check:
|
||||
def __init__(self, page):
|
||||
self.page, self.results, self.errors, self.posts = page, [], [], []
|
||||
page.on('pageerror', lambda error: self.errors.append(str(error)))
|
||||
page.on('request', lambda request: self.posts.append(request.url) if request.method != 'GET' else None)
|
||||
page.route('**/api/update', lambda route: route.fulfill(status=200, content_type='application/json', body='{"detail":"mock"}'))
|
||||
page.route('**/api/graph/rebuild', lambda route: route.fulfill(status=200, content_type='application/json', body='{"detail":"mock"}'))
|
||||
page.route('**/api/practice/refresh', lambda route: route.fulfill(status=200, content_type='application/json', body='{"detail":"mock"}'))
|
||||
# Очередь законов свободна: кнопка «Обновить законодательство» доступна при любом живом состоянии.
|
||||
page.route('**/api/update/progress', lambda route: route.fulfill(status=200, content_type='application/json', body='{"done":1,"total":1,"per_min":0,"eta_min":0,"running":false,"states":{},"updated_at":"2026-10-03T00:00:00Z"}'))
|
||||
def check(self, name, ok, detail=''):
|
||||
self.results.append({'name': name, 'ok': bool(ok), 'detail': detail})
|
||||
def info(self, name, detail): self.results.append({'name': name, 'ok': True, 'info': True, 'detail': detail})
|
||||
def home(self):
|
||||
self.page.goto(BASE + '/', wait_until='domcontentloaded'); self.page.wait_for_selector('#p-main', timeout=20000); self.page.wait_for_timeout(500)
|
||||
self.check('five kind tabs', self.page.locator('.p-tabs a').count() == 5)
|
||||
self.check('twelve code stones', self.page.locator('.p-stone').count() == 12, str(self.page.locator('.p-stone').count()))
|
||||
loaded = self.page.evaluate("() => [...document.querySelectorAll('.p-stone img')].every(img => img.complete && img.naturalWidth > 0)")
|
||||
self.check('code stone images loaded', loaded)
|
||||
self.page.screenshot(path=str(QA / 'pantheon-home.png'))
|
||||
def search_reader(self):
|
||||
inp = self.page.locator('input[aria-label="Поиск по библиотеке"]')
|
||||
self.check('global search exists', inp.count() == 1)
|
||||
inp.fill('ст. 395 ГК'); inp.press('Enter'); self.page.wait_for_url('**#view=search**', timeout=10000); self.page.wait_for_selector('.p-results', timeout=15000)
|
||||
search_query = parse_qs(urlsplit(self.page.url).fragment).get('q', [''])[0]
|
||||
self.check('search preserves original query', search_query == 'ст. 395 ГК', self.page.url)
|
||||
result = self.page.locator('.p-result a').filter(has_text='395').first
|
||||
self.check('search has exact 395 result', result.count() == 1)
|
||||
href = result.get_attribute('href') or ''; result.click(); self.page.wait_for_selector('.p-document', timeout=15000); self.page.wait_for_selector('.p-reading h2', timeout=15000)
|
||||
qs = parse_qs(urlsplit(self.page.url).fragment); self.check('search opens exact reader anchor', '395' in unquote(qs.get('fragment', [''])[0]), self.page.url)
|
||||
self.page.screenshot(path=str(QA / 'pantheon-reader.png'))
|
||||
self.check('reader toc visible', self.page.get_by_role('navigation', name='Оглавление').count() == 1)
|
||||
recent = self.page.evaluate("() => JSON.parse(localStorage.getItem('eunomia:recent:v1') || '[]')")
|
||||
self.check('reader local recent saved for GK article 395', any(item.get('id') == 'legal-corpus:code:gk-rf' for item in recent), str(recent[:2]))
|
||||
next_article = self.page.get_by_role('button', name='Следующая статья')
|
||||
if next_article.count() and not next_article.is_disabled():
|
||||
next_article.click(); self.page.wait_for_timeout(300); self.check('reader next article opens 396', '396' in unquote(self.page.url))
|
||||
else: self.check('reader next article opens 396', False, 'Кнопка следующей статьи недоступна')
|
||||
toc_link = self.page.locator('.p-toc-list a:visible').first
|
||||
self.check('reader has visible toc link', toc_link.count() == 1)
|
||||
if toc_link.count(): toc_link.click()
|
||||
self.page.wait_for_timeout(300)
|
||||
self.page.goto(BASE + '/#doc=legal-corpus%3Acode%3Agk-rf&fragment=doc%3Alegal-corpus%3Acode%3Agk-rf_article_395', wait_until='domcontentloaded'); self.page.wait_for_selector('.p-reading h2', timeout=15000)
|
||||
self.page.get_by_role('button', name='Найти', exact=True).click(); find = self.page.get_by_role('searchbox', name='Найти в тексте'); self.check('reader find input opens', find.count() == 1)
|
||||
whole = self.page.get_by_role('button', name='Открыть весь документ')
|
||||
if whole.count(): whole.click(); self.page.wait_for_timeout(1200)
|
||||
if find.count(): find.fill('ключевой'); self.page.wait_for_timeout(1500); self.check('reader find marks full text', self.page.locator('.p-reading mark').count() > 0)
|
||||
focus = self.page.get_by_role('button', name='Режим чтения'); focus.click(); self.check('reader focus mode enters', self.page.locator('body.p-reading-focus').count() == 1); self.page.keyboard.press('Escape'); self.check('reader focus mode exits on Escape', self.page.locator('body.p-reading-focus').count() == 0)
|
||||
def contents(self):
|
||||
self.page.goto(BASE + '/', wait_until='domcontentloaded'); self.page.wait_for_selector('.p-stone', timeout=15000)
|
||||
stone_href = self.page.locator('.p-stone').filter(has_text='Гражданский кодекс').first.get_attribute('href') or ''
|
||||
doc_id = parse_qs(urlsplit(stone_href).fragment).get('doc', ['legal-corpus:code:gk-rf'])[0]
|
||||
self.page.goto(BASE + '/#view=contents&id=' + doc_id, wait_until='domcontentloaded'); self.page.wait_for_selector('.p-contents', timeout=15000)
|
||||
try: self.page.wait_for_function("() => document.querySelectorAll('.p-contents-list a').length >= 4", timeout=10000)
|
||||
except PlaywrightTimeoutError: pass
|
||||
self.check('GK contents has four parts', self.page.locator('.p-contents-list a').count() >= 4, str(self.page.locator('.p-contents-list a').count()))
|
||||
def plenums(self):
|
||||
self.page.goto(BASE + '/#view=category&kind=plenum', wait_until='domcontentloaded'); self.page.wait_for_selector('.p-topic-grid', timeout=15000)
|
||||
self.check('plenum has eight topics', self.page.locator('.p-topic').count() == 8)
|
||||
self.check('plenum year filter', self.page.locator('select').count() >= 2)
|
||||
if self.page.locator('select').count() >= 2:
|
||||
self.page.locator('select').nth(0).select_option('old'); self.page.locator('select').nth(1).select_option('2020')
|
||||
dates = self.page.locator('.p-document-row small').all_inner_texts(); self.check('plenum year filter applies to rows', not dates or all('2020' in date for date in dates), str(dates[:3]))
|
||||
pager = self.page.locator('.p-pagination button'); self.check('plenum has real pagination when over page size', self.page.locator('.p-document-row').count() <= 12 or pager.count() > 0)
|
||||
enabled_pager = self.page.locator('.p-pagination button:not([disabled])')
|
||||
if enabled_pager.count():
|
||||
before = self.page.locator('.p-document-row').first.inner_text(); enabled_pager.last.click(); self.page.wait_for_timeout(200); self.check('plenum pagination changes first row', self.page.locator('.p-document-row').first.inner_text() != before)
|
||||
def graph(self):
|
||||
self.page.goto(BASE + '/#view=graph', wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-force-canvas canvas', timeout=20000)
|
||||
self.check('graph has real canvas and search', self.page.get_by_label('Поиск узлов').count() == 1)
|
||||
self.page.get_by_role('button', name='Список', exact=True).click()
|
||||
self.page.wait_for_selector('.p-network-list-row')
|
||||
self.page.locator('.p-network-list-row').first.click()
|
||||
self.check('graph selection opens reader link', self.page.locator('.p-selected-node a[href^="#doc="]', has_text='Читать точное место').count() == 1)
|
||||
self.check('selection preserves network route', 'node_id=' not in self.page.url)
|
||||
self.page.get_by_role('button', name='2D', exact=True).click()
|
||||
self.page.wait_for_selector('.p-force-canvas canvas')
|
||||
self.page.get_by_role('button', name='Приблизить карту').click()
|
||||
self.page.get_by_role('button', name='По размеру').click()
|
||||
self.page.screenshot(path=str(QA / 'pantheon-graph.png'))
|
||||
def editions(self):
|
||||
self.page.goto(BASE + '/#view=history&id=legal-corpus%3Acode%3Agk-rf', wait_until='domcontentloaded'); self.page.wait_for_selector('.p-editions', timeout=15000)
|
||||
# Список редакций ГК грузится дольше 800 мс, когда Mac занят сборкой графа (сбой 03.10.2026, 21:03).
|
||||
self.page.wait_for_selector('.p-edition-list, .p-empty', timeout=15000)
|
||||
self.check('editions screen has real history state', self.page.locator('.p-edition-list, .p-empty').count() == 1)
|
||||
compare = self.page.get_by_role('button', name='Сравнить')
|
||||
if compare.count() and not compare.is_disabled(): compare.click(); self.page.wait_for_selector('.p-diff, .p-empty', timeout=10000); self.check('editions compare returns result', self.page.locator('.p-diff, .p-empty').count() > 0)
|
||||
def navigation(self):
|
||||
self.page.set_viewport_size({'width':1440,'height':900}); self.page.goto(BASE + '/', wait_until='domcontentloaded'); self.page.wait_for_selector('#p-main'); desktop_toggle = self.page.locator('.p-sidebar button[aria-label="Свернуть меню"]:visible').first; desktop_toggle.click(); self.page.wait_for_timeout(200); self.check('desktop sidebar collapses', self.page.locator('[aria-label="Развернуть меню"]:visible').count() > 0)
|
||||
self.page.set_viewport_size({'width':390,'height':844}); self.page.reload(wait_until='domcontentloaded'); self.page.wait_for_selector('#p-main'); self.page.locator('#menu-toggle').click(); self.page.wait_for_timeout(200); self.page.keyboard.press('Escape'); self.page.wait_for_timeout(500); self.check('mobile sheet closes and focus returns', self.page.locator('#menu-toggle').evaluate('e=>e===document.activeElement'))
|
||||
self.page.screenshot(path=str(QA / 'pantheon-mobile.png'))
|
||||
self.page.goto(BASE + '/#view=updates', wait_until='domcontentloaded'); self.page.wait_for_selector('.p-research', timeout=15000); update = self.page.get_by_role('button', name='Обновить законодательство')
|
||||
if update.count(): update.click(); self.page.wait_for_timeout(500); self.info('mock update action', 'POST intercepted locally; external update не вызывался')
|
||||
def run(self):
|
||||
self.home(); self.search_reader(); self.contents(); self.plenums(); self.graph(); self.editions(); self.navigation()
|
||||
self.check('no javascript errors', not self.errors, '; '.join(self.errors[:3]))
|
||||
unexpected = [url for url in self.posts if '/api/update' not in url and '/api/graph/rebuild' not in url]
|
||||
self.check('mock update request stayed local', any('/api/update' in url for url in self.posts))
|
||||
self.check('no unexpected non-GET requests', not unexpected, '; '.join(unexpected[:3]))
|
||||
return 0 if all(item['ok'] for item in self.results if not item.get('info')) else 1
|
||||
|
||||
def main():
|
||||
QA.mkdir(parents=True, exist_ok=True)
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, executable_path=executable()); page = browser.new_page(viewport={'width':1440,'height':900}); check = Check(page)
|
||||
try: code = check.run()
|
||||
except Exception as error: check.check('pantheon runner completed', False, f'{type(error).__name__}: {error}'); code = 1
|
||||
browser.close()
|
||||
(QA / 'pantheon-functional.json').write_text(json.dumps({'base':BASE,'results':check.results,'js_errors':check.errors,'non_get':check.posts}, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
|
||||
for item in check.results: print(('INFO' if item.get('info') else 'PASS' if item['ok'] else 'FAIL'), item['name'], item.get('detail',''))
|
||||
return code
|
||||
if __name__ == '__main__': raise SystemExit(main())
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Read-only geometry and screenshot checks for the Pantheon interface."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
from chromium import executable
|
||||
|
||||
OUT = Path(__file__).resolve().parents[1] / 'qa'
|
||||
BASE = 'http://127.0.0.1:18765/'
|
||||
READER = '#doc=legal-corpus%3Acode%3Agk-rf&fragment=doc%3Alegal-corpus%3Acode%3Agk-rf_article_395'
|
||||
|
||||
def main():
|
||||
report, errors = [], []
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, executable_path=executable())
|
||||
page = browser.new_page()
|
||||
page.on('pageerror', lambda error: errors.append(str(error)))
|
||||
for view, route, selector in [('home', '', '.p-stone'), ('reader', READER, '.p-reading h2')]:
|
||||
for width in (320, 390, 768, 1000, 1440, 1920):
|
||||
page.set_viewport_size({'width':width, 'height':1000 if width > 500 else 844})
|
||||
page.goto(BASE + route, wait_until='networkidle')
|
||||
page.wait_for_selector(selector, timeout=20000)
|
||||
page.screenshot(path=str(OUT / f'pantheon-{view}-{width}.png'))
|
||||
geometry = page.evaluate('''() => ({width:innerWidth,scroll:document.documentElement.scrollWidth,
|
||||
search:[...document.querySelectorAll('input[aria-label="Поиск по библиотеке"]')].filter(e=>e.getBoundingClientRect().height>0).length,
|
||||
font:document.fonts.check('16px "Golos Text"'),
|
||||
numbers:document.querySelector('.p-reading')?getComputedStyle(document.querySelector('.p-reading')).fontVariantNumeric:null,
|
||||
tabs:[...document.querySelectorAll('.p-tabs a')].map(e=>({y:e.getBoundingClientRect().y,h:e.getBoundingClientRect().height})),
|
||||
main:[...document.querySelectorAll('main')].length})''')
|
||||
assert geometry['scroll'] <= width + 1, (view, geometry)
|
||||
assert geometry['search'] == 1, (view, geometry)
|
||||
assert geometry['main'] == 1, (view, geometry)
|
||||
assert len({x['y'] for x in geometry['tabs']}) <= 1, geometry
|
||||
if view == 'reader': assert 'lining-nums' in geometry['numbers'], geometry
|
||||
report.append({'view':view, **geometry})
|
||||
for name, route, selector in [('search','#view=search&q=ст.%20395%20ГК','.p-results'),('graph','#view=graph','.p-force-canvas canvas'),('editions','#view=history&id=legal-corpus%3Acode%3Agk-rf','.p-edition-row'),('service','#view=updates','.p-service-card'),('plenum','#view=category&kind=plenum','.p-document-row'),('recent','#view=recent','.p-recent-list')]:
|
||||
for width in (390,1440):
|
||||
page.set_viewport_size({'width':width,'height':1000 if width>500 else 844})
|
||||
page.goto(BASE+route,wait_until='networkidle'); page.wait_for_selector(selector,timeout=20000)
|
||||
value=page.evaluate('document.documentElement.scrollWidth')
|
||||
assert value<=width+1,(name,width,value)
|
||||
page.screenshot(path=str(OUT/f'pantheon-{name}-review-{width}.png'))
|
||||
report.append({'view':name,'width':width,'scroll':value})
|
||||
page.set_viewport_size({'width':390,'height':844});page.goto(BASE,wait_until='networkidle')
|
||||
page.locator('#menu-toggle').click(); page.wait_for_selector('[data-mobile=true]')
|
||||
page.screenshot(path=str(OUT/'pantheon-mobile-menu.png'))
|
||||
page.keyboard.press('Escape');page.wait_for_timeout(250)
|
||||
page.goto(BASE+READER,wait_until='networkidle');page.wait_for_selector('.p-reading h2')
|
||||
page.get_by_role('button',name='Контекст',exact=True).click();page.wait_for_selector('.p-sheet')
|
||||
page.wait_for_timeout(350)
|
||||
bounds=page.locator('.p-sheet').bounding_box()
|
||||
assert bounds and bounds['x']>=0 and bounds['x']+bounds['width']<=391, bounds
|
||||
page.screenshot(path=str(OUT/'pantheon-mobile-context.png'))
|
||||
# 720 CSS pixels at DPR 2 represents the layout area of 1440px at 200%.
|
||||
zoom=browser.new_context(viewport={'width':720,'height':500},device_scale_factor=2,reduced_motion='reduce')
|
||||
zp=zoom.new_page();zp.goto(BASE+READER,wait_until='networkidle');zp.wait_for_selector('.p-reading h2')
|
||||
assert zp.evaluate('document.documentElement.scrollWidth') <= 720
|
||||
zp.screenshot(path=str(OUT/'pantheon-reader-200-equivalent.png'))
|
||||
report.append({'view':'reader','check':'200% equivalent: 720 CSS px / DPR 2; reduced motion','scroll':720})
|
||||
zoom.close(); browser.close()
|
||||
assert not errors, errors
|
||||
(OUT/'pantheon-geometry.json').write_text(json.dumps({'checks':report,'js_errors':errors},ensure_ascii=False,indent=2)+'\n')
|
||||
print(f'PASS: {len(report)} geometry checks; no overflow; one search/main; aligned tabs; lining numerals; zero JS errors')
|
||||
|
||||
if __name__ == '__main__':main()
|
||||
@@ -0,0 +1,415 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Браузерная приемка раздела «Судебная практика» на ширинах 1440 и 390.
|
||||
|
||||
python3 eunomia/tests/practice_check.py
|
||||
|
||||
Без EUNOMIA_URL запросы браузера уходят в настоящий обработчик Эвномии через
|
||||
socketpair: порт не открывается, поэтому проверка идет и в песочнице. С
|
||||
EUNOMIA_URL проверяется уже запущенный сервер. Данные - живые: библиотека и
|
||||
хранилище практики корня Themiz. Снимки экрана содержат тексты актов и
|
||||
ложатся в .agent/ (вне git), в qa/ - только итог без текста актов.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, unquote, urlsplit
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
from chromium import executable
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
BASE = os.environ.get('EUNOMIA_URL', 'http://127.0.0.1:18765').rstrip('/')
|
||||
SHOTS = ROOT / '.agent/maintenance/practice/qa'
|
||||
REPORT = ROOT / 'eunomia/qa/practice-check.txt'
|
||||
AXE = ROOT / 'eunomia/frontend/node_modules/axe-core/axe.min.js'
|
||||
|
||||
|
||||
def bridge(app):
|
||||
"""Маршрут Playwright → обработчик Эвномии через socketpair, без сети."""
|
||||
from eunomia.server import handler
|
||||
serve_request = handler(app)
|
||||
fake = type('Server', (), {'server_port': 18765})()
|
||||
|
||||
def fulfil(route):
|
||||
request, url = route.request, urlsplit(route.request.url)
|
||||
target = url.path + ('?' + url.query if url.query else '')
|
||||
headers = ''.join(f'{k}: {v}\r\n' for k, v in request.headers.items() if k.lower() not in ('host', 'connection'))
|
||||
client, server_side = socket.socketpair()
|
||||
client.sendall(f'{request.method} {target} HTTP/1.1\r\nHost: 127.0.0.1:18765\r\n{headers}'
|
||||
f'Connection: close\r\n\r\n'.encode('latin-1', 'replace') + (request.post_data_buffer or b''))
|
||||
|
||||
def serve():
|
||||
try:
|
||||
serve_request(server_side, ('127.0.0.1', 0), fake)
|
||||
finally:
|
||||
server_side.close()
|
||||
|
||||
worker = threading.Thread(target=serve, daemon=True)
|
||||
worker.start()
|
||||
raw = b''
|
||||
while chunk := client.recv(1 << 16):
|
||||
raw += chunk
|
||||
worker.join(30)
|
||||
client.close()
|
||||
head, _, body = raw.partition(b'\r\n\r\n')
|
||||
lines = head.decode('latin-1').split('\r\n')
|
||||
route.fulfill(status=int(lines[0].split()[1]), body=body,
|
||||
headers=dict(line.split(': ', 1) for line in lines[1:] if ': ' in line))
|
||||
return fulfil
|
||||
|
||||
|
||||
class Check:
|
||||
"""Одна вкладка на обе ширины: одно-процессный Chromium в песочнице не переживает закрытие вкладки."""
|
||||
|
||||
def __init__(self, page):
|
||||
self.page, self.width, self.results, self.errors = page, 0, [], []
|
||||
page.on('pageerror', lambda error: self.errors.append(str(error)))
|
||||
page.on('console', lambda message: self.errors.append(f"{message.text} {message.location.get('url', '')}".strip())
|
||||
if message.type == 'error' else None) # адрес ответа 404 - в отчет: без него дефект не найти
|
||||
|
||||
def resize(self, width, height):
|
||||
self.width = width
|
||||
self.page.set_viewport_size({'width': width, 'height': height})
|
||||
|
||||
def check(self, name, ok, detail=''):
|
||||
self.results.append((f'{self.width}: {name}', bool(ok), str(detail)))
|
||||
|
||||
def open(self, fragment, selector):
|
||||
self.page.goto(BASE + '/' + fragment, wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector(selector, timeout=30000)
|
||||
self.page.wait_for_timeout(250)
|
||||
|
||||
def no_overflow(self, label):
|
||||
width = self.page.evaluate('() => document.documentElement.scrollWidth')
|
||||
self.check(f'{label}: без горизонтальной прокрутки', width <= self.width, f'{width}px')
|
||||
|
||||
def axe(self, label, scope):
|
||||
if not self.page.evaluate('() => !!window.axe'):
|
||||
return self.check(f'{label}: axe-core загружен', False, str(AXE))
|
||||
found = self.page.evaluate('''scope => axe.run({include: [[scope]]}, {runOnly: ['wcag2a', 'wcag2aa', 'wcag21aa', 'wcag22aa']})
|
||||
.then(r => r.violations.filter(v => ['serious', 'critical'].includes(v.impact)).map(v => v.id + ':' + v.nodes.length))''', scope)
|
||||
self.check(f'{label}: axe без серьезных нарушений', not found, ', '.join(found))
|
||||
|
||||
def shot(self, name, full=False):
|
||||
SHOTS.mkdir(parents=True, exist_ok=True)
|
||||
self.page.screenshot(path=str(SHOTS / f'{name}-{self.width}.png'), full_page=full)
|
||||
|
||||
def total(self):
|
||||
text = self.page.locator('.p-results-tools [role=status]').inner_text()
|
||||
digits = re.sub(r'\D', '', text)
|
||||
return int(digits) if digits else 0
|
||||
|
||||
|
||||
def desktop(check):
|
||||
page = check.page
|
||||
check.open('', '.p-practice-teaser')
|
||||
teaser = page.locator('.p-practice-teaser').inner_text()
|
||||
check.check('главная: блок «Судебная практика» с числом актов', re.search(r'\d[\d\s ]* акт', teaser), teaser.split('\n')[-2:])
|
||||
check.check('меню: пункт «Судебная практика»', page.get_by_role('link', name='Судебная практика').count() >= 1)
|
||||
check.axe('главная', '.p-practice-teaser')
|
||||
check.shot('home')
|
||||
page.locator('.p-practice-teaser a').click()
|
||||
page.wait_for_selector('.p-practice-row', timeout=30000)
|
||||
check.check('список: 12 актов на странице', page.locator('.p-practice-row').count() == 12, page.locator('.p-practice-row').count())
|
||||
check.check('список: общее число актов', check.total() > 0, check.total())
|
||||
check.axe('список', '.p-practice')
|
||||
check.no_overflow('список')
|
||||
|
||||
started = time.monotonic()
|
||||
page.get_by_role('searchbox', name='Слова или статья').fill('неустойка')
|
||||
page.get_by_role('button', name='Найти').click()
|
||||
page.wait_for_function("() => location.hash.includes('q=') && document.querySelector('.p-result-excerpt mark')", timeout=30000)
|
||||
check.check('поиск словами: найдено и подсвечено', check.total() > 0 and page.locator('.p-result-excerpt mark').count() > 0,
|
||||
f'{check.total()} актов, {round(time.monotonic() - started, 2)} с с отрисовкой')
|
||||
check.shot('search-words')
|
||||
|
||||
page.get_by_role('searchbox', name='Слова или статья').fill('ст. 333 ГК')
|
||||
page.get_by_role('button', name='Найти').click()
|
||||
page.wait_for_selector('.p-practice-articles .p-chip', timeout=30000)
|
||||
page.wait_for_function("() => document.querySelector('.p-practice-row')", timeout=30000)
|
||||
chip = page.locator('.p-practice-articles .p-chip').first.inner_text()
|
||||
excerpt = page.locator('.p-result-excerpt').first.inner_text()
|
||||
check.check('поиск по статье: «ст. 333 ГК» распознана', 'ст. 333 ГК РФ' in chip, chip)
|
||||
check.check('поиск по статье: цитата со ссылкой на 333', '333' in excerpt, f'{check.total()} актов')
|
||||
|
||||
page.locator('.p-practice-row h2 a').first.click()
|
||||
page.wait_for_selector('.p-practice-act h1', timeout=30000)
|
||||
page.wait_for_selector('.p-act-text p', timeout=30000)
|
||||
source = page.locator('.p-act-card a[target=_blank]').get_attribute('href') or ''
|
||||
digest = page.locator('.p-hash').inner_text().strip()
|
||||
check.check('акт: полный текст', page.locator('.p-act-text p').count() > 3, page.locator('.p-act-text p').count())
|
||||
check.check('акт: адрес источника', source.startswith('https://sudact.ru/'), source)
|
||||
check.check('акт: время загрузки', 'не указано' not in page.locator('.p-act-card dl').inner_text())
|
||||
check.check('акт: SHA-256 и сверка', re.fullmatch(r'[0-9a-f]{64}', digest) and page.get_by_text('Хеш совпал').count() == 1, digest[:12])
|
||||
articles = page.locator('#act-articles + ul li')
|
||||
check.check('акт: статьи, которые цитирует', articles.count() > 0 and page.locator('.p-act-aside').get_by_text('ст. 333 ГК РФ').count() >= 1,
|
||||
articles.count())
|
||||
check.check('акт: ссылки на статьи прямо в тексте', page.locator('.p-act-text a').count() > 0, page.locator('.p-act-text a').count())
|
||||
check.axe('акт', '.p-practice-act')
|
||||
check.no_overflow('акт')
|
||||
check.shot('act')
|
||||
|
||||
page.locator('.p-act-aside').get_by_role('link', name='ст. 333 ГК РФ', exact=True).click()
|
||||
page.wait_for_selector('.p-norm-practice', timeout=30000)
|
||||
fragment = unquote(parse_qs(urlsplit(page.url).fragment).get('fragment', [''])[0])
|
||||
norm = page.locator('.p-norm-practice').inner_text()
|
||||
check.check('статья 333 ГК открыта из акта', fragment.endswith('_article_333'), fragment)
|
||||
check.check('статья 333 ГК: «Практика по статье»', 'ст. 333 ГК РФ' in norm and re.search(r'\d+ акт', norm), norm.replace('\n', ' · '))
|
||||
check.shot('norm')
|
||||
page.locator('.p-norm-practice').click()
|
||||
page.wait_for_selector('.p-practice-row', timeout=30000)
|
||||
check.check('практика по статье: список актов', page.locator('#practice-title').inner_text() == 'Практика по ст. 333 ГК РФ' and check.total() > 0,
|
||||
check.total())
|
||||
month = page.locator('.p-practice-filters select').first
|
||||
value = month.locator('option').nth(1).get_attribute('value')
|
||||
month.select_option(value)
|
||||
page.wait_for_function(f"() => location.hash.includes('month={value}')", timeout=30000)
|
||||
page.wait_for_timeout(500)
|
||||
check.check('фильтр по месяцу сохраняет статью', 'article=333' in page.url, unquote(urlsplit(page.url).fragment))
|
||||
|
||||
check.open('#view=updates', '.p-load .p-load-count')
|
||||
page.wait_for_function("() => / из /.test(document.querySelector('.p-load .p-load-count').textContent)", timeout=30000)
|
||||
card = page.locator('.p-load').filter(has_text='Судебные акты').inner_text()
|
||||
check.check('состояние базы: сколько актов скачано из карты', re.search(r'Скачано [\d\s ]+ из [\d\s ]+ акт', card), card.split('\n')[1:4])
|
||||
|
||||
|
||||
# Подмененные ответы кнопок и полос: приемка не запускает настоящий обход СудАкта и проверку законов.
|
||||
def now_iso():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def acts(**walk):
|
||||
base = {'running': False, 'requested_at': None, 'stopped': None, 'at': '2026-10-03T01:51:30Z',
|
||||
'next_due': '2026-10-03T21:00:00Z', 'found': 0}
|
||||
running = walk.get('running')
|
||||
fresh = {'fresh': True, 'label': 'Актуально на сегодня', 'as_of': '03.10.2026', 'interval_days': 1}
|
||||
return {'done': 96000 if running else 96097, 'total': 96097, 'per_min': 120.0 if running else 0.0,
|
||||
'eta_min': 1 if running else 0, 'updated_at': now_iso(), 'walk': {**base, **walk},
|
||||
'freshness': {**fresh, 'fresh': False, 'label': 'Не актуально: идет обход СудАкта'} if running else fresh}
|
||||
|
||||
|
||||
def law(running=False):
|
||||
missing = [{'id': f'legal-corpus:code:c{n}', 'title': f'Кодекс {n}', 'reason': 'не хватило времени проверки, повтор позже'}
|
||||
for n in range(7)]
|
||||
return {'done': 100 if running else 445, 'total': 445, 'per_min': 12.0 if running else 0.0,
|
||||
'eta_min': 29 if running else 0, 'running': running, 'updated_at': now_iso(),
|
||||
'states': {'queued': 344, 'running': 1, 'blocked': 100} if running else {'blocked': 391, 'deferred': 54},
|
||||
'freshness': {'full': False, 'label': 'Корпус неполный: не готовы 7 документов из 445', 'as_of': None,
|
||||
'interval_days': 7, 'missing': missing}}
|
||||
|
||||
|
||||
def updates(check):
|
||||
"""«Состояние базы»: полосы «Судебные акты» и «Законодательство» с кнопками. Сначала живые данные,
|
||||
затем подмененные ответы: кнопка шлет POST с CSRF, во время работы вторую не запускает,
|
||||
остановку СудАкта называет."""
|
||||
page = check.page
|
||||
check.open('#view=updates', '.p-load progress')
|
||||
page.wait_for_function("() => [...document.querySelectorAll('.p-load .p-load-count')].filter(n => / из /.test(n.textContent)).length === 2",
|
||||
timeout=30000)
|
||||
labels = {'Судебные акты': ('Скачано', {'Обновить судебные акты', 'Обход идет…', 'Обход начнется…', 'Обход остановлен'}),
|
||||
'Законодательство': ('Готово', {'Обновить законодательство', 'Идет обновление…'})}
|
||||
for title, (word, names) in labels.items():
|
||||
card = page.locator('.p-load').filter(has=page.get_by_role('heading', name=title, exact=True))
|
||||
text, value = card.inner_text(), card.locator('progress').get_attribute('value')
|
||||
check.check(f'{title}: полоса 0-100 %, «{word} N из M»', card.count() == 1 and value is not None and 0 <= float(value) <= 100
|
||||
and re.search(rf'{word} [\d\s ]+ из [\d\s ]+', text) and '%' in text, text.split('\n')[1:3])
|
||||
button = card.locator('.p-load-actions button')
|
||||
name = button.inner_text().strip()
|
||||
check.check(f'{title}: кнопка обновления', button.count() == 1 and name in names, name)
|
||||
button.focus()
|
||||
page.keyboard.press('Shift+Tab')
|
||||
page.keyboard.press('Tab')
|
||||
ring = button.evaluate("b => b === document.activeElement && getComputedStyle(b).outlineStyle !== 'none' && parseFloat(getComputedStyle(b).outlineWidth) >= 2")
|
||||
check.check(f'{title}: фокус кнопки виден', ring)
|
||||
marks = {title: page.locator('.p-load').filter(has=page.get_by_role('heading', name=title, exact=True)).locator('.p-load-mark')
|
||||
for title in ('Судебные акты', 'Законодательство')}
|
||||
acts_mark, law_mark = (marks[title].inner_text().strip() if marks[title].count() else '' for title in marks)
|
||||
check.check('отметка свежести практики по живому состоянию', re.fullmatch(r'Актуально на сегодня|Не актуально: .+', acts_mark), acts_mark)
|
||||
check.check('отметка свежести законов по живому состоянию',
|
||||
re.fullmatch(r'Корпус полный · актуально на \d\d\.\d\d\.\d{4}|Корпус неполный: не готов.+|Корпус пуст.+', law_mark), law_mark)
|
||||
if law_mark.startswith('Корпус неполный'):
|
||||
listed = page.locator('.p-load-missing li')
|
||||
check.check('законы: недостача названа (до 5 пунктов и остаток числом)', 1 <= listed.count() <= 6 and ' — ' in listed.first.inner_text(),
|
||||
[listed.nth(n).inner_text() for n in range(min(listed.count(), 2))])
|
||||
check.axe('состояние базы', '.p-service-grid')
|
||||
check.no_overflow('состояние базы')
|
||||
check.shot('updates', full=True) # обе карточки целиком и на 390
|
||||
|
||||
state, posts = {'acts': acts(), 'law': law()}, []
|
||||
|
||||
def answer(key):
|
||||
return lambda route: route.fulfill(status=200, content_type='application/json; charset=utf-8',
|
||||
body=json.dumps(state[key], ensure_ascii=False))
|
||||
|
||||
def press(detail):
|
||||
def fulfil(route):
|
||||
posts.append((urlsplit(route.request.url).path, route.request.headers.get('x-eunomia-csrf', '')))
|
||||
route.fulfill(status=202, content_type='application/json; charset=utf-8',
|
||||
body=json.dumps({'ok': True, 'started': True, 'detail': detail}, ensure_ascii=False))
|
||||
return fulfil
|
||||
|
||||
routes = {BASE + '/api/practice/progress': answer('acts'), BASE + '/api/update/progress': answer('law'),
|
||||
BASE + '/api/practice/refresh': press('Обход СудАкта начнется в течение минуты.'),
|
||||
BASE + '/api/update': press('Задание сохранено в очереди Themiz.')}
|
||||
for url, handler in routes.items():
|
||||
page.route(url, handler)
|
||||
|
||||
def reload(selector): # тот же адрес: goto не перезагрузил бы страницу, полосы ждали бы опроса
|
||||
page.reload(wait_until='domcontentloaded')
|
||||
page.wait_for_selector(selector, timeout=30000)
|
||||
|
||||
try:
|
||||
reload('.p-load-actions .p-primary')
|
||||
page.wait_for_function("() => document.querySelectorAll('.p-load-mark').length === 2", timeout=10000)
|
||||
law_card = page.locator('.p-load').filter(has_text='Законодательство')
|
||||
items = [law_card.locator('.p-load-missing li').nth(n).inner_text() for n in range(law_card.locator('.p-load-missing li').count())]
|
||||
check.check('отметки: «Актуально на сегодня» и недостача законов с причинами, 5 пунктов и остаток',
|
||||
page.locator('.p-load-mark').first.inner_text().strip() == 'Актуально на сегодня'
|
||||
and law_card.locator('.p-load-mark').inner_text().strip() == 'Корпус неполный: не готовы 7 документов из 445'
|
||||
and items[:1] == ['Кодекс 0 — не хватило времени проверки, повтор позже'] and items[-1] == 'И еще 2' and len(items) == 6, items)
|
||||
for name, toast in (('Обновить судебные акты', 'в течение минуты'), ('Обновить законодательство', 'очереди')):
|
||||
page.get_by_role('button', name=name).click()
|
||||
page.wait_for_function(f"() => document.querySelector('.p-toast').textContent.includes('{toast}')", timeout=10000)
|
||||
check.check('кнопки: POST /api/practice/refresh и /api/update с CSRF',
|
||||
[path for path, _ in posts] == ['/api/practice/refresh', '/api/update'] and all(len(token) > 20 for _, token in posts), posts)
|
||||
state.update(acts=acts(running=True), law=law(running=True))
|
||||
reload('.p-load-wait')
|
||||
page.wait_for_function("() => document.querySelectorAll('.p-load-wait').length === 2", timeout=10000)
|
||||
busy = page.locator('.p-load-wait')
|
||||
for button in (busy.nth(0), busy.nth(1)):
|
||||
button.focus()
|
||||
page.keyboard.press('Enter')
|
||||
page.wait_for_timeout(300)
|
||||
acts_card = page.locator('.p-load').filter(has_text='Судебные акты').inner_text()
|
||||
check.check('во время работы: кнопки заняты и вторую работу не запускают',
|
||||
[busy.nth(n).inner_text().strip() for n in (0, 1)] == ['Обход идет…', 'Идет обновление…']
|
||||
and busy.nth(0).get_attribute('aria-disabled') == 'true' and len(posts) == 2, len(posts))
|
||||
check.check('во время работы: скорость и остаток', '120 в минуту, осталось около 1 мин' in acts_card, acts_card.split('\n')[3:5])
|
||||
state['acts'] = acts(stopped='часть 2: СудАкт отказал (rate_limited), повтор через неделю; все части остановлены')
|
||||
reload('.p-load [role=alert]')
|
||||
stopped = page.locator('.p-load').filter(has_text='Судебные акты')
|
||||
check.check('остановка СудАкта: кнопка говорит об этом и обход не запускает',
|
||||
stopped.locator('.p-load-actions button').inner_text().strip() == 'Обход остановлен'
|
||||
and 'rate_limited' in stopped.locator('[role=alert]').inner_text())
|
||||
finally:
|
||||
for url, handler in routes.items():
|
||||
page.unroute(url, handler)
|
||||
|
||||
|
||||
def areas(check):
|
||||
"""Отрасль «Семейные споры»: граф, подкатегории, пересечение, причина отнесения в акте."""
|
||||
page = check.page
|
||||
check.open('#view=practice', '.p-practice-divisions')
|
||||
divisions = page.locator('.p-practice-divisions').inner_text()
|
||||
check.check('деление: производства и отрасли', all(word.casefold() in divisions.casefold() for word in ('Производство', 'Гражданские', 'Отрасли', 'Семейные споры')),
|
||||
divisions.replace('\n', ' · ')[:160])
|
||||
page.locator('.p-practice-divisions a').filter(has_text='Семейные споры').click()
|
||||
page.wait_for_selector('.p-area-graph', timeout=30000)
|
||||
page.wait_for_function("() => document.querySelector('.p-practice-row')", timeout=30000)
|
||||
head = page.locator('.p-area-head').inner_text()
|
||||
area_total = int(re.search(r'(\d+) акт', head)[1])
|
||||
check.check('отрасль: граф с подкатегориями виден', page.locator('.p-area-graph .p-area-node').count() >= 3,
|
||||
page.locator('.p-area-graph .p-area-node').count())
|
||||
check.check('отрасль: список совпадает с числом отрасли', check.total() == area_total, f'{check.total()} = {area_total}')
|
||||
check.axe('отрасль', '.p-area')
|
||||
check.no_overflow('отрасль')
|
||||
check.shot('area')
|
||||
child = page.locator('.p-area-children a').nth(1)
|
||||
expected = int(child.locator('span').inner_text())
|
||||
child.click()
|
||||
page.wait_for_function("() => /area=family-[a-z]+(&|$)/.test(location.hash)", timeout=30000)
|
||||
page.wait_for_timeout(600)
|
||||
check.check('подкатегория: список по ней', check.total() == expected, f'{check.total()} = {expected}')
|
||||
cross = page.locator('.p-area-cross a').first
|
||||
if cross.count():
|
||||
shared = int(re.sub(r'\D', '', cross.locator('span').inner_text()))
|
||||
cross.click()
|
||||
page.wait_for_function("() => decodeURIComponent(location.hash).includes(',family-')", timeout=30000)
|
||||
page.wait_for_timeout(600)
|
||||
check.check('пересечение: общие акты двух подкатегорий', check.total() == shared, f'{check.total()} = {shared}')
|
||||
else:
|
||||
check.check('пересечение: есть хотя бы одно', False, 'нет пересечений в данных')
|
||||
page.locator('.p-practice-row h2 a').first.click()
|
||||
page.wait_for_selector('#act-areas', timeout=30000)
|
||||
card = page.locator('.p-act-areas').inner_text()
|
||||
check.check('акт: отрасль и причина отнесения', 'Семейные споры →' in card and ('предмет требования' in card or 'статьи' in card),
|
||||
card.replace('\n', ' · ')[:160])
|
||||
|
||||
|
||||
def mobile_areas(check):
|
||||
page = check.page
|
||||
check.open('#view=practice&area=family', '.p-area-children')
|
||||
check.check('отрасль: граф скрыт, подкатегории списком', not page.locator('.p-area-graph').is_visible()
|
||||
and page.locator('.p-area-children a').count() >= 3)
|
||||
check.no_overflow('отрасль')
|
||||
check.shot('area')
|
||||
|
||||
|
||||
def mobile(check):
|
||||
page = check.page
|
||||
check.open('', '.p-practice-teaser')
|
||||
check.no_overflow('главная')
|
||||
check.open('#view=practice', '.p-practice-row')
|
||||
check.check('список виден', page.locator('.p-practice-row').count() > 0)
|
||||
check.no_overflow('список')
|
||||
check.shot('list')
|
||||
page.locator('.p-practice-row h2 a').first.click()
|
||||
page.wait_for_selector('.p-act-text p', timeout=30000)
|
||||
check.no_overflow('акт')
|
||||
text_top = page.locator('.p-act-text').bounding_box()['y']
|
||||
aside_top = page.locator('.p-act-aside').bounding_box()['y']
|
||||
check.check('акт: текст выше панели источника', text_top < aside_top, f'{round(text_top)} < {round(aside_top)}')
|
||||
check.shot('act')
|
||||
|
||||
|
||||
def main():
|
||||
app = None
|
||||
if 'EUNOMIA_URL' not in os.environ:
|
||||
from eunomia.server import App
|
||||
app = App(ROOT)
|
||||
started = time.monotonic()
|
||||
app.library.refresh()
|
||||
print(f'библиотека готова за {round(time.monotonic() - started, 1)} с', flush=True)
|
||||
with sync_playwright() as playwright:
|
||||
chrome = executable()
|
||||
browser = playwright.chromium.launch(headless=True, executable_path=chrome,
|
||||
args=['--no-sandbox', '--single-process', '--no-zygote', '--disable-gpu'] if chrome else [])
|
||||
page = browser.new_page()
|
||||
if AXE.is_file(): # CSP Эвномии запрещает встроенные скрипты; init-скрипт идет мимо страницы
|
||||
page.add_init_script(path=str(AXE))
|
||||
if app is not None:
|
||||
page.route(BASE + '/**', bridge(app))
|
||||
check = Check(page)
|
||||
for width, height, scenario in ((1440, 1000, desktop), (1440, 1000, areas), (1440, 1000, updates),
|
||||
(390, 844, mobile), (390, 844, mobile_areas), (390, 844, updates)):
|
||||
check.resize(width, height)
|
||||
check.errors.clear()
|
||||
try:
|
||||
scenario(check)
|
||||
except Exception as exc:
|
||||
check.check('сценарий выполнен до конца', False, f'{type(exc).__name__}: {str(exc)[:300]}')
|
||||
check.check('без ошибок JavaScript', not check.errors, check.errors[:3])
|
||||
results = check.results
|
||||
browser.close()
|
||||
lines = [f"{'✓' if ok else '✗'} {name}{' — ' + detail if detail else ''}" for name, ok, detail in results]
|
||||
REPORT.parent.mkdir(exist_ok=True)
|
||||
REPORT.write_text(f'Приемка «Судебной практики» {time.strftime("%d.%m.%Y %H:%M")}\n' + '\n'.join(lines) + '\n', encoding='utf-8')
|
||||
print('\n'.join(lines))
|
||||
failed = sum(not ok for _, ok, _ in results)
|
||||
print(json.dumps({'checks': len(results), 'failed': failed, 'screenshots': str(SHOTS)}, ensure_ascii=False))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only React acceptance pass for the Eunomia redesign.
|
||||
|
||||
The check uses only GET requests against the already running local server. It
|
||||
does not press update/rebuild actions and does not modify the application.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import unquote, urlencode
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from playwright.sync_api import Page, TimeoutError as PlaywrightTimeoutError, sync_playwright
|
||||
|
||||
|
||||
BASE = os.environ.get("EUNOMIA_URL", "http://127.0.0.1:18765").rstrip("/")
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
QA = ROOT / "qa"
|
||||
|
||||
|
||||
class Acceptance:
|
||||
def __init__(self, page: Page) -> None:
|
||||
self.page = page
|
||||
self.results: list[dict[str, object]] = []
|
||||
self.js_errors: list[str] = []
|
||||
self.method_violations: list[str] = []
|
||||
page.on("pageerror", lambda error: self.js_errors.append(str(error)))
|
||||
page.on("request", self._request)
|
||||
|
||||
def _request(self, request) -> None:
|
||||
if request.method != "GET":
|
||||
self.method_violations.append(f"{request.method} {request.url}")
|
||||
|
||||
def check(self, name: str, condition: bool, detail: str = "") -> None:
|
||||
self.results.append({"name": name, "ok": bool(condition), "detail": detail})
|
||||
|
||||
def info(self, name: str, detail: str) -> None:
|
||||
self.results.append({"name": name, "ok": True, "info": True, "detail": detail})
|
||||
|
||||
def goto(self, hash_value: str = "") -> None:
|
||||
self.page.goto(BASE + ("/" + hash_value if hash_value.startswith("?") else "/"), wait_until="domcontentloaded", timeout=15000)
|
||||
self.page.wait_for_selector("#main-content", timeout=15000)
|
||||
self.page.wait_for_timeout(250)
|
||||
|
||||
def text(self) -> str:
|
||||
return self.page.locator("body").inner_text()
|
||||
|
||||
def screenshot(self, name: str) -> None:
|
||||
self.page.screenshot(path=str(QA / f"redesign-{name}.png"), full_page=False)
|
||||
|
||||
def overflow(self, width: int) -> None:
|
||||
self.page.set_viewport_size({"width": width, "height": 900 if width > 500 else 844})
|
||||
self.goto()
|
||||
value = self.page.evaluate("() => ({width: innerWidth, scroll: document.documentElement.scrollWidth})")
|
||||
self.check(f"no horizontal overflow at {width}px", value["scroll"] <= value["width"] + 1, str(value))
|
||||
|
||||
def home(self) -> None:
|
||||
self.page.set_viewport_size({"width": 1440, "height": 900})
|
||||
self.goto()
|
||||
self.check("home has five library sections", self.page.locator(".collection-grid .collection-link").count() == 5)
|
||||
self.check("home has global search", self.page.get_by_role("button", name="Поиск по библиотеке").count() == 1)
|
||||
self.check("home code shelf is visible", self.page.locator(".book-card").count() > 0)
|
||||
self.screenshot("home")
|
||||
|
||||
def images(self) -> None:
|
||||
self.page.goto(BASE + "/#view=category&kind=code", wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector(".book-card", timeout=15000)
|
||||
self.page.wait_for_timeout(250)
|
||||
cards = self.page.locator(".book-card")
|
||||
images = self.page.locator(".book-card img")
|
||||
loaded = self.page.evaluate("""() => [...document.querySelectorAll('.book-card img')].every(img => img.complete && img.naturalWidth > 0)""")
|
||||
self.check("code category has twelve cards", cards.count() == 12, str(cards.count()))
|
||||
self.check("all code card images loaded", bool(loaded), str(images.count()))
|
||||
|
||||
def sidebar(self) -> None:
|
||||
self.page.set_viewport_size({"width": 1440, "height": 900})
|
||||
self.goto()
|
||||
toggle = self.page.locator("#menu-toggle")
|
||||
self.check("desktop sidebar collapse control exists", toggle.count() == 1)
|
||||
if toggle.count():
|
||||
toggle.click()
|
||||
self.page.wait_for_timeout(100)
|
||||
collapsed = self.page.locator("#menu-toggle")
|
||||
self.check("desktop sidebar collapses", collapsed.get_attribute("aria-expanded") == "false")
|
||||
collapsed.click()
|
||||
self.page.set_viewport_size({"width": 390, "height": 844})
|
||||
self.goto()
|
||||
mobile = self.page.locator('[data-mobile="true"]')
|
||||
self.page.locator("#menu-toggle").click()
|
||||
self.page.wait_for_timeout(150)
|
||||
self.check("mobile sidebar opens in sheet", mobile.count() == 1 and mobile.is_visible())
|
||||
close = mobile.get_by_role("button", name="Закрыть")
|
||||
self.check("mobile sheet close is accessible", close.count() == 1 and close.is_visible())
|
||||
self.page.keyboard.press("Escape")
|
||||
self.page.wait_for_timeout(400)
|
||||
self.check("mobile sheet closes on Escape", not mobile.is_visible())
|
||||
self.check("mobile trigger regains focus", self.page.locator("#menu-toggle").evaluate("el => el === document.activeElement"))
|
||||
|
||||
def command_search(self) -> str | None:
|
||||
self.page.set_viewport_size({"width": 1440, "height": 900})
|
||||
self.goto()
|
||||
self.page.keyboard.press("Control+k")
|
||||
dialog = self.page.get_by_role("dialog")
|
||||
self.check("command opens with Control-K", dialog.count() == 1 and dialog.is_visible())
|
||||
self.check("command has accessible title", dialog.get_by_role("heading").count() >= 0 and bool(dialog.get_attribute("aria-labelledby")))
|
||||
search = dialog.locator('input[aria-label="Запрос для поиска"]')
|
||||
self.check("command input is accessible", search.count() == 1)
|
||||
if not search.count():
|
||||
return None
|
||||
search.fill("ст. 131 ГПК")
|
||||
try:
|
||||
self.page.wait_for_function("() => document.body.innerText.includes('Статья 131')", timeout=7000)
|
||||
except PlaywrightTimeoutError:
|
||||
self.info("command live query", "Результат статьи 131 не пришел за 7 секунд")
|
||||
return None
|
||||
result = dialog.get_by_role("option").filter(has_text="Статья 131").first
|
||||
if not result.count():
|
||||
result = dialog.get_by_text("Статья 131", exact=False).first
|
||||
self.check("command live query shows article result", result.count() == 1)
|
||||
self.screenshot("command")
|
||||
if result.count():
|
||||
result_value = result.get_attribute("data-value") or ""
|
||||
result.click()
|
||||
self.page.wait_for_timeout(500)
|
||||
url = self.page.url
|
||||
self.check("command result navigates to reader", "doc=" in url or "#view=reader" in url or "#doc=" in url, url)
|
||||
if "#doc=" in url or "#view=reader" in url or "doc=" in url:
|
||||
return url
|
||||
# Keep the failed click observable, then use the same GET search
|
||||
# result to exercise the reader checks independently.
|
||||
response = self.page.request.get(BASE + "/api/search?" + urlencode({"q": "ст. 131 ГПК"}))
|
||||
if response.ok:
|
||||
payload = response.json()
|
||||
rows = payload if isinstance(payload, list) else payload.get("results", [])
|
||||
if rows:
|
||||
row = rows[0]
|
||||
resource_id = row.get("resource_id") or row.get("resourceId")
|
||||
fragment_id = row.get("id") or row.get("fragment_id") or row.get("fragmentId")
|
||||
if resource_id and fragment_id:
|
||||
return BASE + "/#" + urlencode({"doc": resource_id, "fragment": fragment_id})
|
||||
self.info("reader acceptance", f"Переход не выполнен; значение команды: {result_value}")
|
||||
return None
|
||||
|
||||
def reader(self, reader_url: str | None) -> None:
|
||||
if not reader_url:
|
||||
self.info("reader acceptance", "Пропущено: поиск не дал точную статью")
|
||||
return
|
||||
self.page.set_viewport_size({"width": 1000, "height": 900})
|
||||
self.page.goto(reader_url, wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector(".reader-page", timeout=15000)
|
||||
self.check("reader exposes article heading", self.page.locator(".fragment-heading, h1").count() > 0)
|
||||
whole = self.page.get_by_role("button", name="Открыть весь документ")
|
||||
if whole.count():
|
||||
whole.click()
|
||||
self.page.wait_for_timeout(500)
|
||||
size = self.page.locator(".size-controls")
|
||||
before = size.locator("button").nth(1).count() if size.count() else 0
|
||||
self.check("reader font controls exist", before == 1)
|
||||
find = self.page.get_by_role("searchbox", name="Найти в документе")
|
||||
self.check("reader find input exists", find.count() == 1)
|
||||
if find.count():
|
||||
find.fill("статья")
|
||||
token = self.page.locator(".reading-text").evaluate("el => (el.textContent.match(/[А-Яа-яA-Za-z]{4,}/) || ['статья'])[0]")
|
||||
find.fill(token)
|
||||
self.page.get_by_role("button", name="Найти", exact=True).click()
|
||||
self.page.wait_for_timeout(250)
|
||||
self.check("reader find creates marks", self.page.locator(".reader-find mark, .reading-text mark").count() > 0, token)
|
||||
prev = self.page.get_by_role("button", name="Предыдущее совпадение")
|
||||
next_button = self.page.get_by_role("button", name="Следующее совпадение")
|
||||
self.check("reader find prev and next controls exist", prev.count() == 1 and next_button.count() == 1)
|
||||
self.screenshot("reader")
|
||||
self.page.set_viewport_size({"width": 390, "height": 844})
|
||||
self.page.reload(wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector(".reader-page", timeout=15000)
|
||||
related = self.page.get_by_role("button", name="Связи")
|
||||
if related.count():
|
||||
related.click()
|
||||
self.page.wait_for_timeout(150)
|
||||
overlay = self.page.locator('.reader-mobile-overlay[role="dialog"], .reader-mobile-sheet[role="dialog"]')
|
||||
try:
|
||||
overlay.wait_for(state="visible", timeout=2000)
|
||||
except PlaywrightTimeoutError:
|
||||
pass
|
||||
self.check("mobile related panel opens", overlay.count() == 1 and overlay.is_visible())
|
||||
self.screenshot("mobile")
|
||||
close = overlay.get_by_role("button", name="Закрыть")
|
||||
if close.count():
|
||||
close.click()
|
||||
elif overlay.count() and overlay.is_visible():
|
||||
overlay.click(position={"x": 2, "y": 2})
|
||||
self.page.set_viewport_size({"width": 1000, "height": 900})
|
||||
self.page.reload(wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector(".reader-page", timeout=15000)
|
||||
self.check("related panel exists at 1000px", self.page.locator(".reader-related").count() == 1)
|
||||
|
||||
def plenums(self) -> None:
|
||||
self.page.set_viewport_size({"width": 1440, "height": 900})
|
||||
self.page.goto(BASE + "/#view=category&kind=plenum", wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector("#main-content", timeout=15000)
|
||||
self.page.wait_for_timeout(500)
|
||||
topics = self.page.locator(".topic-card")
|
||||
self.check("plenum topics show eight directions", topics.count() == 8, str(topics.count()))
|
||||
sort = self.page.locator('select[name="sort"]')
|
||||
year = self.page.locator('select[name="year"]')
|
||||
self.check("plenum has sort and year filters", sort.count() == 1 and year.count() == 1)
|
||||
if sort.count():
|
||||
sort.select_option("new")
|
||||
self.page.get_by_role("button", name="Найти").click()
|
||||
self.page.wait_for_timeout(250)
|
||||
self.check("plenum newest sort is reflected", "sort=new" in self.page.url)
|
||||
sort.select_option("old")
|
||||
self.page.get_by_role("button", name="Найти").click()
|
||||
|
||||
def history(self) -> None:
|
||||
self.page.goto(BASE + "/#view=category&kind=code", wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector(".book-card", timeout=15000)
|
||||
links = self.page.locator("a.book-card")
|
||||
if not links.count():
|
||||
self.info("history acceptance", "Документная ссылка не найдена")
|
||||
return
|
||||
href = links.first.get_attribute("href") or ""
|
||||
doc_id = unquote(href.split("id=", 1)[-1].split("&", 1)[0])
|
||||
self.page.goto(BASE + "/#view=history&id=" + doc_id, wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector("#main-content", timeout=15000)
|
||||
self.page.wait_for_timeout(500)
|
||||
versions = self.page.locator(".version-list .document-row")
|
||||
if versions.count() < 2:
|
||||
self.info("history two versions", f"Доступно копий: {versions.count()}")
|
||||
return
|
||||
self.check("history exposes two versions", True)
|
||||
compare = self.page.get_by_role("button", name="Сравнить")
|
||||
self.check("history compare control exists", compare.count() == 1)
|
||||
if compare.count() and not compare.is_disabled():
|
||||
compare.click()
|
||||
self.page.wait_for_timeout(400)
|
||||
self.check("history compare returns a result", self.page.locator(".diff-columns, .empty-state").count() > 0)
|
||||
|
||||
def graph(self) -> None:
|
||||
self.page.set_viewport_size({"width": 1440, "height": 900})
|
||||
self.page.goto(BASE + "/#view=graph&q=395", wait_until="domcontentloaded")
|
||||
self.page.wait_for_selector("#main-content", timeout=15000)
|
||||
try:
|
||||
self.page.wait_for_function("() => !document.body.innerText.includes('Открываем сохраненные связи')", timeout=10000)
|
||||
except PlaywrightTimeoutError:
|
||||
self.info("graph 395", "Граф не отдал snapshot за 10 секунд")
|
||||
self.screenshot("graph")
|
||||
return
|
||||
candidates = self.page.get_by_role("button").filter(has_text="395")
|
||||
if not candidates.count():
|
||||
candidates = self.page.locator('[role="button"]').filter(has_text="395")
|
||||
self.check("graph search returns a 395 node", candidates.count() > 0)
|
||||
if candidates.count():
|
||||
candidates.first.click()
|
||||
self.page.wait_for_timeout(150)
|
||||
detail = self.page.locator(".selected-node")
|
||||
self.check("graph node opens focused detail", detail.count() == 1)
|
||||
evidence = detail.locator(".relation-detail")
|
||||
self.check("graph detail has evidence when relation exists", evidence.count() == 0 or evidence.first.inner_text().strip() != "")
|
||||
source = evidence.locator('a[href^="http"]') if evidence.count() else self.page.locator("a[href^='http']")
|
||||
self.info("graph source links", f"{source.count()} public source link(s) visible")
|
||||
self.screenshot("graph")
|
||||
|
||||
def run(self) -> int:
|
||||
self.home()
|
||||
self.images()
|
||||
self.sidebar()
|
||||
reader_url = self.command_search()
|
||||
self.reader(reader_url)
|
||||
self.plenums()
|
||||
self.history()
|
||||
self.graph()
|
||||
for width in (390, 720, 1000, 1440, 1920):
|
||||
self.overflow(width)
|
||||
self.page.emulate_media(reduced_motion="reduce")
|
||||
self.goto()
|
||||
effects = self.page.evaluate("""() => [...document.querySelectorAll('*')].filter(el => getComputedStyle(el).animationName !== 'none' && getComputedStyle(el).animationDuration !== '0s').length""")
|
||||
self.check("reduced motion has no active CSS effects", effects == 0, str(effects))
|
||||
self.check("no JavaScript errors", not self.js_errors, "; ".join(self.js_errors[:3]))
|
||||
self.check("no non-GET requests", not self.method_violations, "; ".join(self.method_violations[:3]))
|
||||
return 0 if all(item["ok"] for item in self.results if not item.get("info")) else 1
|
||||
|
||||
|
||||
def main() -> int:
|
||||
QA.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
check = Acceptance(page)
|
||||
try:
|
||||
code = check.run()
|
||||
except Exception as error: # retain the partial report for root
|
||||
check.check("acceptance runner completed", False, f"{type(error).__name__}: {error}")
|
||||
code = 1
|
||||
browser.close()
|
||||
except Exception as error:
|
||||
print(f"BLOCKED: {type(error).__name__}: {error}", file=sys.stderr)
|
||||
return 2
|
||||
report = {"base": BASE, "results": check.results, "js_errors": check.js_errors, "method_violations": check.method_violations}
|
||||
Path(QA / "redesign-check.txt").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
for item in check.results:
|
||||
mark = "INFO" if item.get("info") else "PASS" if item["ok"] else "FAIL"
|
||||
print(f"{mark} {item['name']}: {item.get('detail', '')}")
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,72 @@
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parents[1]))
|
||||
from graph_view import GraphView
|
||||
|
||||
|
||||
class AtomicContractTests(unittest.TestCase):
|
||||
def fixture(self):
|
||||
nodes = [{"id": i, "kind": "point" if i == "child" else "article",
|
||||
"resource_id": "code", "label": "Статья " + i}
|
||||
for i in ("focus", "child", "incoming", "target", "far", "unrelated")]
|
||||
edges = [
|
||||
{"source": "focus", "target": "child", "relation": "contains"},
|
||||
{"source": "incoming", "target": "focus", "relation": "references"},
|
||||
{"source": "child", "target": "target", "relation": "references"},
|
||||
{"source": "target", "target": "far", "relation": "references"},
|
||||
]
|
||||
return {"nodes": nodes, "edges": edges}
|
||||
|
||||
def test_family_expansion_does_not_walk_reference_neighbors(self):
|
||||
for reverse in (False, True):
|
||||
data = self.fixture()
|
||||
if reverse:
|
||||
data["edges"].reverse()
|
||||
value = GraphView(data).network(level="atoms", node_id="focus")
|
||||
self.assertEqual({n["id"] for n in value["nodes"]}, {"focus", "child", "incoming", "target"})
|
||||
self.assertNotIn("far", {n["id"] for n in value["nodes"]})
|
||||
|
||||
def test_structure_toggle_never_removes_child_citations(self):
|
||||
view = GraphView(self.fixture())
|
||||
results = [view.network(level="atoms", node_id="focus", include_contains=flag)
|
||||
for flag in (True, False)]
|
||||
references = [{(e["source"], e["target"]) for e in result["edges"]
|
||||
if e["relation"] == "references"} for result in results]
|
||||
self.assertEqual(references[0], references[1])
|
||||
self.assertIn(("child", "target"), references[0])
|
||||
|
||||
def test_parent_child_duplicate_requires_same_provenance(self):
|
||||
data = self.fixture()
|
||||
for e in data["edges"]:
|
||||
if e["source"] == "child":
|
||||
e.update(source_file="code.md", source_location="L40", evidence={"excerpt": "precise child mention"})
|
||||
data["edges"].append({"source": "focus", "target": "target", "relation": "references",
|
||||
"source_file": "code.md", "source_location": "L40"})
|
||||
view = GraphView(data)
|
||||
edges = view.network(level="atoms", node_id="focus")["edges"]
|
||||
self.assertFalse(any(e["source"] == "focus" and e["target"] == "target" for e in edges))
|
||||
self.assertTrue(any(e["source"] == "child" and e["target"] == "target" for e in edges))
|
||||
self.assertEqual(len(view.edges), 5) # Raw/legacy graph is untouched.
|
||||
data["edges"][-1]["source_location"] = "L15"
|
||||
edges = GraphView(data).network(level="atoms", node_id="focus")["edges"]
|
||||
self.assertTrue(any(e["source"] == "focus" and e["target"] == "target" for e in edges))
|
||||
|
||||
def test_overview_bound_keeps_counterpart_points_and_honest_totals(self):
|
||||
data = self.fixture()
|
||||
value = GraphView(data).network(level="atoms", max_nodes=2)
|
||||
self.assertEqual(len(value["nodes"]), 2)
|
||||
self.assertEqual(value["total_nodes"], 6)
|
||||
self.assertEqual(value["total_edges"], 4)
|
||||
self.assertTrue(value["edges"])
|
||||
self.assertTrue(value["truncated"])
|
||||
|
||||
def test_missing_focus_never_returns_whole_code(self):
|
||||
result = GraphView(self.fixture()).network(level="atoms", node_id="missing", resource_id="code")
|
||||
self.assertEqual(result["status"], "focus_not_found")
|
||||
self.assertEqual(result["nodes"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отметки свежести «Состояния базы» (решение владельца 03.10.2026): законы - «Корпус полный · актуально на
|
||||
ДД.ММ.ГГГГ» или что не готово и почему; практика - «Актуально на сегодня» или почему нет. Живое состояние,
|
||||
а не текст: очередь законов, parts/state.json и подсчет скачанного."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from eunomia import practice # noqa: E402
|
||||
from eunomia.server import App # noqa: E402
|
||||
from test_practice import get # noqa: E402
|
||||
|
||||
DAY = 86400
|
||||
|
||||
|
||||
def iso(moment: float) -> str:
|
||||
return datetime.fromtimestamp(moment).astimezone().isoformat()
|
||||
|
||||
|
||||
def day(moment: float) -> str:
|
||||
return datetime.fromtimestamp(moment).strftime('%d.%m.%Y')
|
||||
|
||||
|
||||
def job(resource_id: str, state: str, checked: float | None, detail: str = '', **rest) -> dict:
|
||||
return {'id': resource_id, 'state': state, 'detail': detail, 'last_checked': iso(checked) if checked else None,
|
||||
'finished_at': None, 'updated_at': time.time() - 3600, **rest}
|
||||
|
||||
|
||||
class FreshnessTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name)
|
||||
self.app = App(self.root)
|
||||
|
||||
def law(self, *jobs: dict) -> dict:
|
||||
queue = {'ok': True, 'queue': {}, 'jobs': list(jobs)}
|
||||
with mock.patch('background_corpus.status', return_value=queue):
|
||||
code, value = get(self.app, '/api/update/progress')
|
||||
self.assertEqual(code, 200)
|
||||
return value['freshness']
|
||||
|
||||
def acts(self, downloaded: int, total: int, **walk) -> dict:
|
||||
path = self.root / practice.STATE_REL / 'parts' / 'state.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps({'active': 10, **walk}), encoding='utf-8')
|
||||
counted = {'done': downloaded, 'total': total, 'per_min': 0.0, 'eta_min': 0, 'updated_at': '2026-10-03T09:00:00Z'}
|
||||
self.app.cache.clear() # полоса кешируется на 5 с, а здесь каждое состояние новое
|
||||
with mock.patch('eunomia.server.progress', lambda root: counted):
|
||||
code, value = get(self.app, '/api/practice/progress')
|
||||
self.assertEqual(code, 200)
|
||||
return value['freshness']
|
||||
|
||||
def test_law_corpus_full_when_every_document_is_current_and_checked_this_week(self):
|
||||
now = time.time()
|
||||
mark = self.law(job('legal-corpus:code:gk-rf', 'current', now - 2 * DAY),
|
||||
job('legal-corpus:plenum:plenum-ot-24032016', 'updated', now - 3600))
|
||||
self.assertTrue(mark['full'])
|
||||
self.assertEqual(mark['label'], f'Корпус полный · актуально на {day(now - 2 * DAY)}') # дата самой старой проверки
|
||||
self.assertEqual((mark['missing'], mark['interval_days']), ([], 7))
|
||||
|
||||
def test_law_mark_counts_and_names_what_is_missing_with_reason(self):
|
||||
now = time.time()
|
||||
mark = self.law(job('legal-corpus:code:gk-rf', 'current', now - DAY),
|
||||
job('legal-corpus:code:tk-rf', 'deferred', now - 20 * DAY, 'job превысил 120.0 с'),
|
||||
job('legal-corpus:code:sk-rf', 'current', now - 8 * DAY),
|
||||
job('legal-corpus:review:vsrf-review-1-2024', 'blocked', None, 'review_parser_not_verified'),
|
||||
job('legal-corpus:act:pp-152-13-02-2024', 'queued', None))
|
||||
self.assertFalse(mark['full'])
|
||||
self.assertEqual(mark['label'], 'Корпус неполный: не готовы 4 документа из 5')
|
||||
reasons = {item['id']: item['reason'] for item in mark['missing']}
|
||||
self.assertEqual(set(reasons), {'legal-corpus:code:tk-rf', 'legal-corpus:code:sk-rf',
|
||||
'legal-corpus:review:vsrf-review-1-2024', 'legal-corpus:act:pp-152-13-02-2024'})
|
||||
self.assertIn('не уложилась в срок', reasons['legal-corpus:code:tk-rf'])
|
||||
self.assertIn(f'проверен {day(now - 8 * DAY)}', reasons['legal-corpus:code:sk-rf']) # старше недели - не актуален
|
||||
self.assertIn('разборщик обзоров', reasons['legal-corpus:review:vsrf-review-1-2024'])
|
||||
self.assertTrue(all(item['title'] for item in mark['missing']))
|
||||
|
||||
def test_law_mark_on_empty_queue_is_not_full(self):
|
||||
self.assertFalse(self.law()['full'])
|
||||
|
||||
def test_practice_actual_today_when_daily_walk_ended_today_and_nothing_left(self):
|
||||
now = datetime.now().astimezone()
|
||||
mark = self.acts(96097, 96097, done=True, at=now.isoformat(), next_due=(now + timedelta(hours=8)).isoformat())
|
||||
self.assertTrue(mark['fresh'])
|
||||
self.assertEqual((mark['label'], mark['interval_days']), ('Актуально на сегодня', 1))
|
||||
|
||||
def test_practice_not_actual_after_yesterday_walk_or_with_acts_left(self):
|
||||
yesterday = datetime.now().astimezone() - timedelta(days=1)
|
||||
mark = self.acts(96097, 96097, done=True, at=yesterday.isoformat())
|
||||
self.assertFalse(mark['fresh'])
|
||||
self.assertIn(f"обход {yesterday.strftime('%d.%m.%Y')}", mark['label'])
|
||||
mark = self.acts(96000, 96097, done=True, at=datetime.now().astimezone().isoformat())
|
||||
self.assertFalse(mark['fresh'])
|
||||
self.assertIn('не скачаны 97 актов', mark['label'])
|
||||
mark = self.acts(96097, 96097, at=datetime.now().astimezone().isoformat()) # обход идет: еще не закончился
|
||||
self.assertFalse(mark['fresh'])
|
||||
mark = self.acts(96097, 96097, done=True, at=datetime.now().astimezone().isoformat(),
|
||||
stopped='часть 2: СудАкт отказал (rate_limited)')
|
||||
self.assertFalse(mark['fresh'])
|
||||
self.assertIn('rate_limited', mark['label'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The built UI and generated art must stay inside the static web directory."""
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from eunomia.server import handler
|
||||
|
||||
|
||||
class StaticFrontendTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.web = Path(self.tmp.name) / 'web'
|
||||
(self.web / 'dist/assets').mkdir(parents=True)
|
||||
(self.web / 'assets/books').mkdir(parents=True)
|
||||
(self.web / 'assets/pantheon').mkdir(parents=True)
|
||||
(self.web / 'index.html').write_text('old interface')
|
||||
(self.web / 'dist/index.html').write_text('React interface')
|
||||
(self.web / 'dist/assets/index-ABC.js').write_text('const app = true;')
|
||||
(self.web / 'assets/books/gk-rf.webp').write_bytes(b'RIFF-test')
|
||||
(self.web / 'assets/pantheon/gk-rf.webp').write_bytes(b'RIFF-pantheon-test')
|
||||
self.secret = Path(self.tmp.name) / 'private.txt'
|
||||
self.secret.write_text('must not be served')
|
||||
(self.web / 'assets/leak.webp').symlink_to(self.secret)
|
||||
patcher = patch('eunomia.server.WEB', self.web)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.server = ThreadingHTTPServer(('127.0.0.1', 0), handler(object()))
|
||||
self.addCleanup(self.server.server_close)
|
||||
self.addCleanup(self.server.shutdown)
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.base = f'http://127.0.0.1:{self.server.server_port}'
|
||||
|
||||
def test_built_index_and_assets_have_correct_content_types(self):
|
||||
with urllib.request.urlopen(self.base + '/') as response:
|
||||
self.assertEqual(response.read(), b'React interface')
|
||||
self.assertIn("default-src 'self'", response.headers['Content-Security-Policy'])
|
||||
with urllib.request.urlopen(self.base + '/assets/index-ABC.js') as response:
|
||||
self.assertIn('javascript', response.headers['Content-Type'])
|
||||
with urllib.request.urlopen(self.base + '/assets/books/gk-rf.webp') as response:
|
||||
self.assertEqual(response.headers['Content-Type'], 'image/webp')
|
||||
with urllib.request.urlopen(self.base + '/assets/pantheon/gk-rf.webp') as response:
|
||||
self.assertEqual(response.read(), b'RIFF-pantheon-test')
|
||||
self.assertEqual(response.headers['Content-Type'], 'image/webp')
|
||||
|
||||
def test_paths_and_symlinks_cannot_escape_static_directory(self):
|
||||
for path in ['/assets/../private.txt', '/assets/%2e%2e/private.txt', '/assets/leak.webp', '/assets/pantheon/../private.txt', '/assets/pantheon/missing.webp', '/assets/missing.js']:
|
||||
with self.subTest(path=path), self.assertRaises(urllib.error.HTTPError) as error:
|
||||
urllib.request.urlopen(self.base + path)
|
||||
self.assertEqual(error.exception.code, 404)
|
||||
|
||||
def test_foreign_origin_cannot_read_assets(self):
|
||||
request = urllib.request.Request(self.base + '/assets/books/gk-rf.webp', headers={'Origin': 'https://example.test'})
|
||||
with self.assertRaises(urllib.error.HTTPError) as error:
|
||||
urllib.request.urlopen(request)
|
||||
self.assertEqual(error.exception.code, 403)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,192 @@
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parents[1]))
|
||||
sys.path.insert(0, str(Path(__file__).parents[2] / "scripts"))
|
||||
from graph_view import GraphView, GraphViewCache
|
||||
|
||||
|
||||
class GraphViewTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.gk = {"id": "gk395", "kind": "article", "label": "Статья 395 ГК РФ"}
|
||||
self.plenum = {"id": "plenum72", "kind": "point", "label": "Пункт 72"}
|
||||
self.data = {"snapshot": "s1", "stale": False, "warnings": [],
|
||||
"nodes": [self.gk, self.plenum], "edges": [{
|
||||
"source": "plenum72", "target": "gk395", "relation": "references",
|
||||
"evidence": {"excerpt": "пункт 6 статьи 395 ГК РФ",
|
||||
"source_url": "https://example.test/a", "revision": "24.06.2025"}}]}
|
||||
|
||||
def test_ego_keeps_exact_opaque_ids_and_evidence(self):
|
||||
view = GraphView(self.data)
|
||||
result = view.ego("gk395")
|
||||
self.assertEqual({node["id"] for node in result["nodes"]}, {"gk395", "plenum72"})
|
||||
self.assertEqual(result["edges"][0]["evidence"]["revision"], "24.06.2025")
|
||||
page = view.ego("gk395", limit=1, offset=1)
|
||||
self.assertEqual(page["offset"], 1)
|
||||
self.assertIn("has_more", page)
|
||||
|
||||
def test_cluster_filter_and_edge_lookup(self):
|
||||
view = GraphView(self.data)
|
||||
self.assertEqual(view.clustered(kind="article")["nodes"], [])
|
||||
self.assertEqual(view.clustered(query="статья 395")["nodes"][0]["id"], "gk395")
|
||||
self.assertEqual(view.edge("plenum72", "gk395")["status"], "ok")
|
||||
|
||||
def test_graph_view_keeps_metadata_without_retaining_node_body(self):
|
||||
data = {**self.data, "nodes": [{**self.gk, "body": "large text"}]}
|
||||
node = GraphView(data).nodes["gk395"]
|
||||
self.assertEqual(node["label"], "Статья 395 ГК РФ")
|
||||
self.assertNotIn("body", node)
|
||||
|
||||
def test_network_overview_aggregates_real_edges_and_atoms_keep_references(self):
|
||||
data = {
|
||||
"snapshot": "s1", "nodes": [
|
||||
{"id": "doc-gk", "kind": "document", "resource_id": "gk", "label": "Гражданский кодекс"},
|
||||
{"id": "doc-gpk", "kind": "document", "resource_id": "gpk", "label": "Гражданский процессуальный кодекс"},
|
||||
{"id": "gk395", "kind": "article", "resource_id": "gk", "label": "Статья 395 ГК РФ"},
|
||||
{"id": "gpk131", "kind": "article", "resource_id": "gpk", "label": "Статья 131 ГПК РФ"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "gk395", "target": "gpk131", "relation": "references", "evidence": {"excerpt": "395"}},
|
||||
{"source": "gk395", "target": "gpk131", "relation": "references"},
|
||||
{"source": "doc-gk", "target": "gk395", "relation": "contains"},
|
||||
{"source": "doc-gpk", "target": "gpk131", "relation": "contains"},
|
||||
],
|
||||
}
|
||||
view = GraphView(data)
|
||||
overview = view.network()
|
||||
self.assertEqual({n["id"] for n in overview["nodes"]}, {"doc-gk", "doc-gpk"})
|
||||
self.assertEqual(len(overview["edges"]), 1)
|
||||
self.assertEqual(overview["edges"][0]["count"], 2)
|
||||
self.assertEqual(overview["edges"][0]["evidence"]["excerpt"], "395")
|
||||
atoms = view.network(level="atoms", resource_id="gk")
|
||||
self.assertEqual({n["id"] for n in atoms["nodes"]}, {"gk395", "gpk131"})
|
||||
self.assertEqual({e["relation"] for e in atoms["edges"]}, {"references"})
|
||||
self.assertLessEqual(len(atoms["nodes"]), 1000)
|
||||
self.assertLessEqual(len(atoms["edges"]), 5000)
|
||||
|
||||
def test_network_query_and_bounds_are_deterministic(self):
|
||||
view = GraphView({
|
||||
"nodes": [{"id": "d", "kind": "document", "resource_id": "r", "label": "Нужный документ"}],
|
||||
"edges": [],
|
||||
})
|
||||
result = view.network(query="нужный", max_nodes=0, max_edges=0)
|
||||
self.assertEqual(result["nodes"][0]["id"], "d")
|
||||
self.assertEqual(result["displayed_nodes"], 1)
|
||||
|
||||
def test_network_kind_uses_resource_id_when_snapshot_lacks_document_kind(self):
|
||||
view = GraphView({
|
||||
"nodes": [
|
||||
{"id": "plenum-doc", "kind": "document", "resource_id": "legal-corpus:plenum:vs-1", "label": "Пленум"},
|
||||
{"id": "act-doc", "kind": "document", "resource_id": "legal-corpus:act:act-1", "label": "Акт"},
|
||||
], "edges": []})
|
||||
result = view.network(kind="plenum")
|
||||
self.assertEqual([node["id"] for node in result["nodes"]], ["plenum-doc"])
|
||||
atoms = GraphView({"nodes": [
|
||||
{"id": "p1", "kind": "article", "resource_id": "legal-corpus:plenum:p", "label": "Пункт 1"},
|
||||
{"id": "c1", "kind": "article", "resource_id": "legal-corpus:code:c", "label": "Статья 1"},
|
||||
], "edges": []}).network(level="atoms", kind="plenum")
|
||||
self.assertEqual([node["id"] for node in atoms["nodes"]], ["p1"])
|
||||
|
||||
def test_atomic_focus_is_exact_and_keeps_inbound_outbound_and_children(self):
|
||||
data = {"nodes": [
|
||||
{"id": "a", "kind": "article", "resource_id": "r", "label": "Статья 1"},
|
||||
{"id": "child", "kind": "point", "resource_id": "r", "label": "Пункт 1"},
|
||||
{"id": "incoming", "kind": "article", "resource_id": "other", "label": "Статья 2"},
|
||||
{"id": "outgoing", "kind": "point", "resource_id": "other", "label": "Пункт 2"},
|
||||
{"id": "unrelated", "kind": "article", "resource_id": "r", "label": "Статья 99"},
|
||||
], "edges": [
|
||||
{"source": "a", "target": "child", "relation": "contains"},
|
||||
{"source": "incoming", "target": "a", "relation": "references"},
|
||||
{"source": "a", "target": "outgoing", "relation": "references"},
|
||||
{"source": "child", "target": "incoming", "relation": "references"},
|
||||
]}
|
||||
result = GraphView(data).network(level="atoms", node_id="a", max_nodes=10)
|
||||
self.assertEqual({n["id"] for n in result["nodes"]}, {"a", "child", "incoming", "outgoing"})
|
||||
self.assertEqual({e["relation"] for e in result["edges"]}, {"contains", "references"})
|
||||
self.assertEqual(result["focus_id"], "a")
|
||||
self.assertNotIn("unrelated", {n["id"] for n in result["nodes"]})
|
||||
|
||||
def test_atomic_focus_unknown_is_honest_and_anchor_survives_limit(self):
|
||||
data = {"nodes": [{"id": "a", "kind": "article", "resource_id": "r", "label": "Статья 1"}], "edges": []}
|
||||
view = GraphView(data)
|
||||
self.assertEqual(view.network(level="atoms", node_id="missing")["status"], "focus_not_found")
|
||||
self.assertEqual(view.network(level="atoms", node_id="a", max_nodes=1)["nodes"][0]["id"], "a")
|
||||
|
||||
def test_atomic_numeric_query_does_not_match_larger_article_number(self):
|
||||
view = GraphView({"nodes": [
|
||||
{"id": "a395", "kind": "article", "resource_id": "r", "label": "Статья 395"},
|
||||
{"id": "a1395", "kind": "article", "resource_id": "r", "label": "Статья 1395"},
|
||||
], "edges": []})
|
||||
self.assertEqual([n["id"] for n in view.network(level="atoms", query="ст. 395")["nodes"]], ["a395"])
|
||||
|
||||
def test_cache_ensure_is_nonblocking_and_loads_in_background(self):
|
||||
with patch("scripts.legal_graph.graph_data", return_value=self.data):
|
||||
cache = GraphViewCache("/tmp/themiz")
|
||||
started = time.monotonic()
|
||||
state = cache.ensure()
|
||||
self.assertLess(time.monotonic() - started, 0.1)
|
||||
self.assertTrue(state["loading"])
|
||||
for _ in range(50):
|
||||
if cache.get() is not None:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
self.assertEqual(cache.get().snapshot, "s1")
|
||||
|
||||
def test_repeated_ensure_does_not_reload_same_pointer(self):
|
||||
with patch("scripts.legal_graph.graph_data", return_value=self.data) as loader:
|
||||
cache = GraphViewCache("/tmp/themiz")
|
||||
cache.ensure()
|
||||
for _ in range(50):
|
||||
if cache.get() is not None: break
|
||||
time.sleep(0.01)
|
||||
self.assertTrue(cache.get())
|
||||
state = cache.ensure()
|
||||
self.assertFalse(state["loading"])
|
||||
self.assertEqual(loader.call_count, 1)
|
||||
|
||||
def test_same_pointer_does_not_reload_after_refresh_interval(self):
|
||||
with patch("scripts.legal_graph.graph_data", return_value=self.data) as loader:
|
||||
cache = GraphViewCache("/tmp/themiz")
|
||||
cache.ensure()
|
||||
for _ in range(50):
|
||||
if cache.get() is not None:
|
||||
break
|
||||
time.sleep(0.01)
|
||||
cache._checked = 0.0
|
||||
state = cache.ensure()
|
||||
self.assertFalse(state["loading"])
|
||||
self.assertEqual(loader.call_count, 1)
|
||||
|
||||
def test_source_metadata_change_marks_cached_view_stale(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
state = root / ".agent/maintenance/legal-graph"
|
||||
snapshot = state / "snapshots/s1"
|
||||
source = root / "source.md"
|
||||
source.write_text("original", encoding="utf-8")
|
||||
snapshot.mkdir(parents=True)
|
||||
(state / "current.json").write_text("{}", encoding="utf-8")
|
||||
(snapshot / "source-manifest.json").write_text(
|
||||
json.dumps({"documents": [{"relative_path": "source.md"}]}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
with patch("scripts.legal_graph.graph_data", return_value=self.data):
|
||||
cache = GraphViewCache(root)
|
||||
cache.ensure()
|
||||
for _ in range(50):
|
||||
if cache.get() is not None: break
|
||||
time.sleep(0.01)
|
||||
os.utime(source, ns=(source.stat().st_atime_ns, source.stat().st_mtime_ns + 1_000_000))
|
||||
cache._checked = 0.0
|
||||
state = cache.ensure()
|
||||
self.assertTrue(state["stale"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Небольшие контракты данных, от которых зависит UI библиотеки Eunomia."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
import legal_graph # noqa: E402
|
||||
from eunomia.library import Library, fragments # noqa: E402
|
||||
from eunomia.server import App # noqa: E402
|
||||
from eunomia.graph_view import GraphView # noqa: E402
|
||||
|
||||
|
||||
def act(*, kind="plenum", title="Акт", number=None, date=None):
|
||||
return {
|
||||
"id": "legal-corpus:%s:synthetic" % kind,
|
||||
"kind": kind,
|
||||
"url": "https://example.test/synthetic",
|
||||
"output": "knowledge/plenumy/synthetic.md",
|
||||
"title": title,
|
||||
"number": number,
|
||||
"date": date,
|
||||
"entry": {},
|
||||
}
|
||||
|
||||
|
||||
class LibrarySummaryContractTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.library = Library(Path(self.tmp.name))
|
||||
|
||||
def summary(self, resource, body, *, meta=None):
|
||||
return self.library._summary(resource, meta or {}, body, True)
|
||||
|
||||
def test_act_date_comes_from_identity_not_revision(self):
|
||||
resource = act(
|
||||
title="Федеральный закон от 12.03.2024 № 42-ФЗ О порядке обращения",
|
||||
)
|
||||
value = self.summary(
|
||||
resource,
|
||||
"# Федеральный закон от 12.03.2024 № 42-ФЗ О порядке обращения\n",
|
||||
meta={"дата_редакции": "08.09.2026"},
|
||||
)
|
||||
self.assertEqual(value["act_date"], "12.03.2024")
|
||||
self.assertEqual(value["revision"], "08.09.2026")
|
||||
self.assertNotEqual(value["act_date"], value["revision"])
|
||||
|
||||
def test_plenum_subject_after_title_and_revision_is_extracted(self):
|
||||
resource = act(
|
||||
title="Постановление Пленума ВС РФ от 12.03.2024 № 42 (ред. от 01.09.2026)"
|
||||
)
|
||||
body = (
|
||||
"# Постановление Пленума ВС РФ от 12.03.2024 № 42 (ред. от 01.09.2026)\n\n"
|
||||
"О некоторых вопросах применения судами законодательства о доказательствах\n\n"
|
||||
"1. Разъяснить судам порядок применения.\n"
|
||||
)
|
||||
value = self.summary(resource, body, meta={"дата_редакции": "01.09.2026"})
|
||||
self.assertEqual(value["act_date"], "12.03.2024")
|
||||
self.assertEqual(value["number"], "42")
|
||||
self.assertEqual(
|
||||
value["subject"],
|
||||
"О некоторых вопросах применения судами законодательства о доказательствах",
|
||||
)
|
||||
|
||||
def test_number_is_numeric_and_unknown_date_stays_null(self):
|
||||
resource = act(
|
||||
title="Постановление Пленума ВС РФ № 7 О практике рассмотрения дел",
|
||||
)
|
||||
value = self.summary(
|
||||
resource,
|
||||
"# Постановление Пленума ВС РФ № 7 О практике рассмотрения дел\n",
|
||||
meta={"дата_редакции": "08.09.2026", "закон": "№ 7"},
|
||||
)
|
||||
self.assertIsNone(value["act_date"])
|
||||
self.assertEqual(value["number"], "7")
|
||||
self.assertIsInstance(value["number"], str)
|
||||
|
||||
def test_fragment_anchors_are_stable_and_unique(self):
|
||||
resource = act(kind="code", title="ГПК РФ")
|
||||
body = (
|
||||
"# ГПК РФ\n\n"
|
||||
"## Статья 131. Форма заявления\n"
|
||||
"1. Первый пункт.\n2. Второй пункт.\n\n"
|
||||
"## Статья 132. Приложения\n"
|
||||
"1. Документы.\n"
|
||||
)
|
||||
items = fragments(resource["id"], body)
|
||||
ids = [item["id"] for item in items]
|
||||
anchors = [anchor["id"] for item in items for anchor in item.get("anchors", [])]
|
||||
base = legal_graph._graph_id(resource["id"])
|
||||
self.assertIn(f"{base}_article_131", ids)
|
||||
self.assertIn(f"{base}_article_132", ids)
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
self.assertEqual(len(anchors), len(set(anchors)))
|
||||
self.assertIn(f"{base}_article_131_point_1", anchors)
|
||||
self.assertIn(f"{base}_article_131_point_2", anchors)
|
||||
|
||||
def test_status_keeps_readable_fallback_when_schedule_fails(self):
|
||||
app = App(Path(self.tmp.name))
|
||||
with mock.patch("background_corpus.status", return_value={"queue": {}, "jobs": []}), \
|
||||
mock.patch("background_corpus.enabled", return_value=False), \
|
||||
mock.patch("background_corpus.schedule", side_effect=RuntimeError("queue unavailable")):
|
||||
status = app.status()
|
||||
self.assertEqual(status["schedule"]["next_run"], None)
|
||||
self.assertFalse(status["schedule"]["enabled"])
|
||||
self.assertIn("ручные задания", status["schedule"]["detail"].lower())
|
||||
|
||||
def test_graph_reader_point_does_not_resolve_to_parent_article(self):
|
||||
resource = act(kind="code", title="ГПК РФ")
|
||||
body = "## Статья 131. Форма заявления\n1. Первый пункт.\n2. Второй пункт.\n1) Вложенный пункт.\n"
|
||||
parts = fragments(resource["id"], body)
|
||||
article = next(p for p in parts if p["kind"] == "article")
|
||||
anchor = article["anchors"][0]
|
||||
self.library.documents[resource["id"]] = {"document": {"kind": "code"}, "body": body, "fragments": parts}
|
||||
base = "doc:" + resource["id"] + ":article:131"
|
||||
nodes = [{"id": base, "kind": "article", "label": article["label"], "resource_id": resource["id"]},
|
||||
{"id": base + ":point:1", "kind": "point", "label": "Пункт 1. Первый пункт", "resource_id": resource["id"]}]
|
||||
view = GraphView({"nodes": nodes, "edges": [{"source": base, "target": base + ":point:1", "relation": "contains"}]})
|
||||
app = App.__new__(App)
|
||||
app.library = self.library
|
||||
app.graph_views = mock.Mock()
|
||||
app.graph_views.get.return_value = view
|
||||
result = app.graph_network({"resource_id": resource["id"], "fragment": anchor["id"]})
|
||||
self.assertEqual(result["focus_id"], base + ":point:1")
|
||||
point = next(n for n in result["nodes"] if n["id"] == result["focus_id"])
|
||||
self.assertEqual(point["reader_id"], anchor["id"])
|
||||
unsupported = app.graph_network({"resource_id": resource["id"], "fragment": article["anchors"][2]["id"]})
|
||||
self.assertEqual(unsupported["status"], "focus_not_found")
|
||||
|
||||
def test_related_with_node_outside_library_is_not_404(self):
|
||||
# Практика 03.10.2026: у ст. 333 ГК РФ соседи из индекса практики (practice:index), а его нет в
|
||||
# библиотеке - reader_location бросал KeyError, сервер отвечал 404 на /api/related.
|
||||
resource = act(kind="code", title="ГК РФ")
|
||||
body = "## Статья 333. Уменьшение неустойки\n1. Первый пункт.\n"
|
||||
parts = fragments(resource["id"], body)
|
||||
self.library.documents[resource["id"]] = {"document": {"kind": "code"}, "body": body, "fragments": parts}
|
||||
article = "doc:" + resource["id"] + ":article:333"
|
||||
practice = "doc:practice:index:entry:1"
|
||||
nodes = [{"id": article, "kind": "article", "label": "Статья 333. Уменьшение неустойки",
|
||||
"resource_id": resource["id"]},
|
||||
{"id": practice, "kind": "practice", "label": "Определение ВС", "resource_id": "practice:index"}]
|
||||
view = GraphView({"nodes": nodes, "edges": [{"source": practice, "target": article, "relation": "references"}]})
|
||||
app = App.__new__(App)
|
||||
app.library = self.library
|
||||
app.graph_views = mock.Mock()
|
||||
app.graph_views.get.return_value = view
|
||||
result = app.related_data(resource["id"], article)
|
||||
self.assertEqual([edge["source_node"]["reader_id"] for edge in result["related"]], [""])
|
||||
self.assertTrue(result["related"][0]["target_node"]["reader_id"])
|
||||
|
||||
def test_graph_waits_for_reader_index_during_cold_start(self):
|
||||
app = App.__new__(App)
|
||||
app.library = self.library
|
||||
app.graph_views = mock.Mock()
|
||||
app.graph_views.ensure.return_value = {"loading": False}
|
||||
app.graph_views.get.return_value = GraphView({"nodes": [], "edges": []})
|
||||
result = app.graph_network({})
|
||||
self.assertTrue(result["loading"])
|
||||
self.assertEqual(result["nodes"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Контракт скорости reader без сети загрузки корпуса."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from eunomia.library import Library # noqa: E402
|
||||
|
||||
|
||||
def resource():
|
||||
return {
|
||||
"id": "legal-corpus:code:gpk-rf",
|
||||
"kind": "code",
|
||||
"parser": "synthetic",
|
||||
"url": "https://example.test/gpk-rf",
|
||||
"output": "knowledge/kodeksy/gpk-rf.md",
|
||||
"title": "ГПК РФ",
|
||||
"entry": {"slug": "gpk-rf"},
|
||||
}
|
||||
|
||||
|
||||
class ReaderPerformanceTests(unittest.TestCase):
|
||||
def test_article_reader_payload_is_compact_and_has_toc(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
item = resource()
|
||||
body = "# ГПК РФ\n\n" + "\n\n".join(
|
||||
f"## Статья {n}. Норма\nТекст пункта {n}." for n in range(1, 80)
|
||||
)
|
||||
path = root / item["output"]
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(
|
||||
"---\n"
|
||||
f'дата_редакции: "08.09.2026"\ncoverage: "full"\n'
|
||||
f'last_checked: "2026-09-08T10:00:00Z"\nsha256: "{hashlib.sha256(body.encode()).hexdigest()}"\n'
|
||||
"---\n" + body,
|
||||
encoding="utf-8",
|
||||
)
|
||||
with mock.patch("corpus_registry.registry", return_value=[item]):
|
||||
library = Library(root)
|
||||
self.assertTrue(library.refresh())
|
||||
article = next(part for part in library.documents[item["id"]]["fragments"] if "article_40" in part["id"])
|
||||
full = library.document(item["id"])
|
||||
initial = library.reader(item["id"])
|
||||
self.assertEqual(initial["selected_id"], full["fragments"][0]["id"])
|
||||
self.assertEqual(initial["fragment"]["id"], full["fragments"][0]["id"])
|
||||
compact = library.reader(item["id"], article["id"])
|
||||
self.assertEqual(compact["fragment"]["id"], article["id"])
|
||||
self.assertEqual(compact["selected_id"], article["id"])
|
||||
self.assertEqual(len(compact["toc"]), 80)
|
||||
self.assertNotIn("body", compact)
|
||||
self.assertLess(len(json.dumps(compact, ensure_ascii=False)), len(json.dumps(full, ensure_ascii=False)))
|
||||
|
||||
def test_reader_resolves_nested_anchor_and_unknown_location(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
item = resource()
|
||||
body = "# ГПК РФ\n\n## Статья 131. Заявление\n1. Первый пункт.\n2. Второй пункт.\n"
|
||||
path = root / item["output"]
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(
|
||||
"---\ncoverage: full\n"
|
||||
f'sha256: "{hashlib.sha256(body.encode()).hexdigest()}"\n---\n{body}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
with mock.patch("corpus_registry.registry", return_value=[item]):
|
||||
library = Library(root)
|
||||
self.assertTrue(library.refresh())
|
||||
article = next(p for p in library.documents[item["id"]]["fragments"] if p["kind"] == "article")
|
||||
anchor = article["anchors"][1]
|
||||
selected = library.reader(item["id"], anchor["id"])
|
||||
self.assertEqual(selected["selected_id"], anchor["id"])
|
||||
self.assertEqual(selected["fragment"]["id"], article["id"])
|
||||
self.assertEqual(selected["toc"][1]["anchors"][1], {"id": anchor["id"], "label": anchor["label"]})
|
||||
unknown = library.reader(item["id"], "opaque-missing-location")
|
||||
self.assertIsNone(unknown["fragment"])
|
||||
self.assertIsNone(unknown["selected_id"])
|
||||
|
||||
def test_plenum_n10_plain_point_anchor_and_source_line_disambiguation(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
item = resource()
|
||||
item.update({
|
||||
"id": "legal-corpus:plenum:n10",
|
||||
"output": "knowledge/plenumy/n10.md",
|
||||
"title": "Постановление Пленума ВС РФ № 10",
|
||||
"kind": "plenum",
|
||||
})
|
||||
body = (
|
||||
"# Постановление Пленума ВС РФ № 10\n\n"
|
||||
"65. Первый пункт по вопросам практики.\n\n"
|
||||
"65. Второй пункт в приложении.\n"
|
||||
)
|
||||
path = root / item["output"]
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(
|
||||
"---\ncoverage: full\n"
|
||||
f'sha256: "{hashlib.sha256(body.encode()).hexdigest()}"\n---\n{body}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
with mock.patch("corpus_registry.registry", return_value=[item]):
|
||||
library = Library(root)
|
||||
self.assertTrue(library.refresh())
|
||||
parts = library.documents[item["id"]]["fragments"]
|
||||
self.assertEqual(len(parts[0]["anchors"]), 2)
|
||||
self.assertEqual(parts[0]["anchors"][0]["label"], "65.")
|
||||
self.assertIsNone(library.reader_location(item["id"], "Пункт 65"))
|
||||
first_offset = body.index("65.")
|
||||
source_line = f"L{body[:first_offset].count(chr(10)) + 1}"
|
||||
resolved = library.reader_location(item["id"], "Пункт 65", source_line)
|
||||
self.assertEqual(resolved, parts[0]["anchors"][0]["id"])
|
||||
|
||||
def test_live_search_and_document_for_gpk131_gk395(self):
|
||||
base = "http://127.0.0.1:18765"
|
||||
try:
|
||||
urllib.request.urlopen(base + "/api/status", timeout=1).close()
|
||||
except OSError as exc:
|
||||
self.skipTest(f"live Eunomia server unavailable: {exc}")
|
||||
for query, resource_id in (("ст. 131 ГПК", "legal-corpus:code:gpk-rf"), ("ст. 395 ГК", "legal-corpus:code:gk-rf")):
|
||||
with self.subTest(query=query):
|
||||
start = time.perf_counter()
|
||||
with urllib.request.urlopen(base + "/api/search?q=" + urllib.parse.quote(query), timeout=5) as response:
|
||||
result = json.load(response)
|
||||
elapsed = time.perf_counter() - start
|
||||
self.assertTrue(result["total"], result)
|
||||
self.assertLess(elapsed, 2.0, f"{query} search took {elapsed:.3f}s")
|
||||
start = time.perf_counter()
|
||||
with urllib.request.urlopen(base + "/api/document?id=" + urllib.parse.quote(resource_id), timeout=15) as response:
|
||||
document = json.load(response)
|
||||
elapsed = time.perf_counter() - start
|
||||
self.assertTrue(document["fragments"])
|
||||
# Current compatibility endpoint still serializes the complete
|
||||
# text; keep a generous ceiling while reader endpoint is rolled out.
|
||||
self.assertLess(elapsed, 15.0, f"{resource_id} document took {elapsed:.3f}s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,968 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Контракты судебной практики: хеши, удаленные акты, повторный импорт, связи, расписание."""
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import plistlib
|
||||
import socket
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from contextlib import closing
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from eunomia import practice # noqa: E402
|
||||
from eunomia.practice import Practice, import_file, run_import, tick # noqa: E402
|
||||
from eunomia.server import App, handler # noqa: E402
|
||||
|
||||
COURT = 'Энский областной суд (Энская область)'
|
||||
BODY = ('Судья ФИО2 дело № 33-101/2026\n'
|
||||
'по исковому заявлению ФИО1 к обществу «Ромашка» о взыскании неустойки за просрочку передачи квартиры\n'
|
||||
'Суд снизил неустойку, применив положения статьи 333 Гражданского кодекса Российской Федерации, '
|
||||
'так как неустойка явно несоразмерна последствиям нарушения обязательства.\n'
|
||||
'Расходы распределены по ст. 98 ГПК РФ.\n')
|
||||
|
||||
|
||||
def page(title: str, body: str = BODY) -> bytes:
|
||||
"""Страница в форме экспорта СудАкта: меню, заголовок, строка суда, текст, подвал."""
|
||||
return (f'[СудАкт](https://sudact.ru/)\n\n- [Верховный суд](https://sudact.ru/vsrf/)\n\n# {title}\n\n'
|
||||
f'[{COURT}](https://sudact.ru/regular/court/AbCdEf12/) - Гражданское\n\n{body}\n'
|
||||
f'### Суд:\n\n{COURT} [(подробнее)](https://sudact.ru/regular/court/AbCdEf12/)\n').encode()
|
||||
|
||||
|
||||
class Corpus:
|
||||
"""Временный корень данных Lynceuz: объекты по хешу и файлы экспорта."""
|
||||
|
||||
def __init__(self, base: Path):
|
||||
self.data = base / 'lynceuz'
|
||||
self.data.mkdir()
|
||||
self.count = 0
|
||||
|
||||
def obj(self, raw: bytes) -> dict:
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
path = self.data / 'objects/sha256' / digest[:2] / digest
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(raw)
|
||||
return {'hash': f'sha256:{digest}', 'path': f'objects/sha256/{digest[:2]}/{digest}', 'bytes': len(raw)}
|
||||
|
||||
def act(self, doc: str, raw: bytes, fetched: str = '2026-10-01T08:00:00.000Z', **text) -> dict:
|
||||
return {'v': 1, 'url': f'https://sudact.ru/regular/doc/{doc}/', 'host': 'sudact.ru', 'section': 'regular',
|
||||
'title': raw.decode().split('\n# ', 1)[1].split('\n', 1)[0] + ' :: СудАкт.ру',
|
||||
'lastmod': '2026-09-18', 'fetched_at': fetched, 'source': self.obj(b'<html>' + raw + b'</html>'),
|
||||
'text': {**self.obj(raw), 'media_type': 'text/markdown', **text}}
|
||||
|
||||
def export(self, *rows: dict) -> Path:
|
||||
self.count += 1
|
||||
path = self.data / 'exports' / f'corpus-{self.count}.jsonl'
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
path.write_text(''.join(json.dumps(row, ensure_ascii=False) + '\n' for row in rows), encoding='utf-8')
|
||||
return path
|
||||
|
||||
|
||||
def get(app: App, path: str) -> tuple[int, dict]:
|
||||
"""HTTP-запрос к настоящему обработчику через socketpair: порт не открывается."""
|
||||
return exchange(app, f'GET {path} HTTP/1.1\r\nHost: 127.0.0.1:18765\r\n\r\n'.encode())
|
||||
|
||||
|
||||
def post(app: App, path: str, body: bytes = b'{}') -> tuple[int, dict]:
|
||||
"""POST кнопки Эвномии: тот же источник, CSRF и JSON, что шлет интерфейс."""
|
||||
return exchange(app, (f'POST {path} HTTP/1.1\r\nHost: 127.0.0.1:18765\r\nOrigin: http://127.0.0.1:18765\r\n'
|
||||
f'X-Eunomia-CSRF: {app.csrf}\r\nContent-Type: application/json\r\n'
|
||||
f'Content-Length: {len(body)}\r\n\r\n').encode() + body)
|
||||
|
||||
|
||||
def exchange(app: App, request: bytes) -> tuple[int, dict]:
|
||||
client, server_side = socket.socketpair()
|
||||
fake = type('Server', (), {'server_port': 18765})()
|
||||
client.sendall(request)
|
||||
|
||||
def serve():
|
||||
try:
|
||||
handler(app)(server_side, ('127.0.0.1', 0), fake)
|
||||
finally:
|
||||
server_side.close()
|
||||
|
||||
worker = threading.Thread(target=serve)
|
||||
worker.start()
|
||||
raw = b''
|
||||
while chunk := client.recv(65536): # читать, пока пишет обработчик: буфер сокета мал
|
||||
raw += chunk
|
||||
worker.join(10)
|
||||
client.close()
|
||||
head, _, body = raw.partition(b'\r\n\r\n')
|
||||
return int(head.split()[1]), json.loads(body)
|
||||
|
||||
|
||||
class PracticeImportTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name) / 'themiz'
|
||||
self.root.mkdir()
|
||||
self.corpus = Corpus(Path(tmp.name))
|
||||
self.view = Practice(self.root)
|
||||
|
||||
def load(self, *rows: dict) -> dict:
|
||||
return import_file(self.root, self.corpus.export(*rows), self.corpus.data)
|
||||
|
||||
def test_requisites_text_and_article_links(self):
|
||||
result = self.load(self.corpus.act('Aa1111Aa', page('Апелляционное определение № 33-101/2026 от 4 марта 2026 г.')))
|
||||
self.assertEqual((result['added'], result['acts'], result['links']), (1, 1, 2))
|
||||
act = self.view.act('Aa1111Aa')
|
||||
self.assertTrue(act['act']['verified'])
|
||||
self.assertEqual(act['act']['kind'], 'Апелляционное определение')
|
||||
self.assertEqual(act['act']['number'], '33-101/2026')
|
||||
self.assertEqual(act['act']['act_date'], '2026-03-04')
|
||||
self.assertEqual((act['act']['court'], act['act']['category']), ('Энский областной суд', 'Гражданское'))
|
||||
self.assertEqual(act['act']['sha256'], hashlib.sha256(page(
|
||||
'Апелляционное определение № 33-101/2026 от 4 марта 2026 г.')).hexdigest())
|
||||
self.assertNotIn('Верховный суд', act['text'])
|
||||
self.assertNotIn('подробнее', act['text'])
|
||||
self.assertEqual([a['label'] for a in act['articles']], ['ст. 333 ГК РФ', 'ст. 98 ГПК РФ'])
|
||||
cited = act['text'][act['links'][0]['start']:act['links'][0]['end']]
|
||||
self.assertEqual(cited, 'статьи 333 Гражданского кодекса Российской Федерации')
|
||||
self.assertEqual(self.view.browse({'q': 'ст. 333 ГК'})['total'], 1)
|
||||
self.assertEqual(self.view.browse({'q': 'статья 333 Гражданского кодекса'})['total'], 1)
|
||||
self.assertEqual(self.view.browse({'q': 'ст. 334 ГК'})['total'], 0)
|
||||
norm = self.view.norm('legal-corpus:code:gk-rf', 'doc:legal-corpus:code:gk-rf_article_333_point_1')
|
||||
self.assertEqual((norm['label'], norm['total']), ('ст. 333 ГК РФ', 1))
|
||||
item = self.view.browse({'code': 'gk-rf', 'article': '333'})['items'][0]
|
||||
self.assertIn('статьи 333 Гражданского кодекса Российской Федерации', item['excerpt'])
|
||||
self.assertTrue(item['subject'].startswith('по исковому заявлению'))
|
||||
|
||||
def test_tampered_text_is_rejected_and_previous_version_kept(self):
|
||||
first = page('Определение № 33-102/2026 от 5 марта 2026 г.')
|
||||
self.load(self.corpus.act('Bb2222Bb', first))
|
||||
changed = self.corpus.act('Bb2222Bb', page('Определение № 33-102/2026 от 5 марта 2026 г.', 'Новый текст.\n'),
|
||||
fetched='2026-10-02T08:00:00.000Z')
|
||||
(self.corpus.data / changed['text']['path']).write_bytes(b'tampered')
|
||||
result = self.load(changed)
|
||||
self.assertEqual((result['rejected'], result['updated']), (1, 0))
|
||||
self.assertIn('SHA-256', next(iter(result['reasons'])))
|
||||
self.assertEqual(self.view.act('Bb2222Bb')['act']['sha256'], hashlib.sha256(first).hexdigest())
|
||||
|
||||
def test_text_path_outside_data_root_is_rejected(self):
|
||||
row = self.corpus.act('Cc3333Cc', page('Решение № 2-1/2026 от 6 марта 2026 г.'))
|
||||
row['text']['path'] = '../../etc/passwd'
|
||||
result = self.load(row)
|
||||
self.assertEqual((result['rejected'], result['acts']), (1, 0))
|
||||
|
||||
def test_reimport_of_same_export_changes_nothing(self):
|
||||
rows = [self.corpus.act(f'Dd{i}444Dd', page(f'Решение № 2-{i}/2026 от {i} марта 2026 г.')) for i in range(1, 4)]
|
||||
export = self.corpus.export(*rows)
|
||||
import_file(self.root, export, self.corpus.data)
|
||||
again = import_file(self.root, export, self.corpus.data)
|
||||
self.assertEqual((again['unchanged'], again['changes'], again['acts']), (3, 0, 3))
|
||||
|
||||
def test_removed_act_is_hidden_and_remembered(self):
|
||||
raw = page('Определение № 33-105/2026 от 9 марта 2026 г.')
|
||||
self.load(self.corpus.act('Ee5555Ee', raw))
|
||||
result = self.load({'v': 1, 'url': 'https://sudact.ru/regular/doc/Ee5555Ee/', 'host': 'sudact.ru',
|
||||
'removed': True, 'at': '2026-10-03T08:00:00.000Z', 'code': 'http_404'})
|
||||
self.assertEqual((result['removed'], result['acts'], result['links']), (1, 0, 0))
|
||||
self.assertEqual(self.view.browse({})['total'], 0)
|
||||
self.assertEqual(self.view.browse({'q': 'неустойка'})['total'], 0)
|
||||
self.assertEqual(self.view.norm('legal-corpus:code:gk-rf', 'doc:legal-corpus:code:gk-rf_article_333')['total'], 0)
|
||||
self.assertEqual(self.view.act('Ee5555Ee')['act']['removed_code'], 'http_404')
|
||||
back = self.load(self.corpus.act('Ee5555Ee', raw, fetched='2026-10-05T08:00:00.000Z'))
|
||||
self.assertEqual((back['updated'], back['acts']), (1, 1))
|
||||
self.assertIsNone(self.view.act('Ee5555Ee')['act']['removed_at'])
|
||||
|
||||
def test_words_find_other_forms_and_query_syntax_is_inert(self):
|
||||
self.load(self.corpus.act('Ff6666Ff', page('Решение № 2-6/2026 от 10 марта 2026 г.')))
|
||||
self.assertEqual(self.view.browse({'q': 'неустойка квартира'})['total'], 1)
|
||||
self.assertEqual(self.view.browse({'q': '"явно несоразмерна"'})['total'], 1)
|
||||
self.assertEqual(self.view.browse({'q': '"несоразмерна явно"'})['total'], 0)
|
||||
self.assertEqual(self.view.browse({'q': 'неустойка OR NEAR( * "'})['total'], 0)
|
||||
with self.assertRaises(ValueError):
|
||||
self.view.browse({'code': 'gk-rf', 'article': '1; DROP TABLE acts'})
|
||||
|
||||
def test_server_routes_and_status(self):
|
||||
self.load(self.corpus.act('Gg7777Gg', page('Решение № 2-7/2026 от 11 марта 2026 г.')))
|
||||
app = App(self.root)
|
||||
code, data = get(app, '/api/practice?q=%D1%81%D1%82.+333+%D0%93%D0%9A')
|
||||
self.assertEqual((code, data['total'], data['items'][0]['doc']), (200, 1, 'Gg7777Gg'))
|
||||
self.assertEqual(get(app, '/api/practice/act?id=Gg7777Gg')[1]['act']['number'], '2-7/2026')
|
||||
self.assertEqual(get(app, '/api/practice/act?id=..%2Fx')[0], 404)
|
||||
self.assertEqual(get(app, '/api/practice/facets')[1]['kinds'][0]['value'], 'Решение')
|
||||
self.assertEqual(get(app, '/api/practice/norm?id=legal-corpus:code:gk-rf'
|
||||
'&fragment=doc:legal-corpus:code:gk-rf_article_333')[1]['total'], 1)
|
||||
with mock.patch('background_corpus.status', return_value={'queue': {}, 'jobs': []}):
|
||||
status = get(app, '/api/status')[1]
|
||||
self.assertTrue(status['practice']['ready'])
|
||||
|
||||
def test_rejected_row_comes_back_then_is_given_up_and_future_date_is_clamped(self):
|
||||
bad = self.corpus.act('Ww2222Ww', page('Решение № 2-12/2026 от 2 марта 2026 г.'), fetched='2026-09-03T08:00:00.000Z')
|
||||
(self.corpus.data / bad['text']['path']).write_bytes(b'tampered')
|
||||
later = self.corpus.act('Ww3333Ww', page('Решение № 2-13/2026 от 3 марта 2026 г.'), fetched='2026-09-05T08:00:00.000Z')
|
||||
calls = []
|
||||
|
||||
def runner(args, timeout):
|
||||
calls.append(args)
|
||||
path = self.corpus.export(bad, later)
|
||||
return {'status': 'ok', 'exit_code': 0, 'artifact_path': str(path.relative_to(self.corpus.data))}
|
||||
|
||||
first = run_import(self.root, data_root=self.corpus.data, runner=runner)
|
||||
self.assertEqual((first['rejected'], first['retrying'], first['watermark']), (1, 1, '2026-09-05T08:00:00.000Z'))
|
||||
second = run_import(self.root, data_root=self.corpus.data, runner=runner)
|
||||
self.assertEqual(calls[1][-2:], ['--since', '2026-09-03T07:00:00Z']) # отказ пришел снова
|
||||
self.assertEqual(second['retrying'], 1)
|
||||
third = run_import(self.root, data_root=self.corpus.data, runner=runner)
|
||||
self.assertEqual((third['retrying'], third['given_up']), (0, 1))
|
||||
run_import(self.root, data_root=self.corpus.data, runner=runner)
|
||||
self.assertEqual(calls[3][-2:], ['--since', '2026-09-05T07:00:00Z']) # знак больше не держит
|
||||
future = self.corpus.act('Ww4444Ww', page('Решение № 2-14/2026 от 4 марта 2026 г.'), fetched='2099-01-01T00:00:00.000Z')
|
||||
third = run_import(self.root, export=self.corpus.export(future), data_root=self.corpus.data)
|
||||
self.assertLess(third['watermark'], '2099')
|
||||
|
||||
def test_old_export_does_not_resurrect_removed_act(self):
|
||||
first = self.corpus.export(self.corpus.act('Rr6666Rr', page('Определение № 33-106/2026 от 9 марта 2026 г.')))
|
||||
import_file(self.root, first, self.corpus.data)
|
||||
self.load({'v': 1, 'url': 'https://sudact.ru/regular/doc/Rr6666Rr/', 'host': 'sudact.ru',
|
||||
'removed': True, 'at': '2026-10-03T08:00:00.000Z', 'code': 'http_410'})
|
||||
again = import_file(self.root, first, self.corpus.data)
|
||||
self.assertEqual((again['unchanged'], again['acts']), (1, 0))
|
||||
self.assertEqual(self.view.act('Rr6666Rr')['act']['removed_code'], 'http_410')
|
||||
|
||||
def test_query_is_bounded_and_control_characters_are_inert(self):
|
||||
self.load(self.corpus.act('Qq7777Qq', page('Решение № 2-7/2026 от 11 марта 2026 г.')))
|
||||
self.assertEqual(practice.parse_query('б д е ж ф х ц ш щ э ю я неустойка')[2], '"неустой"*')
|
||||
self.assertLessEqual(practice.parse_query(' '.join(f'слово{i}' for i in range(30)))[2].count(' AND '), 7)
|
||||
self.assertEqual(self.view.browse({'q': '"не\x00устойка"'})['total'], 0)
|
||||
stats = sqlite3.connect(self.root / practice.STATE_REL / 'practice.sqlite3')
|
||||
self.assertIn('refs', {row[0] for row in stats.execute('SELECT tbl FROM sqlite_stat1')})
|
||||
stats.close()
|
||||
|
||||
def test_empty_store_answers_honestly(self):
|
||||
self.assertEqual(self.view.browse({'q': 'неустойка'})['ready'], False)
|
||||
self.assertEqual(self.view.facets()['months'], [])
|
||||
self.assertEqual(self.view.norm('legal-corpus:code:gk-rf', 'x_article_1')['total'], 0)
|
||||
with self.assertRaises(FileNotFoundError):
|
||||
self.view.act('Aa1111Aa')
|
||||
|
||||
|
||||
CHAPTERS = {'34': 'Глава 7', '38': 'Глава 7', '39': 'Глава 7', '61': 'Глава 12', '63': 'Глава 12',
|
||||
'65': 'Глава 12', '66': 'Глава 12', '80': 'Глава 13', '81': 'Глава 13', '19': 'Глава 4',
|
||||
'124': 'Глава 19'}
|
||||
|
||||
|
||||
class PracticeAreaTests(unittest.TestCase):
|
||||
"""Отрасли без модели: предмет требования или статьи главы СК; причина отнесения видна."""
|
||||
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.tmp = Path(tmp.name)
|
||||
self.root = self.tmp / 'themiz'
|
||||
self.root.mkdir()
|
||||
self.corpus = Corpus(self.tmp)
|
||||
self.view = Practice(self.root)
|
||||
patcher = mock.patch.object(practice, 'code_chapters', return_value=CHAPTERS)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def load(self, *bodies: str) -> dict:
|
||||
rows = [self.corpus.act(f'Zz{i}000Zz', page(f'Решение № 2-{i}/2026 от {i} марта 2026 г.', body))
|
||||
for i, body in enumerate(bodies, 1)]
|
||||
return import_file(self.root, self.corpus.export(*rows), self.corpus.data)
|
||||
|
||||
def nodes(self, doc: str) -> dict:
|
||||
return {item['id']: item['reason'] for item in self.view.act(doc)['areas']}
|
||||
|
||||
def test_claim_places_act_with_visible_reason(self):
|
||||
result = self.load('по иску ФИО1 к ФИО2 о взыскании алиментов на содержание несовершеннолетнего ребенка.\n'
|
||||
'Суд применил ст. 81 СК РФ.\n')
|
||||
self.assertEqual(result['classified'], 1)
|
||||
reason = self.nodes('Zz1000Zz')['family-alimony']
|
||||
self.assertTrue(reason.startswith('предмет требования: «') and 'о взыскании алиментов' in reason, reason)
|
||||
self.assertEqual(self.view.act('Zz1000Zz')['areas'][0]['parent_title'], 'Семейные споры')
|
||||
self.assertEqual(self.view.browse({'area': 'family-alimony'})['total'], 1)
|
||||
tree = self.view.tree()['areas'][0]
|
||||
self.assertEqual((tree['count'], {c['id']: c['count'] for c in tree['children']}['family-alimony']), (1, 1))
|
||||
|
||||
def test_article_in_passing_and_background_do_not_place(self):
|
||||
self.load('по иску ФИО1 к ФИО2 о взыскании долга по договору займа. Имущество нажито в браке (ст. 34 СК РФ).\n',
|
||||
'с иском о взыскании долга по договору займа. После расторжения брака ответчик выехал.\n')
|
||||
self.assertEqual(self.nodes('Zz1000Zz'), {})
|
||||
self.assertEqual(self.nodes('Zz2000Zz'), {})
|
||||
self.assertEqual(self.view.tree()['areas'][0]['count'], 0)
|
||||
|
||||
def test_articles_of_one_chapter_place_only_with_enough_code_articles(self):
|
||||
self.load('по апелляционной жалобе ФИО1. Применены ст. 61, 63, 65 и 66 СК РФ.\n',
|
||||
'по апелляционной жалобе ФИО1. Применены ст. 61 и 63 СК РФ.\n')
|
||||
self.assertEqual(self.nodes('Zz1000Zz'), {'family-children': 'статьи 61, 63, 65, 66 СК РФ'})
|
||||
self.assertEqual(self.nodes('Zz2000Zz'), {})
|
||||
|
||||
def test_two_subcategories_give_an_intersection(self):
|
||||
self.load('по иску ФИО1 к ФИО2 об определении места жительства детей и взыскании алиментов.\n',
|
||||
'по иску ФИО1 к ФИО2 о взыскании алиментов на ребенка.\n')
|
||||
graph = self.view.area('family')
|
||||
self.assertEqual(graph['area']['count'], 2)
|
||||
self.assertEqual(graph['intersections'], [{'a': 'family-alimony', 'b': 'family-children', 'count': 1}])
|
||||
self.assertEqual(self.view.browse({'area': 'family-alimony,family-children'})['total'], 1)
|
||||
with self.assertRaises(KeyError):
|
||||
self.view.area('nonexistent')
|
||||
with self.assertRaises(ValueError):
|
||||
self.view.browse({'area': "family'; DROP"})
|
||||
|
||||
def test_top_articles_cover_last_subcategory_and_skip_article_1(self):
|
||||
self.load('по заявлению ФИО1 об усыновлении ребенка. Применены ст. 1, 124 СК РФ.\n')
|
||||
articles = self.view.area('family')['articles']
|
||||
self.assertIn(('family-guardianship', '124'), {(item['node'], item['article']) for item in articles})
|
||||
self.assertNotIn('1', {item['article'] for item in articles})
|
||||
|
||||
def test_failed_import_keeps_categories_of_committed_acts(self):
|
||||
self.load('по иску ФИО1 к ФИО2 о разделе совместно нажитого имущества.\n') # отпечаток дерева записан
|
||||
body = 'по иску ФИО1 к ФИО2 о взыскании алиментов на ребенка.\n'
|
||||
rows = [self.corpus.act(f'Cr{i}000Cr', page(f'Решение № 2-{i}/2026 от {i} марта 2026 г.', body)) for i in (1, 2, 3)]
|
||||
real = practice._apply
|
||||
|
||||
def flaky(conn, row, data_root):
|
||||
if row['url'].endswith('Cr3000Cr/'):
|
||||
raise RuntimeError('сбой посреди импорта')
|
||||
return real(conn, row, data_root)
|
||||
|
||||
with mock.patch.object(practice, 'BATCH', 1), mock.patch.object(practice, '_apply', flaky):
|
||||
with self.assertRaises(RuntimeError):
|
||||
import_file(self.root, self.corpus.export(*rows), self.corpus.data)
|
||||
self.assertEqual(set(self.nodes('Cr1000Cr')), {'family-alimony'})
|
||||
self.assertEqual(set(self.nodes('Cr2000Cr')), {'family-alimony'})
|
||||
|
||||
def test_new_tree_reclassifies_from_store_without_lynceuz(self):
|
||||
self.load('по иску ФИО1 к ФИО2 о взыскании алиментов на ребенка.\n')
|
||||
tree = json.loads(practice.TAXONOMY.read_text(encoding='utf-8'))
|
||||
for child in tree['areas'][0]['children']:
|
||||
if child['id'] == 'family-alimony':
|
||||
child['claims'] = ['никогда-не-встретится']
|
||||
changed = self.tmp / 'taxonomy.json'
|
||||
changed.write_text(json.dumps(tree, ensure_ascii=False), encoding='utf-8')
|
||||
for path in (self.corpus.data / 'objects').rglob('*'):
|
||||
if path.is_file():
|
||||
path.unlink() # переотнесение обязано читать хранилище, а не Lynceuz
|
||||
with mock.patch.object(practice, 'TAXONOMY', changed):
|
||||
result = import_file(self.root, self.corpus.export(), self.corpus.data)
|
||||
self.assertEqual((result['rows'], result['classified']), (0, 0))
|
||||
self.assertEqual(self.view.tree()['areas'][0]['count'], 0)
|
||||
|
||||
|
||||
class PracticeScheduleTests(unittest.TestCase):
|
||||
"""Часовой тик: импорт только новых актов, сборка подряд до конца корпуса, затем раз в неделю."""
|
||||
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name) / 'themiz'
|
||||
self.root.mkdir()
|
||||
self.corpus = Corpus(Path(tmp.name))
|
||||
self.journal = self.corpus.data / 'corpus/sudact.ru/progress.jsonl'
|
||||
self.journal.parent.mkdir(parents=True)
|
||||
self.journal.write_text('{}\n')
|
||||
self.calls, self.builds = [], []
|
||||
patcher = mock.patch.object(practice, 'default_data_root', return_value=self.corpus.data)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def build(self, exit_code=3, code='partial', limit='max_time', stop=None, indexed=10, manifest=True, failed=0):
|
||||
self.builds.append({'exit_code': exit_code, 'code': code, 'limit': limit, 'stop': stop, 'indexed': indexed,
|
||||
'manifest': manifest, 'failed': failed})
|
||||
|
||||
def runner(self, args, timeout):
|
||||
self.calls.append(args[1])
|
||||
if args[1] == 'build':
|
||||
spec = self.builds.pop(0)
|
||||
if spec['indexed']:
|
||||
with self.journal.open('a') as journal:
|
||||
journal.write('{}\n')
|
||||
result = {'status': 'partial', 'exit_code': spec['exit_code'], 'code': spec['code'],
|
||||
'message': f"corpus sudact.ru: +{spec['indexed']} indexed, 0 unchanged, 0 skipped, 0 failed"
|
||||
+ (f"; stopped at {spec['limit']}" if spec['limit'] else '')}
|
||||
if spec['manifest']:
|
||||
manifest = self.corpus.data / 'runs' / str(len(self.calls)) / 'manifest.json'
|
||||
manifest.parent.mkdir(parents=True)
|
||||
manifest.write_text(json.dumps({'corpus': {'documents': 5, 'limit': spec['limit'], 'stop': spec['stop'],
|
||||
'counts': {'indexed': spec['indexed'], 'unchanged': 0,
|
||||
'skipped': 0, 'failed': spec['failed']}}}))
|
||||
result['manifest_path'] = str(manifest.relative_to(self.corpus.data))
|
||||
return result
|
||||
row = self.corpus.act(f'Hh{len(self.calls)}888Hh', page(f'Решение № 2-{len(self.calls)}/2026 от 12 марта 2026 г.'),
|
||||
fetched=f'2026-10-01T0{len(self.calls) % 10}:00:00.000Z')
|
||||
export = self.corpus.export(row)
|
||||
return {'status': 'ok', 'exit_code': 0, 'artifact_path': str(export.relative_to(self.corpus.data))}
|
||||
|
||||
def run_tick(self, hours=0, **kwargs):
|
||||
return tick(self.root, runner=self.runner, now=datetime(2026, 10, 2, 9, tzinfo=UTC) + timedelta(hours=hours),
|
||||
**kwargs)
|
||||
|
||||
def test_export_since_starts_one_hour_before_last_watermark(self):
|
||||
first = run_import(self.root, runner=self.runner)
|
||||
self.assertIsNone(first['since'])
|
||||
second = run_import(self.root, runner=self.runner)
|
||||
self.assertEqual(second['since'], '2026-10-01T00:00:00Z')
|
||||
self.assertEqual(second['acts'], 2)
|
||||
|
||||
def test_download_runs_chunk_after_chunk_until_map_is_done_then_weekly(self):
|
||||
self.build() # 55 минут вышли, акты качаются
|
||||
self.build(exit_code=0, code='ok', limit=None) # следующий кусок того же запуска: карта пройдена
|
||||
first = self.run_tick()
|
||||
self.assertEqual(self.calls, ['export', 'build', 'export', 'build', 'export']) # импорт после куска
|
||||
self.assertEqual(first['build']['meaning'], 'карта СудАкта пройдена')
|
||||
second = self.run_tick(hours=1)
|
||||
self.assertNotIn('build', second)
|
||||
self.assertIsNone(second['import']) # журнал не менялся - экспорта нет
|
||||
self.assertEqual(len(self.calls), 5)
|
||||
week = Practice(self.root).summary()['build']
|
||||
self.assertEqual((week['meaning'], week['next_due'][:10]), ('карта СудАкта пройдена', '2026-10-09'))
|
||||
|
||||
def test_429_slows_down_once_then_waits_a_week_and_foreign_lock_is_rechecked_hourly(self):
|
||||
self.build(exit_code=5, code='rate_limited', limit=None, stop='rate_limited', indexed=0)
|
||||
first = self.run_tick()['build'] # быстрая скорость: сбавить и повторить через час
|
||||
self.assertEqual((first['meaning'][:23], first['next_due'][:13]), ('СудАкт попросил сбавить', '2026-10-02T10'))
|
||||
self.build(exit_code=5, code='rate_limited', limit=None, stop='rate_limited', indexed=0)
|
||||
self.assertIn('СудАкт отказал (rate_limited)', self.run_tick(hours=1)['build']['meaning']) # вежливо - неделя
|
||||
self.assertNotIn('build', self.run_tick(hours=25))
|
||||
self.build(exit_code=5, code='blocked', limit=None, indexed=0, manifest=False)
|
||||
lock = self.run_tick(hours=24 * 7 + 2)['build']
|
||||
self.assertEqual((lock['meaning'][:22], lock['next_due'][:13]), ('идет другая сборка Lyn', '2026-10-09T12'))
|
||||
|
||||
def test_fast_speed_turns_polite_for_good_on_a_failure_surge(self):
|
||||
args = []
|
||||
spy = lambda command, timeout: (args.append(command) if command[1] == 'build' else None) or self.runner(command, timeout)
|
||||
pace = lambda n: {k: args[n][args[n].index(f'--{k}') + 1] for k in ('concurrency', 'delay', 'max-time')}
|
||||
self.build(indexed=100, failed=19) # 16% сбоев, но меньше 20 - случайность сети
|
||||
self.build(indexed=100, failed=30) # 23% сбоев - перегруз
|
||||
self.build(exit_code=0, code='ok', limit=None)
|
||||
tick(self.root, runner=spy, now=datetime(2026, 10, 2, 9, tzinfo=UTC))
|
||||
self.assertEqual([pace(n) for n in range(3)],
|
||||
[{'concurrency': '20', 'delay': '0.1', 'max-time': '900'}] * 2
|
||||
+ [{'concurrency': '4', 'delay': '0.5', 'max-time': '3300'}])
|
||||
self.assertIn('вежливая, до 2 запросов в секунду', practice.report(Practice(self.root).summary()))
|
||||
|
||||
def test_own_policy_refusal_is_not_site_refusal_and_is_retried_on_next_run(self):
|
||||
# Живой сбой 02.10.2026: launchd без пула fake-IP, robots.txt не запрошен, стоп policy_denied.
|
||||
self.build(exit_code=5, code='policy_denied', limit=None, stop='policy_denied', indexed=0)
|
||||
first = self.run_tick()['build']
|
||||
self.assertNotIn('СудАкт отказал', first['meaning'])
|
||||
self.assertEqual((first['meaning'][:39], first['next_due'][:13]),
|
||||
('Lynceuz сам не выпустил запрос (policy_', '2026-10-02T09'))
|
||||
self.build(exit_code=5, code='policy_denied', limit=None, indexed=0, manifest=False)
|
||||
again = self.run_tick(hours=1 / 4)['build'] # запуск после install через 15 минут - уже сборка
|
||||
self.assertIn('policy_denied', again['meaning']) # без манифеста - по коду
|
||||
|
||||
def test_robots_stop_after_lynceuz_retries_is_network_and_fast_one_is_refusal(self):
|
||||
# Живой сбой 02.10.2026 15:57: robots.txt не ответил 225 с, задача ушла на неделю.
|
||||
clock, args = {'now': 0.0}, []
|
||||
|
||||
def timed(seconds):
|
||||
def runner(command, timeout):
|
||||
if command[1] == 'build':
|
||||
args.extend(command)
|
||||
clock['now'] += seconds
|
||||
return self.runner(command, timeout)
|
||||
return runner
|
||||
|
||||
with mock.patch.object(practice.time, 'monotonic', lambda: clock['now']):
|
||||
self.build(exit_code=5, code='robots_denied', limit=None, stop='robots_denied', indexed=0)
|
||||
slow = tick(self.root, runner=timed(225), now=datetime(2026, 10, 2, 9, tzinfo=UTC))['build']
|
||||
self.build(exit_code=5, code='robots_denied', limit=None, stop='robots_denied', indexed=0)
|
||||
fast = tick(self.root, runner=timed(5), now=datetime(2026, 10, 2, 10, tzinfo=UTC))['build']
|
||||
self.assertEqual((slow['meaning'][:36], slow['next_due'][:13]),
|
||||
('СудАкт не ответил на robots.txt и по', '2026-10-02T09'))
|
||||
self.assertEqual((fast['meaning'], fast['next_due'][:10]),
|
||||
('СудАкт отказал (robots_denied), повтор через неделю', '2026-10-09'))
|
||||
# пределы Lynceuz по умолчанию - 100 страниц и 50 МБ: прогон держит время, а не их
|
||||
self.assertGreaterEqual(int(args[args.index('--max-pages') + 1]), 1000)
|
||||
self.assertGreaterEqual(int(args[args.index('--max-bytes') + 1]), 10 ** 9)
|
||||
|
||||
def test_stop_after_progress_counts_as_refusal_and_message_fallback_works(self):
|
||||
self.build(exit_code=3, code='partial', limit=None, stop='captcha', manifest=False)
|
||||
result = self.run_tick()['build']
|
||||
self.assertEqual((result['stop'], result['indexed']), (None, 10)) # без манифеста: из сообщения
|
||||
self.builds.clear()
|
||||
self.build(exit_code=3, code='partial', limit=None, stop='captcha')
|
||||
self.assertIn('СудАкт отказал (captcha)', self.run_tick(force_build=True)['build']['meaning'])
|
||||
|
||||
def test_broken_build_retries_next_day_and_import_still_runs(self):
|
||||
def broken(args, timeout):
|
||||
if args[1] == 'build':
|
||||
raise subprocess.TimeoutExpired('node', timeout)
|
||||
return self.runner(args, timeout)
|
||||
|
||||
result = tick(self.root, runner=broken, now=datetime(2026, 10, 2, 9, tzinfo=UTC))
|
||||
self.assertEqual(result['import']['acts'], 1)
|
||||
self.assertEqual((result['build']['meaning'], result['build']['next_due'][:10]),
|
||||
('сборка не запустилась', '2026-10-03'))
|
||||
|
||||
def test_failed_export_is_reported_not_hidden(self):
|
||||
self.build(exit_code=0, code='ok', limit=None)
|
||||
failing = lambda args, timeout: ({'status': 'internal_error', 'exit_code': 70} if args[1] == 'export'
|
||||
else self.runner(args, timeout))
|
||||
result = tick(self.root, runner=failing, now=datetime(2026, 10, 2, 9, tzinfo=UTC))
|
||||
self.assertIn('экспорт Lynceuz', result['import']['error'])
|
||||
self.assertIsNone(Practice(self.root).summary()['last_import'])
|
||||
self.assertIn('Последний импорт: нет', practice.report(Practice(self.root).summary()))
|
||||
|
||||
def test_main_build_waits_while_parts_lead_and_resumes_after_their_refusal(self):
|
||||
parts = self.root / practice.STATE_REL / 'parts' / 'state.json'
|
||||
parts.parent.mkdir(parents=True)
|
||||
parts.write_text(json.dumps({'active': 10, 'done': True}))
|
||||
self.run_tick()
|
||||
self.assertNotIn('build', self.calls) # части прошли карту: основная не перекачивает
|
||||
self.assertEqual(practice.read_state(self.root)['build']['meaning'], practice.PARTS_LEAD)
|
||||
parts.write_text(json.dumps({'active': 10, 'stopped': 'часть 2: СудАкт отказал'}))
|
||||
self.build(exit_code=0, code='ok', limit=None)
|
||||
self.run_tick(hours=1)
|
||||
self.assertIn('build', self.calls)
|
||||
|
||||
def test_install_writes_hourly_agent_and_loads_it(self):
|
||||
agent = Path(self.corpus.data).parent / 'LaunchAgents' / f'{practice.LABEL}.plist'
|
||||
runs = []
|
||||
fake = lambda args, **kw: runs.append(args) or subprocess.CompletedProcess(args, 1 if args[1] == 'print' else 0)
|
||||
with mock.patch.object(practice, '_agent', return_value=agent), mock.patch.object(practice.subprocess, 'run', fake):
|
||||
practice.install(self.root)
|
||||
practice.install(self.root) # повторная установка того же задания не падает
|
||||
payload = plistlib.loads(agent.read_bytes())
|
||||
self.assertEqual((payload['ProgramArguments'][2], payload['StartInterval'], payload['RunAtLoad']),
|
||||
('tick', 3600, True))
|
||||
self.assertEqual([args[1] for args in runs], ['print', 'bootstrap', 'print', 'bootstrap'])
|
||||
|
||||
def test_install_carries_fake_ip_pool_and_reloads_own_older_agent(self):
|
||||
agent = Path(self.corpus.data).parent / 'LaunchAgents' / f'{practice.LABEL}.plist'
|
||||
agent.parent.mkdir(parents=True)
|
||||
with mock.patch.dict(practice.os.environ):
|
||||
practice.os.environ.pop('LYNCEUZ_FAKE_IP_POOLS', None)
|
||||
old = practice._payload(self.root) # задание до починки: без пула
|
||||
agent.write_bytes(plistlib.dumps(old))
|
||||
runs, loaded = [], {'now': True}
|
||||
|
||||
def launchctl(args, **kw): # print отвечает 0, пока задание загружено
|
||||
runs.append(args)
|
||||
loaded['now'] = {'bootout': False, 'bootstrap': True}.get(args[1], loaded['now'])
|
||||
return subprocess.CompletedProcess(args, 0 if args[1] != 'print' or loaded['now'] else 113)
|
||||
|
||||
with mock.patch.object(practice, '_agent', return_value=agent), \
|
||||
mock.patch.object(practice.subprocess, 'run', launchctl), \
|
||||
mock.patch.dict(practice.os.environ, {'LYNCEUZ_FAKE_IP_POOLS': '172.19.0.0/16'}):
|
||||
status = lambda: practice.report(Practice(self.root).summary()).splitlines()[-1]
|
||||
self.assertIn('стоит, но без LYNCEUZ_FAKE_IP_POOLS из оболочки', status())
|
||||
practice.install(self.root)
|
||||
self.assertEqual([args[1] for args in runs], ['print', 'bootout', 'print', 'bootstrap'])
|
||||
self.assertEqual(status(), 'Задача: стоит, запуск каждый час.')
|
||||
env = plistlib.loads(agent.read_bytes())['EnvironmentVariables']
|
||||
self.assertEqual(env['LYNCEUZ_FAKE_IP_POOLS'], '172.19.0.0/16')
|
||||
practice.os.environ.pop('LYNCEUZ_FAKE_IP_POOLS')
|
||||
practice.install(self.root) # оболочка без пула: пул из прежнего задания, без перезагрузки
|
||||
self.assertEqual([args[1] for args in runs[4:]], ['print'])
|
||||
self.assertIn('LYNCEUZ_FAKE_IP_POOLS', plistlib.loads(agent.read_bytes())['EnvironmentVariables'])
|
||||
agent.write_bytes(plistlib.dumps({**old, 'ProgramArguments': ['/bin/sh', '-c', 'чужое']}))
|
||||
for action in (lambda: practice.install(self.root), practice.uninstall):
|
||||
with self.assertRaisesRegex(practice.PracticeError, 'чужое'):
|
||||
action()
|
||||
self.assertIn('чужое', plistlib.loads(agent.read_bytes())['ProgramArguments'][2])
|
||||
|
||||
def test_install_keeps_old_agent_when_it_does_not_stop(self):
|
||||
agent = Path(self.corpus.data).parent / 'LaunchAgents' / f'{practice.LABEL}.plist'
|
||||
agent.parent.mkdir(parents=True)
|
||||
agent.write_bytes(plistlib.dumps({**practice._payload(self.root), 'StartInterval': 60}))
|
||||
stuck = lambda args, **kw: subprocess.CompletedProcess(args, 0) # print: все еще загружено
|
||||
with mock.patch.object(practice, '_agent', return_value=agent), \
|
||||
mock.patch.object(practice.subprocess, 'run', stuck), mock.patch.object(practice.time, 'sleep'):
|
||||
with self.assertRaisesRegex(practice.PracticeError, 'не остановилось'):
|
||||
practice.install(self.root)
|
||||
self.assertEqual(plistlib.loads(agent.read_bytes())['StartInterval'], 60) # иначе повтор не заметил бы разницы
|
||||
|
||||
|
||||
|
||||
class PracticeStatusPageTests(unittest.TestCase):
|
||||
"""Локальная страница загрузки: доля по диску, файлы страницы, задача раз в минуту."""
|
||||
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.base = Path(tmp.name)
|
||||
self.root, self.data = self.base / 'themiz', self.base / 'lynceuz'
|
||||
self.root.mkdir()
|
||||
corpus = self.data / 'corpus/sudact.ru'
|
||||
corpus.mkdir(parents=True)
|
||||
locs = lambda kind, n: ''.join(f'<url><loc>https://sudact.ru/{kind}/doc/Ab{i:06d}/</loc></url>' for i in range(n))
|
||||
maps = {'https://sudact.ru/sitemap.xml': b'<loc>https://sudact.ru/sitemap_part_0.xml.gz</loc>',
|
||||
'https://sudact.ru/sitemap_part_0.xml.gz': gzip.compress(
|
||||
f'<urlset>{locs("regular", 5)}<url><loc>https://sudact.ru/regular/court/Xy12/</loc></url></urlset>'.encode()),
|
||||
'https://sudact.ru/sitemap_part_1.xml': f'<urlset>{locs("arbitral", 3)}</urlset>'.encode()}
|
||||
meta = {}
|
||||
for number, (url, raw) in enumerate(maps.items()):
|
||||
(self.data / f'objects/{number}').parent.mkdir(exist_ok=True)
|
||||
(self.data / f'objects/{number}').write_bytes(raw)
|
||||
meta[url] = {'path': f'objects/{number}'}
|
||||
(corpus / 'sitemaps.json').write_text(json.dumps(meta))
|
||||
self.index = corpus / 'index.sqlite'
|
||||
with closing(sqlite3.connect(self.index)) as conn: # схема Lynceuz в нужной части
|
||||
conn.execute('create table docs (id integer primary key, url text not null unique, fetched_at text not null)')
|
||||
conn.executemany('insert into docs (url, fetched_at) values (?, ?)', [
|
||||
(f'u{n}', at) for n, at in enumerate(['2026-10-02T08:00:00.000Z'] * 3 + ['2026-10-02T08:55:30.123Z'] * 2)])
|
||||
conn.commit()
|
||||
patcher = mock.patch.object(practice, 'default_data_root', return_value=self.data)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.now = datetime(2026, 10, 2, 9, tzinfo=UTC)
|
||||
|
||||
def test_progress_counts_index_against_sitemap_and_speed_over_last_ten_minutes(self):
|
||||
practice.update_state(self.root, 'build', {'meaning': 'идет сборка'})
|
||||
self.assertEqual(practice.progress(self.root, now=self.now),
|
||||
{'done': 5, 'total': 8, 'per_min': 0.2, 'eta_min': 15, 'meaning': 'идет сборка',
|
||||
'speed': 'fast', 'updated_at': '2026-10-02T09:00:00Z'})
|
||||
practice.update_state(self.root, 'speed', {'mode': 'polite'})
|
||||
idle = practice.progress(self.root, now=self.now + timedelta(hours=1)) # за 10 минут ничего не пришло
|
||||
self.assertEqual((idle['per_min'], idle['eta_min'], idle['speed']), (0.0, None, 'polite'))
|
||||
with closing(sqlite3.connect(self.index)) as conn:
|
||||
conn.executemany('insert into docs (url, fetched_at) values (?, ?)',
|
||||
[(f'v{n}', '2026-10-02T08:59:00.000Z') for n in range(3)])
|
||||
conn.commit()
|
||||
self.assertEqual(practice.progress(self.root, now=self.now)['eta_min'], 0)
|
||||
part = practice.part_roots(self.root)[0] # часть обошла обновленную карту позже основной сборки
|
||||
(part / 'corpus/sudact.ru').mkdir(parents=True)
|
||||
(part / 'objects').mkdir()
|
||||
(part / 'objects/map').write_bytes(''.join(f'<loc>https://sudact.ru/regular/doc/Zz{n:06d}/</loc>' for n in range(9)).encode())
|
||||
(part / 'corpus/sudact.ru/sitemaps.json').write_text(json.dumps({'https://sudact.ru/sitemap.xml': {'path': 'objects/map'}}))
|
||||
self.assertEqual(practice.progress(self.root, now=self.now)['total'], 9)
|
||||
|
||||
def test_progress_counts_parts_without_repeats(self):
|
||||
part = practice.part_roots(self.root)[3] / 'corpus/sudact.ru'
|
||||
part.mkdir(parents=True)
|
||||
with closing(sqlite3.connect(part / 'index.sqlite')) as conn:
|
||||
conn.execute('create table docs (id integer primary key, url text not null unique, fetched_at text not null)')
|
||||
conn.executemany('insert into docs (url, fetched_at) values (?, ?)', # u0 скачан раньше основной сборкой
|
||||
[('u0', '2026-10-02T08:58:00.000Z'), ('w1', '2026-10-02T08:58:00.000Z')])
|
||||
conn.commit()
|
||||
value = practice.progress(self.root, now=self.now)
|
||||
self.assertEqual((value['done'], value['per_min'], value['eta_min']), (6, 0.3, 7))
|
||||
|
||||
def test_publish_puts_page_and_status_script_side_by_side(self):
|
||||
value = practice.publish(self.root)
|
||||
folder = self.root / practice.STATE_REL / 'status'
|
||||
self.assertEqual(value['page'], (folder / 'index.html').as_uri())
|
||||
self.assertEqual((folder / 'index.html').read_bytes(), practice.STATUS_PAGE.read_bytes())
|
||||
script = (folder / 'status.js').read_text()
|
||||
self.assertTrue(script.startswith('showStatus(') and script.endswith(')\n'), script)
|
||||
self.assertEqual(json.loads(script[len('showStatus('):-2])['done'], 5)
|
||||
self.assertIn('showStatus', practice.STATUS_PAGE.read_text()) # страница ждет именно этот вызов
|
||||
self.assertEqual(sorted(path.name for path in folder.iterdir()), ['index.html', 'status.js']) # без хвостов
|
||||
|
||||
def test_install_parts_takes_vpn_pool_from_build_agent_and_runs_in_full_force(self):
|
||||
agents = self.base / 'LaunchAgents'
|
||||
agents.mkdir()
|
||||
(agents / f'{practice.LABEL}.plist').write_bytes(plistlib.dumps(
|
||||
{'Label': practice.LABEL, 'EnvironmentVariables': {'LYNCEUZ_FAKE_IP_POOLS': '172.19.0.0/16'}}))
|
||||
fake = lambda args, **kw: subprocess.CompletedProcess(args, 1 if args[1] == 'print' else 0)
|
||||
with mock.patch.object(practice, '_agent', lambda label=practice.LABEL: agents / f'{label}.plist'), \
|
||||
mock.patch.object(practice.subprocess, 'run', fake), mock.patch.dict(practice.os.environ):
|
||||
practice.os.environ.pop('LYNCEUZ_FAKE_IP_POOLS', None) # оболочка без пула
|
||||
self.assertEqual(practice.main(['install', '--parts', '--root', str(self.root)]), 0)
|
||||
payload = plistlib.loads((agents / f'{practice.PARTS_LABEL}.plist').read_bytes())
|
||||
self.assertEqual((payload['ProgramArguments'][2], payload['StartInterval'], payload['ProcessType']),
|
||||
('parts', 60, 'Standard'))
|
||||
self.assertNotIn('LowPriorityIO', payload)
|
||||
self.assertEqual(payload['EnvironmentVariables']['LYNCEUZ_FAKE_IP_POOLS'], '172.19.0.0/16')
|
||||
|
||||
def test_install_publish_runs_every_minute_without_build_environment(self):
|
||||
agents = self.base / 'LaunchAgents'
|
||||
runs = []
|
||||
fake = lambda args, **kw: runs.append(args) or subprocess.CompletedProcess(args, 1 if args[1] == 'print' else 0)
|
||||
with mock.patch.object(practice, '_agent', lambda label=practice.LABEL: agents / f'{label}.plist'), \
|
||||
mock.patch.object(practice.subprocess, 'run', fake), \
|
||||
mock.patch.dict(practice.os.environ, {'LYNCEUZ_FAKE_IP_POOLS': '172.19.0.0/16'}):
|
||||
self.assertEqual(practice.main(['install', '--publish', '--root', str(self.root)]), 0)
|
||||
payload = plistlib.loads((agents / f'{practice.PUBLISH_LABEL}.plist').read_bytes())
|
||||
self.assertEqual((payload['Label'], payload['ProgramArguments'][2], payload['StartInterval'], payload['RunAtLoad']),
|
||||
('com.themiz.practice-status', 'publish', 60, True))
|
||||
self.assertEqual(list(payload['EnvironmentVariables']), ['PATH'])
|
||||
self.assertEqual(payload['StandardOutPath'], '/dev/null')
|
||||
self.assertTrue(Path(payload['StandardErrorPath']).parent.is_dir())
|
||||
self.assertFalse((agents / f'{practice.LABEL}.plist').exists()) # задача сборки не тронута
|
||||
self.assertEqual([args[3] for args in runs if args[1] == 'bootstrap'],
|
||||
[str(agents / 'com.themiz.practice-status.plist')])
|
||||
|
||||
|
||||
class PracticePartsTests(unittest.TestCase):
|
||||
"""Параллельная докачка: части не пересекаются, ступени 5 и 10, отказ СудАкта останавливает все."""
|
||||
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name)
|
||||
self.calls, self.lock = [], threading.Lock()
|
||||
self.answer = lambda part: {'exit_code': 3, 'code': 'partial',
|
||||
'message': 'corpus sudact.ru: +7 indexed, 0 unchanged, 0 skipped, 0 failed; '
|
||||
'stopped at max_time'}
|
||||
|
||||
def runner(self, args, timeout):
|
||||
root = Path(args[args.index('--data-root') + 1])
|
||||
with self.lock:
|
||||
self.calls.append((int(root.parent.name), [args[n + 1] for n, arg in enumerate(args) if arg == '--include'],
|
||||
args[args.index('--delay') + 1]))
|
||||
return self.answer(int(root.parent.name))
|
||||
|
||||
def run_parts(self):
|
||||
self.calls.clear()
|
||||
return practice.parts(self.root, runner=self.runner)
|
||||
|
||||
def test_five_parts_then_all_ten_cover_every_letter_once(self):
|
||||
first = self.run_parts()
|
||||
self.assertEqual(sorted(part for part, *_ in self.calls), [0, 1, 2, 3, 4])
|
||||
self.assertEqual(first['active'], 10) # кусок прошел без отказа: включаются все части
|
||||
self.run_parts()
|
||||
globs = [glob for _, includes, _ in self.calls for glob in includes]
|
||||
self.assertEqual(sorted(globs), sorted(f'/*/doc/{char}**' for char in practice.ID_CHARS)) # по разу
|
||||
self.assertEqual({delay for *_, delay in self.calls}, {'0.6'})
|
||||
self.assertEqual(len({root for root in practice.part_roots(self.root)}), 10)
|
||||
|
||||
def test_site_refusal_in_one_part_stops_all_for_good(self):
|
||||
self.answer = lambda part: ({'exit_code': 5, 'code': 'rate_limited', 'message': 'corpus sudact.ru: +0 indexed, '
|
||||
'0 unchanged, 0 skipped, 0 failed; stopped by rate_limited'} if part == 2 else
|
||||
{'exit_code': 3, 'code': 'partial', 'message': 'corpus sudact.ru: +7 indexed, '
|
||||
'0 unchanged, 0 skipped, 0 failed; stopped at max_time'})
|
||||
state = self.run_parts()
|
||||
self.assertIn('часть 2: СудАкт отказал (rate_limited)', state['stopped'])
|
||||
self.assertEqual(state['active'], 5) # ступень не поднялась
|
||||
self.assertEqual(self.run_parts()['stopped'], state['stopped'])
|
||||
self.assertEqual(self.calls, []) # остановлено насовсем
|
||||
|
||||
def test_done_parts_walk_the_map_again_after_a_day(self):
|
||||
path = self.root / practice.STATE_REL / 'parts' / 'state.json'
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text(json.dumps({'active': 10, 'done': True, 'next_due': '2026-09-01T00:00:00Z'}))
|
||||
state = self.run_parts()
|
||||
self.assertEqual(len(self.calls), 10) # сутки прошли: обход всех частей
|
||||
self.assertNotIn('done', state) # в частях еще есть новые акты
|
||||
path.write_text(json.dumps({'active': 10, 'done': True, 'next_due': '2099-01-01T00:00:00Z'}))
|
||||
self.run_parts()
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_next_walk_starts_with_the_next_local_day_whenever_the_mac_wakes(self):
|
||||
with mock.patch.dict(practice.os.environ, {'TZ': 'Europe/Moscow'}):
|
||||
time.tzset()
|
||||
self.addCleanup(time.tzset)
|
||||
self.assertEqual(practice.next_day(datetime(2026, 10, 3, 1, 51, tzinfo=UTC)), # 04:51 по Москве
|
||||
datetime(2026, 10, 3, 21, 0, tzinfo=UTC)) # 00:00 04.10 по Москве
|
||||
|
||||
def test_map_done_in_all_ten_parts_ends_the_download(self):
|
||||
self.answer = lambda part: {'exit_code': 0, 'code': 'ok',
|
||||
'message': 'corpus sudact.ru: +0 indexed, 9 unchanged, 0 skipped, 0 failed'}
|
||||
self.assertNotIn('done', self.run_parts()) # 5 частей прошли карту, остальные еще не начинали
|
||||
self.assertTrue(self.run_parts()['done'])
|
||||
self.run_parts()
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
def test_part_acts_reach_eunomia_once_and_only_after_journal_changes(self):
|
||||
corpus = Corpus(self.root)
|
||||
journal = corpus.data / 'corpus/sudact.ru/progress.jsonl'
|
||||
journal.parent.mkdir(parents=True)
|
||||
journal.write_text('{}\n')
|
||||
export = corpus.export(corpus.act('Pp1888Pp', page('Решение № 2-7/2026 от 12 марта 2026 г.'),
|
||||
fetched='2026-10-02T21:00:00.000Z'))
|
||||
calls = []
|
||||
runner = lambda args, timeout: calls.append(args) or {'status': 'ok', 'exit_code': 0,
|
||||
'artifact_path': str(export.relative_to(corpus.data))}
|
||||
with mock.patch.object(practice, 'part_roots', return_value=[corpus.data]):
|
||||
marks, report = practice._import_parts(self.root, {}, runner)
|
||||
with closing(sqlite3.connect(self.root / practice.STATE_REL / 'practice.sqlite3')) as conn:
|
||||
acts = conn.execute('select count(*) from acts').fetchone()[0]
|
||||
self.assertEqual((report, acts), ({'0': 1}, 1))
|
||||
self.assertEqual(practice._import_parts(self.root, marks, runner)[1], {}) # журнал тот же - без экспорта
|
||||
journal.write_text('{}\n{}\n')
|
||||
practice._import_parts(self.root, marks, runner)
|
||||
self.assertEqual(len(calls), 2)
|
||||
self.assertEqual(calls[1][-2:], ['--since', '2026-10-02T20:00:00Z']) # час перекрытия
|
||||
|
||||
def state(self, **value) -> Path:
|
||||
path = self.root / practice.STATE_REL / 'parts' / 'state.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(value, ensure_ascii=False), encoding='utf-8')
|
||||
return path
|
||||
|
||||
def test_eunomia_button_starts_walk_at_next_run_and_request_goes_at_its_start(self):
|
||||
path = self.state(active=10, done=True, next_due='2099-01-01T00:00:00Z', at='2026-10-03T01:51:30Z')
|
||||
ask, seen, answer = self.root / practice.REFRESH_REL, [], self.answer
|
||||
self.answer = lambda part: seen.append((ask.exists(), json.loads(path.read_text(encoding='utf-8')))) or answer(part)
|
||||
self.assertTrue(practice.request_walk(self.root)['started'])
|
||||
self.assertFalse(practice.request_walk(self.root)['started']) # вторая кнопка - та же просьба
|
||||
self.assertTrue(practice.walk(self.root)['requested_at'])
|
||||
self.run_parts()
|
||||
self.assertEqual(len(self.calls), 10) # срок в 2099 году: обход идет по просьбе
|
||||
requested, on_disk = seen[0]
|
||||
self.assertFalse(requested) # просьба снята в начале обхода
|
||||
self.assertNotIn('done', on_disk) # начало обхода на диске раньше конца куска
|
||||
self.assertNotEqual(on_disk['at'], '2026-10-03T01:51:30Z')
|
||||
walk = practice.walk(self.root)
|
||||
self.assertEqual((walk['running'], walk['requested_at']), (True, None))
|
||||
self.assertFalse(practice.request_walk(self.root)['started']) # обход идет: второй не нужен
|
||||
self.assertFalse(ask.exists())
|
||||
|
||||
def test_eunomia_button_is_refused_while_parts_are_stopped(self):
|
||||
self.state(active=5, stopped='часть 2: СудАкт отказал (rate_limited), повтор через неделю; все части остановлены')
|
||||
with self.assertRaisesRegex(practice.PracticeError, 'остановлена.*rate_limited'):
|
||||
practice.request_walk(self.root)
|
||||
self.assertFalse((self.root / practice.REFRESH_REL).exists())
|
||||
self.assertFalse(practice.walk(self.root)['running'])
|
||||
|
||||
def test_walk_reports_next_day_and_acts_found_by_the_whole_walk(self):
|
||||
self.state(active=10, done=True, next_due='2026-09-01T00:00:00Z', found=5)
|
||||
self.answer = lambda part: {'exit_code': 0, 'code': 'ok',
|
||||
'message': 'corpus sudact.ru: +3 indexed, 9 unchanged, 0 skipped, 0 failed'}
|
||||
state = self.run_parts()
|
||||
walk = practice.walk(self.root)
|
||||
self.assertEqual((walk['running'], walk['found'], walk['next_due']), (False, 30, state['next_due']))
|
||||
|
||||
def test_buttons_routes_cache_progress_and_answer_202_or_409(self):
|
||||
app, counted = App(self.root), []
|
||||
fake = lambda root: counted.append(root) or {'done': 5, 'total': 8, 'per_min': 0.2, 'eta_min': 15,
|
||||
'updated_at': '2026-10-03T09:00:00Z'}
|
||||
with mock.patch('eunomia.server.progress', fake):
|
||||
code, first = get(app, '/api/practice/progress')
|
||||
self.assertEqual((code, first['done'], first['walk']['running']), (200, 5, False))
|
||||
get(app, '/api/practice/progress')
|
||||
self.assertEqual(len(counted), 1) # 5 секунд ответ идет из кеша
|
||||
code, value = post(app, '/api/practice/refresh')
|
||||
self.assertEqual((code, value['started']), (202, True))
|
||||
self.assertIn('в течение минуты', value['detail'])
|
||||
self.assertTrue((self.root / practice.REFRESH_REL).is_file())
|
||||
self.assertTrue(get(app, '/api/practice/progress')[1]['walk']['requested_at']) # кнопка сбросила кеш
|
||||
(self.root / practice.REFRESH_REL).unlink()
|
||||
self.state(active=5, stopped='часть 2: СудАкт отказал (rate_limited), повтор через неделю; все части остановлены')
|
||||
code, value = post(app, '/api/practice/refresh')
|
||||
self.assertEqual(code, 409)
|
||||
self.assertIn('rate_limited', value['error'])
|
||||
self.assertFalse((self.root / practice.REFRESH_REL).exists())
|
||||
|
||||
def test_law_progress_counts_queue_speed_and_stall(self):
|
||||
now = time.time()
|
||||
jobs = [{'id': 'a', 'state': 'updated', 'finished_at': now - 60, 'updated_at': now - 60},
|
||||
{'id': 'b', 'state': 'blocked', 'finished_at': now - 120, 'updated_at': now - 120},
|
||||
{'id': 'c', 'state': 'running', 'finished_at': None, 'updated_at': now - 30},
|
||||
{'id': 'd', 'state': 'queued', 'finished_at': None, 'updated_at': now - 300},
|
||||
{'id': 'e', 'state': 'deferred', 'finished_at': now - 3600, 'updated_at': now - 3600}]
|
||||
queue = {'ok': True, 'queue': {'updated': 1, 'blocked': 1, 'running': 1, 'queued': 1, 'deferred': 1}, 'jobs': jobs}
|
||||
with mock.patch('background_corpus.status', return_value=queue):
|
||||
code, value = get(App(self.root), '/api/update/progress')
|
||||
self.assertEqual((code, value['done'], value['total'], value['per_min'], value['eta_min'], value['running']),
|
||||
(200, 3, 5, 0.2, 10, True)) # отложенный и недоступный ждать не заставляют
|
||||
self.assertEqual(value['states'], queue['queue'])
|
||||
stuck = [{**job, 'state': 'queued', 'finished_at': None, 'updated_at': now - 3600} for job in jobs]
|
||||
with mock.patch('background_corpus.status', return_value={'ok': True, 'queue': {'queued': 5}, 'jobs': stuck}):
|
||||
value = App(self.root).law_progress()
|
||||
self.assertEqual((value['done'], value['eta_min'], value['running']), (0, None, False)) # очередь стоит час
|
||||
|
||||
|
||||
class PracticeGraphTests(unittest.TestCase):
|
||||
"""Общий граф права: статьи практики сливаются с узлами нормативного графа, тексты норм не идут."""
|
||||
|
||||
def test_practice_merges_into_legal_graph_by_article_id(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
root = Path(tmp.name)
|
||||
corpus = Corpus(root)
|
||||
rows = [corpus.act(f'Gg{n}888Gg', page(f'Решение № 2-{n}/2026 от 12 марта 2026 г.')) for n in range(3)]
|
||||
import_file(root, corpus.export(*rows), corpus.data)
|
||||
snapshot = root / '.agent/maintenance/legal-graph/snapshots/20260918T081928.712865Z/graphify-out'
|
||||
snapshot.mkdir(parents=True)
|
||||
article = 'doc:legal-corpus:code:gk-rf:article:333'
|
||||
legal = {'directed': True, 'multigraph': False, 'graph': {}, 'hyperedges': [], 'nodes': [
|
||||
{'id': article, 'label': 'Статья 333. Уменьшение неустойки', 'file_type': 'document', 'kind': 'article',
|
||||
'source_file': 'knowledge/kodeksy/gk-rf.md', 'source_location': 'L1', 'text': 'Если подлежащая уплате'},
|
||||
{'id': 'doc:legal-corpus:plenum:plenum-n-7', 'label': 'Постановление Пленума N 7', 'file_type': 'document',
|
||||
'kind': 'document', 'source_file': 'knowledge/plenumy/plenum-n-7.md', 'source_location': 'L1', 'text': 'п. 69'},
|
||||
{'id': 'doc:legal-corpus:code:gpk-rf:article:98', 'label': 'Статья 98. Распределение судебных расходов',
|
||||
'file_type': 'document', 'kind': 'article', 'source_file': 'knowledge/kodeksy/gpk-rf.md',
|
||||
'source_location': 'L2', 'text': 'Стороне'}],
|
||||
'links': [{'source': 'doc:legal-corpus:plenum:plenum-n-7', 'target': article, 'relation': 'references',
|
||||
'confidence': 'EXTRACTED', 'confidence_score': 1.0, 'source_file': 'knowledge/plenumy/plenum-n-7.md'}]}
|
||||
(snapshot / 'graph.json').write_text(json.dumps(legal, ensure_ascii=False))
|
||||
(snapshot.parent / 'report.json').write_text('{}') # без отчета legal_graph не считает снимок действующим
|
||||
(root / '.agent/maintenance/legal-graph/current.json').write_text(json.dumps({'snapshot': '20260918T081928.712865Z'}))
|
||||
with mock.patch.object(practice, 'TOGETHER_MIN', 1):
|
||||
result = practice.graph(root)
|
||||
built = json.loads((root / practice.GRAPH_REL).read_text())
|
||||
nodes = {node['id']: node for node in built['nodes']}
|
||||
self.assertEqual((nodes[article]['label'], nodes[article]['practice_acts']), ('Статья 333. Уменьшение неустойки', 3))
|
||||
self.assertNotIn('text', nodes[article]) # тексты норм остаются в снимке legal_graph
|
||||
relations = {(edge['source'], edge['target'], edge['relation']) for edge in built['links']}
|
||||
self.assertIn(('doc:legal-corpus:plenum:plenum-n-7', article, 'references'), relations)
|
||||
self.assertTrue({('doc:legal-corpus:code:gpk-rf:article:98', article, 'cited_together'),
|
||||
(article, 'doc:legal-corpus:code:gpk-rf:article:98', 'cited_together')} & relations)
|
||||
self.assertEqual(result['legal_snapshot'], '20260918T081928.712865Z')
|
||||
self.assertEqual(result['mode'], 'full')
|
||||
community = nodes[article]['community']
|
||||
more = [corpus.act(f'Hh{n}777Hh', page(f'Решение № 3-{n}/2026 от 13 марта 2026 г.')) for n in range(2)]
|
||||
import_file(root, corpus.export(*more), corpus.data)
|
||||
with mock.patch.object(practice, 'TOGETHER_MIN', 1), mock.patch.object(practice, 'build_from_json', create=True,
|
||||
side_effect=AssertionError):
|
||||
again = practice.graph(root) # снимок норм тот же: практика встраивается, граф не пересобирается
|
||||
nodes = {node['id']: node for node in json.loads((root / practice.GRAPH_REL).read_text())['nodes']}
|
||||
self.assertEqual((again['mode'], nodes[article]['practice_acts'], nodes[article]['community']), ('embed', 5, community))
|
||||
self.assertEqual(nodes[article]['label'], 'Статья 333. Уменьшение неустойки')
|
||||
|
||||
|
||||
def test_glued_article_numbers_link_to_their_norm_and_supreme_acts_become_nodes(self):
|
||||
"""«статьи 29111 АПК РФ» - ст. 291.11 без надстрочного знака: в графе она сводится к своей норме;
|
||||
номер, которого в графе права нет вовсе, считается по кодексам; акт Верховного Суда - узел с ребром."""
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
root = Path(tmp.name)
|
||||
corpus = Corpus(root)
|
||||
body = ('Судья ФИО2. В силу части 1 статьи 29111 АПК РФ основаниями для отмены являются существенные '
|
||||
'нарушения норм права. Довод о статье 120 ГК РФ отклонен.\n')
|
||||
supreme = corpus.act('Vv1111Vv', page('Определение от 20 сентября 2026 г. по делу № А40-1/2025', body))
|
||||
supreme.update(url='https://sudact.ru/vsrf/doc/Vv1111Vv/', section='vsrf')
|
||||
import_file(root, corpus.export(supreme), corpus.data)
|
||||
snapshot = root / '.agent/maintenance/legal-graph/snapshots/20260918T081928.712865Z/graphify-out'
|
||||
snapshot.mkdir(parents=True)
|
||||
norm = 'doc:legal-corpus:code:apk-rf:article:291.11'
|
||||
legal = {'directed': True, 'multigraph': False, 'graph': {}, 'hyperedges': [], 'links': [], 'nodes': [
|
||||
{'id': norm, 'label': 'Статья 291.11. Основания для отмены', 'file_type': 'document', 'kind': 'article',
|
||||
'source_file': 'knowledge/kodeksy/apk-rf.md', 'source_location': 'L1', 'text': 'Основаниями для отмены'}]}
|
||||
(snapshot / 'graph.json').write_text(json.dumps(legal, ensure_ascii=False))
|
||||
(snapshot.parent / 'report.json').write_text('{}')
|
||||
(root / '.agent/maintenance/legal-graph/current.json').write_text(json.dumps({'snapshot': '20260918T081928.712865Z'}))
|
||||
result = practice.graph(root)
|
||||
built = json.loads((root / practice.GRAPH_REL).read_text())
|
||||
nodes = {node['id']: node for node in built['nodes']}
|
||||
self.assertEqual(nodes[norm]['practice_acts'], 1)
|
||||
self.assertNotIn('doc:legal-corpus:code:apk-rf:article:29111', nodes)
|
||||
self.assertEqual((result['unglued'], result['dropped_articles'], result['dropped_by_code']), (1, 1, {'gk-rf': 1}))
|
||||
act = nodes['sudact:act:1']
|
||||
self.assertEqual((act['kind'], act['doc'], act['source_url']), ('practice_act', 'Vv1111Vv', 'https://sudact.ru/vsrf/doc/Vv1111Vv/'))
|
||||
self.assertIn(('sudact:act:1', norm, 'cites'),
|
||||
{(edge['source'], edge['target'], edge['relation']) for edge in built['links']})
|
||||
self.assertEqual(practice.unglue('koap-rf', '32', {practice.article_id('koap-rf', '3.2')}), None) # у КоАП точка в тексте
|
||||
|
||||
def test_new_extraction_version_rebuilds_graph_without_new_acts(self):
|
||||
"""Ежедневный обход пересобирает граф при новых актах или снимке норм - и при новой версии разбора
|
||||
практики: иначе починка графа ждала бы следующего нового акта СудАкта."""
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
root = Path(tmp.name)
|
||||
corpus = Corpus(root)
|
||||
import_file(root, corpus.export(corpus.act('Kk1111Kk', page('Решение № 2-1/2026 от 12 марта 2026 г.'))), corpus.data)
|
||||
(root / practice.GRAPH_REL).parent.mkdir(parents=True)
|
||||
(root / practice.GRAPH_REL).write_text('{}')
|
||||
last = {'acts': 1, 'legal': None, 'at': '2026-10-03T13:04:42Z'}
|
||||
with mock.patch.object(practice, 'graph', return_value={'mode': 'embed'}) as rebuild:
|
||||
fresh = practice._graph_if_new(root, last)
|
||||
self.assertEqual((rebuild.call_count, fresh['version']), (1, practice.GRAPH_VERSION))
|
||||
self.assertIs(practice._graph_if_new(root, fresh), fresh) # та же версия и те же акты - без сборки
|
||||
self.assertEqual(rebuild.call_count, 1)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""UI Stack gate: the eight audit defects of 22.09.2026 must stay fixed in the built interface.
|
||||
|
||||
Boots Eunomia on a free port and runs ui_stack_check.py against it, so the regression fails inside the
|
||||
regular `python3 -m unittest discover -s eunomia/tests -p 'test_*.py'` run without a manual server.
|
||||
"""
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROBE = Path(__file__).with_name('ui_stack_check.py')
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
class UiStackGateTests(unittest.TestCase):
|
||||
def test_ui_stack_probe_is_green_on_built_interface(self):
|
||||
try:
|
||||
import playwright # noqa: F401
|
||||
except ImportError:
|
||||
self.fail('Python Playwright не установлен: проба UI Stack не может открыть интерфейс')
|
||||
port = free_port()
|
||||
server = subprocess.Popen([sys.executable, str(ROOT / 'scripts/eunomia.py'), '--serve', '--root', str(ROOT),
|
||||
'--port', str(port), '--no-open'], cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.addCleanup(server.wait, 10)
|
||||
self.addCleanup(server.terminate)
|
||||
base = f'http://127.0.0.1:{port}'
|
||||
# Ready means the data API answers, not just the static index: the interface renders from bootstrap.
|
||||
deadline = time.monotonic() + 180
|
||||
while True:
|
||||
try:
|
||||
if urllib.request.urlopen(base + '/api/bootstrap', timeout=30).status == 200:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
if server.poll() is not None or time.monotonic() > deadline:
|
||||
self.fail(f'Эвномия не отдала /api/bootstrap на {base} за 180 с (код процесса {server.poll()})')
|
||||
time.sleep(0.5)
|
||||
probe = subprocess.run([sys.executable, str(PROBE)], cwd=ROOT, env={**os.environ, 'EUNOMIA_URL': base},
|
||||
capture_output=True, text=True, timeout=900)
|
||||
self.assertEqual(probe.returncode, 0, 'проба UI Stack красная:\n' + probe.stdout[-6000:] + probe.stderr[-2000:])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Smoke, overflow and contrast checks for the Pantheon tricolor UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
BASE = os.environ.get("EUNOMIA_URL", "http://127.0.0.1:18765")
|
||||
OUT = Path(__file__).parents[1] / "qa" / "tricolor"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
ROUTES = {
|
||||
"home": "#view=home",
|
||||
"reader": "#doc=legal-corpus%3Acode%3Agpk-rf&fragment=doc%3Alegal-corpus%3Acode%3Agpk-rf_article_131",
|
||||
"plenum": "#view=category&kind=plenum",
|
||||
"history": "#view=history",
|
||||
"search": "#view=search&q=395",
|
||||
}
|
||||
SELECTORS = {"home": ".p-catalog", "reader": ".p-document", "plenum": ".p-catalog", "history": ".p-editions", "search": ".p-research"}
|
||||
|
||||
|
||||
def check(report: dict[str, Any], name: str, ok: bool, detail: Any = "") -> None:
|
||||
report["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
|
||||
|
||||
|
||||
def main() -> int:
|
||||
report: dict[str, Any] = {"base": BASE, "checks": [], "screens": {}, "contrast": {}}
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900}, device_scale_factor=1)
|
||||
for width, label in ((390, "390"), (1440, "1440")):
|
||||
page.set_viewport_size({"width": width, "height": 900})
|
||||
for name, route in ROUTES.items():
|
||||
errors: list[str] = []
|
||||
page_errors: list[str] = []
|
||||
page.on("console", lambda message: errors.append(message.text) if message.type == "error" else None)
|
||||
page.on("pageerror", lambda error: page_errors.append(str(error)))
|
||||
page.goto(BASE + "/" + route, wait_until="domcontentloaded")
|
||||
page.locator(SELECTORS[name]).wait_for(timeout=120000)
|
||||
page.wait_for_timeout(700)
|
||||
overflow = page.evaluate("document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
check(report, f"{name} {label}px renders", page.locator(SELECTORS[name]).count() == 1, page.title())
|
||||
check(report, f"{name} {label}px has no horizontal overflow", overflow == 0, overflow)
|
||||
check(report, f"{name} {label}px has no JavaScript errors", not errors and not page_errors, {"console": errors, "page": page_errors})
|
||||
screen = OUT / f"{name}-{label}.png"
|
||||
page.screenshot(path=str(screen), full_page=True)
|
||||
report["screens"][f"{name}-{label}"] = str(screen.relative_to(OUT.parent.parent))
|
||||
|
||||
if label == "1440":
|
||||
contrast = page.evaluate(
|
||||
"""() => {
|
||||
const parse = value => { const m=value.match(/rgba?\\(([^)]+)\\)/); if(!m)return null; const p=m[1].split(',').map(Number); return {r:p[0],g:p[1],b:p[2],a:p[3]===undefined?1:p[3]}; };
|
||||
const lum = c => { const f=v=>{v/=255;return v<=.03928?v/12.92:Math.pow((v+.055)/1.055,2.4)}; return .2126*f(c.r)+.7152*f(c.g)+.0722*f(c.b); };
|
||||
const ratio=(fg,bg)=>{const a=lum(fg),b=lum(bg);return (Math.max(a,b)+.05)/(Math.min(a,b)+.05)};
|
||||
const bgFor=el=>{for(let n=el;n;n=n.parentElement){const c=parse(getComputedStyle(n).backgroundColor);if(c&&c.a>.95)return c}return {r:247,g:245,b:240,a:1}};
|
||||
const out={};
|
||||
for(const [name,selector] of Object.entries({bodyText:'.p-main',control:'.p-button-primary',input:'.p-field input',search:'.p-search-field',warning:'.p-warning',notice:'.p-notice'})){const el=document.querySelector(selector);if(!el)continue;const s=getComputedStyle(el),fg=parse(s.color),bg=bgFor(el);if(fg)out[name]={ratio:ratio(fg,bg),foreground:s.color,background:`rgb(${bg.r},${bg.g},${bg.b})`};}
|
||||
return out;
|
||||
}"""
|
||||
)
|
||||
report["contrast"][name] = contrast
|
||||
for sample, values in contrast.items():
|
||||
check(report, f"{name} contrast {sample} >= 3", values["ratio"] >= 3, values)
|
||||
if "bodyText" in contrast:
|
||||
check(report, f"{name} body text contrast >= 4.5", contrast["bodyText"]["ratio"] >= 4.5, contrast["bodyText"])
|
||||
browser.close()
|
||||
(OUT / "tricolor-check.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
failures = [item for item in report["checks"] if not item["ok"]]
|
||||
print(json.dumps({"checks": len(report["checks"]), "failures": failures}, ensure_ascii=False, indent=2))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,422 @@
|
||||
#!/usr/bin/env python3
|
||||
"""UI Stack regression probe: every check is named after the audit defect it guards (Д-001…Д-008).
|
||||
|
||||
Run: python3 eunomia/tests/ui_stack_check.py [--out REPORT.json]
|
||||
Needs a running Eunomia at EUNOMIA_URL (default http://127.0.0.1:18765), Python Playwright with Chromium
|
||||
and axe-core: AXE_CORE or eunomia/frontend/node_modules/axe-core/axe.min.js (npm ci in eunomia/frontend).
|
||||
Exit code 1 on any failed check. A crashed section is a failed check, not silence.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from playwright.sync_api import sync_playwright
|
||||
from chromium import executable
|
||||
|
||||
BASE = os.environ.get('EUNOMIA_URL', 'http://127.0.0.1:18765').rstrip('/')
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
AXE = Path(os.environ.get('AXE_CORE') or ROOT / 'frontend/node_modules/axe-core/axe.min.js')
|
||||
RESEARCH = ROOT / 'frontend/src/pantheon/Research.tsx'
|
||||
HOME = str(Path.home())
|
||||
SCREENS = {
|
||||
'главная': ('/', '.p-stone'),
|
||||
'поиск': ('/#view=search&q=395', '.p-result, .p-empty-scene'),
|
||||
'читатель': ('/#doc=legal-corpus%3Acode%3Atk-rf&fragment=doc%3Alegal-corpus%3Acode%3Atk-rf_article_395', 'main h1'),
|
||||
'граф': ('/#view=graph', '.p-force-canvas canvas'),
|
||||
'служба': ('/#view=updates', '.p-job'),
|
||||
}
|
||||
LANDMARK = ('nav, aside, main, header, footer, [role=navigation], [role=complementary], [role=main], '
|
||||
'[role=banner], [role=contentinfo], [role=region][aria-label], section[aria-label], form[aria-label]')
|
||||
# Roles that accept an accessible name from aria-label (ARIA 1.2); generic <div>/<span> do not.
|
||||
NAMED_ROLES = {'region', 'group', 'img', 'figure', 'application', 'navigation', 'complementary', 'main', 'form', 'search'}
|
||||
# Colour maths as in the fixed WCAG-143 block of qa/ui-stack-2026-09-22/scripts/audit.py:
|
||||
# color(srgb r g b / a) is 0..1 per channel, translucent layers are composited down to the first opaque one.
|
||||
CONTRAST = """() => {
|
||||
const parse = s => {const m=s.match(/^color\\(srgb ([\\d.]+) ([\\d.]+) ([\\d.]+)(?: \\/ ([\\d.]+))?\\)/);
|
||||
if(m) return [m[1]*255, m[2]*255, m[3]*255, m[4]===undefined?1:+m[4]];
|
||||
const n=s.match(/[\\d.]+/g).map(Number); return [n[0], n[1], n[2], n.length>3?n[3]:1]};
|
||||
const over = (top, under) => [0,1,2].map(i => top[i]*top[3] + under[i]*(1-top[3])).concat(1);
|
||||
const bgOf = el => {const layers=[]; for(let e=el; e; e=e.parentElement){const c=parse(getComputedStyle(e).backgroundColor); if(c[3]>0){layers.push(c); if(c[3]>=1) break}}
|
||||
return layers.reverse().reduce((bg, layer) => over(layer, bg), [255,255,255,1])};
|
||||
const lum = c => {const [r,g,b]=c.slice(0,3).map(v=>{v/=255;return v<=0.03928?v/12.92:Math.pow((v+0.055)/1.055,2.4)}); return 0.2126*r+0.7152*g+0.0722*b};
|
||||
const ratioOf = (fg, bg) => {const L1=lum(over(fg, bg)), L2=lum(bg); return (Math.max(L1,L2)+0.05)/(Math.min(L1,L2)+0.05)};
|
||||
const measure = el => {const cs=getComputedStyle(el); const px=parseFloat(cs.fontSize), w=parseInt(cs.fontWeight)||400;
|
||||
const need=(px>=24 || (px>=18.66 && w>=700)) ? 3 : 4.5; const ratio=ratioOf(parse(cs.color), bgOf(el));
|
||||
return {color: cs.color, px, ratio: +ratio.toFixed(2), need, pass: ratio >= need}};
|
||||
const rows = [];
|
||||
for (const s of ['.p-hero-copy > p:not(.p-eyebrow)','.p-stone-face span','.p-stone-face small','.p-catalog-total','.p-local-note','.p-tabs a:not([aria-current])','.p-sidebar-note','.p-brand small','.p-eyebrow','.p-tabs span']) {
|
||||
const el = document.querySelector(s); if (el) rows.push({sel: s, ...measure(el)})}
|
||||
const selfcheck = +ratioOf(parse('rgb(88, 101, 121)'), over(parse('color(srgb 1 1 1 / 0.97)'), [255,255,255,1])).toFixed(2);
|
||||
const probe = document.createElement('span'); probe.textContent = 'контроль';
|
||||
probe.style.cssText = 'color: rgb(150, 150, 150); font-size: 12px';
|
||||
(document.querySelector('.p-topbar') || document.body).appendChild(probe);
|
||||
const control = measure(probe); probe.remove();
|
||||
return {rows, selfcheck, control}
|
||||
}"""
|
||||
|
||||
|
||||
def state_labels():
|
||||
"""Human labels of the queue states, read from the component itself so the probe cannot drift from it."""
|
||||
text = RESEARCH.read_text(encoding='utf-8')
|
||||
block = re.search(r'const states[^=]*=\s*\{([^}]*)\}', text)
|
||||
if not block:
|
||||
raise RuntimeError('в Research.tsx не найден словарь states: проба не знает подписей состояний')
|
||||
return dict(re.findall(r"(\w+)\s*:\s*'([^']*)'", block.group(1)))
|
||||
|
||||
|
||||
def status_fixture(real):
|
||||
"""440 jobs in every state, shaped like the live /api/status answer; one failed job carries a home-path error."""
|
||||
template = {'resource_hash': '0' * 64, 'state': 'current', 'priority': 0, 'attempts': 1, 'available_at': None,
|
||||
'lease_until': None, 'progress': {'done': 0, 'pending_count': 0, 'total': 0}, 'detail': None,
|
||||
'freshness': 'unknown', 'availability': 'unknown', 'created_at': 0, 'updated_at': 0, 'started_at': None,
|
||||
'finished_at': None, 'last_checked': None, 'last_updated': None, 'pending_resource_hash': None,
|
||||
'id': 'legal-corpus:code:gk-rf', 'local_file_present': True}
|
||||
live = [job for job in real.get('jobs') or [] if isinstance(job, dict)]
|
||||
cycle = ['deferred', 'blocked', 'failed', 'current', 'updated', 'queued', 'running']
|
||||
jobs = []
|
||||
for i in range(440):
|
||||
job = dict(live[i % len(live)] if live else template)
|
||||
job.update(id=f"{job.get('id') or 'probe'}#probe-{i}", resource_hash=f'{i:064x}', state=cycle[i % len(cycle)])
|
||||
jobs.append(job)
|
||||
missing = Path(HOME, 'Проекты', 'themiz', '.agent', 'maintenance', 'background', 'jobs', '829828fc-probe', 'original.body')
|
||||
jobs[2]['detail'] = f"[Errno 2] No such file or directory: '{missing}'"
|
||||
return {**real, 'jobs': jobs}, bool(live)
|
||||
|
||||
|
||||
class Check:
|
||||
def __init__(self, browser):
|
||||
self.results, self.errors = [], []
|
||||
self.context = browser.new_context(viewport={'width': 1440, 'height': 900})
|
||||
# CDP init script bypasses the app's CSP script-src 'self' without weakening it.
|
||||
self.context.add_init_script(AXE.read_text(encoding='utf-8'))
|
||||
self.page = self.context.new_page()
|
||||
self.page.set_default_timeout(30000)
|
||||
self.page.on('pageerror', lambda error: self.errors.append(f'pageerror: {error}'))
|
||||
self.page.on('console', lambda message: self.errors.append(f'console: {message.text}') if message.type == 'error' else None)
|
||||
for path in ('**/api/update', '**/api/graph/rebuild', '**/api/practice/refresh'):
|
||||
self.page.route(path, lambda route: route.fulfill(status=200, content_type='application/json', body='{"detail":"mock"}'))
|
||||
|
||||
def check(self, name, ok, detail=''):
|
||||
self.results.append({'name': name, 'ok': bool(ok), 'detail': detail})
|
||||
|
||||
def info(self, name, detail):
|
||||
self.results.append({'name': name, 'ok': True, 'info': True, 'detail': detail})
|
||||
|
||||
def section(self, name, run):
|
||||
try:
|
||||
run()
|
||||
except Exception as error: # a crash is a red check with its cause, never silence
|
||||
self.check(f'{name}: раздел выполнен до конца', False, f'{type(error).__name__}: {str(error)[:400]}')
|
||||
|
||||
def open(self, route, ready, wait=700):
|
||||
self.page.goto(BASE + route, wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector(ready)
|
||||
self.page.wait_for_timeout(wait)
|
||||
|
||||
def fragment(self):
|
||||
return parse_qs(urlsplit(self.page.url).fragment)
|
||||
|
||||
def axe(self, rules=None):
|
||||
options = {'resultTypes': ['violations']}
|
||||
if rules:
|
||||
options['runOnly'] = {'type': 'rule', 'values': rules}
|
||||
return self.page.evaluate("""async options => (await axe.run(document, options)).violations
|
||||
.map(v => ({id: v.id, impact: v.impact, nodes: v.nodes.length, target: v.nodes[0] && v.nodes[0].target}))""", options)
|
||||
|
||||
def use_status_fixture(self):
|
||||
real = self.page.request.get(BASE + '/api/status').json()
|
||||
fixture, live = status_fixture(real)
|
||||
if not live:
|
||||
self.info('Д-003 фикстура очереди', 'живых заданий нет: шаблон задания взят из кода пробы, а не из ответа сервера')
|
||||
body = json.dumps(fixture, ensure_ascii=False)
|
||||
self.page.route('**/api/status*', lambda route: route.fulfill(status=200, content_type='application/json', body=body))
|
||||
|
||||
def screens(self):
|
||||
self.use_status_fixture()
|
||||
for name, (route, ready) in SCREENS.items():
|
||||
self.open(route, ready, 3000 if name == 'граф' else 900)
|
||||
dangling = self.page.evaluate("""() => [...document.querySelectorAll('[aria-controls]')].flatMap(el =>
|
||||
el.getAttribute('aria-controls').split(/\\s+/).filter(id => id && !document.getElementById(id))
|
||||
.map(id => ({id, el: el.outerHTML.slice(0, 120)})))""")
|
||||
self.check(f'Д-001 aria-controls ведёт на существующий узел: {name}', not dangling, dangling[:3])
|
||||
violations = self.axe()
|
||||
region = [v for v in violations if v['id'] == 'region']
|
||||
self.check(f'Д-007 всё содержимое внутри landmark (axe region): {name}', not region, region)
|
||||
self.check(f'общее: ноль нарушений axe: {name}', not violations, violations)
|
||||
if name == 'главная':
|
||||
outside = self.page.evaluate(f"""() => [...document.querySelectorAll('[data-sidebar="header"]')]
|
||||
.filter(el => !el.closest({json.dumps(LANDMARK)})).length""")
|
||||
self.check('Д-007 шапка сайдбара лежит в landmark', outside == 0, f'вне landmark: {outside}')
|
||||
if name == 'граф':
|
||||
prohibited = [v for v in violations if v['id'] == 'aria-prohibited-attr']
|
||||
self.check('Д-006 aria-label без допустимой роли (axe aria-prohibited-attr): граф', not prohibited, prohibited)
|
||||
canvas = self.page.evaluate("""() => {const el = document.querySelector('.p-force-canvas');
|
||||
return el && {role: el.getAttribute('role'), label: el.getAttribute('aria-label')}}""")
|
||||
self.check('Д-006 поверхность графа названа через роль, которая принимает имя',
|
||||
bool(canvas and canvas['role'] in NAMED_ROLES and (canvas['label'] or '').strip()), canvas)
|
||||
if name == 'читатель':
|
||||
self.page.wait_for_selector('.p-context', timeout=20000)
|
||||
self.page.wait_for_timeout(800)
|
||||
bare = self.page.evaluate("""() => [...document.querySelectorAll('aside *, .p-context *')]
|
||||
.filter(e => e.children.length === 0 && /^\\d+$/.test((e.textContent || '').trim())
|
||||
&& !(e.getAttribute('aria-label') || e.getAttribute('title')))
|
||||
.slice(0, 4).map(e => ({tag: e.tagName, cls: String(e.className).slice(0, 30), text: e.textContent.trim()}))""")
|
||||
self.check('Д-008 в панели контекста нет голых чисел без имени', not bare, bare)
|
||||
self.page.unroute('**/api/status*')
|
||||
|
||||
def search_box(self):
|
||||
self.open('/', '.p-stone')
|
||||
self.page.keyboard.press('Tab')
|
||||
skip = self.page.evaluate("() => String(document.activeElement.className)")
|
||||
self.check('сохранено: первый Tab ведёт на skip-link', 'p-skip' in skip, skip)
|
||||
self.page.keyboard.press('Escape')
|
||||
search_label = "() => document.activeElement.getAttribute('aria-label') || ''"
|
||||
self.page.keyboard.press('Meta+k')
|
||||
self.page.wait_for_timeout(200)
|
||||
if 'Поиск' not in self.page.evaluate(search_label):
|
||||
self.page.keyboard.press('Control+k')
|
||||
self.page.wait_for_timeout(200)
|
||||
self.check('сохранено: Cmd/Ctrl+K фокусирует поиск', 'Поиск' in self.page.evaluate(search_label))
|
||||
self.page.keyboard.type('395')
|
||||
self.page.wait_for_selector('.p-suggestions [cmdk-item]', timeout=15000)
|
||||
state = """() => {const el = document.activeElement; const ids = (el.getAttribute('aria-controls') || '').split(/\\s+/).filter(Boolean);
|
||||
return {label: el.getAttribute('aria-label') || '', expanded: el.getAttribute('aria-expanded'), ids,
|
||||
missing: ids.filter(id => !document.getElementById(id)), lists: document.querySelectorAll('.p-suggestions').length}}"""
|
||||
opened = self.page.evaluate(state)
|
||||
self.check('Д-001 открытый список: aria-controls указывает на живой список',
|
||||
opened['ids'] and not opened['missing'] and opened['expanded'] == 'true', opened)
|
||||
self.page.keyboard.press('Escape')
|
||||
self.page.wait_for_timeout(200)
|
||||
closed = self.page.evaluate(state)
|
||||
self.check('Д-001 Escape закрывает подсказки и держит фокус в поле', closed['lists'] == 0 and 'Поиск' in closed['label'], closed)
|
||||
self.check('Д-001 закрытый список: aria-controls не висит в пустоте', not closed['missing'], closed)
|
||||
self.page.keyboard.press('Enter')
|
||||
self.page.wait_for_timeout(1200)
|
||||
self.check('сохранено: Enter в поиске даёт q= в URL', self.fragment().get('q') == ['395'], self.page.url)
|
||||
|
||||
def pagination_label(self):
|
||||
return self.page.locator('.p-pagination span').first.inner_text()
|
||||
|
||||
def first_row(self):
|
||||
return self.page.locator('.p-document-row').first.inner_text()
|
||||
|
||||
def catalog_pages(self):
|
||||
self.open('/#view=category&kind=plenum', '.p-pagination')
|
||||
self.page.locator('.p-pagination-actions button', has_text='Следующая').click()
|
||||
self.page.wait_for_timeout(500)
|
||||
label, second = self.pagination_label(), self.first_row()
|
||||
self.check('Д-002 «Следующая» пишет страницу в URL', self.fragment().get('page') == ['2'] and 'страница 2' in label,
|
||||
{'url': self.page.url, 'label': label})
|
||||
self.page.reload(wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-pagination')
|
||||
self.page.wait_for_timeout(700)
|
||||
self.check('Д-002 перезагрузка держит страницу 2', 'страница 2' in self.pagination_label() and self.first_row() == second,
|
||||
self.pagination_label())
|
||||
self.page.go_back(wait_until='domcontentloaded')
|
||||
self.page.wait_for_timeout(900)
|
||||
back = self.page.locator('.p-pagination').count() and self.pagination_label()
|
||||
self.check('Д-002 Back возвращает страницу 1 того же каталога',
|
||||
self.fragment().get('kind') == ['plenum'] and bool(back) and 'страница 1' in back, {'url': self.page.url, 'label': back})
|
||||
|
||||
def catalog_filters(self):
|
||||
self.open('/#view=category&kind=plenum', '.p-topic')
|
||||
before = self.page.url
|
||||
self.page.locator('.p-topic').first.click()
|
||||
self.page.wait_for_timeout(500)
|
||||
row = self.first_row()
|
||||
self.check('Д-002 тема пишется в URL', self.page.url != before and 'topic' in self.fragment(), self.page.url)
|
||||
self.page.reload(wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-document-row')
|
||||
self.page.wait_for_timeout(700)
|
||||
self.check('Д-002 перезагрузка держит тему', self.first_row() == row, self.page.url)
|
||||
self.open('/#view=category&kind=plenum', '.p-pagination')
|
||||
selects = self.page.locator('main select')
|
||||
selects.nth(0).select_option('old')
|
||||
self.page.wait_for_timeout(400)
|
||||
self.check('Д-002 сортировка пишется в URL', self.fragment().get('sort') == ['old'], self.page.url)
|
||||
# Year options carry no value attribute (<option>{year}</option>): pick by index, read select.value.
|
||||
selects.nth(1).select_option(index=1)
|
||||
self.page.wait_for_timeout(400)
|
||||
year = selects.nth(1).evaluate('select => select.value')
|
||||
self.check('Д-002 год пишется в URL', bool(year) and self.fragment().get('year') == [year], self.page.url)
|
||||
|
||||
def document_list(self):
|
||||
# Live corpus has at most 5 documents per non-plenum kind, so DocumentList never pages on real data:
|
||||
# the bootstrap answer is inflated to 30 federal laws built from the live ones.
|
||||
real = self.page.request.get(BASE + '/api/bootstrap').json()
|
||||
laws = [d for d in real.get('documents', []) if d.get('kind') == 'federal-law']
|
||||
if not laws:
|
||||
self.info('Д-002 DocumentList', 'в корпусе нет федеральных законов: пагинацию списка проверить не на чем')
|
||||
return
|
||||
extra = [{**laws[i % len(laws)], 'id': f"{laws[i % len(laws)]['id']}#probe-{i}"} for i in range(30)]
|
||||
body = json.dumps({**real, 'documents': [d for d in real['documents'] if d.get('kind') != 'federal-law'] + extra}, ensure_ascii=False)
|
||||
self.page.route('**/api/bootstrap*', lambda route: route.fulfill(status=200, content_type='application/json', body=body))
|
||||
try:
|
||||
self.page.goto('about:blank') # a hash-only goto keeps the loaded bootstrap; force a real load
|
||||
self.open('/#view=category&kind=federal-law', '.p-pagination')
|
||||
self.page.locator('.p-pagination-actions button', has_text='Следующая').click()
|
||||
self.page.wait_for_timeout(500)
|
||||
self.check('Д-002 DocumentList: страница в URL', self.fragment().get('page') == ['2'], self.page.url)
|
||||
self.page.reload(wait_until='domcontentloaded')
|
||||
self.page.wait_for_selector('.p-pagination')
|
||||
self.page.wait_for_timeout(600)
|
||||
self.check('Д-002 DocumentList: перезагрузка держит страницу', 'страница 2' in self.pagination_label(), self.pagination_label())
|
||||
finally:
|
||||
self.page.unroute('**/api/bootstrap*')
|
||||
self.page.goto('about:blank')
|
||||
|
||||
def rows(self):
|
||||
return self.page.locator('.p-job').all_inner_texts()
|
||||
|
||||
def pick_state(self, label):
|
||||
"""Choose a queue state through whatever control the queue offers: <select> option or button/link."""
|
||||
chosen = self.page.evaluate("""label => {
|
||||
for (const select of document.querySelectorAll('.p-jobs select')) {
|
||||
const option = [...select.options].find(o => o.textContent.includes(label));
|
||||
if (option) { select.value = option.value; select.dispatchEvent(new Event('change', {bubbles: true})); return 'select' } }
|
||||
const control = [...document.querySelectorAll('.p-jobs button, .p-jobs a[href], .p-jobs [role=tab], .p-jobs [role=radio]')]
|
||||
.find(e => e.textContent.includes(label));
|
||||
if (control) { control.click(); return 'click' }
|
||||
return null }""", label)
|
||||
self.page.wait_for_timeout(600)
|
||||
return chosen
|
||||
|
||||
def queue(self, labels):
|
||||
self.use_status_fixture()
|
||||
self.open('/#view=updates', '.p-job', 1000)
|
||||
size = self.page.evaluate("() => ({rows: document.querySelectorAll('.p-job').length, height: document.documentElement.scrollHeight})")
|
||||
self.check('Д-003 по умолчанию строк не больше 50', 0 < size['rows'] <= 50, size)
|
||||
self.check('Д-003 высота страницы не больше 20 000 px', size['height'] <= 20000, size)
|
||||
calm = [labels['current'], labels['updated']]
|
||||
noisy = [row[:80] for row in self.rows() if any(word in row for word in calm)]
|
||||
self.check('Д-003 по умолчанию показано то, что требует внимания', not noisy, noisy[:3])
|
||||
controls = self.page.evaluate("""() => [...document.querySelectorAll('.p-jobs option, .p-jobs button, .p-jobs a[href], .p-jobs [role=tab], .p-jobs [role=radio]')]
|
||||
.map(e => e.textContent.trim())""")
|
||||
wanted = [labels[key] for key in ('deferred', 'blocked', 'failed', 'current', 'updated')]
|
||||
absent = [label for label in wanted if not any(label in text for text in controls)]
|
||||
self.check('Д-003 фильтр по пяти состояниям стоит в очереди', not absent, {'нет подписей': absent})
|
||||
more = self.page.locator('.p-jobs button:not([disabled]), .p-jobs a[href]').filter(has_text=re.compile('Следующ|Далее|Ещё|ещё|Показать'))
|
||||
self.check('Д-003 остальное открывается явным действием', more.count() > 0, more.count())
|
||||
if more.count():
|
||||
first = self.rows()[0]
|
||||
more.first.click()
|
||||
self.page.wait_for_timeout(600)
|
||||
self.check('Д-003 явное действие показывает следующую порцию', self.rows() and self.rows()[0] != first)
|
||||
how = self.pick_state(labels['current'])
|
||||
chosen = self.rows()
|
||||
self.check(f"Д-003 фильтр «{labels['current']}» оставляет только такие задания",
|
||||
how is not None and 0 < len(chosen) <= 50 and all(labels['current'] in row for row in chosen),
|
||||
{'control': how, 'rows': len(chosen)})
|
||||
self.page.unroute('**/api/status*')
|
||||
|
||||
def error_copy(self, labels):
|
||||
self.use_status_fixture()
|
||||
self.open('/#view=updates', '.p-job', 1000)
|
||||
find = """() => {document.querySelectorAll('.p-job details').forEach(d => d.open = true);
|
||||
return [...document.querySelectorAll('.p-job details')].findIndex(d => d.textContent.includes('Errno 2'))}"""
|
||||
index = self.page.evaluate(find)
|
||||
if index < 0 and self.pick_state(labels['failed']):
|
||||
index = self.page.evaluate(find)
|
||||
self.check('Д-004 задание с ошибкой найдено в очереди', index >= 0, index)
|
||||
if index < 0:
|
||||
return
|
||||
copy = self.page.evaluate("""([index, home]) => {const d = document.querySelectorAll('.p-job details')[index];
|
||||
const first = d.querySelector('p');
|
||||
const raw = [...d.querySelectorAll('*')].reverse().find(e => e.textContent.includes('Errno 2'));
|
||||
return {first: first ? first.innerText : null,
|
||||
rawBelow: !!(first && raw && raw !== first && !raw.contains(first) && !first.contains(raw)
|
||||
&& (first.compareDocumentPosition(raw) & Node.DOCUMENT_POSITION_FOLLOWING)),
|
||||
homeVisible: document.body.innerText.includes(home)}}""", [index, HOME])
|
||||
human = copy['first'] or ''
|
||||
self.check('Д-004 первой идёт понятная причина, а не сырая ошибка',
|
||||
bool(human.strip()) and not re.search('Errno|Traceback|No such file', human) and HOME not in human, human[:160])
|
||||
self.check('Д-004 сырая строка оставлена ниже как техническая подробность', copy['rawBelow'], copy['rawBelow'])
|
||||
self.check('Д-004 домашний каталог не виден на странице', not copy['homeVisible'])
|
||||
self.page.unroute('**/api/status*')
|
||||
|
||||
def contrast(self):
|
||||
self.open('/', '.p-stone')
|
||||
measured = self.page.evaluate(CONTRAST)
|
||||
self.check('Д-005 разбор цвета: color(srgb 1 1 1 / 0.97) читается как белый', 5.5 < measured['selfcheck'] < 6.5, measured['selfcheck'])
|
||||
self.check('Д-005 положительный контроль: заведомо бледный текст краснеет', not measured['control']['pass'], measured['control'])
|
||||
bad = [row for row in measured['rows'] if not row['pass']]
|
||||
self.check('Д-005 контраст замеренных подписей не ниже нормы WCAG 1.4.3', measured['rows'] and not bad, bad or len(measured['rows']))
|
||||
contrast = self.axe(['color-contrast'])
|
||||
self.check('Д-005 axe color-contrast на главной', not contrast, contrast)
|
||||
|
||||
def narrow(self):
|
||||
self.page.set_viewport_size({'width': 320, 'height': 720})
|
||||
self.open('/', '.p-stone', 500)
|
||||
width = self.page.evaluate("() => document.documentElement.scrollWidth - document.documentElement.clientWidth")
|
||||
self.check('сохранено: нет горизонтального переполнения на 320 px', width <= 1, width)
|
||||
self.page.set_viewport_size({'width': 1440, 'height': 900})
|
||||
|
||||
def wait_ready(self, limit=180):
|
||||
"""A fresh server answers /api/bootstrap with 0 documents while it indexes (~20 s on the full corpus):
|
||||
checking the interface before status.index.ready would measure the cold start, not the defects."""
|
||||
deadline = time.monotonic() + limit
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + '/api/bootstrap', timeout=30) as response:
|
||||
boot = json.load(response)
|
||||
if (boot.get('status') or {}).get('index', {}).get('ready') and boot.get('documents'):
|
||||
return True
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
self.check('готовность: библиотека закончила индексацию', False, f'index.ready не наступил за {limit} с')
|
||||
return False
|
||||
|
||||
def run(self):
|
||||
self.wait_ready()
|
||||
labels = state_labels()
|
||||
self.section('Д-001 Д-006 Д-007 Д-008 экраны', self.screens)
|
||||
self.section('Д-001 поле поиска', self.search_box)
|
||||
self.section('Д-002 страницы каталога', self.catalog_pages)
|
||||
self.section('Д-002 фильтры каталога', self.catalog_filters)
|
||||
self.section('Д-002 DocumentList', self.document_list)
|
||||
self.section('Д-003 очередь', lambda: self.queue(labels))
|
||||
self.section('Д-004 текст ошибки', lambda: self.error_copy(labels))
|
||||
self.section('Д-005 контраст', self.contrast)
|
||||
self.section('сохранено: узкий экран', self.narrow)
|
||||
self.check('сохранено: ноль ошибок страницы и консоли', not self.errors, self.errors[:5])
|
||||
return 0 if all(item['ok'] for item in self.results if not item.get('info')) else 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('--out', type=Path, help='куда записать JSON-отчёт; без флага только печать')
|
||||
args = parser.parse_args()
|
||||
if not AXE.is_file():
|
||||
print(f'FAIL axe-core не найден: npm ci в eunomia/frontend или AXE_CORE (искал {AXE.name})')
|
||||
return 1
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True, executable_path=executable())
|
||||
check = Check(browser)
|
||||
try:
|
||||
code = check.run()
|
||||
except Exception as error:
|
||||
check.check('проба выполнена до конца', False, f'{type(error).__name__}: {error}')
|
||||
code = 1
|
||||
browser.close()
|
||||
# Reports land in a public repository: the home directory never leaves the machine. The placeholder is
|
||||
# <HOME>, as in the 22.09.2026 reports; '~' would still spell the projects path, which pd_guard rejects.
|
||||
results = json.loads(json.dumps(check.results, ensure_ascii=False).replace(HOME, '<HOME>'))
|
||||
if args.out:
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
report = json.dumps({'base': BASE, 'results': results, 'js_errors': check.errors}, ensure_ascii=False, indent=2)
|
||||
args.out.write_text(report.replace(HOME, '<HOME>') + '\n', encoding='utf-8')
|
||||
for item in results:
|
||||
detail = json.dumps(item.get('detail', ''), ensure_ascii=False)[:300]
|
||||
print('INFO' if item.get('info') else 'PASS' if item['ok'] else 'FAIL', item['name'], detail)
|
||||
failed = sum(1 for item in check.results if not item['ok'])
|
||||
print(json.dumps({'checks': len(check.results), 'failed': failed}, ensure_ascii=False))
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,369 @@
|
||||
/* Эвномия. Навигация по публичной правовой базе; запросы не сохраняются. */
|
||||
(() => {
|
||||
'use strict';
|
||||
const $ = (selector, root = document) => root.querySelector(selector);
|
||||
const app = $('#app');
|
||||
const kinds = {
|
||||
code: ['Кодексы', 'Основные отрасли права', 'К'],
|
||||
'federal-law': ['Федеральные законы', 'Законы по отдельным вопросам', 'ФЗ'],
|
||||
bylaw: ['Подзаконные акты', 'Постановления, приказы и правила', 'А'],
|
||||
plenum: ['Пленумы', 'Разъяснения по применению права', 'П'],
|
||||
review: ['Обзоры практики', 'Правовые позиции и выводы судов', 'О']
|
||||
};
|
||||
const topics = [
|
||||
['civil', 'Гражданское право', 'Договоры, собственность, обязательства', /договор|собственност|обязательств|гражданск.{0,12}кодекс|наслед|сдел[ок]|жилищ|вещн|вред|потребител/i],
|
||||
['process', 'Судебный процесс', 'Иски, доказательства, обжалование', /процесс|производств|судебн.{0,14}решени|подсудност|апелляц|кассац|доказательств|расход|судебн.{0,12}приказ|арбитражн/i],
|
||||
['criminal', 'Уголовное право', 'Преступления и назначение наказания', /уголовн|преступлен|наказани|осужден|приговор|хищени|взяточ|убийств|мошеннич|наркот/i],
|
||||
['admin', 'Административное право', 'Правонарушения и публичные споры', /административн|правонарушени|публичн|государственн.{0,8}служб|избирательн/i],
|
||||
['work', 'Труд и социальные права', 'Работа, пенсии, социальные выплаты', /трудов|работник|работодател|пенси|социальн|заработн|забастов/i],
|
||||
['family', 'Семья и дети', 'Брак, алименты, защита прав детей', /семейн|брачн|алимент|родител|детей|ребенк|усыновл|расторжени.{0,8}брак/i],
|
||||
['business', 'Экономические споры', 'Банкротство, налоги, деятельность компаний', /банкрот|несостоятельн|налог|таможен|экономическ|корпоративн|акционер|предпринимател|конкуренц/i],
|
||||
['other', 'Другие вопросы', 'Документы вне выбранных направлений', null]
|
||||
];
|
||||
const statusNames = {queued:'В очереди', running:'Обновляется', current:'Проверен', updated:'Обновлён', deferred:'Повтор позже', blocked:'Источник недоступен', failed:'Не удалось обновить', error:'Не удалось обновить'};
|
||||
const state = {docs:[], status:{}, csrf:'', ready:false, route:{}, doc:null, selected:'', readerSize:20, graph:null, graphSelected:null, scale:1, pan:{x:0,y:0}, renderId:0, error:''};
|
||||
let toastTimer;
|
||||
const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const params = value => new URLSearchParams(Object.entries(value).filter(([,v]) => v !== undefined && v !== null && v !== '')).toString();
|
||||
const href = value => '#' + params(value);
|
||||
const docHref = (id, fragment='') => href({doc:id, fragment});
|
||||
const labelKind = kind => kinds[kind]?.[0] || 'Документ';
|
||||
const iconPositions = {home:0,code:1,'federal-law':2,bylaw:3,plenum:4,review:5,graph:6,history:7,updates:8,search:9,menu:10,arrow:11,copy:12,close:13,back:14,focus:15};
|
||||
function icon(name) { const n=iconPositions[name]??2; return `<span class="ui-icon" style="--icon-x:${(n%4)*100/3}%;--icon-y:${Math.floor(n/4)*100/3}%" aria-hidden="true"></span>`; }
|
||||
const coverIds = new Set(['gk-rf','gpk-rf','sk-rf','kas-rf','koap-rf','apk-rf','nk-rf-gosposhlina','tk-rf','zhk-rf','zk-rf','uk-rf','upk-rf']);
|
||||
function coverPath(doc) { const id=doc.id.split(':').at(-1); return doc.kind==='code'&&coverIds.has(id)?`/assets/books/${id}.png`:null; }
|
||||
function bookCard(doc) {
|
||||
const cover=coverPath(doc);
|
||||
const caption=!doc.available?'Текст пока не загружен':doc.coverage?.status==='partial'?'Доступна часть текста':doc.id.endsWith(':gk-rf')?'Четыре части':doc.coverage?.status==='full'?'Текст загружен':'Полнота требует проверки';
|
||||
return `<a class="book-card ${cover?'':'book-card-text'}" href="${href({view:'contents',id:doc.id})}">${cover?`<div class="book-card-image"><img src="${cover}" alt="" width="320" height="320" loading="lazy"></div>`:`<span class="law-symbol">${icon(doc.kind)}</span>`}<h2 class="book-title">${escape(bookName(doc))}</h2><p class="book-caption">${caption}</p><span class="book-open">Открыть ${icon('arrow')}</span></a>`;
|
||||
}
|
||||
const docCount = n => `${n} ${n % 10 === 1 && n % 100 !== 11 ? 'документ' : n % 10 >= 2 && n % 10 <= 4 && !(n % 100 >= 12 && n % 100 <= 14) ? 'документа' : 'документов'}`;
|
||||
const normalized = value => String(value || '').toLocaleLowerCase('ru').replaceAll('ё','е');
|
||||
const shortDate = value => {
|
||||
if (!value) return 'не указана';
|
||||
if (/^\d{2}\.\d{2}\.\d{4}$/.test(value)) return value;
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(+parsed) ? String(value) : parsed.toLocaleDateString('ru-RU');
|
||||
};
|
||||
function identity(doc) {
|
||||
const text = [doc.act_date, doc.number, doc.title].filter(Boolean).join(' ');
|
||||
const match = text.match(/\b(\d{2})\.(\d{2})\.(\d{4})\b/);
|
||||
const date = match ? `${match[1]}.${match[2]}.${match[3]}` : null;
|
||||
const key = match ? `${match[3]}-${match[2]}-${match[1]}` : null;
|
||||
const num = String(doc.number || '').match(/^(\d+(?:[-/]\S+)*)$/)?.[1] || text.match(/(?:№|\bN)\s*([\d]+(?:[-/]\S+)*)/)?.[1];
|
||||
return {date, key, year:match?.[3] || '', number:num || ''};
|
||||
}
|
||||
function matchesTopic(doc, topic) {
|
||||
if (!topic || topic === 'all') return true;
|
||||
const text = `${doc.subject || ''} ${doc.title}`;
|
||||
if (topic === 'other') return !topics.some(t => t[3]?.test(text));
|
||||
return topics.find(t => t[0] === topic)?.[3]?.test(text) || false;
|
||||
}
|
||||
async function api(path, options={}) {
|
||||
const headers = {Accept:'application/json', ...(options.headers || {})};
|
||||
if (options.method === 'POST') Object.assign(headers, {'Content-Type':'application/json', 'X-Eunomia-CSRF':state.csrf});
|
||||
const response = await fetch('/api' + path, {...options, headers});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось получить данные. Попробуйте ещё раз.');
|
||||
return data;
|
||||
}
|
||||
function toast(text) {
|
||||
clearTimeout(toastTimer);
|
||||
$('#toast').textContent = text;
|
||||
$('#toast').classList.add('show');
|
||||
toastTimer = setTimeout(() => $('#toast').classList.remove('show'), 5000);
|
||||
}
|
||||
function empty(title, text, action='') {
|
||||
return `<div class="empty-state"><strong>${escape(title)}</strong><p>${escape(text)}</p>${action}</div>`;
|
||||
}
|
||||
function heading(title, subtitle='', actions='') {
|
||||
return `<div class="page-heading"><div><h1>${escape(title)}</h1>${subtitle ? `<p>${escape(subtitle)}</p>` : ''}</div>${actions ? `<div class="heading-actions">${actions}</div>` : ''}</div>`;
|
||||
}
|
||||
function crumbs(items) {
|
||||
$('#breadcrumbs').innerHTML = [{name:'Библиотека',url:href({view:'home'})},...items].map((item,i) => `${i ? '<span aria-hidden="true">/</span>' : ''}${item.url ? `<a class="breadcrumb-link" href="${item.url}">${escape(item.name)}</a>` : `<span aria-current="page">${escape(item.name)}</span>`}`).join('');
|
||||
}
|
||||
function navigate(value) { const target=href(value); if(location.hash===target) route(); else location.hash=target; }
|
||||
function pagination(total, page, size=12, routeValue=state.route) {
|
||||
const pages = Math.max(1,Math.ceil(total/size));
|
||||
if (pages <= 1) return '';
|
||||
return `<nav class="pagination" aria-label="Страницы документов"><a class="button quiet ${page===1?'is-disabled':''}" ${page===1?'aria-disabled="true"':`href="${href({...routeValue,page:page-1})}"`}>Назад</a><span>Страница ${page} из ${pages}</span><a class="button quiet ${page===pages?'is-disabled':''}" ${page===pages?'aria-disabled="true"':`href="${href({...routeValue,page:page+1})}"`}>Далее</a></nav>`;
|
||||
}
|
||||
function collection(kind) {
|
||||
const [title,description,icon]=kinds[kind];
|
||||
const count=state.docs.filter(d=>d.kind===kind).length;
|
||||
return `<a class="collection-link" href="${href({view:'category',kind})}"><span class="collection-icon" aria-hidden="true">${icon}</span><span class="collection-copy"><strong>${title}</strong><span>${description}</span></span><span class="collection-count">${count}</span><span class="collection-arrow" aria-hidden="true">→</span></a>`;
|
||||
}
|
||||
function home() {
|
||||
crumbs([]);
|
||||
app.innerHTML=`<div class="page"><section class="home-intro"><div class="home-intro-copy"><span class="home-label">Эвномия · Themiz</span><h1>Библиотека</h1><p>Нормативные акты и судебная практика</p><form id="home-search" class="home-search"><label class="sr-only" for="home-query">Поиск по библиотеке</label><input id="home-query" type="search" placeholder="Название, статья или фраза" autocomplete="off"><button class="button primary">Найти</button></form><div class="home-examples"><span>Например:</span><a href="${href({view:'search',q:'ст. 395 ГК'})}">ст. 395 ГК</a><a href="${href({view:'search',q:'ст. 131 ГПК'})}">ст. 131 ГПК</a></div></div><img class="goddess-art" src="/eunomia-goddess.png" alt="Образ Эвномии" width="280" height="280"></section><div class="collection-groups"><section class="collection-group"><h2>Нормативные акты</h2>${['code','federal-law','bylaw'].map(collection).join('')}</section><section class="collection-group"><h2>Судебная практика</h2>${['plenum','review'].map(collection).join('')}<a class="graph-entry" href="${href({view:'graph',q:'статья 395'})}"><strong>Связи статей и разъяснений</strong><span>Открыть граф связей →</span></a></section></div><p class="help-note">Тексты хранятся на компьютере. Полнота и дата проверки указаны в документе.</p></div>`;
|
||||
$('#home-search').onsubmit=e=>{e.preventDefault();const q=$('#home-query').value.trim();if(q)navigate({view:'search',q});};
|
||||
}
|
||||
function documentRow(doc) {
|
||||
const meta=identity(doc), coverage=doc.coverage?.status;
|
||||
const title=doc.subject || doc.title;
|
||||
const type = labelKind(doc.kind);
|
||||
const warning = !doc.available ? 'Текст пока не загружен' : coverage==='partial' ? 'Неполный текст' : doc.warnings?.length ? 'Нужна сверка' : '';
|
||||
return `<article class="document-row" data-act-date="${meta.key || ''}"><div class="document-main"><a class="document-title" href="${docHref(doc.id)}">${escape(title)}</a>${doc.subject ? `<div class="document-subject">${escape(doc.title)}</div>`:''}<div class="document-details"><span>${escape(type)}${meta.number ? ' № '+escape(meta.number):''}</span><span>Редакция: ${escape(shortDate(doc.revision))}</span>${warning ? `<span class="status-tag warning">${warning}</span>`:''}</div></div><div class="document-meta"><span class="document-date">${meta.date ? `<time>${meta.date}</time>`:'Дата не указана'}</span><a class="document-open" href="${docHref(doc.id)}" aria-label="Читать: ${escape(title)}">Читать <span aria-hidden="true">→</span></a></div></article>`;
|
||||
}
|
||||
function yearGroups(docs) {
|
||||
let year=null, html='';
|
||||
for (const doc of docs) {
|
||||
const next=identity(doc).year || 'Дата не указана';
|
||||
if(next!==year){ if(year!==null)html+='</div></section>'; html+=`<section class="year-group"><h2>${escape(next)}${/^\d/.test(next)?' год':''}</h2><div class="document-list">`;year=next; }
|
||||
html+=documentRow(doc);
|
||||
}
|
||||
return html+(year!==null?'</div></section>':'');
|
||||
}
|
||||
function category() {
|
||||
const r=state.route, kind=kinds[r.kind]?r.kind:'code', all=state.docs.filter(d=>d.kind===kind);
|
||||
if(['code','federal-law'].includes(kind))return bookLibrary(kind,all);
|
||||
const hasTopics=['plenum','review','federal-law','bylaw'].includes(kind);
|
||||
const showTopics=hasTopics&&!r.topic&&!r.q&&!r.year;
|
||||
const topic=topics.find(t=>t[0]===r.topic);
|
||||
crumbs([{name:labelKind(kind),url:topic?href({view:'category',kind}):null},...(topic?[{name:topic[1]}]:[])]);
|
||||
const years=[...new Set(all.map(d=>identity(d).year).filter(Boolean))].sort();
|
||||
let docs=all.filter(d=>matchesTopic(d,r.topic)&&(!r.year||identity(d).year===r.year)&&(!r.q||normalized(`${d.title} ${d.subject||''} ${d.number||''} ${identity(d).date||''}`).includes(normalized(r.q))));
|
||||
const sort=r.sort||'old';
|
||||
docs.sort((a,b)=>{const aa=identity(a),bb=identity(b);if(!aa.key)return bb.key?1:a.title.localeCompare(b.title,'ru');if(!bb.key)return -1;const cmp=aa.key.localeCompare(bb.key);return (sort==='new'?-cmp:cmp)||aa.number.localeCompare(bb.number,'ru',{numeric:true})||a.title.localeCompare(b.title,'ru');});
|
||||
const page=Math.min(Math.max(1,Number(r.page)||1),Math.max(1,Math.ceil(docs.length/12)));
|
||||
const options=`<option value="">Любое направление</option>${topics.map(t=>`<option value="${t[0]}" ${r.topic===t[0]?'selected':''}>${t[1]}</option>`).join('')}`;
|
||||
app.innerHTML=`<div class="page">${heading(topic?.[1]||labelKind(kind), showTopics?'Выберите направление или найдите документ по названию, номеру и дате.':`${docCount(docs.length)} · Дата акта и редакция показаны отдельно.`)}<form class="category-tools" id="category-filter"><label class="field grow"><span>Поиск в разделе</span><input type="search" name="q" value="${escape(r.q||'')}" placeholder="Название, номер или дата"></label>${hasTopics?`<label class="field"><span>Направление</span><select name="topic">${options}</select></label>`:''}<label class="field"><span>Год акта</span><select name="year"><option value="">Все годы</option>${years.map(y=>`<option ${r.year===y?'selected':''}>${y}</option>`).join('')}</select></label><label class="field"><span>По дате акта</span><select name="sort"><option value="old" ${sort==='old'?'selected':''}>Сначала ранние</option><option value="new" ${sort==='new'?'selected':''}>Сначала новые</option></select></label><button class="button primary" type="submit">Найти</button></form>${showTopics?`<div class="section-heading"><h2>По направлениям</h2><a class="text-link" href="${href({view:'category',kind,topic:'all'})}">Все ${docCount(all.length)} →</a></div><div class="topic-grid">${topics.map(t=>{const count=all.filter(d=>matchesTopic(d,t[0])).length;return `<a class="topic-card" href="${href({view:'category',kind,topic:t[0]})}"><div class="topic-heading"><h3>${t[1]}</h3><span class="topic-count">${count}</span></div><p>${t[2]}</p></a>`;}).join('')}</div><p class="help-note">Направления определены по названиям документов. Один документ может относиться к нескольким направлениям. Полный список доступен по ссылке «Все документы».</p>`:`<div class="list-heading"><span>${docCount(docs.length)}</span><span>${sort==='new'?'От поздних дат к ранним':'От ранних дат к поздним'}</span></div>${docs.length?yearGroups(docs.slice((page-1)*12,page*12)):empty('Документы не найдены','Попробуйте другое направление, год или название.',`<a class="button quiet" href="${href({view:'category',kind,topic:'all'})}">Показать весь раздел</a>`)}${pagination(docs.length,page)}`}</div>`;
|
||||
$('#category-filter').onsubmit=e=>{e.preventDefault();const f=new FormData(e.currentTarget);navigate({view:'category',kind,topic:f.get('topic')||'all',q:f.get('q'),year:f.get('year'),sort:f.get('sort')});};
|
||||
$('#category-filter').querySelectorAll('select').forEach(s=>s.onchange=()=>$('#category-filter').requestSubmit());
|
||||
}
|
||||
function bookName(d){return (d.subject||d.title).replace(/\s+Российской Федерации/g,'').replace(/\s+от\s+\d{2}\.\d{2}\.\d{4}.*$/,'').replace(/^Федеральный закон\s*/,'').replace(/^Закон РФ\s*/,'').replace(/[«»]/g,'');}
|
||||
function bookLibrary(kind,all){
|
||||
crumbs([{name:labelKind(kind)}]);
|
||||
const q=normalized(state.route.q),docs=all.filter(d=>normalized(d.title+' '+(d.subject||'')).includes(q));
|
||||
app.innerHTML=`<div class="page book-library">${heading(labelKind(kind),kind==='code'?'Откройте кодекс и выберите нужную статью.':'Законы по отдельным вопросам.')}<form id="book-filter" class="category-tools"><label class="field grow"><span>Найти ${kind==='code'?'кодекс':'закон'}</span><input name="q" type="search" value="${escape(state.route.q||'')}" placeholder="Название или сокращение"></label><button class="button primary">Найти</button></form><div class="book-grid">${docs.map(d=>`<a class="book-card" href="${href({view:'contents',id:d.id})}"><div class="book-card-image"><img src="/codebook.png" alt="" width="320" height="220" loading="lazy"></div><h2 class="book-title">${escape(bookName(d))}</h2><p class="book-caption">${!d.available?'Текст пока не загружен':d.coverage?.status==='partial'?'Доступна часть текста':d.id.endsWith(':gk-rf')?'Четыре части':d.coverage?.status==='full'?'Текст загружен':'Полнота требует проверки'}</p><span class="book-open">Открыть <span aria-hidden="true">↗</span></span></a>`).join('')}</div>${docs.length?'':empty('Ничего не найдено','Попробуйте другое название.')}</div>`;
|
||||
$('#book-filter').onsubmit=e=>{e.preventDefault();navigate({view:'category',kind,q:new FormData(e.currentTarget).get('q')});};
|
||||
}
|
||||
async function contentsView(token){
|
||||
const r=state.route,d=state.docs.find(d=>d.id===r.id);if(!d){app.innerHTML=empty('Документ не найден','Откройте библиотеку.');return;}
|
||||
crumbs([{name:labelKind(d.kind),url:href({view:'category',kind:d.kind})},{name:bookName(d)}]);
|
||||
app.innerHTML=`<div class="page">${heading(bookName(d),'')}<div id="contents-body"><p class="help-note">Открываем оглавление…</p></div></div>`;
|
||||
try{const data=await api('/reader?'+params({id:d.id}));if(token!==state.renderId)return;const toc=data.toc||[],parts=toc.filter(f=>/^Часть\s+(первая|вторая|третья|четвертая|четвёртая)/i.test(f.label));
|
||||
if(parts.length>1&&!r.part){$('#contents-body').innerHTML=`<p class="contents-intro">Выберите часть кодекса</p><div class="part-grid">${parts.map((f,i)=>`<a class="part-card" href="${href({view:'contents',id:d.id,part:f.id})}"><span class="part-number">${['I','II','III','IV'][i]||i+1}</span><h2>${escape(f.label)}</h2><span>Разделы и статьи →</span></a>`).join('')}</div>`;return;}
|
||||
let rows=toc;if(r.part){const start=toc.findIndex(f=>f.id===r.part),next=toc.findIndex((f,i)=>i>start&&parts.some(p=>p.id===f.id));rows=toc.slice(Math.max(0,start),next<0?toc.length:next);}
|
||||
$('#contents-body').innerHTML=`${parts.length>1?`<a class="text-link" href="${href({view:'contents',id:d.id})}">← Все части кодекса</a>`:''}<div class="section-heading"><h2>${escape(rows[0]?.label?.startsWith('Часть ')?rows[0].label:'Оглавление')}</h2><a class="button quiet" href="${docHref(d.id,rows[0]?.id)}">Читать с начала</a></div><label class="field"><span>Статья, пункт или слово в заголовке</span><input id="contents-find" type="search" placeholder="Например, 395"></label><div class="contents-list">${tocMarkup(rows,d.id)}</div>`;
|
||||
$('#contents-find').oninput=e=>{const q=normalized(e.target.value);$('.contents-list').querySelectorAll('a').forEach(a=>a.hidden=!!q&&!normalized(a.textContent).includes(q));$('.contents-list').querySelectorAll('details').forEach(g=>{g.open=!!q;g.hidden=!!q&&!g.querySelector('a:not([hidden])');});};
|
||||
}catch(e){if(token===state.renderId)$('#contents-body').innerHTML=empty('Оглавление пока недоступно',e.message);}
|
||||
}
|
||||
function highlight(text, query) {
|
||||
const terms=normalized(query).split(/\s+/).filter(x=>x.length>2);
|
||||
if(!terms.length)return escape(text);
|
||||
const pattern=new RegExp('('+terms.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')).join('|')+')','gi');
|
||||
return String(text).split(pattern).map((part,i)=>i%2?`<mark>${escape(part)}</mark>`:escape(part)).join('');
|
||||
}
|
||||
async function searchView(token) {
|
||||
const r=state.route;
|
||||
crumbs([{name:'Поиск'}]);
|
||||
app.innerHTML=`<div class="page">${heading('Поиск по библиотеке',r.q?`По запросу «${r.q}»`:'Введите название, статью, номер или фразу в строке поиска.')}<form class="category-tools" id="search-filter"><label class="field"><span>Вид документа</span><select name="kind"><option value="">Все документы</option>${Object.entries(kinds).map(([k,v])=>`<option value="${k}" ${r.kind===k?'selected':''}>${v[0]}</option>`).join('')}</select></label></form><div id="search-results">${empty('Ищем в локальных текстах','Это может занять несколько секунд.')}</div></div>`;
|
||||
$('#search-filter select').onchange=e=>navigate({...r,kind:e.target.value,page:1});
|
||||
if(!r.q){$('#search-results').innerHTML='';return;}
|
||||
try {
|
||||
const result=await api('/search?'+params({q:r.q,kind:r.kind}));
|
||||
if(token!==state.renderId)return;
|
||||
const rows=result.results||[],page=Math.min(Math.max(1,Number(r.page)||1),Math.max(1,Math.ceil(rows.length/12)));
|
||||
$('#search-results').innerHTML=`<p class="list-heading">Найдено фрагментов: ${result.total||0}${result.total>rows.length?' · показаны наиболее подходящие':''}</p>${rows.slice((page-1)*12,page*12).map(x=>`<article class="result-row"><a href="${docHref(x.resource_id,x.id)}">${escape(x.label||x.title)}</a><p class="document-subject">${escape(x.document||x.title)} · ${escape(labelKind(x.kind))}</p><p class="result-snippet">${highlight(x.snippet||x.text||'',r.q)}</p><div class="document-details"><span>Редакция: ${escape(shortDate(x.revision))}</span>${x.warnings?.length?`<span class="status-tag warning">${escape(x.warnings[0])}</span>`:''}</div></article>`).join('')||empty('Совпадений нет','Попробуйте название документа, точную фразу или, например, «ст. 131 ГПК».')}${pagination(rows.length,page)}`;
|
||||
} catch(e){if(token===state.renderId)$('#search-results').innerHTML=empty('Поиск временно недоступен',e.message);}
|
||||
}
|
||||
function fragmentText(fragment) {
|
||||
let raw=String(fragment.text||''), cursor=0,html='';
|
||||
const anchors=(fragment.anchors||[]).slice().sort((a,b)=>a.offset-b.offset);
|
||||
for(const anchor of anchors){const offset=Math.max(cursor,Math.min(raw.length,anchor.offset));html+=escape(raw.slice(cursor,offset))+`<span id="${escape(anchor.id)}" class="point-anchor"></span>`;cursor=offset;}
|
||||
html+=escape(raw.slice(cursor));
|
||||
return html.replace(/^#{1,6}[^\n]*(?:\n|$)/,'').replace(/\n{3,}/g,'\n\n');
|
||||
}
|
||||
function tocMarkup(parts, id) {
|
||||
let html='', group=false;
|
||||
for (const f of parts) {
|
||||
if (/^Глава\s/i.test(f.label)) {
|
||||
if (group) html+='</details>';
|
||||
html+=`<details class="toc-group"><summary>${escape(f.label)}</summary>`;
|
||||
group=true;
|
||||
} else {
|
||||
if (/^(Раздел|Часть)\s/i.test(f.label) && group) {html+='</details>';group=false;}
|
||||
html+=`<a class="toc-link" href="${docHref(id,f.id)}" data-fragment="${escape(f.id)}" data-level="${f.kind==='article'||f.kind==='point'?'2':'1'}">${escape(f.label)}</a>`;
|
||||
}
|
||||
}
|
||||
return html+(group?'</details>':'');
|
||||
}
|
||||
async function reader(token) {
|
||||
const r=state.route;
|
||||
if(!state.doc||state.doc.document.id!==r.doc||!state.doc.fragments.some(f=>f.id===r.fragment||(f.anchors||[]).some(a=>a.id===r.fragment))){
|
||||
app.innerHTML=empty('Открываем документ','Загружаем сохранённый текст.');
|
||||
try{const data=await api('/reader?'+params({id:r.doc,fragment:r.fragment}));if(token!==state.renderId)return;state.doc={...data,fragments:data.fragment?[data.fragment]:[],related:[]};}catch(e){if(token===state.renderId)app.innerHTML=empty('Не удалось открыть документ',e.message);return;}
|
||||
}
|
||||
const d=state.doc.document,parts=state.doc.fragments||[],meta=identity(d);
|
||||
crumbs([{name:labelKind(d.kind),url:href({view:'category',kind:d.kind})},{name:meta.number?'№ '+meta.number:'Документ'}]);
|
||||
const warning=d.warnings||[];
|
||||
app.innerHTML=`<div class="wide-page"><div class="reader-document-head">${heading(d.subject||d.title,`${labelKind(d.kind)}${meta.number?' № '+meta.number:''}${meta.date?' от '+meta.date:''}`)}<div class="inline-actions"><a class="button quiet" href="${href({view:'history',id:d.id})}">История редакций</a><button class="button quiet" data-action="update" data-id="${escape(d.id)}">Обновить этот документ</button></div></div>${warning.length?`<details class="notice warning"><summary>${escape(warning[0])}<span>Подробнее</span></summary><ul>${warning.map(w=>`<li>${escape(w)}</li>`).join('')}</ul></details>`:''}<div class="reader-shell"><aside class="reader-toc" aria-label="Оглавление"><button class="reader-panel-toggle button quiet" data-toggle="toc-content" aria-expanded="false">Оглавление</button><div id="toc-content" class="reader-panel-content"><h2>Оглавление</h2><label class="field"><span>Статья или пункт</span><input type="search" id="toc-search" placeholder="Например, 131"></label><div class="toc-scroll">${tocMarkup(parts,d.id)}</div></div></aside><article class="reader-center"><div class="document-toolbar"><div class="inline-actions"><button class="button quiet" data-action="copy-text">Копировать текст</button><button class="button quiet" data-action="copy-link">Копировать ссылку</button><a class="button quiet" href="${safeURL(d.source_url)}" target="_blank" rel="noopener noreferrer">Источник ↗</a></div><div class="size-controls" aria-label="Размер текста"><button data-size="-2" aria-label="Уменьшить текст">А−</button><button data-size="2" aria-label="Увеличить текст">А+</button></div></div><div class="reader-find"><label class="field grow"><span>Найти в документе</span><input type="search" id="reader-find" placeholder="Слово или фраза"></label><button class="button quiet" data-action="find-prev" aria-label="Предыдущее совпадение">↑</button><button class="button quiet" data-action="find-next" aria-label="Следующее совпадение">↓</button><span id="find-count" role="status"></span></div><div class="reader-meta"><span>Редакция: <strong>${escape(shortDate(d.revision))}</strong></span><span>Копия получена: ${escape(shortDate(d.retrieved_at))}</span><span>Успешная проверка: ${escape(shortDate(d.last_checked))}</span>${d.effective_date?`<span>Вступление в силу: ${escape(shortDate(d.effective_date))}</span>`:''}</div><div class="reading-text" style="font-size:${state.readerSize}px">${parts.length?parts.map(f=>`<section class="text-fragment" id="${escape(f.id)}"><h2 class="fragment-heading">${escape(f.label)}</h2><div class="fragment-body">${fragmentText(f)}</div></section>`).join(''):empty('Текст пока не загружен','Можно открыть первоисточник или поставить документ на обновление.')}</div></article><aside class="reader-related"><button class="reader-panel-toggle button quiet" data-toggle="related-content" aria-expanded="false">Связанные материалы</button><div id="related-content" class="reader-panel-content"><h2>Связанные материалы</h2><p class="muted" id="related-caption">К документу</p><div id="related-list"></div><a class="text-link" href="${href({view:'graph',resource_id:d.id})}">Показать на карте связей →</a></div></aside></div></div>`;
|
||||
$('#toc-search').oninput=e=>{const q=normalized(e.target.value);$('.toc-scroll').querySelectorAll('a').forEach(a=>a.hidden=!!q&&!normalized(a.textContent).includes(q));$('.toc-scroll').querySelectorAll('details').forEach(group=>{group.open=!!q;group.hidden=!!q&&!group.querySelector('a:not([hidden])');});};
|
||||
let findTimer; $('#reader-find').oninput=()=>{clearTimeout(findTimer);findTimer=setTimeout(async()=>{const whole=$('[data-action=whole-document]');if(whole&&!whole.disabled)await action(whole);findInDocument();},180);};
|
||||
$('.toc-scroll').innerHTML=tocMarkup(state.doc.toc||parts,d.id);
|
||||
$('.document-toolbar .inline-actions').insertAdjacentHTML('afterbegin','<button class="button quiet" data-action="whole-document">Весь документ</button>');
|
||||
$('.document-toolbar').insertAdjacentHTML('beforeend','<button class="button quiet related-open" data-action="related" aria-expanded="false">Связанные материалы</button>');
|
||||
$('.reader-related').insertAdjacentHTML('afterbegin','<button class="button quiet related-close" data-action="related">Закрыть панель</button>');
|
||||
$('.document-toolbar').append($('.reader-find'));
|
||||
renderRelated(r.fragment);
|
||||
if(r.fragment)jump(r.fragment,false);else{state.selected=parts[0]?.id||'';window.scrollTo(0,0);} loadRelated(state.selected);
|
||||
}
|
||||
function safeURL(url){try{const u=new URL(url);return ['https:','http:'].includes(u.protocol)?escape(u.href):'#';}catch{return '#';}}
|
||||
let relatedToken=0;
|
||||
async function loadRelated(fragment=''){
|
||||
const id=state.doc?.document.id, request=++relatedToken;if(!id)return;
|
||||
const root=$('#related-list');if(root)root.innerHTML='<p class="help-note">Загружаем связанные фрагменты…</p>';
|
||||
try{const data=await api('/related?'+params({id,fragment}));if(request!==relatedToken||state.doc?.document.id!==id)return;state.doc.related=data.related||[];state.doc.graphLoading=data.loading;const graphLink=$('.reader-related .text-link');if(graphLink)graphLink.href=href({view:'graph',node_id:data.node_id||undefined,resource_id:data.node_id?undefined:id});renderRelated(fragment);if(data.loading)setTimeout(()=>{if(state.doc?.document.id===id&&state.route.doc===id)loadRelated(fragment);},1500);}catch{if(request===relatedToken&&root)root.innerHTML='<p class="help-note">Связи пока недоступны. Текст можно читать.</p>';}
|
||||
}
|
||||
function renderRelated(fragment=''){
|
||||
const root=$('#related-list');if(!root)return;
|
||||
const id=state.doc.document.id;
|
||||
const edges=state.doc.related||[];
|
||||
$('#related-caption').textContent=fragment?'К выбранной статье или пункту':'К документу целиком';
|
||||
root.innerHTML=edges.slice(0,30).map(e=>{const source=e.source_node||{},target=e.target_node||{},other=source.resource_id===id?target:source;return `<details class="relation-item"><summary>${escape(other.label||'Связанный фрагмент')} · ${escape(other.document_title||'')}</summary><div class="relation-detail"><span class="status-tag">${e.relation==='references'?'Прямая ссылка':e.relation==='thematic'?'Тематическая связь':'Связь из графа'}</span><p>${escape(e.evidence?.excerpt||'Доказательство связи не предоставлено.')}</p><p>Редакция: ${escape(shortDate(e.evidence?.revision))}</p>${e.evidence?.source_url?`<a href="${safeURL(e.evidence.source_url)}" target="_blank" rel="noopener noreferrer">Источник связи ↗</a>`:''}<a class="button quiet" href="${docHref(other.resource_id,other.reader_id||'')}">Открыть фрагмент →</a></div></details>`;}).join('')||`<p class="help-note">${state.status.graph?.available?'В сохранённом графе не найдено подтверждённых связей.':'Карта связей ещё не собрана. Читать документ можно уже сейчас.'}</p>`;
|
||||
}
|
||||
function jump(id,update=true){
|
||||
let node=document.getElementById(id);
|
||||
if(!node){if(update)navigate({doc:state.doc.document.id,fragment:id});return;}
|
||||
state.selected=id;
|
||||
$('.toc-scroll')?.querySelectorAll('a').forEach(a=>a.classList.toggle('is-active',a.dataset.fragment===id));
|
||||
const active=$('.toc-scroll .is-active');
|
||||
if(active){const group=active.closest('details');if(group)group.open=true;const toc=$('.toc-scroll');toc.scrollTop+=active.getBoundingClientRect().top-toc.getBoundingClientRect().top-60;}
|
||||
node.scrollIntoView({behavior:'instant',block:'start'});
|
||||
const overlays=[$('.topbar'),$('.document-toolbar'),$('.reader-find')].filter(n=>n&&['sticky','fixed'].includes(getComputedStyle(n).position));
|
||||
const top=Math.max(0,...overlays.map(n=>n.getBoundingClientRect().bottom))+16;
|
||||
window.scrollTo({top:window.scrollY+node.getBoundingClientRect().top-top,behavior:'instant'});
|
||||
if(update)history.replaceState(null,'',docHref(state.doc.document.id,id));
|
||||
loadRelated(id);
|
||||
}
|
||||
let findNodes=[],findIndex=-1;
|
||||
function findInDocument(){
|
||||
const q=normalized($('#reader-find')?.value),root=$('.reading-text');if(!root)return;
|
||||
root.querySelectorAll('mark').forEach(m=>m.replaceWith(document.createTextNode(m.textContent)));root.normalize();findNodes=[];findIndex=-1;
|
||||
if(q){const walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT);const texts=[];while(walker.nextNode())texts.push(walker.currentNode);for(const text of texts){const norm=normalized(text.textContent);let pos=norm.indexOf(q),start=0;if(pos<0)continue;const output=document.createDocumentFragment();while(pos>=0){output.append(text.textContent.slice(start,pos));const mark=document.createElement('mark');mark.textContent=text.textContent.slice(pos,pos+q.length);output.append(mark);findNodes.push(mark);start=pos+q.length;pos=norm.indexOf(q,start);}output.append(text.textContent.slice(start));text.replaceWith(output);}}
|
||||
$('#find-count').textContent=q?`${findNodes.length} совпадений`:'';
|
||||
}
|
||||
function nextFind(delta){if(!findNodes.length)return;findIndex=(findIndex+delta+findNodes.length)%findNodes.length;findNodes[findIndex].scrollIntoView({block:'center'});$('#find-count').textContent=`${findIndex+1} из ${findNodes.length}`;}
|
||||
async function historyView(token){
|
||||
const r=state.route;crumbs([{name:'История редакций'}]);
|
||||
if(!r.id){app.innerHTML=`<div class="page">${heading('История редакций','Откройте документ и выберите «История редакций», чтобы сравнить его сохранённые копии.')}<label class="field"><span>Найти документ для сравнения</span><input type="search" id="history-picker" placeholder="Название или номер"></label><div id="history-documents"></div></div>`;const update=()=>{const q=normalized($('#history-picker').value);const list=state.docs.filter(d=>normalized(`${d.title} ${d.subject||''}`).includes(q)).slice(0,12);$('#history-documents').innerHTML=list.map(d=>`<div class="result-row"><a href="${href({view:'history',id:d.id})}">${escape(d.subject||d.title)}</a></div>`).join('');};$('#history-picker').oninput=update;update();return;}
|
||||
const d=state.docs.find(d=>d.id===r.id);
|
||||
app.innerHTML=`<div class="page">${heading('История редакций',d?.subject||d?.title||'',`<a class="button quiet" href="${docHref(r.id)}">Читать документ</a>`)}<div id="history-body">${empty('Загружаем снимки','Только реально сохранённые версии.')}</div></div>`;
|
||||
try{
|
||||
const data=await api('/history?'+params({id:r.id}));if(token!==state.renderId)return;
|
||||
const versions=data.versions||[];
|
||||
const option=(v,i)=>`<option value="${v.id}">${escape(shortDate(v.retrieved_at))} · редакция ${escape(shortDate(v.revision))}${v.current?' · текущая копия':''}</option>`;
|
||||
$('#history-body').innerHTML=`<p class="notice">${escape(data.note||'Показаны сохранённые копии документа.')}</p><p class="muted">Наблюдение в Эвномии начато: ${escape(shortDate(data.observation_started))}</p><div class="version-list">${versions.map(v=>`<div class="version-item"><span>Редакция <strong>${escape(shortDate(v.revision))}</strong>${v.current?' · текущая копия':''}</span><span>Получена ${escape(shortDate(v.retrieved_at))}</span>${v.effective_date?`<span>Вступила в силу ${escape(shortDate(v.effective_date))}</span>`:''}</div>`).join('')}</div>${versions.length>1?`<form class="history-controls" id="compare-form"><label class="field grow"><span>Более ранняя копия</span><select name="before">${versions.map(option).join('')}</select></label><label class="field grow"><span>Более поздняя копия</span><select name="after">${versions.map(option).join('')}</select></label><label class="field"><span>Статья или пункт</span><input name="fragment" placeholder="Например, Статья 131"></label><button class="button primary">Сравнить</button></form><div id="diff-result"></div>`:empty('Предыдущих снимков пока нет','История будет пополняться по мере получения новых копий. Прошлые редакции не восстанавливаются автоматически.')}`;
|
||||
if(versions.length>1){$('#compare-form [name=after]').value=versions.at(-1).id;$('#compare-form').onsubmit=async e=>{e.preventDefault();const form=new FormData(e.currentTarget);if(form.get('before')===form.get('after'))return toast('Выберите две разные копии.');$('#diff-result').innerHTML=empty('Сравниваем тексты','');try{const diff=await api('/diff?'+params({id:r.id,...Object.fromEntries(form)}));if(token!==state.renderId)return;$('#diff-result').innerHTML=`<p class="notice">${escape(diff.note||'Сравнение локальных копий.')}</p>${diff.formatting_only?'<p>Отличается только форматирование.</p>':''}${(diff.changes||[]).map(c=>`<section class="diff-section"><h2>${escape(c.label)} <span class="status-tag">${{added:'Добавлено',removed:'Удалено',changed:'Изменено'}[c.kind]||'Отличается'}</span></h2><div class="diff-grid"><div class="diff-old"><h3>Было</h3>${escape(c.before||'Фрагмент отсутствовал')}</div><div class="diff-new"><h3>Стало</h3>${escape(c.after||'Фрагмент отсутствует')}</div></div></section>`).join('')||empty('Текстовых различий не найдено','В выбранных копиях и пределах указанного фрагмента.')}`;}catch(err){toast(err.message);}};}
|
||||
}catch(e){if(token===state.renderId)$('#history-body').innerHTML=empty('История временно недоступна',e.message);}
|
||||
}
|
||||
|
||||
let graphController=null;
|
||||
async function graphView(token){
|
||||
const r=state.route;crumbs([{name:'Граф связей'}]);graphController?.destroy();
|
||||
app.innerHTML=`<div class="page wide-page">${heading('Граф правовых связей','От статьи к разъяснению суда и обратно.',`<button class="button quiet" data-action="graph">Пересобрать граф</button>`)}<form id="graph-filter" class="category-tools"><label class="field grow"><span>Документ, статья или пункт</span><input name="q" value="${escape(r.q||'')}" placeholder="Например, статья 395"></label><label class="field"><span>Вид документа</span><select name="kind"><option value="">Все виды</option>${Object.entries(kinds).map(([k,v])=>`<option value="${k}" ${r.kind===k?'selected':''}>${v[0]}</option>`).join('')}</select></label><button class="button primary">Найти</button><a class="button quiet" href="${href({view:'graph'})}">Вся база</a></form><div id="graph-content"><p class="help-note">Открываем сохранённые связи…</p></div></div>`;
|
||||
$('#graph-filter').onsubmit=e=>{e.preventDefault();navigate({view:'graph',...Object.fromEntries(new FormData(e.currentTarget))});};
|
||||
try{
|
||||
const data=await api('/graph?'+params({q:r.q,kind:r.kind,resource_id:r.resource_id,node_id:r.node_id,limit:8,offset:r.offset||0}));if(token!==state.renderId)return;
|
||||
state.graph=data;
|
||||
if(data.loading){$('#graph-content').innerHTML=empty('Загружаем сохранённый граф','Документы и поиск доступны в библиотеке.');setTimeout(()=>{if(token===state.renderId)graphView(token);},1500);return;}
|
||||
if(!data.nodes?.length){$('#graph-content').innerHTML=empty('Узлы не найдены','Попробуйте номер статьи или название документа.');return;}
|
||||
$('#graph-content').innerHTML=`<p class="help-note">Сборка ${escape(shortDate(data.report?.built_at))} · ${data.total} узлов в выборке. Дата сборки не означает проверку законодательства.</p>${data.stale?'<p class="notice warning">Документы изменились после сборки. Связи требуют сверки.</p>':''}<div class="graph-workspace"><div class="graph-stage"><div class="graph-zoom inline-actions"><button class="button quiet" data-zoom="in" aria-label="Приблизить граф">+</button><button class="button quiet" data-zoom="out" aria-label="Отдалить граф">−</button><button class="button quiet" data-zoom="reset">Показать целиком</button></div><div class="graph-mount" id="graph-mount"></div><p class="help-note">Выберите узел, чтобы увидеть источник связи. Карту можно перетаскивать.</p></div><aside class="graph-sidebar"><div id="node-detail">${empty('Выберите статью или документ','Здесь появятся связи и подтверждающие их фрагменты.')}</div><details class="graph-accessible-list"><summary>Все узлы на экране</summary><div class="graph-node-list">${data.nodes.map(n=>`<button class="graph-node-button" data-node="${escape(n.id)}">${escape(n.label)}</button>`).join('')}</div></details></aside></div><div class="pagination">${Number(r.offset)>0?`<a class="button quiet" href="${href({...r,offset:Math.max(0,Number(r.offset)-12)})}">Назад</a>`:''}${data.has_more?`<a class="button quiet" href="${href({...r,offset:Number(r.offset||0)+12})}">Далее</a>`:''}</div>`;
|
||||
$('.pagination').querySelectorAll('a').forEach(a=>{const direction=a.textContent==='Назад'?-1:1;a.href=href({...r,offset:Math.max(0,Number(r.offset||0)+direction*(data.focus_id?7:8))});});
|
||||
graphController=window.EunomiaGraph.mount($('#graph-mount'),data,{onSelect:n=>selectGraphNode(n.id),onOpen:n=>navigate({doc:n.resource_id,fragment:n.reader_id||''}),onExplore:n=>navigate({view:'graph',node_id:n.id})});
|
||||
if(data.focus_id)selectGraphNode(data.focus_id);
|
||||
}catch(e){if(token===state.renderId)$('#graph-content').innerHTML=empty('Связи временно недоступны',e.message);}
|
||||
}
|
||||
function selectGraphNode(id){
|
||||
const node=state.graph?.nodes.find(n=>n.id===id);if(!node)return;
|
||||
const edges=state.graph.edges.filter(e=>e.source===id||e.target===id);
|
||||
$('#node-detail').innerHTML=`<div class="selected-node"><span class="status-tag">${escape(labelKind(node.document_kind))}</span><h2>${escape(node.label)}</h2>${node.document_title?`<p class="muted">${escape(node.document_title)}</p>`:''}<div class="inline-actions"><a class="button primary" href="${docHref(node.resource_id,node.reader_id||'')}">${node.reader_id?'Читать фрагмент':'Читать документ'}</a><a class="button quiet" href="${href({view:'graph',node_id:id})}">Связи этого узла</a></div><h3>Подтверждения связей</h3>${edges.map(e=>{const other=state.graph.nodes.find(n=>n.id===(e.source===id?e.target:e.source)),ev=e.evidence||{};return `<details class="relation-item" ${edges.length<4?'open':''}><summary>${escape(other?.label||'Связанный документ')}</summary><div class="relation-detail"><span class="status-tag">${e.relation==='references'?'Прямая ссылка':e.relation==='thematic'?'Тематическая связь':'Состав документа'}</span><p>${escape(ev.excerpt||'Текст доказательства не сохранён.')}</p><p>Редакция: ${escape(shortDate(ev.revision))}</p>${ev.source_url?`<a class="text-link" href="${safeURL(ev.source_url)}" target="_blank" rel="noopener noreferrer">Источник доказательства ↗</a>`:''}${other?`<a class="button quiet" href="${docHref(other.resource_id,other.reader_id||'')}">Открыть ${other.reader_id?'фрагмент':'документ'} →</a>`:''}</div></details>`;}).join('')||'<p class="help-note">Откройте связи этого узла, чтобы увидеть соседние статьи и разъяснения.</p>'}</div>`;
|
||||
}
|
||||
function updatesView() {
|
||||
crumbs([{name:'Обновления'}]);const s=state.status,schedule=s.schedule||{},queue=s.queue||{};
|
||||
const next=schedule.next_run||schedule.next_due_at;
|
||||
const jobs=s.jobs||[],r=state.route,page=Math.min(Math.max(1,Number(r.page)||1),Math.max(1,Math.ceil(jobs.length/12)));
|
||||
app.innerHTML=`<div class="page">${heading('Обновления','Рабочие копии документов доступны во время обновления.',`<button class="button primary" data-action="update">Обновить базу сейчас</button>`)}<div class="updates-summary"><section class="schedule-details"><h2>Расписание</h2><dl><dt>Фоновое обновление</dt><dd>${schedule.enabled?'Включено':'Не включено'}</dd><dt>Проверка источников</dt><dd>Раз в семь дней</dd><dt>Следующая проверка</dt><dd>${next?escape(shortDate(next)):'Пока не определена'}</dd></dl><p class="help-note">${schedule.enabled?'Закрытие браузера не останавливает обновление.':'Автоматический запуск ещё не настроен в Themiz. Ручной запрос сохраняется в очереди.'}</p></section><section class="schedule-details"><h2>Связи документов</h2><p>${s.graph?.available?'Последняя сборка: '+escape(shortDate(s.graph.built_at)):'Граф пока не собран.'}</p><p class="help-note">Обновляется после изменения документов. Можно пересобрать отдельно.</p><button class="button quiet" data-action="graph">Пересобрать граф</button></section></div><div class="section-heading"><h2>Задания</h2><span>${Object.entries(queue).map(([k,v])=>`${statusNames[k]||'Другой статус'}: ${v}`).join(' · ')||'Очередь пуста'}</span></div>${jobs.slice((page-1)*12,page*12).map(j=>{const d=state.docs.find(d=>d.id===j.id);return `<div class="document-row"><div class="document-main">${d?`<a class="document-title" href="${docHref(d.id)}">${escape(d.subject||d.title)}</a>`:'Каталог нормативных источников'}${j.detail?`<details class="job-detail"><summary>Подробности</summary><p>${escape(j.detail)}</p></details>`:''}</div><span class="status-tag ${['blocked','failed','deferred'].includes(j.state)?'warning':''}">${statusNames[j.state]||'Ожидает проверки'}</span></div>`;}).join('')||empty('Заданий пока нет','Запрос на обновление появится здесь после нажатия кнопки.')}${pagination(jobs.length,page)}</div>`;
|
||||
}
|
||||
async function action(button) {
|
||||
const name=button.dataset.action;
|
||||
if(name==='whole-document'){
|
||||
button.disabled=true;button.textContent='Открываем полный текст…';
|
||||
try{const id=state.doc.document.id,data=await api('/document?'+params({id}));if(state.route.doc!==id)return;state.doc={...state.doc,...data};$('.reading-text').innerHTML=data.fragments.map(f=>`<section class="text-fragment" id="${escape(f.id)}"><h2 class="fragment-heading">${escape(f.label)}</h2><div class="fragment-body">${fragmentText(f)}</div></section>`).join('');button.textContent='Открыт весь документ';if(state.selected)jump(state.selected,false);}catch(e){button.disabled=false;button.textContent='Весь документ';toast(e.message);}return;
|
||||
}
|
||||
if(name==='related'){
|
||||
const panel=$('.reader-related');panel.classList.toggle('is-open');
|
||||
$('#related-content').classList.add('is-open');
|
||||
button.setAttribute('aria-expanded',String(panel.classList.contains('is-open')));
|
||||
return;
|
||||
}
|
||||
if(name==='copy-link'||name==='copy-text'){
|
||||
let text=location.href;
|
||||
if(name==='copy-text'){const selected=window.getSelection()?.toString();const part=state.doc?.fragments.find(f=>f.id===state.selected||state.selected.startsWith(f.id+'_point_'));text=selected||part?.text||state.doc?.body||'';}
|
||||
try{await navigator.clipboard.writeText(text);toast(name==='copy-link'?'Ссылка скопирована.':'Текст скопирован.');}catch{toast('Не удалось скопировать. Выделите текст и нажмите Ctrl+C или ⌘C.');}return;
|
||||
}
|
||||
if(name==='find-next')return nextFind(1);if(name==='find-prev')return nextFind(-1);
|
||||
if(!['update','graph'].includes(name))return;
|
||||
button.disabled=true;const old=button.textContent;button.textContent='Сохраняем запрос…';
|
||||
try{const result=await api(name==='graph'?'/graph/rebuild':'/update',{method:'POST',body:JSON.stringify(button.dataset.id?{id:button.dataset.id}:{})});toast(result.detail||'Запрос сохранён.');state.status=await api('/status');if(state.route.view==='updates')updatesView();}catch(e){toast(e.message);}finally{button.disabled=false;button.textContent=old;}
|
||||
}
|
||||
async function bootstrap() {
|
||||
try{const data=await api('/bootstrap');state.docs=data.documents||[];state.status=data.status||{};state.csrf=data.csrf||'';state.ready=state.docs.length>0||!state.status.index?.indexing;state.error='';$('#api-state').textContent=state.ready?'Документы на компьютере':'Загружаем библиотеку';$('#api-dot').parentElement.classList.add('ok');if(state.status.index?.indexing&&!state.docs.length)setTimeout(bootstrap,1500);}catch(e){state.error=e.message;$('#api-state').textContent='Нет связи с библиотекой';}
|
||||
route();
|
||||
}
|
||||
function closeMenu(){ $('#sidebar').classList.remove('open');$('#sidebar').inert=innerWidth<=760;$('#menu-toggle').setAttribute('aria-expanded','false'); }
|
||||
async function route() {
|
||||
const r=Object.fromEntries(new URLSearchParams(location.hash.slice(1)));if(!r.view)r.view=r.doc?'reader':'home';state.route=r;document.body.dataset.view=r.view;const token=++state.renderId;
|
||||
document.querySelectorAll('.nav-item').forEach(a=>{const active=a.dataset.route===(r.view==='category'?`category&kind=${r.kind}`:r.doc?`category&kind=${state.docs.find(d=>d.id===r.doc)?.kind}`:r.view);a.classList.toggle('is-active',active);if(active)a.setAttribute('aria-current','page');else a.removeAttribute('aria-current');});
|
||||
$('#global-search').value=r.view==='search'?r.q||'':'';closeMenu();
|
||||
document.title=(r.doc?'Чтение документа':r.view==='category'?labelKind(r.kind):{home:'Правовая библиотека',search:'Поиск',graph:'Связи документов',history:'История редакций',updates:'Обновления'}[r.view]||'Библиотека')+' — Эвномия';
|
||||
if(state.error){app.innerHTML=empty('Не удалось подключиться к библиотеке','Проверьте, что локальное приложение запущено.','<button class="button primary" data-retry>Попробовать снова</button>');return;}
|
||||
if(!state.ready){app.innerHTML=empty('Готовим библиотеку к чтению','При первом запуске проверяем документы на компьютере. Страница откроется автоматически.');return;}
|
||||
if(r.doc){await reader(token);return;}
|
||||
state.selected='';window.scrollTo(0,0);
|
||||
if(r.view==='contents')await contentsView(token);else if(r.view==='category')category();else if(r.view==='search')await searchView(token);else if(r.view==='history')await historyView(token);else if(r.view==='graph')await graphView(token);else if(r.view==='updates')updatesView();else home();
|
||||
}
|
||||
function drawGraph() {}
|
||||
app.addEventListener('click',e=>{
|
||||
const button=e.target.closest('[data-action]');if(button){action(button);return;}
|
||||
const toc=e.target.closest('[data-fragment]');if(toc&&state.route.doc){e.preventDefault();jump(toc.dataset.fragment);return;}
|
||||
const toggle=e.target.closest('[data-toggle]');if(toggle){const panel=document.getElementById(toggle.dataset.toggle);panel.classList.toggle('is-open');toggle.setAttribute('aria-expanded',String(panel.classList.contains('is-open')));return;}
|
||||
const size=e.target.closest('[data-size]');if(size){state.readerSize=Math.max(16,Math.min(30,state.readerSize+Number(size.dataset.size)));$('.reading-text').style.fontSize=state.readerSize+'px';return;}
|
||||
const node=e.target.closest('[data-node]');if(node){selectGraphNode(node.dataset.node);return;}
|
||||
const zoom=e.target.closest('[data-zoom]');if(zoom){if(zoom.dataset.zoom==='reset')graphController?.reset();else graphController?.zoom(zoom.dataset.zoom==='in'?1.25:.8);return;}
|
||||
if(e.target.closest('[data-retry]'))bootstrap();
|
||||
});
|
||||
$('#global-search-form').onsubmit=e=>{e.preventDefault();const q=$('#global-search').value.trim();if(q)navigate({view:'search',q});};
|
||||
$('#menu-toggle').onclick=()=>{const open=$('#sidebar').classList.toggle('open');$('#sidebar').inert=!open;$('#menu-toggle').setAttribute('aria-expanded',String(open));if(open)$('#sidebar a').focus();};
|
||||
$('[data-close-menu]').onclick=closeMenu;
|
||||
document.addEventListener('keydown',e=>{
|
||||
if(e.key==='Escape'&&$('#sidebar').classList.contains('open')){closeMenu();$('#menu-toggle').focus();}
|
||||
if(e.key==='Tab'&&innerWidth<=760&&$('#sidebar').classList.contains('open')){
|
||||
const links=[...$('#sidebar').querySelectorAll('a')],first=links[0],last=links.at(-1);
|
||||
if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}
|
||||
else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}
|
||||
}
|
||||
if((e.ctrlKey||e.metaKey)&&e.key==='k'){e.preventDefault();$('#global-search').focus();}
|
||||
});
|
||||
$('.skip-link').onclick=e=>{e.preventDefault();app.focus();};
|
||||
$('#refresh-all').onclick=bootstrap;
|
||||
const tip=document.createElement('div');tip.id='control-tip';tip.className='control-tooltip';tip.setAttribute('role','tooltip');tip.hidden=true;document.body.append(tip);
|
||||
let tipOwner=null;
|
||||
function tipText(el){
|
||||
if(el.id==='refresh-all')return 'Обновить сведения на экране. Загрузку документов не запускает.';
|
||||
const actions={update:el.dataset.id?'Получить свежую копию этого документа через очередь Themiz.':'Поставить источники на проверку и загрузку через очередь Themiz.',graph:'Пересобрать связи по сохранённым документам. Источники заново не загружаются.',related:'Показать нормы и разъяснения, связанные с выбранным фрагментом.', 'copy-link':'Скопировать постоянную ссылку на выбранную статью или пункт.', 'copy-text':'Скопировать выделение или открытый фрагмент документа.', 'whole-document':'Показать весь сохранённый текст документа на одной странице.', 'find-prev':'Перейти к предыдущему совпадению в тексте.', 'find-next':'Перейти к следующему совпадению в тексте.'};
|
||||
if(el.dataset.action)return actions[el.dataset.action];
|
||||
if(el.dataset.size)return Number(el.dataset.size)>0?'Увеличить размер текста документа.':'Уменьшить размер текста документа.';
|
||||
if(el.dataset.zoom)return {in:'Приблизить узлы графа.',out:'Отдалить узлы графа.',reset:'Показать все узлы текущей выборки.'}[el.dataset.zoom];
|
||||
return '';
|
||||
}
|
||||
function showTip(e){const el=e.target.closest('button,[data-action]');if(!el)return;const text=tipText(el);if(!text)return;tipOwner=el;tip.textContent=text;tip.hidden=false;el.setAttribute('aria-describedby',tip.id);const r=el.getBoundingClientRect();tip.style.left=Math.max(12,Math.min(innerWidth-tip.offsetWidth-12,r.left))+'px';tip.style.top=Math.min(innerHeight-tip.offsetHeight-12,r.bottom+10)+'px';}
|
||||
function hideTip(){tip.hidden=true;tipOwner?.removeAttribute('aria-describedby');tipOwner=null;}
|
||||
document.addEventListener('pointerover',showTip);document.addEventListener('focusin',showTip);
|
||||
document.addEventListener('pointerout',e=>{if(tipOwner&&!tipOwner.contains(e.relatedTarget))hideTip();});document.addEventListener('focusout',hideTip);document.addEventListener('keydown',e=>{if(e.key==='Escape')hideTip();});window.addEventListener('scroll',hideTip,{passive:true});
|
||||
$('#refresh-all').setAttribute('aria-label','Обновить сведения на экране');
|
||||
window.addEventListener('hashchange',route);
|
||||
window.addEventListener('resize',()=>{drawGraph();$('#sidebar').inert=innerWidth<=760&&!$('#sidebar').classList.contains('open');});
|
||||
bootstrap();
|
||||
})();
|
||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.2 MiB |