feat(frontend): implement legal search interface
This commit is contained in:
1 parent
84ae32b8a3
commit
d01fdabd68
26 files changed
+1142
-52
No files matched your search
@@ -86,6 +86,15 @@ spacing:
|
||||
генеративного изображения. Название продукта — **Акылдаш**; «УКУК» из
|
||||
ранних концепций не используется.
|
||||
|
||||
Изображение определяет целевую композицию, пропорции панелей и расположение
|
||||
элементов поискового экрана. Эта спецификация определяет семантические токены,
|
||||
шрифты, доступность и правила поведения. Расхождения между ними фиксируются
|
||||
до реализации; утверждённые токены не заменяются цветами, взятыми пипеткой
|
||||
из растрового изображения. Изменения постоянных правил вносятся сюда явно.
|
||||
Этапы работ, исходные измерения и критерии визуальной приёмки находятся в
|
||||
[плане точного воспроизведения поискового интерфейса](docs/product/frontend-pixel-perfect-plan.md).
|
||||
План не является второй дизайн-системой и не означает завершение реализации.
|
||||
|
||||
**Key Characteristics:**
|
||||
|
||||
- Спокойное чтение и компактные, понятные элементы управления.
|
||||
@@ -162,6 +171,34 @@ spacing:
|
||||
Разворачивание документа и поиск внутри него реализуются только вместе
|
||||
с работающим поведением, а не как декоративные кнопки.
|
||||
|
||||
### Композиция поискового экрана
|
||||
|
||||
- Первая строка desktop: знак и название, разделитель и подпись продукта
|
||||
слева; подписанное поле поиска с очисткой и кнопкой «Найти» в центре;
|
||||
переключатель языка интерфейса справа. Служебные действия авторизованного
|
||||
пользователя не вытесняют поиск и не меняют эту иерархию.
|
||||
- Вторая строка: навигация «Поиск» / «Об источниках» и удаляемые активные
|
||||
фильтры. Сведения о демонстрационном режиме показываются только в нём.
|
||||
- Ниже расположены три смежные панели: фильтры, результаты, документ.
|
||||
Иерархия создаётся фонами и непрерывными тонкими разделителями, без
|
||||
промежутков между самостоятельными карточками панелей.
|
||||
- Фильтры имеют компактные группы, текстовое действие сброса, выбор органа
|
||||
и пару полей даты в одной строке при достаточной ширине. Вид элемента
|
||||
выбора соответствует одиночному или множественному контракту API.
|
||||
- Заголовок результатов и счётчик находятся слева, сортировка справа.
|
||||
Высота строк зависит от содержимого; едины отступы и типографика.
|
||||
Выбранный результат имеет мягкий красный фон, тонкую красную рамку
|
||||
и текстовый признак открытия.
|
||||
- Панель документа начинается с контекстной навигации и разворачивания,
|
||||
затем идут название, компактные метаданные, действия, поиск внутри
|
||||
документа и единое поле чтения. Название документа имеет отдельную
|
||||
типографическую роль, отличную от заголовков интерфейсных панелей.
|
||||
- При коротком содержимом footer расположен у нижней границы окна;
|
||||
длинное содержимое доступно прокруткой без перекрытия текста и управления.
|
||||
Бренд находится слева, фактические версии frontend и backend справа.
|
||||
- Поисковая страница не показывает инструменты оценивания лаборатории.
|
||||
Общие стили и ресурсы не смешивают композицию этих двух сценариев.
|
||||
|
||||
Внутренняя лаборатория сохраняет свой двухпанельный сценарий: фактический
|
||||
порядок результатов и оценивание слева, текст выбранной редакции справа.
|
||||
Она не получает фильтры, аналитику или публичную навигацию исключительно
|
||||
@@ -176,8 +213,9 @@ spacing:
|
||||
горизонтальной прокрутки; широкие таблицы имеют отдельную обозначенную
|
||||
область прокрутки.
|
||||
|
||||
Проверочные размеры при реализации: **1440, 1024 и 390 px**. Это размеры
|
||||
проверки, а не заранее навязанные CSS breakpoints.
|
||||
Проверочные размеры при реализации: **1280×800, 1440, 1024 и 390 px**.
|
||||
1280×800 — основной размер сравнения поискового экрана с референсом.
|
||||
Это размеры проверки, а не заранее навязанные CSS breakpoints.
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
@@ -204,6 +242,13 @@ spacing:
|
||||
помечается `aria-hidden`, не находится под текстом и не мешает нажатию.
|
||||
На телефоне орнамент сокращается либо убирается.
|
||||
|
||||
Поисковый desktop включает небольшой золотистый орнамент в свободной нижней
|
||||
части панели фильтров. Он не перекрывает длинные списки и не резервирует
|
||||
место ценой недоступности управления. Знак бренда и орнамент поставляются
|
||||
как SVG-ресурсы. Favicon использует тот же знак, адаптированный для малых
|
||||
размеров; проверяется читаемость 16×16 и 32×32. Иконки управления имеют
|
||||
согласованные толщину линий, оптический размер и выравнивание.
|
||||
|
||||
## Components
|
||||
|
||||
Это требования к будущей реализации, а не перечень уже обновлённых компонентов.
|
||||
|
||||
@@ -10,7 +10,8 @@ Telegram-бот — только часть рабочего окружения
|
||||
## Текущее состояние
|
||||
|
||||
Сейчас реализованы Telegram-бот-секретарь версии `0.2.2`, backend версии
|
||||
`0.12.2` и внутренний frontend лаборатории `0.1.2`. Авторизация хранится в
|
||||
`0.13.0` и frontend `0.2.0` с поисковым экраном и внутренней лабораторией.
|
||||
Авторизация хранится в
|
||||
SQLite; первый пользователь `admin` создаётся интерактивной CLI-командой.
|
||||
Поиск расширяет аббревиатуры организационно-правовых форм и поднимает
|
||||
действующий Налоговый кодекс для запросов о налоге на прибыль.
|
||||
@@ -18,8 +19,8 @@ SQLite; первый пользователь `admin` создаётся инт
|
||||
| Компонент | Версия | Состояние |
|
||||
|---|---:|---|
|
||||
| Telegram-бот | `0.2.2` | на Synology работает `0.2.1`; обновление после слияния |
|
||||
| Backend | `0.12.2` | авторизация, поиск с фильтрами и ограниченный staging текущего API Минюста |
|
||||
| Frontend | `0.1.2` | лаборатория поиска, личный кабинет и управление учетными записями |
|
||||
| Backend | `0.13.0` | авторизация, поиск с фильтрами, ограниченный staging и статические ресурсы |
|
||||
| Frontend | `0.2.0` | поиск по правовой базе, просмотр редакций и внутренняя лаборатория |
|
||||
| Сбор и обработка правовых данных | `0.8.0` | добавлены relevance set и оценка выдачи |
|
||||
| RAG и база знаний | — | ещё не созданы |
|
||||
|
||||
@@ -62,4 +63,4 @@ python3 -m unittest discover -s tools/telegram-bot -v
|
||||
|
||||
---
|
||||
|
||||
Акылдаш · Telegram-бот v0.2.2 · Backend v0.12.2 · Frontend v0.1.2
|
||||
Акылдаш · Telegram-бот v0.2.2 · Backend v0.13.0 · Frontend v0.2.0
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Backend Акылдаш
|
||||
|
||||
Версия: `0.12.2`
|
||||
Версия: `0.13.0`
|
||||
|
||||
Первая backend-область проекта — загрузка правовых документов из официального
|
||||
Open Data API ЦБД Минюста Кыргызской Республики. Код расположен в
|
||||
@@ -296,4 +296,4 @@ PYTHONPATH=backend python3 -m search.query "ЖЧК ачуу тартиби" --la
|
||||
|
||||
---
|
||||
|
||||
Акылдаш · Backend v0.12.2 · Frontend v0.1.2
|
||||
Акылдаш · Backend v0.13.0 · Frontend v0.2.0
|
||||
@@ -23,7 +23,7 @@ from typing import Callable
|
||||
from ingestion.minjust_cbd import atomic_write, connect_manifest, json_bytes
|
||||
|
||||
API_ROOT = "https://cbd.minjust.gov.kg/api/v1"
|
||||
APP_VERSION = "0.12.2"
|
||||
APP_VERSION = "0.13.0"
|
||||
REQUEST_CONTRACT = {
|
||||
"version": 2,
|
||||
"endpoint": "/GetEdition",
|
||||
|
||||
@@ -26,6 +26,14 @@ LANGUAGES = {"ru", "ky"}
|
||||
CODE = re.compile(r"^[0-9]+$")
|
||||
MAX_PAGE_SIZE = 100
|
||||
MAX_RESULT_WINDOW = 10_000
|
||||
STATIC_ASSETS = {
|
||||
"/static/fonts/noto-sans-cyrillic-ext.woff2": ("fonts/noto-sans-cyrillic-ext.woff2", "font/woff2"),
|
||||
"/static/fonts/noto-sans-cyrillic.woff2": ("fonts/noto-sans-cyrillic.woff2", "font/woff2"),
|
||||
"/static/fonts/noto-sans-latin.woff2": ("fonts/noto-sans-latin.woff2", "font/woff2"),
|
||||
"/static/fonts/noto-serif-cyrillic-ext.woff2": ("fonts/noto-serif-cyrillic-ext.woff2", "font/woff2"),
|
||||
"/static/fonts/noto-serif-cyrillic.woff2": ("fonts/noto-serif-cyrillic.woff2", "font/woff2"),
|
||||
"/static/fonts/noto-serif-latin.woff2": ("fonts/noto-serif-latin.woff2", "font/woff2"),
|
||||
}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
@@ -303,6 +311,17 @@ class Api:
|
||||
except (OSError, UnicodeError) as error:
|
||||
raise ApiError(500, "review interface is unavailable") from error
|
||||
|
||||
@staticmethod
|
||||
def static_asset(route: str) -> tuple[str, bytes]:
|
||||
asset = STATIC_ASSETS.get(route)
|
||||
if asset is None:
|
||||
raise ApiError(404, "static asset not found")
|
||||
path = Path(__file__).with_name("static") / asset[0]
|
||||
try:
|
||||
return asset[1], path.read_bytes()
|
||||
except OSError as error:
|
||||
raise ApiError(500, "static asset is unavailable") from error
|
||||
|
||||
def handle(self, method: str, path: str, body: dict | None = None, user: dict | None = None) -> tuple[int, dict]:
|
||||
parsed = urllib.parse.urlsplit(path)
|
||||
query = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)
|
||||
@@ -386,6 +405,18 @@ def handler(api: Api):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if method == "GET" and route in STATIC_ASSETS:
|
||||
content_type, body = api.static_asset(route)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Cache-Control", "public, max-age=604800, immutable")
|
||||
self.send_header("X-Content-Type-Options", "nosniff")
|
||||
self.send_header("X-Frame-Options", "DENY")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if not (method == "POST" and route in {"/auth/login", "/auth/logout"}):
|
||||
if not user:
|
||||
raise ApiError(401, "authentication required")
|
||||
|
||||
@@ -17,7 +17,7 @@ from typing import Iterator
|
||||
|
||||
from search.catalog import authority_codes, legal_force_code, source_code
|
||||
|
||||
APP_VERSION = "0.12.2"
|
||||
APP_VERSION = "0.13.0"
|
||||
LANGUAGES = {"ru", "ky"}
|
||||
DEFAULT_MAPPING = Path(__file__).with_name("minjust-fragments-index.json")
|
||||
|
||||
|
||||
+488
-40
@@ -3,8 +3,16 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="theme-color" content="#F7F2E8">
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 48 48'%3E%3Ccircle cx='24' cy='24' r='20' fill='none' stroke='%239D2633' stroke-width='3'/%3E%3Cpath d='M24 5v38M5 24h38M11 11l26 26M37 11 11 37' fill='none' stroke='%239D2633' stroke-width='3'/%3E%3C/svg%3E">
|
||||
<title>Оценка поисковой выдачи · Акылдаш</title>
|
||||
<style>
|
||||
@font-face { font-family: "Noto Sans"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-sans-cyrillic-ext.woff2") format("woff2"); unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; }
|
||||
@font-face { font-family: "Noto Sans"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-sans-cyrillic.woff2") format("woff2"); unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; }
|
||||
@font-face { font-family: "Noto Sans"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-sans-latin.woff2") format("woff2"); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; }
|
||||
@font-face { font-family: "Noto Serif"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-serif-cyrillic-ext.woff2") format("woff2"); unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; }
|
||||
@font-face { font-family: "Noto Serif"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-serif-cyrillic.woff2") format("woff2"); unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; }
|
||||
@font-face { font-family: "Noto Serif"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-serif-latin.woff2") format("woff2"); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; }
|
||||
:root { color-scheme: light; font: 16px/1.5 "Noto Sans", sans-serif; color: #38262A; background: #F7F2E8; --ink: #38262A; --muted: #786469; --line: #DED3CE; --surface: #fff; --surface-muted: #FBF8F4; --brand: #9D2633; --brand-dark: #84202B; --accent: #A37B32; --focus: #245C78; --subtle: #F8EBED; --serif: "Noto Serif", serif; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; color: var(--ink); background: #F7F2E8; }
|
||||
@@ -138,15 +146,198 @@
|
||||
@media (max-width: 480px) { .review__search { grid-template-columns: 1fr; } .review__search .review__field:first-child, .review__search button { grid-column: auto; } .review__rating { grid-template-columns: repeat(2, minmax(0, 1fr)); } .search__query-row { grid-template-columns: 1fr 1fr; } .search__query-row > input { grid-column: 1 / -1; } .review__nav { align-items: start; flex-wrap: wrap; } .review__nav-links { order: 3; width: 100%; flex-wrap: wrap; } .review__nav-account { margin-inline-start: auto; } }
|
||||
@media (hover: hover) { button:hover { background: var(--surface-muted); border-color: var(--muted); } .review__button--primary:hover { background: var(--brand-dark); border-color: var(--brand-dark); } .review__result:hover { background: var(--subtle); } .review__result-title:hover, .search__result-title:hover { background: none; color: var(--brand); } .review__rating label:hover { border-color: var(--brand); } }
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; transition: none !important; } }
|
||||
:root { --color-bg: #F7F2E8; --color-surface: #fff; --color-surface-muted: #FBF8F4; --color-text: #38262A; --color-text-secondary: #786469; --color-border: #DED3CE; --color-primary: #9D2633; --color-primary-hover: #84202B; --color-accent: #A37B32; --color-highlight: #FFF0C7; --color-focus: #245C78; --color-success: #246843; --search-header-height: 76px; --search-nav-height: 50px; }
|
||||
body:has(.search:not([hidden])) { width: 100%; height: 100dvh; min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
|
||||
body:has(.search:not([hidden])) > .review__header { display: none; }
|
||||
body:has(.search:not([hidden])) > footer.review__header { display: none; }
|
||||
body:has(.search:not([hidden])) > .review__actions { display: none; }
|
||||
body.review__locked .search__chrome { visibility: hidden; }
|
||||
body:has(.search:not([hidden])) > .search__chrome { display: block; }
|
||||
.search__chrome { display: none; background: var(--surface); border-block-end: 1px solid var(--line); }
|
||||
.search[hidden] { display: none !important; }
|
||||
.search__topbar { min-height: var(--search-header-height); display: grid; grid-template-columns: minmax(270px, 350px) minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 5px 32px; border-block-end: 1px solid var(--line); }
|
||||
.search__brand { display: flex; min-width: 0; align-items: center; gap: 12px; color: var(--ink); text-decoration: none; white-space: nowrap; }
|
||||
.search__brand-mark { width: 44px; height: 44px; flex: none; color: var(--brand); }
|
||||
.search__brand-name { font: 700 26px/1.1 var(--serif); }
|
||||
.search__brand-divider { width: 1px; height: 32px; background: var(--line); }
|
||||
.search__brand-description { color: var(--muted); font-size: 14px; }
|
||||
.search__query { display: grid; grid-template-columns: minmax(0, 1fr) 160px; gap: 12px; align-items: end; min-width: 0; padding: 0; border: 0; background: transparent; }
|
||||
.search__query label { display: grid; gap: 4px; color: var(--muted); font-size: 14px; font-weight: 500; }
|
||||
.search__query label > span { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.search__query-input { position: relative; }
|
||||
.search__query input { height: 44px; padding-inline: 42px; }
|
||||
.search__query-icon { position: absolute; inset-inline-start: 12px; inset-block-start: 11px; width: 22px; height: 22px; color: var(--ink); pointer-events: none; }
|
||||
.search__query-clear { position: absolute; inset-inline-end: 4px; inset-block-start: 3px; width: 38px; height: 38px; min-height: 38px; padding: 0; border: 0; color: var(--muted); }
|
||||
.search__query .review__button--primary { height: 44px; }
|
||||
.search__ui-language { display: flex; align-items: center; gap: 4px; white-space: nowrap; }
|
||||
.search__ui-language button { min-width: 36px; min-height: 40px; border: 0; border-radius: 0; padding: 0 4px; color: var(--muted); }
|
||||
.search__ui-language button[aria-pressed="true"] { color: var(--ink); border-block-end: 2px solid var(--brand); }
|
||||
.search__account { display: flex; align-items: center; gap: 6px; margin-inline-start: auto; }
|
||||
.search__account button { min-height: 40px; padding-inline: 8px; font-size: 13px; }
|
||||
.search__subnav { min-height: var(--search-nav-height); display: flex; align-items: center; gap: 12px; padding: 6px 32px; overflow-x: auto; white-space: nowrap; }
|
||||
.search__subnav a, .search__subnav button { min-height: 36px; padding: 5px 14px; text-decoration: none; }
|
||||
.search__mobile-filters, .search__mobile-back, .search__filter-close, .search__filter-overlay { display: none; }
|
||||
.search__subnav a.is-active { background: var(--brand); color: #fff; border-color: var(--brand); }
|
||||
.search__subnav .search__nav-text { color: var(--ink); }
|
||||
.search__chips { display: flex; gap: 8px; align-items: center; min-width: 0; overflow-x: auto; margin-inline-start: 8px; }
|
||||
.search__chip { display: inline-flex; align-items: center; gap: 8px; min-height: 34px; border: 1px solid var(--line); border-radius: 6px; padding: 4px 10px; font-size: 14px; }
|
||||
.search__chip button { min-height: 24px; width: 24px; padding: 0; border: 0; font-size: 18px; line-height: 1; }
|
||||
.search { width: 100%; max-width: none; min-height: 0; flex: 1; display: flex; flex-direction: column; margin: 0; }
|
||||
.search__sr-only { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.search__status { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.search__layout { flex: 1; min-height: 0; grid-template-columns: minmax(210px, 226px) minmax(350px, 422px) minmax(400px, 1fr); border-block: 1px solid var(--line); }
|
||||
.search__filters, .search__results, .search__document { min-height: 0; padding: 14px 16px 20px; }
|
||||
.search__filters { position: relative; display: flex; flex-direction: column; overflow: auto; background: var(--surface-muted); padding-inline: 30px 16px; }
|
||||
.search__filters .review__panel-heading { margin-block-end: 18px; }
|
||||
.search__filters .review__panel-heading button { min-height: 36px; padding: 2px; border: 0; color: var(--brand); text-decoration: underline; text-underline-offset: 3px; }
|
||||
.search__filter { margin-block: 0 22px; }
|
||||
.search__filter h3 { margin-block-end: 6px; font-size: 16px; }
|
||||
.search__filter label { min-height: 38px; gap: 10px; }
|
||||
.search__filter input[type="radio"] { appearance: none; position: relative; width: 24px; min-height: 24px; height: 24px; flex: none; margin: 0; border: 1px solid var(--line); border-radius: 6px; padding: 0; background: #fff; }
|
||||
.search__filter input[type="radio"]:checked { border-color: var(--success); background: var(--success); }
|
||||
.search__filter input[type="radio"]:checked::after { content: ''; position: absolute; width: 6px; height: 11px; inset: 3px 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
|
||||
.search__filter--authority { display: grid; gap: 5px; margin-block: 0 22px; }
|
||||
.search__filter--authority label { display: grid; min-height: auto; gap: 5px; font-weight: 600; }
|
||||
.search__filter--authority select { min-height: 42px; padding-block: 7px; font-weight: 400; }
|
||||
.search__date-label { display: block; margin-block: 0 7px; font-size: 16px; font-weight: 600; }
|
||||
.search__dates { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.search__dates label { min-width: 0; }
|
||||
.search__dates input { min-height: 42px; padding: 7px 9px; }
|
||||
.search__ornament { width: calc(100% - 12px); height: 56px; flex: none; margin: auto 6px 0; color: var(--accent); pointer-events: none; }
|
||||
.search__results { overflow: auto; background: var(--surface-muted); }
|
||||
.search__results .review__panel-heading { align-items: start; margin-block-end: 6px; }
|
||||
.search__results .review__panel-heading select { min-height: 40px; padding: 6px 10px; font-size: 14px; }
|
||||
.search__sort-label { display: grid; gap: 3px; color: var(--muted); font-size: 12px; }
|
||||
.search__result { position: relative; padding: 16px 10px; border-block-end: 1px solid var(--line); }
|
||||
.search__result--selected { margin-inline: -6px; border: 1px solid var(--brand); border-radius: 5px; background: var(--subtle); }
|
||||
.search__result-title { display: block; width: 100%; min-height: auto; margin: 0; padding: 0; text-align: start; font-size: 18px; line-height: 1.35; }
|
||||
.search__result--selected .search__result-title { padding-inline-end: 68px; }
|
||||
.search__opened { position: absolute; inset-block-start: 18px; inset-inline-end: 8px; color: var(--muted); font-size: 14px; }
|
||||
.search__result-meta { margin: 10px 0 0; color: var(--muted); }
|
||||
.search__result-snippet { margin: 10px 0 0; color: var(--ink); line-height: 1.45; }
|
||||
.search__result-snippet mark, .search__document-body mark { color: inherit; background: var(--color-highlight); padding: 0 2px; }
|
||||
.search__document-body mark.is-current { outline: 2px solid var(--color-accent); outline-offset: 1px; }
|
||||
.search__result em { font-style: normal; }
|
||||
.search__pagination { padding-block-start: 12px; }
|
||||
.search__pagination button { min-height: 40px; padding: 6px 12px; }
|
||||
.search__document { padding: 14px 28px 28px; background: var(--surface); overflow: auto; }
|
||||
.search__document-head { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: start; }
|
||||
.search__breadcrumbs { display: flex; gap: 12px; align-items: center; color: var(--muted); font-size: 14px; }
|
||||
.search__breadcrumbs span:first-child { color: var(--brand); }
|
||||
.search__document-head h2 { grid-column: 1 / -1; margin-block: 0 8px; color: var(--ink); font: 700 32px/1.2 var(--serif); }
|
||||
.search__document-head .search__expand { min-height: 32px; border: 0; padding: 0 4px; }
|
||||
.search__document-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 0 0 10px; padding: 0; border: 0; color: var(--muted); }
|
||||
.search__document-meta a { color: var(--brand); }
|
||||
.search__document-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-block-end: 10px; }
|
||||
.search__document-toolbar button, .search__document-toolbar select { min-height: 42px; padding: 6px 12px; }
|
||||
.search__document-toolbar label { display: grid; gap: 2px; color: var(--muted); font-size: 12px; }
|
||||
.search__document-toolbar select { width: 180px; max-width: 180px; overflow: hidden; text-overflow: ellipsis; color: var(--ink); font-size: 14px; }
|
||||
.search__document-toolbar .search__edition-label { display: block; }
|
||||
.search__document-toolbar .search__edition-label select { width: 160px; max-width: 160px; }
|
||||
.search__source-link { max-width: 150px; margin-inline-start: auto; color: var(--brand); font-size: 14px; white-space: nowrap; }
|
||||
.search__document-language { display: inline-flex !important; align-items: center; gap: 6px !important; margin-inline-start: auto; font-size: 12px !important; }
|
||||
.search__document-language select { min-height: 34px; max-width: 130px; padding: 4px 8px; font-size: 14px; }
|
||||
.search__toc { margin-block-end: 10px; }
|
||||
.search__toc summary { width: fit-content; min-height: 42px; padding: 9px 8px; border: 1px solid var(--line); border-radius: 6px; cursor: pointer; font-size: 14px; }
|
||||
.search__toc ol { margin-block: 8px; padding-inline-start: 24px; }
|
||||
.search__toc a { color: var(--brand); }
|
||||
.search__find { display: grid; grid-template-columns: minmax(0,1fr) auto auto auto; gap: 8px; align-items: center; padding: 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface-muted); }
|
||||
.search__find label { grid-column: 1 / -1; font-size: 14px; }
|
||||
.search__find input { min-height: 40px; }
|
||||
.search__find button { min-width: 40px; min-height: 40px; padding: 4px 10px; }
|
||||
.search__find-count { white-space: nowrap; font-size: 14px; }
|
||||
.search__document-note { margin: 6px 0 18px; padding: 6px 10px; border-radius: 6px; background: var(--surface-muted); color: var(--muted); font-size: 14px; }
|
||||
.search__document-body { max-width: 75ch; margin: 0; font: 400 18px/1.65 "Noto Sans", sans-serif; }
|
||||
.search__document-body h1, .search__document-body h2, .search__document-body h3 { font-family: var(--serif); }
|
||||
.search__document-body h2 { margin-block: 24px 10px; font-size: 24px; }
|
||||
.search__document-body img { max-width: 100%; height: auto; }
|
||||
.search__footer { min-height: 56px; display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 10px 32px; color: var(--muted); font-size: 14px; }
|
||||
.search__footer strong { color: var(--ink); }
|
||||
.search__about { max-width: 42rem; }
|
||||
.search__about h2 { font: 600 24px/1.3 var(--serif); }
|
||||
.search__about a { color: var(--brand); }
|
||||
#document-dialog.search__expanded { width: min(1200px, calc(100vw - 32px)); max-width: none; padding: 24px; }
|
||||
#document-dialog.search__expanded .search__document-body { max-width: 78ch; margin: 24px auto; }
|
||||
@media (max-width: 1100px) {
|
||||
.search__topbar { grid-template-columns: minmax(230px, 310px) minmax(0,1fr) auto; gap: 12px; padding-inline: 20px; }
|
||||
.search__brand-description, .search__account #signed-in-user { display: none; }
|
||||
.search__layout { grid-template-columns: minmax(190px, 210px) minmax(320px, 1fr) minmax(380px, 1.3fr); }
|
||||
.search__filters { padding-inline: 20px 12px; }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
body:has(.search:not([hidden])) { height: auto; min-height: 100dvh; overflow: visible; }
|
||||
.search__topbar { grid-template-columns: auto minmax(0,1fr) auto; }
|
||||
.search__brand-divider, .search__brand-description { display: none; }
|
||||
.search__query { grid-template-columns: minmax(0,1fr) 112px; }
|
||||
.search__layout { grid-template-columns: minmax(0, 1fr); }
|
||||
.search__filters, .search__results { border-inline-end: 0; border-block-end: 1px solid var(--line); }
|
||||
.search__filters { padding: 16px 24px; }
|
||||
.search__mobile-filters { display: inline-flex; }
|
||||
.search__filters { display: none; }
|
||||
.search__filters.is-open { position: fixed; z-index: 21; inset: 0 0 0 auto; display: block; width: min(360px, calc(100vw - 32px)); overflow: auto; background: var(--surface-muted); box-shadow: -12px 0 32px rgb(56 38 42 / .18); }
|
||||
.search__filter-overlay.is-open { position: fixed; z-index: 20; inset: 0; display: block; background: rgb(56 38 42 / .42); }
|
||||
.search__filter-close { display: inline-flex; }
|
||||
.search__mobile-back { display: inline-flex; }
|
||||
.search__layout[data-mobile-view="document"] .search__results { display: none; }
|
||||
.search__layout[data-mobile-view="document"] .search__document { display: block; }
|
||||
.search__layout[data-mobile-view="results"] .search__document { display: none; }
|
||||
.search__layout[data-mobile-view="results"] .search__results { display: block; }
|
||||
.search__layout[data-mobile-view="document"] .search__filters { display: none; }
|
||||
.search__ornament { display: none; }
|
||||
.search__document { min-height: 30rem; }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.search__topbar { grid-template-columns: minmax(0,1fr) auto; gap: 8px; padding: 10px 16px; }
|
||||
.search__brand { grid-column: 1; gap: 8px; }
|
||||
.search__brand-mark { width: 36px; height: 36px; }
|
||||
.search__brand-name { font-size: 22px; }
|
||||
.search__ui-language { grid-column: 2; grid-row: 1; }
|
||||
.search__account { grid-column: 1 / -1; grid-row: 3; }
|
||||
.search__query { grid-column: 1 / -1; grid-row: 2; grid-template-columns: minmax(0,1fr) 96px; gap: 8px; }
|
||||
.search__query .review__button--primary { padding-inline: 8px; }
|
||||
.search__subnav { padding-inline: 12px; gap: 4px; }
|
||||
.search__chips { margin-inline-start: 4px; }
|
||||
.search__filters, .search__results { padding: 16px; }
|
||||
.search__document { padding: 18px 16px; }
|
||||
.search__document-head h2 { font-size: 26px; }
|
||||
.search__document-toolbar { gap: 6px; }
|
||||
.search__source-link { margin-inline-start: 0; }
|
||||
.search__find { grid-template-columns: minmax(0,1fr) auto auto; }
|
||||
.search__find-count { grid-column: 1 / -1; grid-row: 3; }
|
||||
.search__footer { align-items: start; flex-direction: column; padding: 12px 16px; }
|
||||
.search__dates { max-width: 320px; }
|
||||
.search__date-label { margin-block-start: 16px; }
|
||||
.search__account #search-users-open, .search__account #search-logout { display: none; }
|
||||
}
|
||||
@media print {
|
||||
body:has(.search:not([hidden])) { display: block; background: #fff; }
|
||||
.search__chrome, .search__filters, .search__results, .search__document-toolbar, .search__toc, .search__find, .search__footer, .search__expand { display: none !important; }
|
||||
.search__document-toolbar { display: block !important; }
|
||||
.search__document-toolbar label, .search__document-toolbar button, .search__document-toolbar .search__toc { display: none !important; }
|
||||
.search__source-link { display: inline !important; }
|
||||
.search, .search__layout, .search__document { display: block; width: auto; min-height: 0; overflow: visible; border: 0; padding: 0; }
|
||||
.search__document-body { max-width: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<a class="review__skip" href="#results">Перейти к результатам</a>
|
||||
<header class="review__header">
|
||||
<div class="review__nav"><div class="review__eyebrow">Акылдаш</div><nav class="review__nav-links" aria-label="Основная навигация"><a id="search-nav" href="/">Поиск</a><a id="review-nav" href="/review">Лаборатория</a><button id="account-open" type="button">Личный кабинет</button><button id="users-open" type="button" hidden>Пользователи</button></nav><div class="review__nav-account"><span id="signed-in-user"></span><button id="logout" type="button">Выйти</button></div></div>
|
||||
<div class="review__nav"><div class="review__eyebrow">Акылдаш</div><nav class="review__nav-links" aria-label="Основная навигация"><a id="review-search-nav" href="/">Поиск</a><a id="review-review-nav" href="/review">Лаборатория</a><button id="review-account-open" type="button">Личный кабинет</button><button id="review-users-open" type="button" hidden>Пользователи</button></nav><div class="review__nav-account"><span id="review-signed-in-user"></span><button id="review-logout" type="button">Выйти</button></div></div>
|
||||
<div class="review__header-content"><div class="review__header-top"><button id="tutorial-open" type="button">Как это работает</button></div>
|
||||
<h1>Проверка качества поиска</h1><p>Сопоставляйте запрос с текстом документов и сохраняйте оценку выдачи.</p></div>
|
||||
</header>
|
||||
<header class="search__chrome" aria-label="Акылдаш">
|
||||
<div class="search__topbar">
|
||||
<a class="search__brand" href="/" aria-label="Акылдаш — поиск по правовой базе">
|
||||
<svg class="search__brand-mark" viewBox="0 0 48 48" role="img" aria-label="Знак Акылдаш"><circle cx="24" cy="24" r="20" fill="none" stroke="currentColor" stroke-width="3"/><path d="M24 5v38M5 24h38M11 11l26 26M37 11 11 37M17 7c2 8 12 8 14 0M17 41c2-8 12-8 14 0M7 17c8 2 8 12 0 14M41 17c-8 2-8 12 0 14" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></svg>
|
||||
<span class="search__brand-name">Акылдаш</span><span class="search__brand-divider" aria-hidden="true"></span><span class="search__brand-description">Правовая база Кыргызстана</span>
|
||||
</a>
|
||||
<form class="search__query" id="public-search-form"><div><label for="public-query">Поиск по правовой базе</label><div class="search__query-input"><svg class="search__query-icon" viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.8" cy="10.8" r="7" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="m16 16 5 5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg><input id="public-query" maxlength="500" autocomplete="off" placeholder="Введите правовой вопрос или название документа"><button class="search__query-clear" id="clear-query" type="button" aria-label="Очистить запрос"><svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true"><path d="m5 5 10 10m0-10L5 15" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg></button></div></div><button class="review__button--primary" type="submit">Найти</button></form>
|
||||
<div class="search__ui-language" role="group" aria-label="Язык интерфейса"><button id="ui-ru" type="button" aria-pressed="true">RU</button><span aria-hidden="true">/</span><button id="ui-ky" type="button" aria-pressed="false">KY</button></div>
|
||||
</div>
|
||||
<nav class="search__subnav" aria-label="Основная навигация"><a id="search-nav" class="is-active" href="/">Поиск</a><button id="sources-open" class="search__nav-text" type="button">Об источниках</button><a id="review-nav" href="/review">Лаборатория</a><button class="search__mobile-filters" id="mobile-filters-open" type="button" aria-expanded="false">Фильтры</button><div class="search__chips" id="active-filters" aria-label="Активные фильтры"></div><div class="search__account"><span id="signed-in-user"></span><button id="search-account-open" type="button">Личный кабинет</button><button id="search-users-open" type="button" hidden>Пользователи</button><button id="search-logout" type="button">Выйти</button></div></nav>
|
||||
</header>
|
||||
<main class="review__main" id="review">
|
||||
<form class="review__search" id="search-form">
|
||||
<label class="review__field">Юридический запрос<input id="query" name="q" maxlength="500" required autocomplete="off" placeholder="Например, как открыть ОсОО?"></label>
|
||||
@@ -162,21 +353,22 @@
|
||||
</main>
|
||||
<main class="search" id="search-page" hidden>
|
||||
<h1 class="search__sr-only">Поиск по правовой базе</h1>
|
||||
<form class="search__query" id="public-search-form"><label for="public-query">Поиск по правовой базе</label><div class="search__query-row"><input id="public-query" maxlength="500" autocomplete="off" placeholder="Введите правовой вопрос или название документа"><button class="review__button--primary" type="submit">Найти</button><label class="search__language">Язык<select id="public-language"><option value="ru">Русский</option><option value="ky">Кыргызский</option></select></label></div></form>
|
||||
<p class="review__status" id="public-status" role="status" aria-live="polite"></p>
|
||||
<div class="search__layout"><aside class="search__filters" aria-labelledby="filters-heading"><div class="review__panel-heading"><h2 id="filters-heading">Фильтры</h2><button id="clear-filters" type="button">Сбросить</button></div><div id="filter-fields"></div><label>Дата принятия от<input id="date-from" type="date"></label><label>Дата принятия до<input id="date-to" type="date"></label></aside>
|
||||
<section class="search__results" aria-labelledby="search-results-heading"><div class="review__panel-heading"><div><h2 id="search-results-heading">Результаты</h2><span class="review__panel-hint" id="result-count">Введите запрос</span></div><label>Сортировка<select id="sort-order"><option value="relevance">По релевантности</option><option value="date">По дате</option></select></label></div><ol id="public-results" class="search__result-list"><li class="review__empty"><strong>Начните с поиска</strong>Введите запрос, чтобы найти документы.</li></ol><div class="search__pagination"><button id="page-prev" type="button" disabled>Назад</button><span id="page-label">Страница 1</span><button id="page-next" type="button" disabled>Далее</button></div></section>
|
||||
<section class="search__document" aria-labelledby="public-document-heading"><div class="review__panel-heading"><h2 id="public-document-heading">Документ</h2></div><div class="search__document-controls"><label>Редакция<select id="document-edition" disabled></select></label><label>Язык документа<select id="document-language" disabled></select></label></div><p id="public-document-meta" class="review__document-meta">Выберите результат, чтобы прочитать доступную редакцию.</p><article id="public-document-body" class="review__document-body"></article></section>
|
||||
<p class="search__sr-only" id="public-status" role="status" aria-live="polite"></p>
|
||||
<div class="search__layout" id="search-layout"><aside class="search__filters" id="search-filters" aria-labelledby="filters-heading"><div class="review__panel-heading"><h2 id="filters-heading">Фильтры</h2><button id="clear-filters" type="button">Сбросить</button><button class="search__filter-close" id="mobile-filters-close" type="button">Закрыть фильтры</button></div><div id="filter-fields"></div><div class="search__filter search__filter--authority"><label for="public-language">Язык поиска<select id="public-language"><option value="ru">Русский</option><option value="ky">Кыргызский</option></select></label></div><span class="search__date-label">Дата принятия</span><div class="search__dates"><label><span class="search__sr-only">Дата принятия от</span><input id="date-from" type="date" aria-label="Дата принятия от"></label><label><span class="search__sr-only">Дата принятия до</span><input id="date-to" type="date" aria-label="Дата принятия до"></label></div><svg class="search__ornament" viewBox="0 0 220 56" aria-hidden="true"><path d="M2 34h60c15 0 17 17 31 17s16-17 30-17h95M2 41h55c13 0 17 13 31 13 15 0 17-13 31-13h99M98 42c-15-16 7-17 13-29 6 12 28 13 13 29-8 8-18 8-26 0Zm13-29v34M106 39l15-15m-15 15L96 27" fill="none" stroke="currentColor" stroke-width="1.5"/></svg></aside><button class="search__filter-overlay" id="filter-overlay" type="button" aria-label="Закрыть фильтры"></button>
|
||||
<section class="search__results" aria-labelledby="search-results-heading"><div class="review__panel-heading"><div><h2 id="search-results-heading">Результаты</h2><span class="review__panel-hint" id="result-count">Введите запрос</span></div><label class="search__sort-label">Сортировка<select id="sort-order"><option value="relevance">По релевантности</option><option value="date">По дате</option></select></label></div><ol id="public-results" class="search__result-list"><li class="review__empty"><strong>Начните с поиска</strong>Введите запрос, чтобы найти документы.</li></ol><div class="search__pagination"><button id="page-prev" type="button" disabled>Назад</button><span id="page-label">Страница 1</span><button id="page-next" type="button" disabled>Далее</button></div></section>
|
||||
<section class="search__document" id="public-document-panel" aria-labelledby="public-document-heading"><div class="search__document-head"><div class="search__breadcrumbs"><span>Документ</span><span aria-hidden="true">/</span><span id="document-breadcrumb">Выберите результат</span></div><div><button class="search__mobile-back" id="document-back" type="button">К результатам</button><button class="search__expand" id="document-expand" type="button" aria-label="Развернуть документ">Развернуть</button></div><h2 id="public-document-heading">Документ</h2></div><p id="public-document-meta" class="search__document-meta"><span id="document-facts">Выберите результат, чтобы прочитать доступную редакцию.</span><label class="search__document-language">Язык<select id="document-language" disabled aria-label="Язык документа"></select></label></p><div class="search__document-toolbar"><details class="search__toc" id="document-toc"><summary>Содержание</summary><nav aria-label="Содержание документа"><ol id="document-toc-list"><li>Оглавление появится после загрузки документа</li></ol></nav></details><label class="search__edition-label"><select id="document-edition" disabled aria-label="Редакция документа"></select></label><button id="document-print" type="button">Печать</button><a id="document-source" class="search__source-link" href="#" target="_blank" rel="noreferrer" hidden>Официальный источник</a></div><div class="search__find"><label for="document-find">Найти в документе</label><input id="document-find" type="search" placeholder="Фраза в документе" disabled><span class="search__find-count" id="document-find-count" aria-live="polite"></span><button id="document-find-prev" type="button" disabled aria-label="Предыдущее совпадение"><svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true"><path d="m12 4-6 6 6 6" fill="none" stroke="currentColor" stroke-width="1.8"/></svg></button><button id="document-find-next" type="button" disabled aria-label="Следующее совпадение"><svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true"><path d="m8 4 6 6-6 6" fill="none" stroke="currentColor" stroke-width="1.8"/></svg></button></div><p class="search__document-note" id="document-note" hidden></p><article id="public-document-body" class="search__document-body"></article></section>
|
||||
</div>
|
||||
</main>
|
||||
<footer class="search__footer"><span><strong>Акылдаш</strong> <span aria-hidden="true">·</span> Түндүк</span><span>Frontend v0.2.0 <span aria-hidden="true">·</span> Backend v0.13.0</span></footer>
|
||||
<div class="review__actions"><div class="review__actions-inner"><label>Проверяющий<input id="reviewer" readonly aria-label="Проверяющий"></label><label>Комментарий к выдаче <input id="overall-comment" maxlength="4000" placeholder="Что важно учесть? (необязательно)"></label><button class="review__button--primary" id="save" type="button">Сохранить оценку</button></div></div>
|
||||
<dialog id="login-dialog" aria-labelledby="login-heading"><form class="review__page" id="login-form"><h2 id="login-heading">Вход в Акылдаш</h2><p>Введите учетные данные, выданные администратором.</p><label>Логин<input id="login-username" name="username" autocomplete="username" required minlength="3" maxlength="64"></label><label>Пароль<input id="login-password" name="password" type="password" autocomplete="current-password" required></label><p id="login-error" class="review__status review__status--error" role="alert"></p><button class="review__button--primary" type="submit">Войти</button></form></dialog>
|
||||
<dialog id="password-dialog" aria-labelledby="password-heading"><form class="review__page" id="password-form"><h2 id="password-heading">Создайте новый пароль</h2><p class="review__notice">Для продолжения замените временный пароль. Используйте не менее 12 символов.</p><label>Текущий пароль<input id="current-password" type="password" autocomplete="current-password" required></label><label>Новый пароль<input id="new-password" type="password" autocomplete="new-password" minlength="12" maxlength="256" required></label><label>Повторите новый пароль<input id="confirm-password" type="password" autocomplete="new-password" minlength="12" maxlength="256" required></label><p id="password-error" class="review__status review__status--error" role="alert"></p><button class="review__button--primary" type="submit">Сохранить пароль</button></form></dialog>
|
||||
<dialog id="account-dialog" aria-labelledby="account-heading"><section class="review__page"><h2 id="account-heading">Личный кабинет</h2><dl><dt>Логин</dt><dd id="profile-username"></dd><dt>Роль</dt><dd id="profile-role">Администратор</dd><dt>Дата создания</dt><dd id="profile-created"></dd></dl><form id="profile-password-form"><h3>Изменить пароль</h3><p>Новый пароль должен содержать не менее 12 символов.</p><label>Текущий пароль<input id="profile-current-password" type="password" autocomplete="current-password" required></label><label>Новый пароль<input id="profile-new-password" type="password" autocomplete="new-password" minlength="12" maxlength="256" required></label><p id="profile-error" role="alert" class="review__status review__status--error"></p><div class="review__page-actions"><button class="review__button--primary" type="submit">Изменить пароль</button><button type="button" data-close="account-dialog">Закрыть</button></div></form></section></dialog>
|
||||
<dialog id="users-dialog" aria-labelledby="users-heading"><section class="review__page"><h2 id="users-heading">Управление пользователями</h2><form id="create-user-form"><label>Логин<input id="new-username" autocomplete="off" minlength="3" maxlength="64" required></label><label>Временный пароль<input id="temporary-password" type="password" autocomplete="new-password" minlength="12" maxlength="256" required></label><p>Пароль — от 12 символов. Новый пользователь сменит его при первом входе. Передайте временный пароль отдельно.</p><p id="users-error" role="alert" class="review__status review__status--error"></p><button class="review__button--primary" type="submit">Создать пользователя</button></form><ul id="user-list" class="review__user-list"></ul><button type="button" data-close="users-dialog">Закрыть</button></section></dialog>
|
||||
<dialog id="document-dialog"><button class="review__dialog-close" id="dialog-close" type="button">Закрыть</button><h2 id="dialog-heading">Документ</h2><div class="review__document-body" id="dialog-body"></div></dialog>
|
||||
<dialog class="search__about" id="sources-dialog" aria-labelledby="sources-heading"><button class="review__dialog-close" id="sources-close" type="button">Закрыть</button><h2 id="sources-heading">Источники документов</h2><p>Поиск выполняется по документам, подготовленным из правовых источников Кыргызской Республики. Для каждого результата доступная редакция и ссылка на официальный источник показываются в панели документа.</p><p>Официальный источник: <a href="https://cbd.minjust.gov.kg/" target="_blank" rel="noreferrer">Централизованный банк данных правовой информации Министерства юстиции Кыргызской Республики</a>.</p></dialog>
|
||||
<div class="review__tour-spotlight" id="tutorial-spotlight" hidden aria-hidden="true"></div><dialog class="review__tour" id="tutorial-dialog" aria-labelledby="tutorial-heading" aria-describedby="tutorial-text"><div class="review__tour-content"><p class="review__tour-kicker">Короткое знакомство</p><h2 id="tutorial-heading"></h2><p id="tutorial-text"></p><div class="review__tour-footer"><span class="review__tour-progress" id="tutorial-progress"></span><div class="review__tour-actions"><button id="tutorial-skip" type="button">Пропустить</button><button class="review__button--primary" id="tutorial-next" type="button">Далее</button></div></div></div></dialog>
|
||||
<footer class="review__header"><div class="review__header-content">Акылдаш · Frontend v0.1.2 · Backend v0.12.2 · Внутренняя лаборатория релевантности</div></footer>
|
||||
<footer class="review__header"><div class="review__header-content">Акылдаш · Frontend v0.2.0 · Backend v0.13.0 · Внутренняя лаборатория релевантности</div></footer>
|
||||
<script>
|
||||
document.body.classList.add('review__locked');
|
||||
const DRAFT_KEY = 'akyldash-search-review-draft';
|
||||
@@ -192,73 +384,329 @@
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let account = null;
|
||||
const reviewRoute = location.pathname === '/review';
|
||||
$('review').hidden = !reviewRoute; $('search-page').hidden = reviewRoute; $('review-nav').classList.toggle('is-active', reviewRoute); $('search-nav').classList.toggle('is-active', !reviewRoute);
|
||||
if (!reviewRoute) { document.title = 'Поиск по правовой базе · Акылдаш'; document.querySelector('.review__header-content').hidden = true; $('tutorial-open').hidden = true; document.querySelector('.review__skip').href = '#public-results'; document.querySelector('footer .review__header-content').textContent = 'Акылдаш · Frontend v0.1.2 · Backend v0.12.2'; }
|
||||
$('review').hidden = !reviewRoute; $('search-page').hidden = reviewRoute; $('review-review-nav').classList.toggle('is-active', reviewRoute); $('review-search-nav').classList.toggle('is-active', !reviewRoute); $('review-nav').classList.toggle('is-active', reviewRoute); $('search-nav').classList.toggle('is-active', !reviewRoute);
|
||||
if (!reviewRoute) { document.title = 'Поиск по правовой базе · Акылдаш'; document.querySelector('.review__header-content').hidden = true; $('tutorial-open').hidden = true; document.querySelector('.review__skip').href = '#public-results'; document.querySelector('footer .review__header-content').textContent = 'Акылдаш · Frontend v0.2.0 · Backend v0.13.0'; }
|
||||
async function apiFetch(path, options = {}) { const response = await fetch(path, {credentials: 'same-origin', ...options}); if (response.status === 401 && path !== '/auth/login') { document.body.classList.add('review__locked'); if (!$('login-dialog').open) $('login-dialog').showModal(); $('login-username').focus(); } return response; }
|
||||
const showLogin = () => { document.body.classList.add('review__locked'); if (!$('login-dialog').open) $('login-dialog').showModal(); $('login-username').focus(); };
|
||||
const enterWorkspace = (user) => { account = user; $('signed-in-user').textContent = `${user.username} · ${user.role}`; $('reviewer').value = user.username; $('profile-username').textContent = user.username; $('profile-role').textContent = user.role; $('profile-created').textContent = new Date(user.created_at * 1000).toLocaleDateString('ru-RU'); $('users-open').hidden = user.username.toLowerCase() !== 'admin'; document.body.classList.remove('review__locked'); if (!reviewRoute) initSearchPage(); else if (!hasSeenTour()) setTimeout(openTutorial, 350); };
|
||||
const filterFields = [['document_types', 'Вид документа', 'document_type'], ['statuses', 'Статус', 'status'], ['authorities', 'Орган принятия', 'authority'], ['legal_forces', 'Юридическая сила', 'legal_force']];
|
||||
const enterWorkspace = (user) => { account = user; $('signed-in-user').textContent = `${user.username} · ${user.role}`; $('review-signed-in-user').textContent = `${user.username} · ${user.role}`; $('reviewer').value = user.username; $('profile-username').textContent = user.username; $('profile-role').textContent = user.role; $('profile-created').textContent = new Date(user.created_at * 1000).toLocaleDateString('ru-RU'); $('search-users-open').hidden = $('review-users-open').hidden = user.username.toLowerCase() !== 'admin'; document.body.classList.remove('review__locked'); if (!reviewRoute) initSearchPage(); else if (!hasSeenTour()) setTimeout(openTutorial, 350); };
|
||||
const filterFields = [['statuses', 'Статус', 'status'], ['document_types', 'Вид документа', 'document_type'], ['authorities', 'Орган принятия', 'authority']];
|
||||
let filterCatalogs = {};
|
||||
let filterCatalogsLoaded = false;
|
||||
let publicPage = 1;
|
||||
let selectedPublicDocument = null;
|
||||
const selectedFilters = () => Object.fromEntries(filterFields.map(([key,, parameter]) => [parameter, document.querySelector(`input[name="filter-${parameter}"]:checked`)?.value || '']));
|
||||
function renderFilterCatalogs(payload) { filterCatalogs = payload; const root = $('filter-fields'); root.replaceChildren(); filterFields.forEach(([key, title, parameter]) => { const items = payload[key] || []; if (!items.length) return; const group = document.createElement('section'); group.className = 'search__filter'; const heading = document.createElement('h3'); heading.textContent = title; group.append(heading); items.forEach((item) => { const label = document.createElement('label'); const input = document.createElement('input'); input.type = 'radio'; input.name = `filter-${parameter}`; input.value = item.code; input.addEventListener('change', () => runSearch(1)); const text = document.createElement('span'); text.textContent = `${item.labels.ru || item.labels.ky || item.code} (${item.count})`; label.append(input, text); group.append(label); }); root.append(group); }); }
|
||||
function renderPublicResults(results) { const list = $('public-results'); list.replaceChildren(); if (!results.length) { list.innerHTML = '<li class="review__empty"><strong>Документы не найдены</strong>Измените запрос или сбросьте фильтры.</li>'; return; } results.forEach((result, index) => { const row = document.createElement('li'); row.className = 'search__result'; const title = document.createElement('button'); title.type = 'button'; title.className = 'search__result-title'; title.textContent = result.name || 'Название не указано'; title.addEventListener('click', () => openPublicDocument(result, row)); const meta = document.createElement('p'); meta.className = 'review__meta'; meta.textContent = [result.type, result.status, result.date_adopted, result.number, result.legal_force].filter(Boolean).join(' · '); const snippet = document.createElement('p'); snippet.textContent = result.snippet || 'Для документа нет выдержки из текста.'; row.append(title, meta, snippet); list.append(row); }); }
|
||||
async function runSearch(page = 1) { const query = $('public-query').value.trim(); if (!query) { $('public-status').textContent = 'Введите запрос, чтобы начать поиск.'; return; } publicPage = page; $('public-status').textContent = 'Выполняется поиск…'; const params = new URLSearchParams({q: query, language: $('public-language').value, page: String(page), page_size: '20', sort: $('sort-order').value}); for (const [key, value] of Object.entries(selectedFilters())) if (value) params.set(key, value); if ($('date-from').value) params.set('date_from', $('date-from').value); if ($('date-to').value) params.set('date_to', $('date-to').value); history.replaceState(null, '', `/?${params}`); try { const response = await apiFetch(`/search?${params}`); const payload = await response.json(); if (!response.ok) throw new Error(payload.error || 'Не удалось выполнить поиск.'); renderPublicResults(payload.results); $('result-count').textContent = `${payload.results.length} документов`; $('public-status').textContent = payload.results.length ? `Результаты для запроса «${query}».` : `По запросу «${query}» документов нет. Измените запрос или фильтры.`; $('page-label').textContent = `Страница ${page}`; $('page-prev').disabled = page <= 1; $('page-next').disabled = !payload.has_next; } catch (error) { $('public-status').textContent = error.message || 'Не удалось выполнить поиск. Повторите попытку.'; $('result-count').textContent = 'Поиск недоступен'; } }
|
||||
let searchRequest = 0;
|
||||
let editionRequest = 0;
|
||||
let currentDocumentHtml = '';
|
||||
let documentMatches = [];
|
||||
let activeDocumentMatch = -1;
|
||||
const selectedFilters = () => Object.fromEntries(filterFields.map(([key,, parameter]) => [parameter, parameter === 'authority' ? $('filter-authority')?.value || '' : document.querySelector(`input[name="filter-${parameter}"]:checked`)?.value || '']));
|
||||
function renderFilterCatalogs(payload) {
|
||||
filterCatalogs = payload;
|
||||
filterCatalogsLoaded = true;
|
||||
const root = $('filter-fields');
|
||||
root.replaceChildren();
|
||||
filterFields.forEach(([key, title, parameter]) => {
|
||||
const items = payload[key] || [];
|
||||
if (!items.length) return;
|
||||
const group = document.createElement('section');
|
||||
group.className = parameter === 'authority' ? 'search__filter search__filter--authority' : 'search__filter';
|
||||
if (parameter === 'authority') {
|
||||
const label = document.createElement('label');
|
||||
label.htmlFor = 'filter-authority';
|
||||
label.append(document.createTextNode(title));
|
||||
const select = document.createElement('select');
|
||||
select.id = 'filter-authority';
|
||||
const all = document.createElement('option');
|
||||
all.value = '';
|
||||
all.textContent = 'Все органы';
|
||||
select.append(all);
|
||||
items.forEach((item) => { const option = document.createElement('option'); option.value = item.code; option.textContent = `${item.labels.ru || item.labels.ky || item.code} (${item.count})`; select.append(option); });
|
||||
select.addEventListener('change', () => runSearch(1));
|
||||
label.append(select);
|
||||
group.append(label);
|
||||
} else {
|
||||
const heading = document.createElement('h3');
|
||||
heading.textContent = title;
|
||||
group.append(heading);
|
||||
items.forEach((item) => {
|
||||
const label = document.createElement('label');
|
||||
const input = document.createElement('input');
|
||||
input.type = 'radio'; input.name = `filter-${parameter}`; input.value = item.code;
|
||||
input.addEventListener('change', () => runSearch(1));
|
||||
const text = document.createElement('span');
|
||||
text.textContent = `${item.labels.ru || item.labels.ky || item.code} (${item.count})`;
|
||||
label.append(input, text); group.append(label);
|
||||
});
|
||||
}
|
||||
root.append(group);
|
||||
});
|
||||
}
|
||||
function syncFilterChips() {
|
||||
const root = $('active-filters');
|
||||
root.replaceChildren();
|
||||
const filters = selectedFilters();
|
||||
const labels = Object.fromEntries(filterFields.map(([key, title, parameter]) => [parameter, {title, items: filterCatalogs[key] || []}]));
|
||||
Object.entries(filters).forEach(([parameter, value]) => {
|
||||
if (!value) return;
|
||||
const item = labels[parameter].items.find((candidate) => candidate.code === value);
|
||||
const chip = document.createElement('span'); chip.className = 'search__chip';
|
||||
chip.append(document.createTextNode(item?.labels.ru || item?.labels.ky || value));
|
||||
const remove = document.createElement('button'); remove.type = 'button'; remove.innerHTML = '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="m5 5 10 10m0-10L5 15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>'; remove.setAttribute('aria-label', `Убрать фильтр «${labels[parameter].title}»`);
|
||||
remove.addEventListener('click', () => { if (parameter === 'authority') $('filter-authority').value = ''; else { const input = document.querySelector(`input[name="filter-${parameter}"]:checked`); if (input) input.checked = false; } runSearch(1); });
|
||||
chip.append(remove); root.append(chip);
|
||||
});
|
||||
[['date-from', 'date_from', 'От'], ['date-to', 'date_to', 'До']].forEach(([id, key, label]) => {
|
||||
if (!$(`${id}`).value) return;
|
||||
const value = $(`${id}`).value;
|
||||
const chip = document.createElement('span'); chip.className = 'search__chip'; chip.append(document.createTextNode(`${label}: ${value}`));
|
||||
const remove = document.createElement('button'); remove.type = 'button'; remove.innerHTML = '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="m5 5 10 10m0-10L5 15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>'; remove.setAttribute('aria-label', `Убрать дату ${value}`); remove.addEventListener('click', () => { $(id).value = ''; runSearch(1); });
|
||||
chip.append(remove); root.append(chip);
|
||||
});
|
||||
}
|
||||
function appendHighlighted(parent, value, query) {
|
||||
const text = String(value || '');
|
||||
if (!query) { parent.textContent = text; return; }
|
||||
const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const pattern = new RegExp(escaped, 'giu');
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
parent.append(document.createTextNode(text.slice(cursor, match.index)));
|
||||
const mark = document.createElement('mark'); mark.textContent = match[0]; parent.append(mark);
|
||||
cursor = match.index + match[0].length;
|
||||
}
|
||||
parent.append(document.createTextNode(text.slice(cursor)));
|
||||
}
|
||||
function renderPublicResults(results) {
|
||||
const list = $('public-results');
|
||||
list.replaceChildren();
|
||||
if (!results.length) {
|
||||
const empty = document.createElement('li'); empty.className = 'review__empty';
|
||||
const heading = document.createElement('strong'); heading.textContent = 'Документы не найдены';
|
||||
empty.append(heading, document.createTextNode('Измените запрос или сбросьте фильтры.')); list.append(empty); return;
|
||||
}
|
||||
results.forEach((result) => {
|
||||
const row = document.createElement('li'); row.className = 'search__result'; row.dataset.code = result.code;
|
||||
const title = document.createElement('button'); title.type = 'button'; title.className = 'search__result-title'; title.textContent = result.name || 'Название не указано';
|
||||
title.addEventListener('click', () => openPublicDocument(result, row));
|
||||
const meta = document.createElement('p'); meta.className = 'search__result-meta'; meta.textContent = [result.type, result.status, result.date_adopted, result.number, result.legal_force].filter(Boolean).join(' · ');
|
||||
const snippet = document.createElement('p'); snippet.className = 'search__result-snippet'; appendHighlighted(snippet, result.snippet || 'Для документа нет выдержки из текста.', $('public-query').value.trim());
|
||||
row.append(title, meta, snippet); list.append(row);
|
||||
});
|
||||
}
|
||||
async function runSearch(page = 1, updateUrl = true) {
|
||||
const query = $('public-query').value.trim();
|
||||
if (!query) { $('public-status').textContent = 'Введите запрос, чтобы начать поиск.'; syncFilterChips(); return; }
|
||||
publicPage = Math.max(1, page);
|
||||
const requestId = ++searchRequest;
|
||||
$('public-status').textContent = 'Выполняется поиск…';
|
||||
const params = new URLSearchParams({q: query, language: $('public-language').value, page: String(publicPage), page_size: '20', sort: $('sort-order').value});
|
||||
for (const [key, value] of Object.entries(selectedFilters())) if (value) params.set(key, value);
|
||||
if ($('date-from').value) params.set('date_from', $('date-from').value);
|
||||
if ($('date-to').value) params.set('date_to', $('date-to').value);
|
||||
if (updateUrl) history.pushState(null, '', `/?${params}`);
|
||||
syncFilterChips();
|
||||
try {
|
||||
const response = await apiFetch(`/search?${params}`);
|
||||
const payload = await response.json();
|
||||
if (requestId !== searchRequest) return;
|
||||
if (!response.ok) throw new Error(payload.error || 'Не удалось выполнить поиск.');
|
||||
renderPublicResults(payload.results || []);
|
||||
const count = (payload.results || []).length;
|
||||
$('result-count').textContent = `${count} ${count === 1 ? 'результат' : 'результата'} на странице`;
|
||||
$('public-status').textContent = count ? `Результаты для запроса «${query}».` : `По запросу «${query}» документов нет. Измените запрос или фильтры.`;
|
||||
$('page-label').textContent = `Страница ${publicPage}`;
|
||||
$('page-prev').disabled = publicPage <= 1;
|
||||
$('page-next').disabled = !payload.has_next;
|
||||
} catch (error) {
|
||||
if (requestId !== searchRequest) return;
|
||||
$('public-status').textContent = error.message || 'Не удалось выполнить поиск. Повторите попытку.';
|
||||
$('result-count').textContent = 'Поиск недоступен';
|
||||
}
|
||||
}
|
||||
function buildDocumentToc() {
|
||||
const body = $('public-document-body');
|
||||
const headings = [...body.querySelectorAll('h1, h2, h3')];
|
||||
const root = $('document-toc-list'); root.replaceChildren();
|
||||
if (!headings.length) { const item = document.createElement('li'); item.textContent = 'В тексте нет разделов'; root.append(item); return; }
|
||||
headings.forEach((heading, index) => {
|
||||
if (!heading.id) heading.id = `document-section-${index + 1}`;
|
||||
const item = document.createElement('li'); const link = document.createElement('a'); link.href = `#${heading.id}`; link.textContent = heading.textContent.trim();
|
||||
link.addEventListener('click', (event) => { event.preventDefault(); heading.scrollIntoView({block: 'start'}); heading.focus({preventScroll: true}); });
|
||||
if (!heading.hasAttribute('tabindex')) heading.tabIndex = -1;
|
||||
item.append(link); root.append(item);
|
||||
});
|
||||
}
|
||||
function highlightDocumentMatches() {
|
||||
const body = $('public-document-body'); body.innerHTML = currentDocumentHtml;
|
||||
documentMatches = []; activeDocumentMatch = -1;
|
||||
const query = $('document-find').value.trim();
|
||||
if (query) {
|
||||
const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT, {acceptNode: (node) => node.parentElement.closest('script, style, mark') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT});
|
||||
const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode);
|
||||
const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const pattern = new RegExp(escaped, 'giu');
|
||||
nodes.forEach((node) => {
|
||||
const text = node.nodeValue; const matches = [...text.matchAll(pattern)];
|
||||
if (!matches.length) return;
|
||||
const fragment = document.createDocumentFragment(); let cursor = 0;
|
||||
matches.forEach((match) => { fragment.append(document.createTextNode(text.slice(cursor, match.index))); const mark = document.createElement('mark'); mark.textContent = match[0]; mark.dataset.match = String(documentMatches.length); documentMatches.push(mark); fragment.append(mark); cursor = match.index + match[0].length; });
|
||||
fragment.append(document.createTextNode(text.slice(cursor))); node.replaceWith(fragment);
|
||||
});
|
||||
}
|
||||
const count = documentMatches.length;
|
||||
$('document-find-count').textContent = count ? `1 из ${count}` : query ? 'Совпадений нет' : '';
|
||||
$('document-find-prev').disabled = $('document-find-next').disabled = count === 0;
|
||||
if (count) moveDocumentMatch(1);
|
||||
buildDocumentToc();
|
||||
}
|
||||
function moveDocumentMatch(step) {
|
||||
if (!documentMatches.length) return;
|
||||
activeDocumentMatch = (activeDocumentMatch + step + documentMatches.length) % documentMatches.length;
|
||||
documentMatches.forEach((mark, index) => { mark.classList.toggle('is-current', index === activeDocumentMatch); });
|
||||
$('document-find-count').textContent = `${activeDocumentMatch + 1} из ${documentMatches.length}`;
|
||||
documentMatches[activeDocumentMatch].scrollIntoView({block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth'});
|
||||
}
|
||||
let filterReturnFocus = null;
|
||||
function closeMobileFilters() {
|
||||
$('search-filters').classList.remove('is-open'); $('filter-overlay').classList.remove('is-open');
|
||||
$('search-filters').removeAttribute('aria-modal'); $('search-filters').removeAttribute('role'); $('search-filters').setAttribute('aria-hidden', 'true'); $('mobile-filters-open').setAttribute('aria-expanded', 'false');
|
||||
filterReturnFocus?.focus();
|
||||
}
|
||||
function openMobileFilters() {
|
||||
filterReturnFocus = document.activeElement;
|
||||
$('search-filters').classList.add('is-open'); $('filter-overlay').classList.add('is-open');
|
||||
$('search-filters').setAttribute('role', 'dialog'); $('search-filters').setAttribute('aria-modal', 'true'); $('search-filters').setAttribute('aria-hidden', 'false'); $('mobile-filters-open').setAttribute('aria-expanded', 'true');
|
||||
$('mobile-filters-close').focus();
|
||||
}
|
||||
function setMobileView(view) {
|
||||
if (!matchMedia('(max-width: 900px)').matches) { $('search-layout').removeAttribute('data-mobile-view'); return; }
|
||||
$('search-layout').dataset.mobileView = view;
|
||||
if (view === 'document') { $('public-document-heading').tabIndex = -1; $('public-document-heading').focus(); }
|
||||
}
|
||||
async function loadPublicEdition() {
|
||||
if (!selectedPublicDocument) return;
|
||||
const {code} = selectedPublicDocument;
|
||||
const edition = $('document-edition').value;
|
||||
const editionInfo = selectedPublicDocument.editions.find((item) => item.source_code === edition);
|
||||
const language = $('document-language').value;
|
||||
const editionInfo = selectedPublicDocument.editions.find((item) => String(item.source_code) === String(edition));
|
||||
const languages = editionInfo?.available_languages || [];
|
||||
const languageSelect = $('document-language');
|
||||
[...languageSelect.options].forEach((option) => { option.disabled = !languages.includes(option.value); });
|
||||
if (!languages.length) { $('public-document-meta').textContent = 'В этой редакции нет доступного текста.'; $('public-document-body').replaceChildren(); return; }
|
||||
if (!languages.includes(languageSelect.value)) languageSelect.value = languages[0];
|
||||
const language = languageSelect.value;
|
||||
$('public-document-meta').textContent = 'Загрузка редакции…';
|
||||
if (!languages.includes(language)) { $('document-facts').textContent = 'В этой редакции нет доступного текста на выбранном языке.'; $('public-document-body').replaceChildren(); return; }
|
||||
const requestId = ++editionRequest;
|
||||
$('document-facts').textContent = 'Загрузка редакции…';
|
||||
try {
|
||||
const response = await apiFetch(`/documents/${encodeURIComponent(code)}/editions/${encodeURIComponent(edition)}?language=${encodeURIComponent(language)}`);
|
||||
const payload = await response.json();
|
||||
if (requestId !== editionRequest || selectedPublicDocument?.code !== code || $('document-edition').value !== edition || $('document-language').value !== language) return;
|
||||
if (!response.ok) throw new Error(payload.error || 'Редакция недоступна.');
|
||||
const content = payload.content[language];
|
||||
const meta = $('public-document-meta'); meta.replaceChildren();
|
||||
const details = document.createElement('span'); details.textContent = [selectedPublicDocument.type, selectedPublicDocument.status, selectedPublicDocument.date_adopted].filter(Boolean).join(' · ');
|
||||
const source = document.createElement('a'); source.href = `https://cbd.minjust.gov.kg/${encodeURIComponent(code)}/edition/${encodeURIComponent(edition)}/${encodeURIComponent(language)}`; source.target = '_blank'; source.rel = 'noreferrer'; source.textContent = 'Официальный источник';
|
||||
meta.append(details, document.createTextNode(' · '), source);
|
||||
$('public-document-body').innerHTML = content.html;
|
||||
} catch (error) { $('public-document-meta').textContent = error.message || 'Не удалось загрузить документ.'; $('public-document-body').replaceChildren(); }
|
||||
const meta = $('document-facts'); meta.replaceChildren();
|
||||
const type = document.createElement('span'); type.textContent = selectedPublicDocument.type || 'Документ';
|
||||
const status = document.createElement('span'); status.textContent = selectedPublicDocument.status || '';
|
||||
const date = document.createElement('span'); date.textContent = selectedPublicDocument.date_adopted || '';
|
||||
meta.append(type, document.createTextNode(' · '), status, ...(date.textContent ? [document.createTextNode(' · '), date] : []));
|
||||
const source = $('document-source'); source.href = `https://cbd.minjust.gov.kg/${encodeURIComponent(code)}/edition/${encodeURIComponent(edition)}/${encodeURIComponent(language)}`; source.hidden = false;
|
||||
currentDocumentHtml = content.html || '';
|
||||
$('public-document-body').innerHTML = currentDocumentHtml;
|
||||
$('public-document-body').lang = language;
|
||||
$('document-find').disabled = false; $('document-note').hidden = true;
|
||||
highlightDocumentMatches();
|
||||
} catch (error) {
|
||||
if (requestId !== editionRequest) return;
|
||||
$('document-facts').textContent = error.message || 'Не удалось загрузить документ.';
|
||||
$('public-document-body').replaceChildren();
|
||||
}
|
||||
}
|
||||
async function openPublicDocument(result, row) {
|
||||
document.querySelectorAll('.search__result--selected').forEach((item) => item.classList.remove('search__result--selected'));
|
||||
row.classList.add('search__result--selected'); selectedPublicDocument = result;
|
||||
row.classList.add('search__result--selected'); selectedPublicDocument = result; ++editionRequest;
|
||||
const opened = document.createElement('span'); opened.className = 'search__opened'; opened.textContent = 'Открыт'; row.append(opened);
|
||||
$('document-breadcrumb').textContent = result.name || 'Документ';
|
||||
$('public-document-heading').textContent = result.name || 'Документ'; $('public-document-body').replaceChildren();
|
||||
row.querySelector('.search__opened')?.remove();
|
||||
setMobileView('document');
|
||||
$('document-find').value = ''; $('document-find').disabled = true; $('document-note').hidden = true;
|
||||
$('document-source').hidden = true; $('document-edition').replaceChildren(); $('document-language').replaceChildren();
|
||||
try {
|
||||
const response = await apiFetch(`/documents/${encodeURIComponent(result.code)}/editions`);
|
||||
const payload = await response.json();
|
||||
if (selectedPublicDocument !== result) return;
|
||||
if (!response.ok) throw new Error(payload.error || 'Не удалось получить список редакций.');
|
||||
selectedPublicDocument.editions = payload.editions || [];
|
||||
const editionSelect = $('document-edition'); editionSelect.replaceChildren();
|
||||
const editionSelect = $('document-edition');
|
||||
(payload.editions || []).forEach((edition) => { const option = document.createElement('option'); option.value = edition.source_code; const name = edition.name?.[$('public-language').value] || edition.name?.ru || edition.name?.ky; option.textContent = [name, edition.source_code].filter(Boolean).join(' · '); editionSelect.append(option); });
|
||||
const matchedEdition = [...editionSelect.options].find((option) => option.value === String(result.edition));
|
||||
if (matchedEdition) editionSelect.value = matchedEdition.value;
|
||||
editionSelect.disabled = !editionSelect.options.length;
|
||||
const languages = payload.available_languages || [];
|
||||
const languageSelect = $('document-language'); languageSelect.replaceChildren();
|
||||
const languageSelect = $('document-language');
|
||||
languages.forEach((language) => { const option = document.createElement('option'); option.value = language; option.textContent = language === 'ru' ? 'Русский' : 'Кыргызский'; languageSelect.append(option); });
|
||||
languageSelect.disabled = !languages.length;
|
||||
if (!languages.length || !editionSelect.options.length) throw new Error('Для документа нет доступных редакций с текстом.');
|
||||
languageSelect.value = languages.includes($('public-language').value) ? $('public-language').value : languages[0];
|
||||
await loadPublicEdition();
|
||||
} catch (error) { $('public-document-meta').textContent = error.message || 'Документ недоступен.'; }
|
||||
} catch (error) { if (selectedPublicDocument === result) $('document-facts').textContent = error.message || 'Документ недоступен.'; }
|
||||
}
|
||||
$('document-edition').addEventListener('change', loadPublicEdition); $('document-language').addEventListener('change', loadPublicEdition);
|
||||
async function initSearchPage() { if (reviewRoute || filterCatalogs.length) return; const params = new URLSearchParams(location.search); $('public-query').value = params.get('q') || ''; $('public-language').value = params.get('language') || 'ru'; $('sort-order').value = params.get('sort') || 'relevance'; $('date-from').value = params.get('date_from') || ''; $('date-to').value = params.get('date_to') || ''; const response = await apiFetch(`/search/filters?language=${encodeURIComponent($('public-language').value)}`); if (response.ok) renderFilterCatalogs(await response.json()); for (const [key,, parameter] of filterFields) { const value = params.get(parameter); const input = value && document.querySelector(`input[name="filter-${parameter}"][value="${CSS.escape(value)}"]`); if (input) input.checked = true; } const query = params.get('q'); if (query) runSearch(Number(params.get('page') || 1)); }
|
||||
async function initSearchPage() {
|
||||
if (reviewRoute) return;
|
||||
const params = new URLSearchParams(location.search);
|
||||
$('public-query').value = params.get('q') || '';
|
||||
$('public-language').value = params.get('language') || 'ru';
|
||||
$('sort-order').value = params.get('sort') || 'relevance';
|
||||
$('date-from').value = params.get('date_from') || '';
|
||||
$('date-to').value = params.get('date_to') || '';
|
||||
const uiLanguage = (() => { try { return localStorage.getItem('akyldash-ui-language') || 'ru'; } catch (_) { return 'ru'; } })();
|
||||
setUiLanguage(uiLanguage);
|
||||
setMobileView('results');
|
||||
if (!filterCatalogsLoaded) { const response = await apiFetch(`/search/filters?language=${encodeURIComponent($('public-language').value)}`); if (response.ok) renderFilterCatalogs(await response.json()); }
|
||||
document.querySelectorAll('#filter-fields input:checked').forEach((input) => { input.checked = false; });
|
||||
if ($('filter-authority')) $('filter-authority').value = '';
|
||||
for (const [key,, parameter] of filterFields) {
|
||||
const value = params.get(parameter);
|
||||
if (parameter === 'authority') { const select = $('filter-authority'); if (select) select.value = value || ''; }
|
||||
else { const input = value && document.querySelector(`input[name="filter-${parameter}"][value="${CSS.escape(value)}"]`); if (input) input.checked = true; }
|
||||
}
|
||||
syncFilterChips();
|
||||
if (params.get('q')) await runSearch(Number(params.get('page') || 1), false);
|
||||
}
|
||||
function setUiLanguage(language) {
|
||||
const ky = language === 'ky';
|
||||
$('ui-ru').setAttribute('aria-pressed', String(!ky)); $('ui-ky').setAttribute('aria-pressed', String(ky));
|
||||
document.documentElement.lang = ky ? 'ky' : 'ru';
|
||||
const words = ky ? {search: 'Издөө', sources: 'Булактар жөнүндө', filters: 'Чыпкалар', clear: 'Тазалоо', document: 'Документ', results: 'Натыйжалар', all: 'Бардык органдар', find: 'Документтен издөө', toc: 'Мазмуну', print: 'Басып чыгаруу', account: 'Жеке кабинет', result: 'Табуу'} : {search: 'Поиск', sources: 'Об источниках', filters: 'Фильтры', clear: 'Сбросить', document: 'Документ', results: 'Результаты', all: 'Все органы', find: 'Найти в документе', toc: 'Содержание', print: 'Печать', account: 'Личный кабинет', result: 'Найти'};
|
||||
$('search-nav').textContent = words.search; $('sources-open').textContent = words.sources; $('filters-heading').textContent = words.filters; $('clear-filters').textContent = words.clear; $('mobile-filters-open').textContent = words.filters; $('mobile-filters-close').textContent = words.clear; $('search-results-heading').textContent = words.results; $('public-document-heading').textContent = selectedPublicDocument?.name || words.document; $('document-find').previousElementSibling.textContent = words.find; $('document-toc').querySelector('summary').textContent = words.toc; $('document-print').textContent = words.print; $('search-account-open').textContent = words.account; $('public-search-form').querySelector('button[type="submit"]').textContent = words.result;
|
||||
try { localStorage.setItem('akyldash-ui-language', ky ? 'ky' : 'ru'); } catch (_) {}
|
||||
}
|
||||
$('ui-ru').addEventListener('click', () => setUiLanguage('ru'));
|
||||
$('ui-ky').addEventListener('click', () => setUiLanguage('ky'));
|
||||
$('public-search-form').addEventListener('submit', (event) => { event.preventDefault(); runSearch(1); });
|
||||
$('sort-order').addEventListener('change', () => runSearch(1)); $('date-from').addEventListener('change', () => runSearch(1)); $('date-to').addEventListener('change', () => runSearch(1)); $('public-language').addEventListener('change', async () => { const response = await apiFetch(`/search/filters?language=${encodeURIComponent($('public-language').value)}`); if (response.ok) renderFilterCatalogs(await response.json()); if ($('public-query').value.trim()) runSearch(1); });
|
||||
$('clear-query').addEventListener('click', () => { $('public-query').value = ''; $('public-query').focus(); $('public-query').dispatchEvent(new Event('input', {bubbles: true})); });
|
||||
$('sort-order').addEventListener('change', () => runSearch(1));
|
||||
$('date-from').addEventListener('change', () => runSearch(1)); $('date-to').addEventListener('change', () => runSearch(1));
|
||||
$('public-language').addEventListener('change', async () => { const response = await apiFetch(`/search/filters?language=${encodeURIComponent($('public-language').value)}`); if (response.ok) renderFilterCatalogs(await response.json()); if ($('public-query').value.trim()) runSearch(1); });
|
||||
$('page-prev').addEventListener('click', () => runSearch(publicPage - 1)); $('page-next').addEventListener('click', () => runSearch(publicPage + 1));
|
||||
$('clear-filters').addEventListener('click', () => { document.querySelectorAll('#filter-fields input:checked').forEach((input) => { input.checked = false; }); $('date-from').value = ''; $('date-to').value = ''; $('sort-order').value = 'relevance'; runSearch(1); });
|
||||
async function loadUsers() {
|
||||
$('clear-filters').addEventListener('click', () => { document.querySelectorAll('#filter-fields input:checked').forEach((input) => { input.checked = false; }); if ($('filter-authority')) $('filter-authority').value = ''; $('date-from').value = ''; $('date-to').value = ''; $('sort-order').value = 'relevance'; runSearch(1); });
|
||||
window.addEventListener('popstate', () => { if (!reviewRoute) initSearchPage(); });
|
||||
window.addEventListener('resize', () => { if (!matchMedia('(max-width: 900px)').matches) { closeMobileFilters(); $('search-layout').removeAttribute('data-mobile-view'); } });
|
||||
$('document-find').addEventListener('input', highlightDocumentMatches);
|
||||
$('document-find-prev').addEventListener('click', () => moveDocumentMatch(-1)); $('document-find-next').addEventListener('click', () => moveDocumentMatch(1));
|
||||
$('mobile-filters-open').addEventListener('click', openMobileFilters); $('mobile-filters-close').addEventListener('click', closeMobileFilters); $('filter-overlay').addEventListener('click', closeMobileFilters);
|
||||
$('search-filters').addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape') { closeMobileFilters(); return; }
|
||||
if (event.key !== 'Tab' || !$('search-filters').classList.contains('is-open')) return;
|
||||
const controls = [...$('search-filters').querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), [href]')].filter((node) => node.offsetParent !== null);
|
||||
if (!controls.length) return;
|
||||
const first = controls[0]; const last = controls[controls.length - 1];
|
||||
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
|
||||
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
|
||||
});
|
||||
$('document-back').addEventListener('click', () => { setMobileView('results'); document.querySelector('.search__result--selected .search__result-title')?.focus(); });
|
||||
$('document-edition').addEventListener('change', loadPublicEdition); $('document-language').addEventListener('change', loadPublicEdition);
|
||||
$('document-print').addEventListener('click', () => window.print());
|
||||
$('document-expand').addEventListener('click', () => { $('dialog-heading').textContent = $('public-document-heading').textContent; $('dialog-body').innerHTML = currentDocumentHtml; $('document-dialog').classList.add('search__expanded'); $('document-dialog').showModal(); });
|
||||
$('dialog-close').addEventListener('click', () => { $('document-dialog').close(); if (state.selected) state.selected.focus(); });
|
||||
$('document-dialog').addEventListener('close', () => $('document-dialog').classList.remove('search__expanded'));
|
||||
$('sources-open').addEventListener('click', () => $('sources-dialog').showModal());
|
||||
$('sources-close').addEventListener('click', () => $('sources-dialog').close());
|
||||
async function loadUsers() {
|
||||
$('users-error').textContent = '';
|
||||
const response = await apiFetch('/admin/users');
|
||||
if (!response.ok) { $('users-error').textContent = 'Не удалось загрузить список пользователей.'; return; }
|
||||
@@ -287,10 +735,10 @@
|
||||
$('password-form').addEventListener('submit', async (event) => { event.preventDefault(); $('password-error').textContent = ''; if ($('new-password').value !== $('confirm-password').value) { $('password-error').textContent = 'Новые пароли не совпадают.'; $('confirm-password').focus(); return; } const response = await fetch('/auth/change-password', {method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({current_password: $('current-password').value, new_password: $('new-password').value})}); const payload = await response.json(); if (!response.ok) { $('password-error').textContent = payload.error || 'Не удалось изменить пароль.'; return; } $('password-dialog').close(); sessionTemporaryPassword = ''; $('password-form').reset(); enterWorkspace(payload.account); });
|
||||
$('profile-password-form').addEventListener('submit', async (event) => { event.preventDefault(); $('profile-error').textContent = ''; const response = await apiFetch('/auth/change-password', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({current_password: $('profile-current-password').value, new_password: $('profile-new-password').value})}); const payload = await response.json(); if (!response.ok) { $('profile-error').textContent = payload.error || 'Не удалось изменить пароль.'; return; } $('account-dialog').close(); $('profile-password-form').reset(); enterWorkspace(payload.account); });
|
||||
$('create-user-form').addEventListener('submit', async (event) => { event.preventDefault(); $('users-error').textContent = ''; const response = await apiFetch('/admin/users', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username: $('new-username').value, password: $('temporary-password').value})}); const payload = await response.json(); if (!response.ok) { $('users-error').textContent = payload.error || 'Не удалось создать учетную запись.'; return; } $('create-user-form').reset(); await loadUsers(); });
|
||||
$('account-open').addEventListener('click', () => $('account-dialog').showModal());
|
||||
$('users-open').addEventListener('click', async () => { await loadUsers(); $('users-dialog').showModal(); });
|
||||
['review-account-open', 'search-account-open'].forEach((id) => $(id).addEventListener('click', () => $('account-dialog').showModal()));
|
||||
['review-users-open', 'search-users-open'].forEach((id) => $(id).addEventListener('click', async () => { await loadUsers(); $('users-dialog').showModal(); }));
|
||||
document.querySelectorAll('[data-close]').forEach((button) => button.addEventListener('click', () => $(button.dataset.close).close()));
|
||||
$('logout').addEventListener('click', async () => { await fetch('/auth/logout', {method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json'}, body: '{}'}); account = null; document.body.classList.add('review__locked'); showLogin(); });
|
||||
['review-logout', 'search-logout'].forEach((id) => $(id).addEventListener('click', async () => { await fetch('/auth/logout', {method: 'POST', credentials: 'same-origin', headers: {'Content-Type': 'application/json'}, body: '{}'}); account = null; document.body.classList.add('review__locked'); showLogin(); }));
|
||||
(async () => { const response = await fetch('/auth/me', {credentials: 'same-origin'}); if (!response.ok) { showLogin(); return; } const payload = await response.json(); if (payload.account.must_change_password) { $('password-dialog').showModal(); $('current-password').focus(); return; } enterWorkspace(payload.account); })();
|
||||
const setStatus = (text, error = false) => { $('status').textContent = text; $('status').classList.toggle('review__status--error', error); $('status').setAttribute('role', error ? 'alert' : 'status'); $('status').setAttribute('aria-live', error ? 'assertive' : 'polite'); };
|
||||
const setError = (text) => setStatus(text, true);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) NotoSans-Italic[wdth,wght].ttf: Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||
|
||||
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:
|
||||
http://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 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) NotoSerif-Italic[wdth,wght].ttf: Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic)
|
||||
|
||||
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:
|
||||
http://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.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -24,6 +24,13 @@ class SearchApiTest(unittest.TestCase):
|
||||
(edition / "ru/content.txt").write_text("Текст\n", encoding="utf-8")
|
||||
return Api("http://opensearch:9200", "current", root)
|
||||
|
||||
def test_static_font_assets_are_allowlisted(self):
|
||||
content_type, body = Api.static_asset("/static/fonts/noto-sans-cyrillic-ext.woff2")
|
||||
self.assertEqual(content_type, "font/woff2")
|
||||
self.assertTrue(body.startswith(b"wOF2"))
|
||||
with self.assertRaisesRegex(ApiError, "static asset not found"):
|
||||
Api.static_asset("/static/fonts/../../DESIGN.md")
|
||||
|
||||
def test_search_pagination_filters_and_highlight(self):
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
api = self.make_api(Path(temporary))
|
||||
|
||||
+1
-1
@@ -45,4 +45,4 @@
|
||||
|
||||
---
|
||||
|
||||
Акылдаш · Telegram-бот v0.2.2 · Backend v0.12.2 · Frontend v0.1.2
|
||||
Акылдаш · Telegram-бот v0.2.2 · Backend v0.13.0 · Frontend v0.2.0
|
||||
@@ -137,7 +137,7 @@ protected file metadata remain unverified.
|
||||
removed afterward. This does not verify VPS startup, DNS, or public TLS.
|
||||
- The app has no migration framework or SMTP setup. Repository versions on this
|
||||
branch are:
|
||||
backend `0.12.2`, frontend `0.1.2`, Telegram bot `0.2.2` (the bot is not
|
||||
backend `0.13.0`, frontend `0.2.0`, Telegram bot `0.2.2` (the bot is not
|
||||
deployed on this VPS).
|
||||
|
||||
## Corpus readiness (2026-10-18)
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
# План точного воспроизведения поискового интерфейса
|
||||
|
||||
Дата: 22 октября 2026 года.
|
||||
|
||||
Статус: реализация и локальная визуальная приёмка выполнены в
|
||||
`feature/frontend-pixel-perfect`; CI и ручная проверка PR ещё ожидаются.
|
||||
|
||||
## 1. Цель, границы и источники истины
|
||||
|
||||
Привести существующую авторизованную поисковую страницу `/` к композиции
|
||||
утверждённого изображения «Акылдаш · Түндүк», сохранив реальные API,
|
||||
авторизацию, безопасность и отдельный сценарий лаборатории `/review`.
|
||||
|
||||
Источники:
|
||||
|
||||
- [DESIGN.md](../../DESIGN.md) — единственная нормативная дизайн-система:
|
||||
токены, типографика, доступность, постоянные правила компонентов.
|
||||
- [Исходный концепт](../design/tunduk-desktop-concept.png) — визуальный
|
||||
эталон композиции. Вложение пользователя 1280×800 визуально соответствует
|
||||
этому сохранённому изображению более высокого разрешения.
|
||||
- [План frontend СПС](frontend-search-sps-plan.md) — продуктовый контекст.
|
||||
- [Readiness plan](frontend-design-readiness-plan.md) — отдельные условия
|
||||
готовности публичного продукта, которые этот план не отменяет.
|
||||
|
||||
Изображение задаёт композицию и пропорции; `DESIGN.md` задаёт токены,
|
||||
шрифты и ограничения. До реализации фиксировать расхождения, а не молча
|
||||
изменять палитру, шрифты или доступность ради совпадения растровых пикселей.
|
||||
Временные задачи и результаты измерений остаются здесь; новые постоянные
|
||||
правила добавляются в `DESIGN.md` без копирования всей дизайн-системы.
|
||||
|
||||
Не входят: публичный запуск, изменение прав доступа, ранжирования, корпуса,
|
||||
индекса, production, регистрация, аналитика, сравнение редакций, переход
|
||||
на новый frontend framework. Содержимое демонстрационного документа
|
||||
не становится юридическими данными продукта.
|
||||
|
||||
Figma не является обязательной зависимостью: сохранённого эталона достаточно.
|
||||
При необходимости совместного редактирования можно подготовить отдельный
|
||||
Figma-макет с Auto Layout и переменными, ссылающийся на эти же правила;
|
||||
это не заменяет проверку фактической вёрстки в браузере.
|
||||
|
||||
## 2. Проверенные факты и ограничения аудита
|
||||
|
||||
Исходная проверка была выполнена по коду и изображениям без браузера.
|
||||
Последующие результаты Playwright сохранены в
|
||||
[отчёте визуальной приёмки](visual-review/README.md). Они относятся к
|
||||
локальному UI со стабильными fixture-ответами и не подтверждают состояние
|
||||
production или актуального OpenSearch.
|
||||
|
||||
Основные файлы:
|
||||
|
||||
- `backend/search/review.html` — разметка, встроенные CSS и JavaScript обоих
|
||||
сценариев, footer и авторизация.
|
||||
- `backend/search/api.py` — выдача страницы для `/` и `/review`, API поиска,
|
||||
фильтров и редакций.
|
||||
- `backend/test_search_api.py` — существующие проверки API.
|
||||
- `.gitea/workflows/ci.yaml` — обязательные проверки и сборка образов.
|
||||
|
||||
| Проблема | Подтверждение в реализации | Требуемый результат |
|
||||
|---|---|---|
|
||||
| Другая шапка | Общая `.review__header`, поиск отдельной формой ниже | Бренд, поиск и язык в одной верхней строке |
|
||||
| Нет второй строки эталона | Нет общей полосы навигации и активных фильтров | Навигация и удаляемые фильтры под шапкой |
|
||||
| Другие пропорции | `.search__layout`: `230px / .9fr / 1.2fr`, `min-height: 65vh` | Измеренная сетка и корректная высота рабочей области |
|
||||
| Не тот вид фильтров | Все справочники выводятся radio-списками, даты вертикально | Компактные группы, select органа, даты рядом |
|
||||
| Выбранный результат неполон | Есть только фоновое выделение | Фон, рамка, подпись «Открыт», точные отступы |
|
||||
| Неполная панель документа | Есть заголовок, select редакции/языка, метаданные и текст | Полная иерархия и работающие действия эталона |
|
||||
| Смешаны стили документа | Объявлен `.search__document-body`, статья использует `.review__document-body` | Одна корректная область стилей поискового документа |
|
||||
| Шрифты не поставляются | Noto указаны в CSS, локальные файлы не найдены | Проверенная загрузка локальных шрифтов |
|
||||
| Нет фирменных ресурсов | Знак сделан CSS-кружком; орнамент и favicon отсутствуют | SVG-знак, орнамент, favicon |
|
||||
| Лабораторная панель на поиске | `.review__actions` вне скрываемого `<main>`; для `/` не скрывается | Оценивание только на `/review` |
|
||||
| Счётчик вводит в заблуждение | Выводится `payload.results.length`; API не возвращает total | Явное число на странице либо отдельно реализованный total |
|
||||
| Нет визуального контроля | Найденные тесты проверяют API, не геометрию страницы | Воспроизводимые браузерные снимки и сравнение |
|
||||
|
||||
Язык поиска уже существует, но отдельного переключения интерфейса нет.
|
||||
Редакции и язык документа уже загружаются через API. Оглавление, поиск внутри,
|
||||
разворачивание и кнопка печати пока не реализованы.
|
||||
|
||||
## 3. Этап 0 — воспроизводимый эталон
|
||||
|
||||
- [ ] Перед реализацией перечитать актуальные инструкции, `DESIGN.md`,
|
||||
реализацию маршрутов и обязательные проверки; проверить доступность
|
||||
установленного Ponytail согласно правилам репозитория.
|
||||
- [ ] Сохранить чужие незакоммиченные изменения. Обновить локальный `main`
|
||||
из remote и создать тематическую `feature/` или `fix/` ветку безопасным
|
||||
способом, не перенося посторонние изменения в PR.
|
||||
- [ ] Зафиксировать основной viewport 1280×800 CSS px, браузер и его версию,
|
||||
ОС, масштаб 100%, device scale factor и высоты остальных viewport.
|
||||
- [ ] Получить исходный снимок текущего интерфейса на тех же размерах.
|
||||
- [ ] Подготовить детерминированные тестовые данные: запрос «налог на прибыль»,
|
||||
три результата из изображения, выбран первый, открыта соответствующая
|
||||
демонстрационная редакция, одинаковые фильтры и положение прокрутки.
|
||||
- [ ] Изолировать fixture от реального режима и пометить демонстрационное
|
||||
содержимое. Не добавлять подмену юридических данных в production-путь.
|
||||
- [ ] Нормализовать сохранённое изображение до 1280×800 без изменения
|
||||
пропорций и сохранить параметры подготовки эталона.
|
||||
- [ ] Записать выявленные конфликты изображения с нормативной типографикой
|
||||
и токенами; разрешить их до настройки мелких деталей.
|
||||
|
||||
Критерий завершения: один и тот же тестовый сценарий воспроизводится
|
||||
независимо от состояния OpenSearch и текущей реальной выдачи; реальный режим
|
||||
продолжает использовать API. Авторизация не ослабляется ради снимков.
|
||||
|
||||
## 4. Этап 1 — карта геометрии
|
||||
|
||||
Ниже предварительные ориентиры по вложению 1280×800. Это ещё не точные
|
||||
измерения и не универсальные CSS-константы для любого экрана.
|
||||
|
||||
| Область | Начальный ориентир |
|
||||
|---|---|
|
||||
| Шапка | y = 0–76 px |
|
||||
| Навигация и активные фильтры | y = 76–126 px |
|
||||
| Рабочая область | y = 126–743 px |
|
||||
| Footer | y = 743–800 px |
|
||||
| Фильтры | x = 0–226 px; ширина около 226 px |
|
||||
| Результаты | x = 226–648 px; ширина около 422 px |
|
||||
| Документ | x = 648–1280 px; ширина около 632 px |
|
||||
|
||||
- [ ] Уточнить координаты по исходнику и заполнить таблицу фактических
|
||||
измерений: границы, внутренние отступы, высоты полей и кнопок,
|
||||
межстрочные интервалы, положение текста и разделителей.
|
||||
- [ ] Описать поведение сетки вне 1280×800: фиксированная/ограниченная
|
||||
ширина фильтров и гибкие результаты/документ с минимальными ширинами.
|
||||
- [ ] Разделить метрики повторяемых элементов и высоты, зависящие от текста.
|
||||
Не выравнивать принудительно высоту всех результатов или разделов.
|
||||
- [ ] Определить владельца прокрутки каждой области, поведение footer
|
||||
при коротком содержимом и доступность длинного документа.
|
||||
|
||||
Критерий завершения: геометрия описана измерениями и адаптивными правилами,
|
||||
а не независимыми приблизительными настройками каждого блока.
|
||||
|
||||
## 5. Этап 2 — разделение сценариев и базовых стилей
|
||||
|
||||
- [ ] Разделить композиции поиска и лаборатории, сохранив маршруты,
|
||||
авторизацию, кабинет, управление пользователями, обучение и черновики.
|
||||
- [ ] Ограничить лабораторные элементы маршрутом `/review`, включая
|
||||
панель проверяющего и сохранения.
|
||||
- [ ] Использовать общий слой семантических токенов и базовых элементов;
|
||||
стили поискового экрана изолировать BEM-классами.
|
||||
- [ ] Устранить дублирующие и неиспользуемые правила, исправить класс статьи.
|
||||
- [ ] Убрать зависимость шапки и footer поиска от лабораторного layout.
|
||||
- [ ] Если CSS/JS/ресурсы выносятся из HTML, добавить ограниченную выдачу
|
||||
static-файлов с MIME, защитой от обхода путей и сохранением защитных
|
||||
заголовков. Убедиться, что ресурсы входят в production-образ.
|
||||
|
||||
Ожидаемые зоны изменений: `backend/search/review.html`, при необходимости
|
||||
каталог static-ресурсов рядом с ним и `backend/search/api.py`.
|
||||
Не вводить Next.js, React или новый сборщик только ради этой задачи.
|
||||
|
||||
Критерий завершения: оба сценария работают независимо, общие CSS не меняют
|
||||
их композицию случайным образом; существующие права доступа сохранены.
|
||||
|
||||
## 6. Этап 3 — шрифты, знак, орнамент и favicon
|
||||
|
||||
- [ ] Поставить локальные WOFF2 Noto Sans 400/500/600 и Noto Serif 600/700
|
||||
с лицензиями; исключить случайное синтетическое начертание.
|
||||
- [ ] Проверить загрузку, `font-display`, кириллицу и `Ө ө Ү ү Ң ң`.
|
||||
Визуальные снимки выполнять после `document.fonts.ready`.
|
||||
- [ ] Подготовить SVG-знак по визуальному направлению референса;
|
||||
сверить размер, толщину линий и положение относительно названия.
|
||||
- [ ] Подготовить отдельный симметричный золотистый SVG-орнамент,
|
||||
`aria-hidden`, без перекрытия управления и текста.
|
||||
- [ ] Подготовить favicon SVG и растровый fallback для 16×16/32×32;
|
||||
подключить в `<head>`, проверить выдачу, MIME и вид во вкладке.
|
||||
- [ ] Подготовить единые SVG-иконки поиска, очистки, календаря, печати,
|
||||
оглавления, разворачивания и стрелок; иконкам-кнопкам дать доступные имена.
|
||||
- [ ] Перенести значения в токены, не размножать HEX по компонентам.
|
||||
|
||||
Критерий завершения: шрифты реально загружены, знак и орнамент являются
|
||||
ресурсами, favicon отображается; нет CSS-заглушек вместо фирменной графики.
|
||||
|
||||
## 7. Этап 4 — сборка композиции
|
||||
|
||||
Работать от крупных областей к деталям; сначала геометрия, затем типографика.
|
||||
|
||||
- [ ] Шапка: знак, название, разделитель, подпись продукта, поле с подписью
|
||||
и очисткой, «Найти», язык интерфейса. Служебные действия доступны компактно.
|
||||
- [ ] Вторая строка: «Поиск», «Об источниках», удаляемые фильтры;
|
||||
демонстрационная подпись только для fixture. «Об источниках» открывает
|
||||
реальные сведения о происхождении данных, а не пустую заглушку.
|
||||
- [ ] Три панели: непрерывные границы, правильные фоны и пропорции,
|
||||
отсутствие лишнего свободного ряда статуса в стабильном состоянии.
|
||||
Сообщения для скринридера сохраняются.
|
||||
- [ ] Фильтры: заголовок, текстовый сброс, статус, вид, орган, даты рядом,
|
||||
орнамент в свободной нижней части без перекрытия длинного содержимого.
|
||||
- [ ] Результаты: заголовок и честный счётчик, компактная сортировка,
|
||||
строки выдачи, выбранная строка с рамкой/фоном/«Открыт», метаданные,
|
||||
безопасная подсветка выдержки, пагинация.
|
||||
- [ ] Документ: breadcrumbs и разворачивание, отдельная роль заголовка,
|
||||
компактные метаданные, язык, действия, поиск внутри, поле чтения.
|
||||
- [ ] Footer: бренд слева, фактические версии frontend/backend справа;
|
||||
не копировать устаревшую backend-версию и слово «макет» из изображения.
|
||||
|
||||
Критерий завершения: порядок, вложенность и пропорции всех крупных зон
|
||||
соответствуют эталону; нет лишних лабораторных блоков.
|
||||
|
||||
## 8. Этап 5 — рабочее поведение и интеграция
|
||||
|
||||
- [ ] Сохранить поиск, сортировку, пагинацию, загрузку редакций и языков.
|
||||
- [ ] Синхронизировать состояние с URL, восстановление по ссылке и историю
|
||||
навигации; отдельный фильтр удаляется без сброса остальных.
|
||||
- [ ] Согласовать вид фильтров с контрактом: текущий API принимает одиночные
|
||||
значения. Не имитировать множественный выбор checkbox без поддержки API.
|
||||
Если нужен multiselect, отдельно описать и проверить расширение контракта.
|
||||
- [ ] Разделить язык интерфейса, поиска и текста документа. Для RU/KY
|
||||
перевести подписи, статусы и ошибки; смена UI не подменяет текст редакции.
|
||||
- [ ] Не выдавать число на странице за общее: использовать явную подпись
|
||||
либо отдельно реализовать достоверный total с проверкой его семантики.
|
||||
- [ ] Построить оглавление по реальным заголовкам, с корректными якорями;
|
||||
при отсутствии структуры показать понятное состояние.
|
||||
- [ ] Реализовать поиск по текстовым узлам документа: ввод/очистка,
|
||||
подсветка, активное совпадение, счётчик, предыдущий/следующий,
|
||||
прокрутка и состояние нулевого результата. Не повреждать HTML,
|
||||
ссылки и таблицы; не вставлять пользовательский запрос через `innerHTML`.
|
||||
- [ ] Реализовать разворачивание/возврат с сохранением выбранной редакции,
|
||||
прокрутки и корректного фокуса.
|
||||
- [ ] Добавить печать через print CSS: документ, его реквизиты и источник
|
||||
без поисковых и служебных панелей.
|
||||
- [ ] Защитить смену запроса/документа/редакции от запоздавших ответов
|
||||
через отмену запроса или проверку актуальности результата.
|
||||
- [ ] Сохранить безопасный вывод очищенного документного HTML и ссылок,
|
||||
обработку ошибок и ограничения авторизации.
|
||||
|
||||
Критерий завершения: каждый видимый элемент эталона выполняет действие;
|
||||
нет декоративных кнопок, фиктивных языков и выдуманных юридических статусов.
|
||||
|
||||
## 9. Этап 6 — адаптивность, типографика и состояния
|
||||
|
||||
- [ ] Настроить размеры, веса, line-height и отступы после фиксации сетки.
|
||||
Сверить переносы названия документа, результатов и плотность абзацев.
|
||||
- [ ] Проверить 1280×800 и ширины 1440/1024/390 px, включая длинный контент.
|
||||
Высоты и параметры окружения записать в отчёте, breakpoints выбирать
|
||||
по фактическому помещению содержимого.
|
||||
- [ ] На узких экранах открывать фильтры отдельной доступной панелью,
|
||||
документ — отдельным представлением с возвратом к результатам.
|
||||
- [ ] Сокращать/убирать орнамент на телефоне; сохранять текст без
|
||||
горизонтальной прокрутки, таблицы — в собственной области прокрутки.
|
||||
- [ ] Проверить длинные RU/KY-названия, одноязычную редакцию, отсутствие
|
||||
текста/редакций, много фильтров, широкие таблицы, изображения и ссылки.
|
||||
- [ ] Проверить loading, empty, error, retry, disabled, hover и focus-visible;
|
||||
сообщение об ошибке не уничтожает введённый запрос или черновик.
|
||||
- [ ] Проверить Tab/Enter/Escape, возврат фокуса, доступные имена,
|
||||
live-сообщения, контраст, масштабирование и `prefers-reduced-motion`.
|
||||
Компактный desktop не уменьшает touch-области ниже требований `DESIGN.md`.
|
||||
|
||||
Критерий завершения: точность desktop не приводит к переполнению,
|
||||
недоступности действий или потере контекста на узком экране.
|
||||
|
||||
## 10. Этап 7 — визуальная приёмка
|
||||
|
||||
Выполнить один пакет первичных снимков всех контрольных размеров,
|
||||
собрать дефекты по областям, исправить одним пакетом и выполнить один
|
||||
подтверждающий проход. Новые циклы обосновывать конкретными оставшимися
|
||||
дефектами или замечаниями независимого reviewer, не бесконечной полировкой.
|
||||
|
||||
- [ ] Дождаться шрифтов, изображений и стабильных данных; отключить
|
||||
влияющую на снимок анимацию, задать исходную прокрутку.
|
||||
- [ ] Открыть каждый снимок и убедиться, что это правильный сценарий,
|
||||
а не login, ошибка, незагруженная страница или другой маршрут.
|
||||
- [ ] Для 1280×800 подготовить overlay 50%, difference image и отдельные
|
||||
сравнения шапки, фильтров, результатов, документа и footer.
|
||||
- [ ] Сохранить снимки остальных размеров и отчёт с условиями, отклонениями,
|
||||
исправлениями и известными ограничениями.
|
||||
- [ ] Передать независимому reviewer запрос пользователя, эталон,
|
||||
`DESIGN.md`, этот план, diff и снимки всех проверенных размеров.
|
||||
|
||||
Критерии для детерминированного fixture при 1280×800:
|
||||
|
||||
| Проверка | Условие приёмки |
|
||||
|---|---|
|
||||
| Границы крупных зон | Отклонение от зафиксированной карты до 2 CSS px |
|
||||
| Отступы и размеры управления | Отклонение до 2 CSS px от измерений |
|
||||
| Ключевые заголовки | Совпадают переносы при согласованных шрифтах; исключения объяснены |
|
||||
| Композиция | Все зоны и элементы эталона присутствуют, порядок совпадает |
|
||||
| Ресурсы | Загружены шрифты, знак, орнамент, favicon, единые иконки |
|
||||
| Рабочий сценарий | Поиск, фильтры, редакции, действия и навигация работают |
|
||||
| Адаптивность | Нет перекрытий, обрезанного управления и общей горизонтальной прокрутки |
|
||||
| Изоляция | Нет лабораторного оценивания на поиске, `/review` без регрессий |
|
||||
|
||||
Нулевая попиксельная разница не является критерием: сглаживание текста,
|
||||
растровая природа концепта и нормативные токены дают объяснимые различия.
|
||||
Один процент сходства всего экрана не заменяет проверки каждой области.
|
||||
Достижение допусков подтверждается измерениями, а не общей оценкой «похоже».
|
||||
|
||||
## 11. Этап 8 — проверки, версия и PR
|
||||
|
||||
Этот этап относится к реализации в feature-ветке. Frontend повышен до `0.2.0`,
|
||||
backend — до `0.13.0` для allowlist-выдачи локальных шрифтов. Контракт Search
|
||||
API v1 не менялся.
|
||||
|
||||
- [ ] Выполнить все проверки из актуальных `AGENTS.md` и CI: backend,
|
||||
Telegram bot, backup, deploy, host guard, verifier guard, shell syntax,
|
||||
Compose/Caddy и production images в предусмотренном окружении.
|
||||
- [ ] Добавить проверки фактических изменений: выдача static/favicon,
|
||||
браузерные сценарии поиска/редакций/поиска внутри/навигации и регрессии
|
||||
лаборатории. Для визуального сравнения использовать стабильный fixture.
|
||||
- [ ] Повысить frontend semver по реальному объёму: minor при добавлении
|
||||
совместимых функций; patch для одних исправлений. Backend повышать,
|
||||
если меняется его поведение; версии в footer должны быть согласованы.
|
||||
- [ ] После первого commit выполнить push, найти существующий PR ветки
|
||||
через `gitea-api`; создать один PR в `main`, только если его ещё нет.
|
||||
- [ ] После каждого push независимый reviewer проверяет полный текущий PR,
|
||||
прежние исправления и оставляет краткий PR-комментарий с явным выводом
|
||||
о наличии или отсутствии блокирующих замечаний; reviewer не редактирует код.
|
||||
- [ ] Исправить обоснованные замечания в той же ветке/PR, повторить проверки,
|
||||
commit/push и независимый review.
|
||||
- [ ] После успешных проверок и устранения блокирующих замечаний обновить
|
||||
существующий changelog, записав значимые изменения для пользователя.
|
||||
- [ ] Commit/push changelog в тот же PR, повторить обязательные проверки
|
||||
и независимый review окончательного состояния.
|
||||
|
||||
Готовность к merge: проверки проходят, финальный review не содержит
|
||||
блокирующих замечаний, changelog и версии согласованы, визуальные доказательства
|
||||
доступны reviewer. Не сливать автоматически и не развёртывать production.
|
||||
|
||||
## 12. Порядок выполнения и итоговые материалы
|
||||
|
||||
Зависимости: эталон → измерения → разделение сценариев → ресурсы → композиция
|
||||
→ поведение → адаптивность и состояния → визуальная приёмка → финальный PR.
|
||||
Не начинать микроподгонку кнопок до исправления общей геометрии.
|
||||
|
||||
Ожидаемые материалы реализации:
|
||||
|
||||
- обновлённая поисковая страница и сохранённый сценарий лаборатории;
|
||||
- локальные шрифты с лицензиями, SVG-знак, орнамент, favicon и иконки;
|
||||
- детерминированный тестовый сценарий и воспроизводимый способ снимков;
|
||||
- карта измерений, снимки, overlay/diff и отчёт приёмки;
|
||||
- результаты обязательных проверок и независимого review;
|
||||
- версии, changelog и один PR без автоматического merge.
|
||||
|
||||
Чекбоксы отмечать только после выполнения и проверки. Локальные проверки,
|
||||
которые реально выполнены, зафиксированы в отчёте visual-review.
|
||||
Этот документ не подтверждает готовность API, публичного продукта или
|
||||
production.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Приёмка поискового экрана
|
||||
|
||||
Проверка выполнена 22 октября 2026 года в Chromium 156.0.8078.4, Playwright
|
||||
1.64.1, headless, device scale factor 1. Макеты проверены при 1280×800,
|
||||
1440×900, 1024×900 и 390×844 CSS px.
|
||||
|
||||
## Снимки
|
||||
|
||||
- [1280×800 — основной экран](desktop-1280x800.png)
|
||||
- [1440 px](desktop-1440px.png)
|
||||
- [1024 px](desktop-1024px.png)
|
||||
- [390 px — мобильный просмотр документа](mobile-390px.png)
|
||||
- [Overlay 50% с приложенным референсом](overlay-50.png)
|
||||
- [Карта абсолютной разницы пикселей](pixel-difference.png)
|
||||
|
||||
## Фактическая проверка
|
||||
|
||||
- При 1280×800 шапка занимает 127 px, рабочая область — y=127–744,
|
||||
footer — y=744–800; границы колонок x=0/226/648/1280.
|
||||
- Горизонтального переполнения при 1440, 1024 и 390 px нет.
|
||||
- Загружены Noto Sans и Noto Serif, включая кириллические наборы; повторяющихся
|
||||
HTML id нет, ошибок JavaScript в сценарии не зарегистрировано.
|
||||
- Playwright проверил фильтры и URL, открытие редакции, поиск по документу
|
||||
(1-е и 2-е совпадения), независимость языка текста от языка интерфейса,
|
||||
разворачивание документа, мобильную панель фильтров и возврат к результатам,
|
||||
а также изоляцию маршрутов поиска и `/review`.
|
||||
|
||||
Для снимков Playwright перехватывал API и отдавал локальные детерминированные
|
||||
fixture-ответы. Подпись «Демонстрационные данные» добавлялась только в тестовой
|
||||
странице перед снимком. Эти юридические тексты и результаты не входят в код
|
||||
продукта. Overlay растягивает исходный растр 1586×992 до 1280×800; разница
|
||||
пропорций менее 0,1%.
|
||||
|
||||
## Оставшиеся визуальные отличия
|
||||
|
||||
Сглаживание текста и содержимое документа отличаются от растрового макета.
|
||||
Поля даты показывают системный формат Chromium. Переключатель языка интерфейса
|
||||
и поле языка поиска остаются разными состояниями. Автоматические изображения
|
||||
показывают рабочую композицию, но не являются попиксельным доказательством
|
||||
юридического содержимого или доступности во всех браузерах.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 164 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 173 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 188 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.1 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 715 KiB |
Reference in new issue
Block a user