Merge pull request 'Согласовать поиск, кабинет и лабораторию с макетом' (#56) from fix/uiux-visual-feedback into main
Reviewed-on: #56 Reviewed-by: agent <agent@vakanaut.ru>
This commit was merged in pull request #56.
This commit is contained in:
commit
8bd2b53469
9 files changed
+668
-142
No files matched your search
@@ -2,6 +2,17 @@
|
||||
|
||||
## Не выпущено
|
||||
|
||||
- Frontend `0.3.2`: устранены пересечения названия бренда с поиском и
|
||||
мобильной навигации документа; навигационные ссылки получили общие quiet и
|
||||
primary состояния.
|
||||
- Frontend `0.3.1`: уточнена компоновка поиска, лаборатории и кабинета;
|
||||
splitter сохраняет минимальную ширину панелей, а на средних экранах фильтры
|
||||
открываются доступной боковой панелью. Исправлено отображение футера на
|
||||
маршруте пользователей и browser fixture смены пароля.
|
||||
- Frontend `0.3.0` / Backend `0.13.1`: добавлен доступный splitter для
|
||||
изменения ширины результатов и документа. Язык поиска находится в фильтрах;
|
||||
состояния открытия, оглавление правовых заголовков, лаборатория и кабинет
|
||||
приведены к последовательной и компактной компоновке.
|
||||
- Frontend `0.2.6` / Backend `0.13.1`: двухпанельная компоновка поиска
|
||||
сохраняется до ширины 1175 px, чтобы три панели не обрезались при
|
||||
промежуточных ширинах окна.
|
||||
|
||||
@@ -10,7 +10,7 @@ Telegram-бот — только часть рабочего окружения
|
||||
## Текущее состояние
|
||||
|
||||
Сейчас реализованы Telegram-бот-секретарь версии `0.2.2`, backend версии
|
||||
`0.13.0` и frontend `0.2.3` с поисковым экраном и внутренней лабораторией.
|
||||
`0.13.1` и frontend `0.3.2` с поисковым экраном и внутренней лабораторией.
|
||||
Авторизация хранится в
|
||||
SQLite; первый пользователь `admin` создаётся интерактивной CLI-командой.
|
||||
Поиск расширяет аббревиатуры организационно-правовых форм и поднимает
|
||||
@@ -19,8 +19,8 @@ SQLite; первый пользователь `admin` создаётся инт
|
||||
| Компонент | Версия | Состояние |
|
||||
|---|---:|---|
|
||||
| Telegram-бот | `0.2.2` | на Synology работает `0.2.1`; обновление после слияния |
|
||||
| Backend | `0.13.0` | авторизация, поиск с фильтрами, ограниченный staging и статические ресурсы |
|
||||
| Frontend | `0.2.3` | поиск по правовой базе, просмотр редакций и внутренняя лаборатория |
|
||||
| Backend | `0.13.1` | авторизация, поиск с фильтрами, ограниченный staging и статические ресурсы |
|
||||
| Frontend | `0.3.2` | поиск по правовой базе, просмотр редакций, настраиваемая ширина панелей и внутренняя лаборатория |
|
||||
| Сбор и обработка правовых данных | `0.8.0` | добавлены relevance set и оценка выдачи |
|
||||
| RAG и база знаний | — | ещё не созданы |
|
||||
|
||||
@@ -63,4 +63,4 @@ python3 -m unittest discover -s tools/telegram-bot -v
|
||||
|
||||
---
|
||||
|
||||
Акылдаш · Telegram-бот v0.2.2 · Backend v0.13.0 · Frontend v0.2.3
|
||||
Акылдаш · Telegram-бот v0.2.2 · Backend v0.13.1 · Frontend v0.3.2
|
||||
@@ -465,7 +465,7 @@ def main() -> int:
|
||||
else:
|
||||
documents, fragments = export_bulk(arguments.input, arguments.output, arguments.index, arguments.limit)
|
||||
destination = arguments.output
|
||||
print(f"documents={documents} fragments={fragments} destination={destination}\nAkyldash · Backend v{APP_VERSION} · Frontend v0.2.6")
|
||||
print(f"documents={documents} fragments={fragments} destination={destination}\nAkyldash · Backend v{APP_VERSION} · Frontend v0.3.2")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
+338
-77
@@ -14,14 +14,14 @@
|
||||
@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; }
|
||||
: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; --sans: "Noto Sans", sans-serif; --serif: "Noto Serif", serif; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; color: var(--ink); background: #F7F2E8; }
|
||||
.review__skip { position: absolute; inset-block-start: 0; inset-inline-start: -10000px; padding: .5rem 1rem; background: var(--surface); }
|
||||
.review__skip:focus { inset-inline-start: 1rem; z-index: 2; }
|
||||
.review__header, .review__main { max-width: 1320px; margin: auto; padding-inline: clamp(1rem, 3vw, 3rem); }
|
||||
.review__header { padding-block: 0 1.5rem; background: var(--surface); border-block-end: 1px solid var(--line); }
|
||||
.review__header h1 { max-width: 24ch; margin: 1.5rem 0 .4rem; font: 700 clamp(1.75rem, 3vw, 2rem)/1.2 var(--serif); }
|
||||
.review__header h1 { max-width: none; margin: 1.5rem 0 .4rem; font: 700 clamp(1.75rem, 3vw, 2rem)/1.2 var(--serif); }
|
||||
.review__header p { max-width: 65ch; margin: 0; color: var(--muted); }
|
||||
.review__header-top { display: flex; justify-content: space-between; gap: 1rem; align-items: start; }
|
||||
.review__eyebrow { display: inline-flex; align-items: center; gap: .5rem; color: var(--ink); font: 600 1.1rem/1.25 var(--serif); }
|
||||
@@ -39,7 +39,8 @@
|
||||
button:active { scale: .96; }
|
||||
button:disabled { cursor: wait; opacity: .55; }
|
||||
.review__button--primary { background: var(--brand); color: #fff; border-color: var(--brand); }
|
||||
.review__status { min-height: 1.7rem; margin-block: 1rem; color: var(--muted); }
|
||||
.review__status { min-height: 0; margin-block: 0; color: var(--muted); }
|
||||
.review__status:not(:empty) { margin-block: .5rem; }
|
||||
.review__status--error { color: #9D2633; }
|
||||
.review__workspace { display: grid; grid-template-columns: minmax(24rem, .9fr) minmax(28rem, 1.1fr); gap: 1rem; align-items: start; }
|
||||
.review__results, .review__document { min-width: 0; background: var(--surface); border: 1px solid var(--line); border-radius: 6px; padding: clamp(1rem, 2vw, 1.5rem); }
|
||||
@@ -48,13 +49,13 @@
|
||||
.review__panel-hint { color: var(--muted); font-size: .875rem; }
|
||||
.review__results-list { display: grid; gap: .75rem; margin: 0; padding: 0; list-style: none; }
|
||||
.review__result { padding: 1rem 0; border: 0; border-block-end: 1px solid var(--line); border-radius: 0; background: var(--surface); transition-property: background-color, border-color; transition-duration: 150ms; transition-timing-function: cubic-bezier(.2, 0, 0, 1); }
|
||||
.review__result--selected { background: var(--subtle); box-shadow: none; }
|
||||
.review__result--selected { padding: 8px 10px; background: var(--subtle); box-shadow: none; }
|
||||
.review__result:first-child { border-block-start: 1px solid var(--line); }
|
||||
.review__result-title { display: flex; gap: .65rem; align-items: baseline; width: 100%; min-height: 44px; text-align: start; font-weight: 700; border: 0; padding: 0; background: none; color: var(--brand-dark); }
|
||||
.review__rank { flex: 0 0 auto; color: var(--brand); font-variant-numeric: tabular-nums; }
|
||||
.review__meta { margin-block: .5rem; color: var(--muted); font-size: .875rem; }
|
||||
.review__rating { display: grid; grid-template-columns: repeat(4, 1fr); gap: .4rem; margin-block: 1rem .75rem; padding: 0; border: 0; }
|
||||
.review__rating legend { width: 100%; margin-block-end: .35rem; font-size: .875rem; font-weight: 700; color: var(--muted); grid-column: 1 / -1; }
|
||||
.review__meta { margin-block: 4px; color: var(--muted); font-size: .875rem; }
|
||||
.review__rating { display: grid; grid-template-columns: repeat(4, 1fr); gap: .35rem; margin-block: 8px 6px; padding: 0; border: 0; }
|
||||
.review__rating legend { width: 100%; margin-block-end: 2px; font-size: .875rem; font-weight: 700; color: var(--muted); grid-column: 1 / -1; }
|
||||
.review__rating label { display: grid; place-items: center; min-width: 0; min-height: 44px; padding: .45rem .25rem; border: 1px solid var(--line); border-radius: 6px; color: var(--muted); text-align: center; font-size: .875rem; cursor: pointer; }
|
||||
.review__rating label:has(input:checked) { border-color: var(--brand); background: var(--brand); color: #fff; }
|
||||
.review__rating label:has(input:focus-visible) { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
@@ -110,7 +111,7 @@
|
||||
.search__layout { display: grid; grid-template-columns: 230px minmax(320px, .9fr) minmax(420px, 1.2fr); min-height: 65vh; border-block: 1px solid var(--line); background: var(--surface); }
|
||||
.search__filters, .search__results, .search__document { min-width: 0; padding: 1rem; }
|
||||
.search__filters, .search__results { border-inline-end: 1px solid var(--line); }
|
||||
.search__filters h2, .search__results h2, .search__document h2 { margin: 0; font: 600 1.5rem/1.3 var(--serif); }
|
||||
.search__filters > .review__panel-heading h2, .search__results > .review__panel-heading h2 { margin: 0; font: 600 1.25rem/1.3 var(--sans); }
|
||||
.search__filters .review__panel-heading, .search__results .review__panel-heading { align-items: center; }
|
||||
.search__filter { margin-block: 1.25rem; }
|
||||
.search__filter h3 { margin: 0 0 .4rem; font-size: 1rem; }
|
||||
@@ -161,9 +162,11 @@
|
||||
.review__workspace { grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); }
|
||||
.review__document { position: static; max-height: min(68dvh, 860px); overflow: auto; overscroll-behavior: contain; }
|
||||
.review__document-body { max-width: 72ch; margin-inline: auto; }
|
||||
.review__document-body > h2:first-child { font: 600 30px/38px var(--serif); }
|
||||
.review__document-body table { display: block; max-width: 100%; overflow-x: auto; }
|
||||
.review__document-body p:empty { display: none; }
|
||||
.review__document-body a { color: var(--brand-dark); text-underline-offset: .18em; }
|
||||
.review__document-meta a { color: var(--brand-dark); text-underline-offset: .18em; }
|
||||
.search__layout[data-filters-hidden="true"] { grid-template-columns: minmax(320px, .8fr) minmax(0, 1.5fr); }
|
||||
.search__layout[data-filters-hidden="true"] .search__filters { display: none; }
|
||||
.search__layout.is-expanded { position: fixed; z-index: 15; inset: 0; display: block; overflow: auto; background: var(--surface); }
|
||||
@@ -178,14 +181,15 @@
|
||||
.search__layout:not([data-has-document="true"]) .search__toc,
|
||||
.search__layout:not([data-has-document="true"]) #document-source { display: none; }
|
||||
.search__layout:not([data-has-document="true"]) .search__document-body { display: none; }
|
||||
.search__layout:not([data-has-document="true"]) .search__document-head h2 { display: none; }
|
||||
.search__mobile-filters { display: inline-flex; }
|
||||
.search__account button { display: inline-flex; width: auto; min-height: 44px; gap: 8px; align-items: center; padding: 8px 12px; }
|
||||
.search__account-label { display: inline; }
|
||||
.search__document-body table, .review__document-body table { display: block; max-width: 100%; overflow-x: auto; }
|
||||
.search__table-scroll { max-width: 100%; margin-block: 1rem; overflow-x: auto; overscroll-behavior-inline: contain; }
|
||||
.search__table-scroll table { width: max-content; min-width: 100%; border-collapse: collapse; }
|
||||
.search__filters .review__panel-heading { align-items: center; flex-wrap: wrap; }
|
||||
.search__filters .review__panel-heading h2 { flex: 1 1 auto; }
|
||||
.search__filters .review__panel-heading { align-items: center; flex-wrap: nowrap; justify-content: space-between; gap: 8px; }
|
||||
.search__filters .review__panel-heading h2 { flex: 0 1 auto; white-space: nowrap; }
|
||||
.search__filters .review__panel-heading button { flex: 0 0 auto; }
|
||||
.search__filter label { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 8px; min-height: 40px; }
|
||||
.search__filter label span { min-width: 0; overflow-wrap: anywhere; }
|
||||
@@ -212,6 +216,8 @@
|
||||
body.is-users-route { min-height: 100dvh; display: flex; flex-direction: column; }
|
||||
body.is-users-route > .review__header { display: block; width: 100%; padding-block-end: 0; }
|
||||
body.is-users-route > .review__header > .review__header-content { display: none; }
|
||||
body.is-users-route > .review__actions { display: none; }
|
||||
body.is-users-route > .search__footer { display: none; }
|
||||
body.is-users-route > footer.review__header { display: block; margin-block-start: auto; }
|
||||
.review__users-page { width: min(1200px, 100%); flex: 1; margin-inline: auto; padding: 28px clamp(16px, 4vw, 48px); }
|
||||
.review__users-page[hidden] { display: none !important; }
|
||||
@@ -233,7 +239,6 @@
|
||||
.search__layout:not([data-filters-hidden="true"]) .search__filters > .search__dates,
|
||||
.search__layout:not([data-filters-hidden="true"]) .search__filters > .search__date-label,
|
||||
.search__layout:not([data-filters-hidden="true"]) .search__filters > #filter-fields { grid-column: 1 / -1; }
|
||||
.search__filters .search__ornament { display: none; }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
body:has(.search:not([hidden])) { height: auto; min-height: 100dvh; overflow: visible; }
|
||||
@@ -281,12 +286,11 @@
|
||||
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(390px, 430px) minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 5px 26px; 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__topbar { min-height: var(--search-header-height); display: grid; grid-template-columns: 166px minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 5px 26px; border-block-end: 1px solid var(--line); }
|
||||
.search__brand { display: flex; min-width: 0; align-items: center; gap: 8px; 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__brand-name { font: 700 22px/1.1 var(--serif); }
|
||||
.search__brand-divider, .search__brand-description { display: none; }
|
||||
.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; }
|
||||
@@ -300,9 +304,10 @@
|
||||
.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 { width: 40px; min-height: 40px; padding: 8px; }
|
||||
.search__account-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-block-end: 16px; }
|
||||
.search__account-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-block: 24px 0; }
|
||||
.search__subnav { min-height: var(--search-nav-height); display: flex; align-items: center; gap: 12px; padding: 6px 26px; overflow-x: auto; white-space: nowrap; }
|
||||
.search__subnav a, .search__subnav button { min-height: 36px; padding: 5px 14px; text-decoration: none; }
|
||||
.search__subnav a, .search__subnav button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 5px 14px; text-align: center; text-decoration: none; }
|
||||
.search__subnav a:not(.is-active) { color: var(--ink); }
|
||||
.search__mobile-filters, .search__mobile-back, .search__filter-close, .search__filter-overlay { display: none; }
|
||||
.search__subnav a.is-active { min-width: 97px; background: var(--brand); color: #fff; border-color: var(--brand); }
|
||||
.search__subnav .search__nav-text { margin-inline: 11px 28px; padding-inline: 0; border: 0; color: var(--ink); font-size: 13px; }
|
||||
@@ -311,8 +316,7 @@
|
||||
.search__chips .search__chip { padding-inline: 4px; }
|
||||
.search__chips .search__chip button { width: 16px; }
|
||||
.search__language-chip { padding-inline: 4px; }
|
||||
.search__language-chip select { width: 78px; min-width: 0; min-height: 24px; border: 0; padding: 0 12px 0 0; background: transparent; font-size: 14px; }
|
||||
html[lang="ky"] .search__language-chip select { width: 100px; }
|
||||
.search__language-chip select { width: auto; min-width: 126px; min-height: 36px; border: 0; padding: 0 12px 0 0; background: transparent; 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; }
|
||||
@@ -320,7 +324,9 @@
|
||||
.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 { margin-block-end: 8px; }
|
||||
#search-filters > .review__panel-heading { margin-block-end: 0; }
|
||||
#search-filters > .search__filter-language { margin-block-start: 0; }
|
||||
.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 16px; }
|
||||
.search__filter--document-type { margin-block-end: 24px; }
|
||||
@@ -340,7 +346,6 @@
|
||||
.search__dates label:not(.has-value) input { color: transparent; }
|
||||
.search__date-placeholder { position: absolute; inset-inline-start: 9px; inset-block-start: 50%; color: var(--muted); font-size: 14px; pointer-events: none; transform: translateY(-50%); }
|
||||
.search__dates label.has-value .search__date-placeholder { display: none; }
|
||||
.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: 0; }
|
||||
.search__results .review__panel-heading select { min-height: 40px; padding: 6px 10px; font-size: 14px; }
|
||||
@@ -363,7 +368,7 @@
|
||||
.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 4px; color: var(--ink); font: 700 36px/1 var(--serif); }
|
||||
.search__document-head h2 { grid-column: 1 / -1; margin-block: 0 4px; color: var(--ink); font: 600 30px/38px 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; padding: 0; border: 0; color: var(--muted); }
|
||||
.search__document-meta a { color: var(--brand); }
|
||||
@@ -374,7 +379,7 @@
|
||||
.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 { display: inline-flex; align-items: center; gap: 6px; margin-inline-start: auto; font-size: 12px; }
|
||||
.search__document-language select { min-height: 28px; max-width: 130px; padding: 4px 8px; font-size: 14px; }
|
||||
.search__toc { margin-block-end: 0; }
|
||||
.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; }
|
||||
@@ -428,8 +433,11 @@
|
||||
.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; }
|
||||
.search__document-head { grid-template-columns: minmax(0, 1fr); }
|
||||
.search__document-head > div:nth-child(2) { display: flex; justify-content: space-between; gap: 8px; }
|
||||
.search__breadcrumbs { min-width: 0; flex-wrap: wrap; }
|
||||
.search__breadcrumbs #document-breadcrumb { min-width: 0; overflow-wrap: anywhere; }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.search__topbar { grid-template-columns: minmax(0,1fr) auto; gap: 8px; padding: 10px 16px; }
|
||||
@@ -466,6 +474,7 @@
|
||||
body.is-users-route { width: 100%; height: auto; min-height: 100dvh; overflow: visible; display: flex; flex-direction: column; }
|
||||
body.is-users-route > header.review__header { display: block; width: 100%; padding-block-end: 0; }
|
||||
body.is-users-route > header.review__header > .review__header-content { display: none; }
|
||||
body.is-users-route > .review__actions { display: none; }
|
||||
body.is-users-route > footer.review__header { display: block; width: 100%; margin-block-start: auto; }
|
||||
.search__layout { grid-template-columns: clamp(256px, 19.45vw, 280px) clamp(360px, 30vw, 408px) minmax(560px, 1fr); }
|
||||
.search__account button { width: auto; min-width: 44px; min-height: 44px; padding: 8px 12px; }
|
||||
@@ -486,14 +495,134 @@
|
||||
.review__nav-links { order: 3; width: 100%; flex-wrap: wrap; }
|
||||
.review__nav-account { margin-inline-start: auto; }
|
||||
}
|
||||
/* Shared follow-up corrections: consistent navigation, compact public search,
|
||||
and a continuous workspace that keeps controls aligned to the same shell. */
|
||||
.review__nav { width: min(100%, 1440px); max-width: 1440px; }
|
||||
.review__nav-links a, .review__nav-links button, #search-review-nav {
|
||||
display: inline-flex; align-items: center; justify-content: center; min-height: 44px;
|
||||
padding: 8px 14px; border: 1px solid var(--line); border-radius: 6px;
|
||||
color: var(--brand); background: var(--surface); text-decoration: none; font: inherit;
|
||||
}
|
||||
.review__nav-links a:hover, .review__nav-links button:hover, #search-review-nav:hover { border-color: var(--line); background: var(--surface-muted); color: var(--brand); }
|
||||
.review__nav-links .is-active, #search-review-nav.is-active { border-color: var(--brand); background: var(--brand); color: #fff; }
|
||||
.review__nav-links .is-active:hover, #search-review-nav.is-active:hover { border-color: var(--brand-dark); background: var(--brand-dark); color: #fff; }
|
||||
.review__nav-links a:focus-visible, .search__subnav a:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.review__nav-links [hidden], .search__account-actions [hidden] { display: none !important; }
|
||||
.review__nav-account > span { color: var(--muted); }
|
||||
.review__header-content { width: 100%; max-width: none; padding-inline: 24px; }
|
||||
body:has(#review:not([hidden])) { min-height: 100dvh; height: 100dvh; overflow: hidden; }
|
||||
body:has(#review:not([hidden])) > .review__header { padding: 0; }
|
||||
body:has(#review:not([hidden])) > #review { width: 100%; max-width: none; min-height: 0; margin: 0; padding: 0; display: flex; flex-direction: column; }
|
||||
body:has(#review:not([hidden])) > .review__actions { width: 100%; min-height: 96px; flex: 0 0 96px; box-sizing: border-box; margin: 0; padding: 0 24px; }
|
||||
body:has(#review:not([hidden])) > footer.review__header { width: 100%; margin: 0; }
|
||||
.review__header-content, .review__actions-inner { width: 100%; max-width: none; }
|
||||
body:has(#review:not([hidden])) .review__nav { height: 64px; min-height: 64px; padding-block: 0; }
|
||||
body:has(#review:not([hidden])) .review__header-content { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; height: 64px; }
|
||||
body:has(#review:not([hidden])) .review__heading-copy { min-width: 0; display: grid; grid-template-rows: 32px 20px; align-content: center; }
|
||||
body:has(#review:not([hidden])) .review__header-top { grid-column: 2; grid-row: 1; align-self: center; padding: 0; }
|
||||
body:has(#review:not([hidden])) .review__header-content h1 { max-width: none; margin: 0; font: 600 26px/32px var(--sans); }
|
||||
body:has(#review:not([hidden])) .review__header-content p { max-width: none; margin: 0; font: 400 14px/20px var(--sans); white-space: nowrap; }
|
||||
.review__search { gap: 12px; padding: 12px 24px; border: 0; border-block-end: 1px solid var(--line); border-radius: 0; background: transparent; }
|
||||
#status.review__status { grid-column: 1 / -1; margin: 0; }
|
||||
#status.review__status:empty { display: none; }
|
||||
#status.review__status--success { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.review__workspace { min-height: 0; flex: 1 1 0; grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); gap: 0; align-items: stretch; overflow: hidden; border-block: 1px solid var(--line); background: var(--surface); }
|
||||
.review__results, .review__document { min-height: 0; max-height: none; padding: 14px 24px; border: 0; border-radius: 0; background: var(--surface); }
|
||||
.review__results { overflow: auto; border-inline-end: 1px solid var(--line); }
|
||||
.review__document { position: static; overflow: auto; overscroll-behavior: contain; }
|
||||
.review__document-meta { overflow-wrap: anywhere; }
|
||||
.review__actions-inner { padding: 5px 24px; border: 0; border-block-start: 1px solid var(--line); border-radius: 0; background: transparent; }
|
||||
body:has(#review:not([hidden])) > footer.review__header { height: 44px; min-height: 44px; }
|
||||
body:has(#review:not([hidden])) > footer.review__header .review__header-content { display: flex; align-items: center; height: 44px; padding-block: 0; }
|
||||
.search__subnav { flex-wrap: wrap; overflow: visible; white-space: normal; }
|
||||
.search__subnav a.is-active { min-width: 0; text-align: center; }
|
||||
.search__nav-text { flex: 0 0 auto; }
|
||||
.search__chips { flex: 1 1 8rem; }
|
||||
.search__filter-language { display: grid; gap: 5px; margin-block: 0 16px; color: var(--muted); font-size: .875rem; font-weight: 600; }
|
||||
.search__filter-language select { min-height: 42px; width: 100%; padding: 7px 10px; color: var(--ink); background: var(--surface); border: 1px solid var(--line); }
|
||||
.search__layout { grid-template-columns: minmax(264px, clamp(264px, calc(20vw + 8px), 288px)) minmax(360px, 38.1fr) 8px minmax(560px, 61.9fr); }
|
||||
.search__layout[data-filters-hidden="true"] { grid-template-columns: minmax(360px, 38.1fr) 8px minmax(560px, 61.9fr); }
|
||||
.search__filters { margin-inline-end: 8px; }
|
||||
.search__mobile-filters { display: inline-flex; }
|
||||
.search__layout[data-filters-hidden="true"] .search__filters { display: none; }
|
||||
.search__splitter { position: relative; z-index: 1; align-self: stretch; justify-self: center; width: 12px; min-width: 12px; min-height: 100%; margin-inline: -2px; padding: 0; border: 0; border-radius: 0; background: linear-gradient(90deg, transparent 2px, var(--surface-muted) 2px 10px, transparent 10px); cursor: col-resize; touch-action: none; }
|
||||
.search__splitter::before { position: absolute; inset-block: 0; inset-inline-start: 50%; width: 1px; background: var(--line); content: ''; transform: translateX(-50%); }
|
||||
.search__splitter::after { position: absolute; inset-block-start: 50%; inset-inline-start: 50%; width: 3px; height: 40px; border-radius: 2px; background: var(--muted); content: ''; transform: translate(-50%, -50%); }
|
||||
.search__splitter:hover::after, .search__splitter:focus-visible::after { background: var(--brand); }
|
||||
body:has(#review:not([hidden])) > .review__header, body:has(#review:not([hidden])) > footer.review__header { width: 100%; max-width: none; margin: 0; padding-inline: 0; }
|
||||
body:has(#review:not([hidden])) .review__nav, body:has(#review:not([hidden])) .review__header-content { width: 100%; max-width: none; padding-inline: 24px; }
|
||||
body:has(#review:not([hidden])) .review__header-content h1 { font: 600 26px/32px var(--sans); }
|
||||
body:has(#review:not([hidden])) .review__panel-heading h2 { font: 600 20px/26px var(--sans); }
|
||||
body.is-users-route > .search__footer { display: none !important; }
|
||||
|
||||
.search__pagination[hidden] { display: none; }
|
||||
.search__document-language[hidden] { display: none; }
|
||||
.search__account-actions { display: grid; grid-template-columns: max-content max-content; justify-content: start; gap: 8px; }
|
||||
.search__account-actions a { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); color: var(--brand-dark); font-weight: 600; text-decoration: none; }
|
||||
.search__account-actions a:hover { border-color: var(--brand); background: var(--subtle); }
|
||||
#search-logout { grid-column: 1 / -1; justify-self: start; min-height: 36px; margin-block-start: 2px; padding-inline: 0; border: 0; color: var(--muted); background: transparent; }
|
||||
#account-dialog dl { display: grid; grid-template-columns: minmax(7.5rem, max-content) minmax(0, 1fr); gap: 8px 16px; margin: 16px 0 24px; }
|
||||
#account-dialog { width: min(560px, calc(100vw - 32px)); max-width: none; }
|
||||
#account-dialog > .review__page { padding: 16px; }
|
||||
#account-dialog dt { color: var(--muted); }
|
||||
#account-dialog dd { min-width: 0; margin: 0; overflow-wrap: anywhere; }
|
||||
#account-dialog .review__dialog-heading { inset-block-start: -16px; align-items: center; min-height: 44px; height: 44px; margin: -16px -16px 12px; padding: 0 16px; }
|
||||
.review__password-field { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; }
|
||||
.review__password-field input { min-width: 0; }
|
||||
.review__password-toggle { min-height: 44px; padding-inline: 10px; white-space: nowrap; }
|
||||
#account-dialog .review__dialog-heading h2 { max-width: none; padding: 0; font: 600 20px/28px var(--sans); }
|
||||
#account-dialog .review__dialog-heading button { display: grid; place-items: center; flex: 0 0 44px; width: 44px; min-height: 44px; padding: 0; }
|
||||
#public-document-body img, #document-body img { max-width: 100%; height: auto; object-fit: contain; }
|
||||
@media (min-width: 901px) and (max-width: 1191px) {
|
||||
#search-layout { grid-template-columns: minmax(360px, 38.1fr) minmax(560px, 61.9fr); }
|
||||
#search-layout .search__filters { display: none; }
|
||||
#search-layout .search__filters.is-open { position: fixed; z-index: 21; inset: 16px auto 16px 16px; display: block; width: min(360px, calc(100vw - 32px)); overflow: auto; padding: 20px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); box-shadow: 0 12px 40px rgb(34 28 28 / .2); }
|
||||
.search__filter-close { display: inline-flex; }
|
||||
.search__filter-overlay.is-open { position: fixed; z-index: 20; inset: 0; display: block; background: rgb(56 38 42 / .42); }
|
||||
.search__splitter { display: none; }
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
body:has(#review:not([hidden])) { min-height: 100svh; height: auto; overflow: visible; }
|
||||
body:has(#review:not([hidden])) > #review { flex: none; padding-inline: 16px; }
|
||||
body:has(#review:not([hidden])) .review__nav, body:has(#review:not([hidden])) .review__header-content { padding-inline: 16px; }
|
||||
body:has(#review:not([hidden])) .review__header-content { display: flex; flex-direction: column; align-items: stretch; gap: 8px; height: auto; padding-block: 12px; }
|
||||
body:has(#review:not([hidden])) .review__heading-copy { display: block; }
|
||||
body:has(#review:not([hidden])) .review__header-top { align-self: flex-start; }
|
||||
.review__search { padding-inline: 16px; }
|
||||
body:has(#review:not([hidden])) .review__header-top { padding-block: 0 8px; }
|
||||
body:has(#review:not([hidden])) .review__header-content h1, body:has(#review:not([hidden])) .review__header-content p { display: block; }
|
||||
body:has(#review:not([hidden])) .review__header-content p { white-space: normal; }
|
||||
body:has(#review:not([hidden])) > footer.review__header { height: auto; min-height: 44px; }
|
||||
.review__workspace { min-height: 0; max-height: none; flex: none; display: grid; grid-template-columns: minmax(0, 1fr); overflow: visible; }
|
||||
.review__results, .review__document { max-height: none; overflow: visible; border-inline: 0; }
|
||||
.review__results { border-block-end: 1px solid var(--line); }
|
||||
.review__document { display: block; }
|
||||
.review__results, .review__document { padding-inline: 16px; }
|
||||
body:has(#review:not([hidden])) > .review__actions { flex: 0 0 auto; padding-inline: 0; }
|
||||
.review__actions-inner { padding-inline: 16px; }
|
||||
body:has(#review:not([hidden])) > footer.review__header { height: auto; min-height: 44px; }
|
||||
.search__layout, .search__layout[data-filters-hidden="true"] { display: block; }
|
||||
.search__splitter { display: none; }
|
||||
.search__filter-language { margin-block-end: 16px; }
|
||||
.search__filters { display: none; }
|
||||
.search__filters.is-open { display: block; }
|
||||
.search__mobile-filters { display: inline-flex; }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.search__subnav { gap: 4px; padding-inline: 12px; }
|
||||
.search__subnav a, .search__subnav button { padding-inline: 10px; }
|
||||
.search__chips { flex: 1 1 100%; order: 4; }
|
||||
.search__account { margin-inline-start: auto; }
|
||||
#account-dialog dl { grid-template-columns: minmax(0, 1fr); gap: 2px; }
|
||||
#account-dialog dd { margin-block-end: 10px; }
|
||||
}
|
||||
</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="review-search-nav" href="/">Поиск</a><a id="review-review-nav" href="/review">Лаборатория</a><button id="review-account-open" type="button">Личный кабинет</button><a id="review-users-open" href="/users" hidden>Пользователи</a></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 id="route-heading">Проверка качества поиска</h1><p id="route-description">Сопоставляйте запрос с текстом документов и сохраняйте оценку выдачи.</p></div>
|
||||
<div class="review__header-content"><div class="review__heading-copy"><h1 id="route-heading">Проверка качества поиска</h1><p id="route-description">Сопоставляйте запрос с текстом документов и сохраняйте оценку выдачи.</p></div><div class="review__header-top"><button id="tutorial-open" type="button">Как это работает</button></div></div>
|
||||
</header>
|
||||
<header class="search__chrome" aria-label="Акылдаш">
|
||||
<div class="search__topbar">
|
||||
@@ -504,7 +633,7 @@
|
||||
<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><label class="search__chip search__language-chip"><span class="search__sr-only">Язык поиска</span><select id="public-language" aria-label="Язык поиска"><option value="ru">Русский</option><option value="ky">Кыргызский</option></select></label><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" class="search__sr-only"></span><button id="search-account-open" type="button" aria-label="Личный кабинет" title="Личный кабинет"><svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><circle cx="12" cy="8" r="3.5" fill="none" stroke="currentColor" stroke-width="1.7"/><path d="M5 20c.5-3.5 3-5.5 7-5.5s6.5 2 7 5.5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg><span class="search__account-label">Кабинет</span></button></div></nav>
|
||||
<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="search-review-nav" href="/review">Лаборатория</a><button class="search__mobile-filters" id="mobile-filters-open" type="button" aria-controls="search-filters" aria-expanded="false">Фильтры</button><div class="search__chips" id="active-filters" aria-label="Активные фильтры"></div><div class="search__account"><span id="signed-in-user" class="search__sr-only"></span><button id="search-account-open" type="button" aria-label="Личный кабинет" title="Личный кабинет"><svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><circle cx="12" cy="8" r="3.5" fill="none" stroke="currentColor" stroke-width="1.7"/><path d="M5 20c.5-3.5 3-5.5 7-5.5s6.5 2 7 5.5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg><span class="search__account-label">Кабинет</span></button></div></nav>
|
||||
</header>
|
||||
<main class="review__main" id="review">
|
||||
<form class="review__search" id="search-form">
|
||||
@@ -512,8 +641,8 @@
|
||||
<label class="review__field review__field--small">Язык запроса<select id="language" name="language"><option value="ru">Русский</option><option value="ky">Кыргызский</option></select></label>
|
||||
<label class="review__field review__field--small">Результатов<select id="page-size" name="page_size"><option>10</option><option>20</option></select></label>
|
||||
<button class="review__button--primary" type="submit">Показать результаты</button>
|
||||
<div class="review__status" id="status" role="status" aria-live="polite"></div>
|
||||
</form>
|
||||
<div class="review__status" id="status" role="status" aria-live="polite"></div>
|
||||
<div class="review__workspace">
|
||||
<section class="review__results" aria-labelledby="results-heading"><div class="review__panel-heading"><h2 id="results-heading">Результаты поиска</h2><span class="review__panel-hint">Оцените каждый документ</span></div><ol class="review__results-list" id="results"><li class="review__empty"><strong>Начните с запроса</strong>Введите юридический вопрос выше, чтобы увидеть результаты.</li></ol></section>
|
||||
<section class="review__document" id="document-panel" aria-labelledby="document-heading"><div class="review__panel-heading"><h2 id="document-heading">Просмотр документа</h2><span class="review__panel-hint">Откройте результат</span></div><div class="review__document-meta" id="document-meta">Выберите название в списке, чтобы прочитать документ.</div><article class="review__document-body" id="document-body"></article></section>
|
||||
@@ -522,16 +651,17 @@
|
||||
<main class="search" id="search-page" hidden>
|
||||
<h1 class="search__sr-only">Поиск по правовой базе</h1>
|
||||
<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><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="Дата принятия от"><span class="search__date-placeholder" aria-hidden="true">От</span></label><label><span class="search__sr-only">Дата принятия до</span><input id="date-to" type="date" aria-label="Дата принятия до"><span class="search__date-placeholder" aria-hidden="true">До</span></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 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><label class="search__filter-language search__language-chip"><span>Язык поиска</span><select id="public-language" aria-label="Язык поиска"><option value="ru">Русский</option><option value="ky">Кыргызский</option></select></label><div id="filter-fields"></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="Дата принятия от"><span class="search__date-placeholder" aria-hidden="true">От</span></label><label><span class="search__sr-only">Дата принятия до</span><input id="date-to" type="date" aria-label="Дата принятия до"><span class="search__date-placeholder" aria-hidden="true">До</span></label></div></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" data-state="initial"><li class="review__empty">Введите запрос, чтобы начать поиск.</li></ol><div class="search__pagination" hidden><button id="page-prev" type="button" disabled>Назад</button><span id="page-label">Страница 1</span><button id="page-next" type="button" disabled>Далее</button></div></section>
|
||||
<button class="search__splitter" id="search-splitter" type="button" role="separator" aria-orientation="vertical" aria-controls="public-results public-document-panel" aria-label="Изменить ширину списка результатов и документа" aria-valuemin="25" aria-valuemax="55" aria-valuenow="36" tabindex="0"></button>
|
||||
<section class="search__document" id="public-document-panel" aria-labelledby="public-document-heading"><div class="search__document-head"><div class="search__breadcrumbs" hidden><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" hidden>Язык<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.6 <span aria-hidden="true">·</span> Backend v0.13.1</span></footer>
|
||||
<footer class="search__footer"><span><strong>Акылдаш</strong> <span aria-hidden="true">·</span> Правовая база Кыргызстана</span><span>Frontend v0.3.2 <span aria-hidden="true">·</span> Backend v0.13.1</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" disabled>Сначала выполните поиск</button><p id="draft-status" class="review__status" role="status" aria-live="polite">Черновик появится после поиска.</p></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><div class="review__account-tabs" role="tablist" aria-label="Разделы личного кабинета"><button id="profile-tab" type="button" role="tab" aria-controls="profile-panel" aria-selected="true">Профиль</button><button id="security-tab" type="button" role="tab" aria-controls="security-panel" aria-selected="false" tabindex="-1">Безопасность</button></div><section id="profile-panel" role="tabpanel" aria-labelledby="profile-tab"><nav class="search__account-actions" aria-label="Действия учетной записи"><a id="review-nav" href="/review">Лаборатория</a><button id="search-users-open" type="button" hidden>Пользователи</button><button id="search-logout" type="button">Выйти</button></nav><dl><dt>Логин</dt><dd id="profile-username"></dd><dt>Роль</dt><dd id="profile-role">Администратор</dd><dt>Дата создания</dt><dd id="profile-created"></dd></dl></section><section id="security-panel" role="tabpanel" aria-labelledby="security-tab" hidden><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><label>Повторите новый пароль<input id="profile-confirm-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></section></dialog>
|
||||
<dialog id="account-dialog" aria-labelledby="account-heading"><section class="review__page"><h2 id="account-heading">Личный кабинет</h2><div class="review__account-tabs" role="tablist" aria-label="Разделы личного кабинета"><button id="profile-tab" type="button" role="tab" aria-controls="profile-panel" aria-selected="true">Профиль</button><button id="security-tab" type="button" role="tab" aria-controls="security-panel" aria-selected="false" tabindex="-1">Безопасность</button></div><section id="profile-panel" role="tabpanel" aria-labelledby="profile-tab"><dl><dt>Логин</dt><dd id="profile-username"></dd><dt>Роль</dt><dd id="profile-role">Администратор</dd><dt>Дата создания</dt><dd id="profile-created"></dd></dl><nav class="search__account-actions" aria-label="Действия учетной записи"><a id="review-nav" href="/review">Лаборатория</a><a id="search-users-open" href="/users" hidden>Управление пользователями</a><button id="search-logout" type="button">Выйти</button></nav></section><section id="security-panel" role="tabpanel" aria-labelledby="security-tab" hidden><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><label>Повторите новый пароль<input id="profile-confirm-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></div></form></section></section></dialog>
|
||||
<main class="review__users-page" id="users-page" hidden>
|
||||
<div class="review__users-heading"><div><h2 id="users-heading">Пользователи</h2><p id="users-description">Права на действия определяются сервером.</p></div><div class="review__users-actions"><div class="search__ui-language" role="group" aria-label="Язык интерфейса"><button id="users-ui-ru" type="button" aria-pressed="true">RU</button><span aria-hidden="true">/</span><button id="users-ui-ky" type="button" aria-pressed="false">KY</button></div><button id="create-user-open" class="review__button--primary" type="button">Создать пользователя</button></div></div>
|
||||
<p id="users-list-error" role="alert" class="review__status review__status--error"></p>
|
||||
@@ -545,7 +675,7 @@
|
||||
<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.2.6 · Backend v0.13.1 · Внутренняя лаборатория релевантности</div></footer>
|
||||
<footer class="review__header"><div class="review__header-content">Акылдаш · Frontend v0.3.2 · Backend v0.13.1 · Внутренняя лаборатория релевантности</div></footer>
|
||||
<script>
|
||||
document.body.classList.add('review__locked');
|
||||
const DRAFT_KEY = 'akyldash-search-review-draft';
|
||||
@@ -567,8 +697,8 @@
|
||||
};
|
||||
const copy = (key) => searchCopy[uiLanguage][key];
|
||||
const modalCopy = {
|
||||
ru: {account: 'Личный кабинет', lab: 'Лаборатория', users: 'Пользователи', logout: 'Выйти', role: 'Роль', admin: 'Администратор', created: 'Дата создания', changePassword: 'Изменить пароль', passwordRequirement: 'Новый пароль должен содержать не менее 12 символов.', currentPassword: 'Текущий пароль', newPassword: 'Новый пароль', confirmPassword: 'Повторите новый пароль', change: 'Изменить пароль', close: 'Закрыть', usersHeading: 'Управление пользователями', temporaryPassword: 'Временный пароль', temporaryPasswordHelp: 'Пароль — от 12 символов. Новый пользователь сменит его при первом входе. Передайте временный пароль отдельно.', createUser: 'Создать пользователя', sourcesHeading: 'Источники документов', sourceIntro: 'Поиск выполняется по документам, подготовленным из правовых источников Кыргызской Республики. Для каждого результата доступная редакция и ссылка на официальный источник показываются в панели документа.', officialSource: 'Официальный источник:', sourceName: 'Централизованный банк данных правовой информации Министерства юстиции Кыргызской Республики', loginHeading: 'Вход в Акылдаш', loginHelp: 'Введите учетные данные, выданные администратором.', username: 'Логин', password: 'Пароль', login: 'Войти', newPasswordHeading: 'Создайте новый пароль', newPasswordHelp: 'Для продолжения замените временный пароль. Используйте не менее 12 символов.', loginError: 'Не удалось войти. Проверьте логин и пароль.', passwordMismatch: 'Новые пароли не совпадают.', passwordChangeError: 'Не удалось изменить пароль.', usersLoadError: 'Не удалось загрузить список пользователей.', passwordResetError: 'Не удалось сбросить пароль.', userDeleteError: 'Не удалось удалить учетную запись.', userCreateError: 'Не удалось создать учетную запись.'},
|
||||
ky: {account: 'Жеке кабинет', lab: 'Лаборатория', users: 'Колдонуучулар', logout: 'Чыгуу', role: 'Ролу', admin: 'Администратор', created: 'Түзүлгөн күнү', changePassword: 'Сырсөздү өзгөртүү', passwordRequirement: 'Жаңы сырсөз кеминде 12 белгиден турушу керек.', currentPassword: 'Учурдагы сырсөз', newPassword: 'Жаңы сырсөз', confirmPassword: 'Жаңы сырсөздү кайталаңыз', change: 'Сырсөздү өзгөртүү', close: 'Жабуу', usersHeading: 'Колдонуучуларды башкаруу', temporaryPassword: 'Убактылуу сырсөз', temporaryPasswordHelp: 'Сырсөз кеминде 12 белгиден турушу керек. Жаңы колдонуучу биринчи киргенде аны өзгөртөт. Убактылуу сырсөздү өзүнчө жөнөтүңүз.', createUser: 'Колдонуучу түзүү', sourcesHeading: 'Документтердин булактары', sourceIntro: 'Издөө Кыргыз Республикасынын укуктук булактарынан даярдалган документтер боюнча жүргүзүлөт. Ар бир документ үчүн жеткиликтүү редакция жана расмий булактын шилтемеси көрсөтүлөт.', officialSource: 'Расмий булак:', sourceName: 'Кыргыз Республикасынын Юстиция министрлигинин укуктук маалыматтарынын борборлоштурулган банкы', loginHeading: 'Акылдашка кирүү', loginHelp: 'Администратор берген эсептик дайындарды киргизиңиз.', username: 'Колдонуучунун аты', password: 'Сырсөз', login: 'Кирүү', newPasswordHeading: 'Жаңы сырсөз түзүңүз', newPasswordHelp: 'Улантуу үчүн убактылуу сырсөздү алмаштырыңыз. Кеминде 12 белги колдонуңуз.', loginError: 'Кирүү мүмкүн болгон жок. Колдонуучунун атын жана сырсөздү текшериңиз.', passwordMismatch: 'Жаңы сырсөздөр дал келген жок.', passwordChangeError: 'Сырсөздү өзгөртүү мүмкүн болгон жок.', usersLoadError: 'Колдонуучулардын тизмесин жүктөө мүмкүн болгон жок.', passwordResetError: 'Сырсөздү баштапкы абалга келтирүү мүмкүн болгон жок.', userDeleteError: 'Колдонуучуну өчүрүү мүмкүн болгон жок.', userCreateError: 'Колдонуучуну түзүү мүмкүн болгон жок.'}
|
||||
ru: {account: 'Личный кабинет', lab: 'Лаборатория', users: 'Пользователи', logout: 'Выйти', role: 'Роль', admin: 'Администратор', created: 'Дата создания', changePassword: 'Изменить пароль', passwordRequirement: 'Новый пароль должен содержать не менее 12 символов.', currentPassword: 'Текущий пароль', newPassword: 'Новый пароль', confirmPassword: 'Повторите новый пароль', change: 'Изменить пароль', close: 'Закрыть', showPassword: 'Показать пароль', hidePassword: 'Скрыть пароль', usersHeading: 'Управление пользователями', temporaryPassword: 'Временный пароль', temporaryPasswordHelp: 'Пароль — от 12 символов. Новый пользователь сменит его при первом входе. Передайте временный пароль отдельно.', createUser: 'Создать пользователя', sourcesHeading: 'Источники документов', sourceIntro: 'Поиск выполняется по документам, подготовленным из правовых источников Кыргызской Республики. Для каждого результата доступная редакция и ссылка на официальный источник показываются в панели документа.', officialSource: 'Официальный источник:', sourceName: 'Централизованный банк данных правовой информации Министерства юстиции Кыргызской Республики', loginHeading: 'Вход в Акылдаш', loginHelp: 'Введите учетные данные, выданные администратором.', username: 'Логин', password: 'Пароль', login: 'Войти', newPasswordHeading: 'Создайте новый пароль', newPasswordHelp: 'Для продолжения замените временный пароль. Используйте не менее 12 символов.', loginError: 'Не удалось войти. Проверьте логин и пароль.', passwordMismatch: 'Новые пароли не совпадают.', passwordChangeError: 'Не удалось изменить пароль.', usersLoadError: 'Не удалось загрузить список пользователей.', passwordResetError: 'Не удалось сбросить пароль.', userDeleteError: 'Не удалось удалить учетную запись.', userCreateError: 'Не удалось создать учетную запись.'},
|
||||
ky: {account: 'Жеке кабинет', lab: 'Лаборатория', users: 'Колдонуучулар', logout: 'Чыгуу', role: 'Ролу', admin: 'Администратор', created: 'Түзүлгөн күнү', changePassword: 'Сырсөздү өзгөртүү', passwordRequirement: 'Жаңы сырсөз кеминде 12 белгиден турушу керек.', currentPassword: 'Учурдагы сырсөз', newPassword: 'Жаңы сырсөз', confirmPassword: 'Жаңы сырсөздү кайталаңыз', change: 'Сырсөздү өзгөртүү', close: 'Жабуу', showPassword: 'Сырсөздү көрсөтүү', hidePassword: 'Сырсөздү жашыруу', usersHeading: 'Колдонуучуларды башкаруу', temporaryPassword: 'Убактылуу сырсөз', temporaryPasswordHelp: 'Сырсөз кеминде 12 белгиден турушу керек. Жаңы колдонуучу биринчи киргенде аны өзгөртөт. Убактылуу сырсөздү өзүнчө жөнөтүңүз.', createUser: 'Колдонуучу түзүү', sourcesHeading: 'Документтердин булактары', sourceIntro: 'Издөө Кыргыз Республикасынын укуктук булактарынан даярдалган документтер боюнча жүргүзүлөт. Ар бир документ үчүн жеткиликтүү редакция жана расмий булактын шилтемеси көрсөтүлөт.', officialSource: 'Расмий булак:', sourceName: 'Кыргыз Республикасынын Юстиция министрлигинин укуктук маалыматтарынын борборлоштурулган банкы', loginHeading: 'Акылдашка кирүү', loginHelp: 'Администратор берген эсептик дайындарды киргизиңиз.', username: 'Колдонуучунун аты', password: 'Сырсөз', login: 'Кирүү', newPasswordHeading: 'Жаңы сырсөз түзүңүз', newPasswordHelp: 'Улантуу үчүн убактылуу сырсөздү алмаштырыңыз. Кеминде 12 белги колдонуңуз.', loginError: 'Кирүү мүмкүн болгон жок. Колдонуучунун атын жана сырсөздү текшериңиз.', passwordMismatch: 'Жаңы сырсөздөр дал келген жок.', passwordChangeError: 'Сырсөздү өзгөртүү мүмкүн болгон жок.', usersLoadError: 'Колдонуучулардын тизмесин жүктөө мүмкүн болгон жок.', passwordResetError: 'Сырсөздү баштапкы абалга келтирүү мүмкүн болгон жок.', userDeleteError: 'Колдонуучуну өчүрүү мүмкүн болгон жок.', userCreateError: 'Колдонуучуну түзүү мүмкүн болгон жок.'}
|
||||
};
|
||||
const modalMessage = (key) => modalCopy[uiLanguage][key];
|
||||
const reviewRoute = location.pathname === '/review';
|
||||
@@ -578,11 +708,11 @@
|
||||
$('review-review-nav').classList.toggle('is-active', reviewRoute); $('review-search-nav').classList.toggle('is-active', searchRoute); $('review-users-open').classList.toggle('is-active', usersRoute); $('review-nav').classList.toggle('is-active', reviewRoute); $('search-nav').classList.toggle('is-active', searchRoute);
|
||||
document.body.classList.toggle('is-review-route', reviewRoute);
|
||||
document.body.classList.toggle('is-search-route', searchRoute); document.body.classList.toggle('is-users-route', usersRoute);
|
||||
if (usersRoute) { document.title = 'Пользователи · Акылдаш'; $('route-heading').textContent = 'Пользователи'; $('route-description').textContent = 'Управляйте учётными записями. Доступ к действиям проверяется сервером.'; $('tutorial-open').hidden = true; document.querySelector('.review__skip').href = '#users-page'; document.querySelector('footer .review__header-content').textContent = 'Акылдаш · Frontend v0.2.6 · Backend v0.13.1'; }
|
||||
else 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.6 · Backend v0.13.1'; }
|
||||
if (usersRoute) { document.title = 'Пользователи · Акылдаш'; $('route-heading').textContent = 'Пользователи'; $('route-description').textContent = 'Управляйте учётными записями. Доступ к действиям проверяется сервером.'; $('tutorial-open').hidden = true; document.querySelector('.review__skip').href = '#users-page'; document.querySelector('footer .review__header-content').textContent = 'Акылдаш · Frontend v0.3.2 · Backend v0.13.1'; }
|
||||
else 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.3.2 · Backend v0.13.1'; }
|
||||
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}`; $('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'); const canManageUsers = user.role === 'admin'; $('search-users-open').hidden = $('review-users-open').hidden = !canManageUsers; document.body.classList.remove('review__locked'); if (usersRoute) { if (!canManageUsers) { location.replace('/'); return; } document.body.classList.add('is-admin'); const savedLanguage = (() => { try { return localStorage.getItem('akyldash-ui-language') || 'ru'; } catch (_) { return 'ru'; } })(); updateUsersLanguage(savedLanguage); } else if (searchRoute) initSearchPage(); };
|
||||
const enterWorkspace = (user) => { account = user; $('signed-in-user').textContent = user.username; $('review-signed-in-user').textContent = user.username; $('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'); const canManageUsers = user.role === 'admin'; $('search-users-open').hidden = $('review-users-open').hidden = !canManageUsers; document.body.classList.remove('review__locked'); if (usersRoute) { if (!canManageUsers) { location.replace('/'); return; } document.body.classList.add('is-admin'); const savedLanguage = (() => { try { return localStorage.getItem('akyldash-ui-language') || 'ru'; } catch (_) { return 'ru'; } })(); updateUsersLanguage(savedLanguage); } else if (searchRoute) initSearchPage(); };
|
||||
const filterFields = [['statuses', {ru: 'Статус', ky: 'Статус'}, 'status'], ['document_types', {ru: 'Вид документа', ky: 'Документтин түрү'}, 'document_type'], ['authorities', {ru: 'Орган принятия', ky: 'Кабыл алган орган'}, 'authority']];
|
||||
let filterCatalogs = {};
|
||||
let filterCatalogsLoaded = false;
|
||||
@@ -591,6 +721,7 @@
|
||||
let searchRequest = 0;
|
||||
let editionRequest = 0;
|
||||
let currentDocumentHtml = '';
|
||||
let applyResultsSplitter = null;
|
||||
let documentMatches = [];
|
||||
let activeDocumentMatch = -1;
|
||||
function sanitizeDocumentHtml(html) {
|
||||
@@ -725,10 +856,10 @@
|
||||
list.replaceChildren();
|
||||
if (results === null || !results.length) {
|
||||
const empty = document.createElement('li'); empty.className = 'review__empty';
|
||||
const failed = results === null;
|
||||
const heading = document.createElement('strong'); heading.textContent = failed ? 'Поиск временно недоступен' : copy('noResults');
|
||||
empty.append(heading, document.createTextNode(failed ? 'Проверьте подключение и повторите запрос.' : copy('noResultsHint'))); list.append(empty); return;
|
||||
list.dataset.state = results === null ? 'error' : 'empty';
|
||||
empty.textContent = results === null ? copy('searchError') : copy('noResults'); list.append(empty); return;
|
||||
}
|
||||
list.dataset.state = 'results';
|
||||
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 || copy('noTitle');
|
||||
@@ -738,11 +869,28 @@
|
||||
row.append(title, meta, snippet); list.append(row);
|
||||
});
|
||||
}
|
||||
function clearOpenedMarkers() { document.querySelectorAll('.search__opened').forEach((marker) => marker.remove()); }
|
||||
function clearSelectedPublicDocument() {
|
||||
++editionRequest; selectedPublicDocument = null; currentDocumentHtml = '';
|
||||
$('search-layout').removeAttribute('data-has-document'); $('search-layout').removeAttribute('data-has-editions');
|
||||
$('document-breadcrumb').parentElement.hidden = true; $('public-document-heading').textContent = copy('document');
|
||||
$('document-facts').textContent = copy('chooseDocument'); $('public-document-body').replaceChildren();
|
||||
$('document-source').hidden = true; $('document-source').removeAttribute('href');
|
||||
$('document-edition').replaceChildren(); $('document-edition').disabled = true;
|
||||
$('document-language').replaceChildren(); $('document-language').disabled = true; $('document-language').parentElement.hidden = true;
|
||||
$('document-find').value = ''; $('document-find').disabled = true; $('document-note').hidden = true;
|
||||
$('document-toc-list').replaceChildren(); $('document-find-prev').disabled = $('document-find-next').disabled = true;
|
||||
$('document-find-count').textContent = '';
|
||||
}
|
||||
async function runSearch(page = 1, updateUrl = true) {
|
||||
const query = $('public-query').value.trim();
|
||||
if (!query) { $('public-status').textContent = copy('queryRequired'); syncFilterChips(); return; }
|
||||
publicPage = Math.max(1, page);
|
||||
const requestId = ++searchRequest;
|
||||
clearOpenedMarkers(); clearSelectedPublicDocument();
|
||||
setMobileView('results');
|
||||
const loading = document.createElement('li'); loading.className = 'review__empty'; loading.textContent = copy('searching'); $('public-results').dataset.state = 'loading'; $('public-results').replaceChildren(loading);
|
||||
document.querySelector('.search__pagination').hidden = true;
|
||||
$('public-status').textContent = copy('searching');
|
||||
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);
|
||||
@@ -762,24 +910,60 @@
|
||||
$('page-label').textContent = `${copy('page')} ${publicPage}`;
|
||||
$('page-prev').disabled = publicPage <= 1;
|
||||
$('page-next').disabled = !payload.has_next;
|
||||
document.querySelector('.search__pagination').hidden = !(publicPage > 1 || payload.has_next);
|
||||
} catch (error) {
|
||||
if (requestId !== searchRequest) return;
|
||||
$('public-status').textContent = error.message || copy('searchError');
|
||||
renderPublicResults(null);
|
||||
$('result-count').textContent = copy('noResultsCount');
|
||||
document.querySelector('.search__pagination').hidden = true;
|
||||
}
|
||||
}
|
||||
function buildDocumentToc() {
|
||||
const body = $('public-document-body');
|
||||
const headings = [...body.querySelectorAll('h1, h2, h3')];
|
||||
const entries = [];
|
||||
const structuralHeading = (paragraph) => {
|
||||
const normalized = paragraph.textContent.replace(/\s+/g, ' ').trim();
|
||||
const bold = [...paragraph.querySelectorAll('b, strong')].some((node) => node.textContent.replace(/\s+/g, ' ').trim() === normalized);
|
||||
if (!bold) return null;
|
||||
const patterns = [
|
||||
{level: 1, pattern: /^(?:раздел|бөлүм)\s+(?:№\s*)?[\divxlcdm]+(?:[\s.:—–-]+.*)?$/iu},
|
||||
{level: 2, pattern: /^глава\s+(?:№\s*)?[\divxlcdm]+(?:[\s.:—–-]+.*)?$/iu},
|
||||
{level: 3, pattern: /^(?:статья|берене|бап)\s+(?:№\s*)?[\divxlcdm]+(?:[\s.:—–-]+.*)?$/iu}
|
||||
];
|
||||
return patterns.find(({pattern}) => pattern.test(normalized))?.level ?? null;
|
||||
};
|
||||
body.querySelectorAll('h1, h2, h3, p').forEach((element) => {
|
||||
const level = /^H[123]$/.test(element.tagName) ? Number(element.tagName[1]) : structuralHeading(element);
|
||||
if (level) entries.push({element, level});
|
||||
});
|
||||
const root = $('document-toc-list'); root.replaceChildren();
|
||||
if (!headings.length) { const item = document.createElement('li'); item.textContent = copy('noSections'); 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);
|
||||
if (!entries.length) { const item = document.createElement('li'); item.textContent = copy('noSections'); root.append(item); return; }
|
||||
const usedIds = new Set([...body.querySelectorAll('[id]')].map((element) => element.id));
|
||||
const lastItems = [];
|
||||
const childLists = new WeakMap();
|
||||
entries.forEach(({element, level}, index) => {
|
||||
const item = document.createElement('li');
|
||||
let targetList = root;
|
||||
if (level > 1) {
|
||||
const parent = lastItems[level - 2] || lastItems[0];
|
||||
if (parent) {
|
||||
targetList = childLists.get(parent);
|
||||
if (!targetList) { targetList = document.createElement('ol'); parent.append(targetList); childLists.set(parent, targetList); }
|
||||
}
|
||||
}
|
||||
let id = element.id;
|
||||
if (!id || [...body.querySelectorAll('[id]')].filter((candidate) => candidate.id === id).length > 1) {
|
||||
const baseId = `document-section-${index + 1}`;
|
||||
id = baseId;
|
||||
let suffix = 2;
|
||||
while (usedIds.has(id)) id = `${baseId}-${suffix++}`;
|
||||
element.id = id; usedIds.add(id);
|
||||
}
|
||||
const link = document.createElement('a'); link.href = `#${id}`; link.textContent = element.textContent.replace(/\s+/g, ' ').trim();
|
||||
link.addEventListener('click', (event) => { event.preventDefault(); element.scrollIntoView({block: 'start'}); element.focus({preventScroll: true}); });
|
||||
if (!element.hasAttribute('tabindex')) element.tabIndex = -1;
|
||||
item.append(link); targetList.append(item); lastItems[level - 1] = item; lastItems.length = level;
|
||||
});
|
||||
}
|
||||
function highlightDocumentMatches() {
|
||||
@@ -832,8 +1016,58 @@
|
||||
$('search-layout').dataset.mobileView = view;
|
||||
if (view === 'document') { $('public-document-heading').tabIndex = -1; $('public-document-heading').focus(); }
|
||||
}
|
||||
function initResultsSplitter() {
|
||||
const layout = $('search-layout'); const splitter = $('search-splitter');
|
||||
const minimum = 25; const maximum = 55; const storageKey = 'akyldash-search-results-share';
|
||||
let value = 35.7; let userAdjusted = false;
|
||||
try { const saved = Number(localStorage.getItem(storageKey)); if (Number.isFinite(saved) && saved >= minimum && saved <= maximum) { value = saved; userAdjusted = true; } } catch (_) {}
|
||||
const apply = (next, persist = false) => {
|
||||
const filtersHidden = layout.dataset.filtersHidden === 'true';
|
||||
const wide = matchMedia('(min-width: 1192px)').matches;
|
||||
const compact = matchMedia('(min-width: 901px) and (max-width: 1191px)').matches;
|
||||
if (compact) { layout.style.gridTemplateColumns = ''; return; }
|
||||
if (!wide) return;
|
||||
const divider = 8;
|
||||
const filterTrack = filtersHidden ? 0 : Math.min(288, Math.max(264, layout.clientWidth * 0.2 + 8));
|
||||
const available = layout.clientWidth - filterTrack - divider;
|
||||
const minShare = Math.max(minimum, 360 / available * 100);
|
||||
const maxShare = Math.min(maximum, (available - 560) / available * 100);
|
||||
const preferredShare = (layout.clientWidth * 0.15 + 192) / available * 100;
|
||||
value = Math.max(minShare, Math.min(maxShare, userAdjusted ? next : preferredShare));
|
||||
layout.style.gridTemplateColumns = filtersHidden
|
||||
? `minmax(360px, ${value}fr) ${divider}px minmax(560px, ${100 - value}fr)`
|
||||
: `minmax(264px, ${filterTrack}px) minmax(360px, ${value}fr) ${divider}px minmax(560px, ${100 - value}fr)`;
|
||||
splitter.setAttribute('aria-valuemin', String(minShare)); splitter.setAttribute('aria-valuemax', String(maxShare));
|
||||
splitter.setAttribute('aria-valuenow', String(value));
|
||||
if (persist) { try { localStorage.setItem(storageKey, String(value)); } catch (_) {} }
|
||||
};
|
||||
apply(value);
|
||||
applyResultsSplitter = apply;
|
||||
window.addEventListener('resize', () => apply(value, true));
|
||||
let dragging = false;
|
||||
splitter.addEventListener('pointerdown', (event) => {
|
||||
if (matchMedia('(max-width: 900px)').matches) return;
|
||||
event.preventDefault(); dragging = true; splitter.setPointerCapture(event.pointerId);
|
||||
});
|
||||
splitter.addEventListener('pointermove', (event) => {
|
||||
if (!dragging) return;
|
||||
const rect = layout.getBoundingClientRect();
|
||||
const filterTrack = layout.dataset.filtersHidden === 'true' ? 0 : Math.min(288, Math.max(264, layout.clientWidth * 0.2 + 8));
|
||||
const available = layout.clientWidth - filterTrack - 8;
|
||||
if (available > 0) { userAdjusted = true; apply(((event.clientX - rect.left - filterTrack) / available) * 100); }
|
||||
});
|
||||
const finishDrag = (event) => { if (!dragging) return; dragging = false; apply(value, true); if (splitter.hasPointerCapture(event.pointerId)) splitter.releasePointerCapture(event.pointerId); };
|
||||
splitter.addEventListener('pointerup', finishDrag); splitter.addEventListener('pointercancel', finishDrag);
|
||||
splitter.addEventListener('keydown', (event) => {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
const next = event.key === 'Home' ? Number(splitter.getAttribute('aria-valuemin')) : event.key === 'End' ? Number(splitter.getAttribute('aria-valuemax')) : value + (event.key === 'ArrowRight' ? 2 : -2);
|
||||
userAdjusted = true; apply(next, true);
|
||||
});
|
||||
return apply;
|
||||
}
|
||||
async function loadPublicEdition() {
|
||||
if (!selectedPublicDocument) return;
|
||||
if (!selectedPublicDocument) return false;
|
||||
const requestId = ++editionRequest;
|
||||
const {code} = selectedPublicDocument;
|
||||
const edition = $('document-edition').value;
|
||||
@@ -842,13 +1076,15 @@
|
||||
const languages = editionInfo?.available_languages || [];
|
||||
if (!languages.includes(language) && languages.length) { language = languages[0]; $('document-language').value = language; }
|
||||
$('document-source').hidden = true; $('document-source').removeAttribute('href');
|
||||
$('document-language').parentElement.hidden = true;
|
||||
clearOpenedMarkers(); $('search-layout').removeAttribute('data-has-document');
|
||||
currentDocumentHtml = ''; $('public-document-body').replaceChildren();
|
||||
if (!languages.includes(language)) { $('document-facts').textContent = copy('editionMissing'); return; }
|
||||
if (!languages.includes(language)) { $('document-facts').textContent = copy('editionMissing'); return false; }
|
||||
$('document-facts').textContent = copy('loadingEdition');
|
||||
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 (requestId !== editionRequest || selectedPublicDocument?.code !== code || $('document-edition').value !== edition || $('document-language').value !== language) return false;
|
||||
if (!response.ok) throw new Error(payload.error || copy('editionUnavailable'));
|
||||
const content = payload.content[language];
|
||||
const meta = $('document-facts'); meta.replaceChildren();
|
||||
@@ -864,25 +1100,33 @@
|
||||
$('document-expand').setAttribute('aria-expanded', 'false');
|
||||
$('document-find').disabled = false; $('document-note').hidden = true;
|
||||
highlightDocumentMatches();
|
||||
$('document-language').parentElement.hidden = languages.length < 2;
|
||||
const selectedRow = document.querySelector('.search__result--selected');
|
||||
if (selectedRow && selectedPublicDocument?.code === selectedRow.dataset.code) {
|
||||
const opened = document.createElement('span'); opened.className = 'search__opened'; opened.textContent = copy('opened'); selectedRow.append(opened);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (requestId !== editionRequest) return;
|
||||
if (requestId !== editionRequest) return false;
|
||||
$('document-source').hidden = true; $('document-source').removeAttribute('href');
|
||||
currentDocumentHtml = '';
|
||||
$('document-facts').textContent = error.message || copy('editionUnavailable');
|
||||
$('public-document-body').replaceChildren();
|
||||
$('search-layout').removeAttribute('data-has-document');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
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; ++editionRequest; currentDocumentHtml = '';
|
||||
$('search-layout').removeAttribute('data-has-document'); $('search-layout').removeAttribute('data-has-editions');
|
||||
row.querySelector('.search__opened')?.remove();
|
||||
const opened = document.createElement('span'); opened.className = 'search__opened'; opened.textContent = copy('opened'); row.append(opened);
|
||||
clearOpenedMarkers();
|
||||
$('document-breadcrumb').textContent = result.name || copy('document');
|
||||
$('document-breadcrumb').parentElement.hidden = false;
|
||||
$('public-document-heading').textContent = result.name || copy('document'); $('public-document-body').replaceChildren();
|
||||
setMobileView('document');
|
||||
$('document-find').value = ''; $('document-find').disabled = true; $('document-note').hidden = true;
|
||||
$('document-source').hidden = true; $('document-source').removeAttribute('href'); $('document-edition').replaceChildren(); $('document-language').replaceChildren();
|
||||
$('document-source').hidden = true; $('document-source').removeAttribute('href'); $('document-edition').replaceChildren(); $('document-language').replaceChildren(); $('document-language').parentElement.hidden = true;
|
||||
try {
|
||||
const response = await apiFetch(`/documents/${encodeURIComponent(result.code)}/editions`);
|
||||
const payload = await response.json();
|
||||
@@ -902,10 +1146,11 @@
|
||||
$('search-layout').dataset.hasEditions = 'true';
|
||||
languageSelect.value = languages.includes($('public-language').value) ? $('public-language').value : languages[0];
|
||||
await loadPublicEdition();
|
||||
} catch (error) { if (selectedPublicDocument === result) $('document-facts').textContent = error.message || 'Документ недоступен.'; }
|
||||
} catch (error) { if (selectedPublicDocument === result) { $('document-facts').textContent = error.message || 'Документ недоступен.'; $('document-language').parentElement.hidden = true; } }
|
||||
}
|
||||
async function initSearchPage() {
|
||||
if (!searchRoute) return;
|
||||
initResultsSplitter();
|
||||
const params = new URLSearchParams(location.search);
|
||||
$('public-query').value = params.get('q') || '';
|
||||
$('public-language').value = params.get('language') || 'ru';
|
||||
@@ -936,7 +1181,8 @@
|
||||
const setLabels = (selector, values) => document.querySelectorAll(selector).forEach((label, index) => { if (label.firstChild?.nodeType === Node.TEXT_NODE) label.firstChild.textContent = `${values[index]} `; });
|
||||
const setText = (id, key) => { if ($(id)) $(id).textContent = copy(key); };
|
||||
setText('search-nav', 'search'); setText('sources-open', 'sources'); setText('filters-heading', 'filters');
|
||||
setText('clear-filters', 'clear'); setText('mobile-filters-open', 'filters'); setText('mobile-filters-close', 'close');
|
||||
setText('clear-filters', 'clear'); setText('mobile-filters-close', 'close');
|
||||
$('mobile-filters-open').textContent = matchMedia('(max-width: 900px)').matches || $('search-layout').dataset.filtersHidden !== 'true' ? copy('filters') : (ky ? 'Чыпкаларды көрсөтүү' : 'Показать фильтры');
|
||||
setText('search-results-heading', 'results'); setText('document-print', 'print');
|
||||
$('search-account-open').setAttribute('aria-label', ky ? 'Жеке кабинет' : 'Личный кабинет'); $('search-account-open').title = $('search-account-open').getAttribute('aria-label');
|
||||
$('public-search-form').querySelector('button[type="submit"]').textContent = ky ? 'Издөө' : 'Найти';
|
||||
@@ -963,16 +1209,16 @@
|
||||
$('document-find-prev').setAttribute('aria-label', ky ? 'Мурунку дал келүү' : 'Предыдущее совпадение'); $('document-find-next').setAttribute('aria-label', ky ? 'Кийинки дал келүү' : 'Следующее совпадение');
|
||||
$('document-source').textContent = copy('source');
|
||||
const modal = modalCopy[uiLanguage];
|
||||
setText('account-heading', 'account'); $('review-nav').textContent = modal.lab; $('search-users-open').textContent = modal.users; $('search-logout').textContent = modal.logout;
|
||||
$('account-heading').textContent = modal.account; $('review-nav').textContent = modal.lab; $('search-users-open').textContent = modal.usersHeading; $('search-logout').textContent = modal.logout;
|
||||
$('profile-role').textContent = account?.role === 'admin' ? modal.admin : account?.role || '';
|
||||
document.querySelectorAll('.review__password-toggle').forEach((button) => { const visible = button.getAttribute('aria-pressed') === 'true'; const label = visible ? modal.hidePassword : modal.showPassword; button.textContent = label; button.setAttribute('aria-label', label); button.title = label; });
|
||||
$('profile-tab').textContent = ky ? 'Профиль' : 'Профиль'; $('security-tab').textContent = ky ? 'Коопсуздук' : 'Безопасность';
|
||||
document.querySelectorAll('[data-close]').forEach((button) => button.setAttribute('aria-label', modal.close));
|
||||
document.querySelectorAll('[data-close]').forEach((button) => { button.setAttribute('aria-label', modal.close); button.title = modal.close; });
|
||||
const accountLabels = document.querySelectorAll('#account-dialog dt'); accountLabels[1].textContent = modal.role; accountLabels[2].textContent = modal.created;
|
||||
$('profile-created').textContent = account?.created_at ? new Intl.DateTimeFormat(ky ? 'ky-KG' : 'ru-RU').format(new Date(account.created_at * 1000)) : '';
|
||||
document.querySelector('#profile-password-form h3').textContent = modal.changePassword; setLabels('#profile-password-form label', [modal.currentPassword, modal.newPassword, modal.confirmPassword]);
|
||||
document.querySelector('#profile-password-form p').textContent = modal.passwordRequirement;
|
||||
document.querySelector('#profile-password-form button[type="submit"]').textContent = modal.change;
|
||||
document.querySelector('[data-close="account-dialog"]').textContent = modal.close;
|
||||
$('users-heading').textContent = modal.usersHeading; setLabels('#create-user-form label', [modal.username, modal.temporaryPassword]);
|
||||
document.querySelector('#create-user-form p').textContent = modal.temporaryPasswordHelp;
|
||||
document.querySelector('#create-user-form button').textContent = modal.createUser;
|
||||
@@ -988,15 +1234,24 @@
|
||||
document.querySelectorAll('.search__opened').forEach((item) => { item.textContent = copy('opened'); });
|
||||
if (documentMatches.length) $('document-find-count').textContent = `${activeDocumentMatch + 1} ${ky ? 'ичинен' : 'из'} ${documentMatches.length}`;
|
||||
else if ($('document-find').value.trim()) $('document-find-count').textContent = copy('noMatches');
|
||||
const resultTotal = $('public-results').querySelector('.review__empty') ? 0 : $('public-results').children.length;
|
||||
if ($('public-query').value.trim()) {
|
||||
$('result-count').textContent = `${resultTotal} ${resultTotal === 1 ? copy('oneResult') : copy('manyResults')}`;
|
||||
$('public-status').textContent = resultTotal ? `${copy('resultsFor')} «${$('public-query').value.trim()}».` : `«${$('public-query').value.trim()}»: ${copy('noDocuments')}`;
|
||||
const resultList = $('public-results');
|
||||
const resultTotal = resultList.querySelectorAll('[data-code]').length;
|
||||
const query = $('public-query').value.trim();
|
||||
const state = resultList.dataset.state || 'initial';
|
||||
if (state === 'initial') {
|
||||
$('result-count').textContent = ''; $('public-status').textContent = query ? copy('searching') : copy('queryRequired');
|
||||
resultList.querySelector('.review__empty').textContent = ky ? 'Издөө баштоо үчүн суроо киргизиңиз.' : 'Введите запрос, чтобы начать поиск.';
|
||||
} else if (state === 'loading') {
|
||||
$('result-count').textContent = copy('searching'); $('public-status').textContent = copy('searching');
|
||||
resultList.querySelector('.review__empty').textContent = copy('searching');
|
||||
} else if (state === 'error') {
|
||||
$('result-count').textContent = copy('noResultsCount'); $('public-status').textContent = copy('searchError');
|
||||
resultList.querySelector('.review__empty').textContent = copy('searchError');
|
||||
} else {
|
||||
setText('result-count', 'enterQuery'); setText('public-status', 'queryRequired');
|
||||
$('result-count').textContent = `${resultTotal} ${resultTotal === 1 ? copy('oneResult') : copy('manyResults')}`;
|
||||
$('public-status').textContent = resultTotal ? `${copy('resultsFor')} «${query}».` : `«${query}»: ${copy('noDocuments')}`;
|
||||
if (state === 'empty') resultList.querySelector('.review__empty').textContent = copy('noResults');
|
||||
}
|
||||
const empty = $('public-results').querySelector('.review__empty');
|
||||
if (empty) { empty.querySelector('strong').textContent = copy('noResults'); empty.lastChild.textContent = copy('noResultsHint'); }
|
||||
const pageMatch = $('page-label').textContent.match(/\d+/); if (pageMatch) $('page-label').textContent = `${copy('page')} ${pageMatch[0]}`;
|
||||
if (filterCatalogsLoaded) {
|
||||
const selected = selectedFilters(); renderFilterCatalogs(filterCatalogs);
|
||||
@@ -1022,12 +1277,13 @@
|
||||
$('document-find').addEventListener('input', highlightDocumentMatches);
|
||||
$('document-find-prev').addEventListener('click', () => moveDocumentMatch(-1)); $('document-find-next').addEventListener('click', () => moveDocumentMatch(1));
|
||||
$('mobile-filters-open').addEventListener('click', () => {
|
||||
if (matchMedia('(max-width: 900px)').matches) openMobileFilters();
|
||||
if (matchMedia('(max-width: 1191px)').matches) openMobileFilters();
|
||||
else {
|
||||
const hidden = $('search-layout').dataset.filtersHidden !== 'true';
|
||||
$('search-layout').dataset.filtersHidden = String(hidden);
|
||||
$('mobile-filters-open').setAttribute('aria-expanded', String(!hidden));
|
||||
$('mobile-filters-open').textContent = hidden ? 'Показать фильтры' : 'Скрыть фильтры';
|
||||
$('mobile-filters-open').textContent = hidden ? (uiLanguage === 'ky' ? 'Чыпкаларды көрсөтүү' : 'Показать фильтры') : copy('filters');
|
||||
applyResultsSplitter?.(Number($('search-splitter').getAttribute('aria-valuenow')));
|
||||
}
|
||||
});
|
||||
$('mobile-filters-close').addEventListener('click', closeMobileFilters); $('filter-overlay').addEventListener('click', closeMobileFilters);
|
||||
@@ -1086,7 +1342,7 @@
|
||||
document.querySelectorAll('.review__user-table-head [role="columnheader"]').forEach((cell, index) => { cell.textContent = [words.login, words.role, words.state, words.lastLogin, words.actions][index]; });
|
||||
$('create-user-heading').textContent = words.create; document.querySelectorAll('#create-user-form label').forEach((label, index) => { const input = label.querySelector('input'); label.firstChild.textContent = `${[words.username, words.tempPassword][index]} `; if (input) label.append(input); }); document.querySelector('#create-user-form p').textContent = words.tempHelp; document.querySelector('#create-user-form button[type="submit"]').textContent = words.create;
|
||||
$('delete-user-heading').textContent = words.deleteHeading; $('delete-user-confirm').textContent = words.delete; document.querySelectorAll('#create-user-dialog [data-close], #delete-user-dialog [data-close]').forEach((button) => button.textContent = words.cancel);
|
||||
document.querySelector('footer .review__header-content').textContent = `Акылдаш · Frontend v0.2.6 · Backend v0.13.1`;
|
||||
document.querySelector('footer .review__header-content').textContent = `Акылдаш · Frontend v0.3.2 · Backend v0.13.1`;
|
||||
if (usersRoute && account) loadUsers();
|
||||
};
|
||||
$('users-ui-ru').addEventListener('click', () => updateUsersLanguage('ru'));
|
||||
@@ -1142,7 +1398,6 @@
|
||||
$('create-user-open').addEventListener('click', () => { $('create-user-dialog').showModal(); $('create-user-heading').focus(); });
|
||||
$('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(); $('create-user-dialog').close(); await loadUsers(); });
|
||||
['review-account-open', 'search-account-open'].forEach((id) => $(id).addEventListener('click', () => { $('account-dialog').showModal(); $('profile-tab').focus(); }));
|
||||
$('search-users-open').addEventListener('click', () => { $('account-dialog').close(); location.assign('/users'); });
|
||||
[['profile-tab', 'security-tab'], ['security-tab', 'profile-tab']].forEach(([id, other]) => $(id).addEventListener('click', () => {
|
||||
const selected = $(id), target = id === 'profile-tab' ? $('profile-panel') : $('security-panel');
|
||||
const inactive = id === 'profile-tab' ? $('security-panel') : $('profile-panel');
|
||||
@@ -1163,10 +1418,16 @@
|
||||
close.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>';
|
||||
heading.tabIndex = -1; heading.before(chrome); chrome.append(heading, close);
|
||||
});
|
||||
document.querySelectorAll('#profile-password-form input[type="password"]').forEach((input) => {
|
||||
const field = document.createElement('span'); field.className = 'review__password-field'; input.before(field); field.append(input);
|
||||
const toggle = document.createElement('button'); toggle.type = 'button'; toggle.className = 'review__password-toggle'; toggle.setAttribute('aria-pressed', 'false'); toggle.setAttribute('aria-label', modalCopy[uiLanguage].showPassword); toggle.title = modalCopy[uiLanguage].showPassword; toggle.textContent = modalCopy[uiLanguage].showPassword;
|
||||
toggle.addEventListener('click', () => { const visible = input.type === 'password'; input.type = visible ? 'text' : 'password'; toggle.setAttribute('aria-pressed', String(visible)); const label = visible ? modalCopy[uiLanguage].hidePassword : modalCopy[uiLanguage].showPassword; toggle.setAttribute('aria-label', label); toggle.title = label; toggle.textContent = label; });
|
||||
field.append(toggle);
|
||||
});
|
||||
document.querySelectorAll('[data-close]').forEach((button) => button.addEventListener('click', () => $(button.dataset.close).close()));
|
||||
['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 setStatus = (text, error = false) => { const status = $('status'); const busy = !error && /(?:выполняется|загрузка|жүктөлүүдө)/i.test(text); status.textContent = text; status.classList.toggle('review__status--error', error); status.classList.toggle('review__status--busy', busy); status.classList.toggle('review__status--success', Boolean(text) && !error && !busy); status.setAttribute('role', error ? 'alert' : 'status'); status.setAttribute('aria-live', error ? 'assertive' : 'polite'); };
|
||||
const setError = (text) => setStatus(text, true);
|
||||
const escapeText = (value) => value == null ? '' : String(value);
|
||||
const readDraft = () => { try { return JSON.parse(localStorage.getItem(draftStorageKey()) || 'null'); } catch (_) { return null; } };
|
||||
@@ -1201,12 +1462,12 @@
|
||||
let tutorialStep = 0; let tutorialReturnFocus = null;
|
||||
function clearTourTarget() { $('tutorial-spotlight').hidden = true; $('document-panel').classList.remove('review__document--tour-visible'); }
|
||||
function renderTutorial() {
|
||||
const step = TOUR_STEPS[tutorialStep]; const target = $(step.target);
|
||||
const step = TOUR_STEPS[tutorialStep]; const mobileDocumentTarget = step.target === 'document-panel' && matchMedia('(max-width: 800px)').matches; const target = mobileDocumentTarget ? $('document-heading') : $(step.target);
|
||||
$('document-panel').classList.toggle('review__document--tour-visible', step.target === 'document-panel' && matchMedia('(max-width: 800px)').matches);
|
||||
const dialog = $('tutorial-dialog');
|
||||
const focusedControl = dialog.open && dialog.contains(document.activeElement) ? document.activeElement.id : 'tutorial-next';
|
||||
if (dialog.open) dialog.close();
|
||||
target.scrollIntoView({block: 'nearest', inline: 'nearest'});
|
||||
target.scrollIntoView({block: mobileDocumentTarget ? 'center' : 'nearest', inline: 'nearest'});
|
||||
const bounds = target.getBoundingClientRect();
|
||||
$('tutorial-spotlight').style.cssText = `inset-block-start: ${Math.max(8, bounds.top - 4)}px; inset-inline-start: ${Math.max(8, bounds.left - 4)}px; inline-size: ${bounds.width + 8}px; block-size: ${bounds.height + 8}px;`;
|
||||
$('tutorial-spotlight').hidden = false;
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# Единый план корректировки интерфейса «Акылдаш»
|
||||
|
||||
Дата аудита: **23 октября 2026 года**.
|
||||
Статус на 23 октября 2026 года: реализация внесена в ветку
|
||||
`feature/uiux-tunduk-corrections`; локальная браузерная проверка прошла.
|
||||
Ожидаются CI и ручное PR review.
|
||||
Базовые пункты UI-01—UI-33 исправлены и вошли в `main` через PR #54.
|
||||
На 24 октября 2026 года отдельный follow-up по замечаниям владельца для поиска,
|
||||
личного кабинета и лаборатории реализован; локальный браузерный набор пройден.
|
||||
Ожидаются CI и ручное PR review для pushed SHA.
|
||||
|
||||
Этот файл заменяет `frontend-pixel-perfect-plan.md` и является единственным
|
||||
рабочим планом исправления UI/UX поиска, лаборатории и служебных окон.
|
||||
@@ -223,6 +224,25 @@ browser zoom: в доступном headless Chromium Ctrl+Plus не меняе
|
||||
Не мигрировать существующий Python frontend на React/Next.js ради этих
|
||||
исправлений. Не менять ранжирование, корпус или права доступа в UI-задаче.
|
||||
|
||||
## 9. Follow-up замечания владельца: поиск, кабинет и лаборатория
|
||||
|
||||
Повторный просмотр трёх экранов выявил отдельные проблемы уже после PR #54.
|
||||
Исправления остаются в этом плане, чтобы не создавать параллельный список:
|
||||
|
||||
| Поверхность | Наблюдение | Реализация и проверка |
|
||||
|---|---|---|
|
||||
| Поиск: выдача и чтение | Метка «Открыт» ставилась до ответа, могла оставаться после ошибки и дублироваться; оглавление пропускало структурные заголовки из жирных `p > b > span`; выбор языка был обрезан и расположен в навигации; в фильтрах оставался декоративный SVG с пустым резервом; активный пункт «Поиск» визуально смещался | Метка очищается при смене результата/редакции и появляется только после успешной загрузки; оглавление распознаёт самостоятельные заголовки раздела/главы/статьи на RU/KY, назначает уникальные якоря и строит вложенные списки; язык поиска находится в фильтрах с полной шириной; SVG и его место удалены; ссылки навигации используют палитру Акылдаш. Проверка: ошибки и гонки загрузки, заголовки RU/KY и обычные упоминания, уникальные якоря, диапазон и доступность splitter |
|
||||
| Личный кабинет | Навигация выглядела ссылкой браузера; закрытие занимало строку текстом; подписи и значения профиля стояли в столбик; заголовок был крупным; появлялось горизонтальное переполнение; действие управления пользователями было неочевидным | Ссылки кабинета оформлены как действия с сохранением семантики `<a>`; крестик остаётся SVG-кнопкой 44×44 с доступной подписью; профиль выровнен в пары «поле — значение»; заголовок компактнее; длинные значения переносятся; администратор получает явную ссылку «Управление пользователями». Проверка: RU/KY, скрытие ссылки для не-администратора, фокус/закрытие диалога и ширина содержимого |
|
||||
| Лаборатория | Дублировалась роль рядом с именем; ссылки навигации не имели вида кнопок; оболочка, форма, рабочая область, сохранение и footer имели разные границы; пустое сообщение резервировало высоту; панели выглядели разрозненными карточками; основной заголовок переносился; мобильный экран наследовал искусственную высоту | В шапке показывается только имя, роль остаётся в профиле; навигация сохраняет ссылки и получает единый вид кнопок; все участки выровнены по общему shell; пустой live status не добавляет зазор; результаты и документ образуют общую поверхность с внутренней прокруткой на desktop; заголовок использует доступную ширину и размеры по макету Figma; mobile возвращается к естественному потоку с прокруткой документа. Проверка: desktop/mobile, пустой status, сохранение после длинного документа и отсутствие page overflow |
|
||||
|
||||
Frontend повышен до **0.3.0** из-за добавления доступного изменения ширины
|
||||
панелей. Backend и его API не менялись. Fixture данные искусственные; preview
|
||||
слушает только loopback, запрещает запросы за пределы своего origin и не
|
||||
использует авторизационные cookies или production API. Браузерный прогон прошёл
|
||||
на 24 октября 2026 года; пять скриншотов сохранены в `current-progress` рядом
|
||||
с отчётом assignment. CI и независимое ревью проверяются для конкретного pushed
|
||||
SHA.
|
||||
|
||||
## 7. Приёмка: что значит «вылизанный интерфейс»
|
||||
|
||||
| Проверка | Условие |
|
||||
|
||||
@@ -2,35 +2,26 @@ const { chromium } = require('playwright');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const repo = path.resolve(__dirname, '../..');
|
||||
const artifacts = path.join(repo, 'docs/product/visual-review');
|
||||
const artifacts = process.env.VISUAL_REVIEW_ARTIFACTS || path.join(repo, 'docs/product/visual-review');
|
||||
const html = fs.readFileSync(path.join(repo, 'backend/search/review.html'), 'utf8');
|
||||
const root = path.join(repo, 'backend/search/static/fonts');
|
||||
const {docs, reviewDocs, catalogs, passwordChangeAccount, article, articleKy} = require('./fixtures.cjs');
|
||||
fs.mkdirSync(artifacts, {recursive: true});
|
||||
const docs = [
|
||||
{code:'doc-1',name:'Налоговый кодекс Кыргызской Республики',type:'Кодекс',status:'Действует',snippet:'… положения о налоге на прибыль и порядке его исчисления …',edition:'2024',editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']} ]},
|
||||
{code:'doc-2',name:'О введении в действие Налогового кодекса Кыргызской Республики',type:'Закон',status:'Действует',snippet:'… устанавливается порядок введения в действие Налогового кодекса Кыргызской Республики …'},
|
||||
{code:'doc-3',name:'Порядок заполнения налоговой отчётности',type:'Постановление',snippet:'… рекомендации по заполнению налоговой отчётности, включая показатели по налогу на прибыль …'}
|
||||
];
|
||||
const reviewDocs = [
|
||||
{code:'review-a',name:'Fixture document A',type:'fixture',status:'active',edition:'2026'},
|
||||
{code:'review-b',name:'Fixture document B',type:'fixture',status:'active',edition:'2025'}
|
||||
];
|
||||
const fixtureState = {users:[{username:'fixture-user',role:'user',must_change_password:true,last_login_at:null,first_login_at:1780000000,password_reset_at:null}],passwordChanges:0,userCreates:0,passwordResets:0,userDeletes:0,reviewSaves:0,lastReviewRatings:[]};
|
||||
const catalogs = {document_types:[{code:'code',labels:{ru:'Кодекс',ky:'Кодекс'},count:12},{code:'law',labels:{ru:'Закон',ky:'Мыйзам'},count:10},{code:'decree',labels:{ru:'Постановление',ky:'Токтом'},count:8}],statuses:[{code:'active',labels:{ru:'Действует',ky:'Күчүндө'},count:24},{code:'repealed',labels:{ru:'Утратил силу',ky:'Күчүн жоготту'},count:5}],authorities:[{code:'ministries_and_committees',labels:{ru:'Министерства и комитеты',ky:'Министрликтер'},count:5}],legal_forces:[]};
|
||||
const article = '<h2>Налог на прибыль</h2><p><a href="../../tmp/old.html">Old local reference</a> <a href="http://cbd.minjust.gov.kg/old">Legacy HTTP reference</a> <a href="https://cbd.minjust.gov.kg/doc-1" ping="https://evil.invalid/ping">Official reference</a> <a href="https://127.0.0.1/private">Private address reference</a><img src="../../tmp/old.png" srcset="https://evil.invalid/pixel 1x, https://192.168.1.10/pixel 2x"><img alt="Private address image" src="https://192.168.1.10/pixel"></p><p>Текст документа приведён для примера оформления. Здесь будут отображаться положения выбранной редакции. По запросу налог на прибыль читатель найдёт нужный фрагмент.</p><h2>Налоговая отчётность</h2><p>В этом разделе отображается текст выбранной редакции. Поиск внутри документа помогает перейти к нужному фрагменту.</p><p>Далее приводятся положения о налоге на прибыль.</p><p>Упоминание запроса налог на прибыль в следующем разделе.</p>';
|
||||
let failNextEdition = false; let delayNextEdition = false; let failReviewDocumentB = false; let delayReviewDocumentA = false;
|
||||
let failNextEdition = false; let delayNextEdition = false; let delayNextPublicMetadata = false; let failReviewDocumentB = false; let delayReviewDocumentA = false; let delayNextReviewSearch = false;
|
||||
(async()=>{
|
||||
const browser = await chromium.launch({headless:true});
|
||||
const page = await browser.newPage({viewport:{width:1280,height:800},deviceScaleFactor:1});
|
||||
const page = await browser.newPage({viewport:{width:1440,height:800},deviceScaleFactor:1});
|
||||
await page.addInitScript(()=>{if(!sessionStorage.getItem('visual-review-splitter-reset')){localStorage.removeItem('akyldash-search-results-share');sessionStorage.setItem('visual-review-splitter-reset','1');}});
|
||||
const errors=[]; page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.route('**/*', async route=>{
|
||||
const req=route.request(), url=new URL(req.url());
|
||||
if (req.isNavigationRequest()) return route.fulfill({status:200,contentType:'text/html; charset=utf-8',body:html});
|
||||
const p=url.pathname;
|
||||
if(p==='/auth/me') return route.fulfill({json:{account:{username:'admin',role:'admin',created_at:1780000000,must_change_password:false}}});
|
||||
if(p==='/auth/me') return route.fulfill({json:{account:passwordChangeAccount}});
|
||||
if(p==='/search/filters') return route.fulfill({json:catalogs});
|
||||
if(p==='/search-reviews' && req.method()==='POST') { fixtureState.reviewSaves++; fixtureState.lastReviewRatings=req.postDataJSON().results.map((result)=>({code:result.code,rating:result.rating})); return route.fulfill({json:{id:42}}); }
|
||||
if(p==='/auth/change-password' && req.method()==='POST') { fixtureState.passwordChanges++; return route.fulfill({json:{account:{username:'admin',role:'admin',created_at:1780000000,must_change_password:false}}}); }
|
||||
if(p==='/auth/change-password' && req.method()==='POST') { fixtureState.passwordChanges++; return route.fulfill({json:{account:passwordChangeAccount}}); }
|
||||
if(p==='/admin/users' && req.method()==='GET') return route.fulfill({json:{users:fixtureState.users}});
|
||||
if(p==='/admin/users' && req.method()==='POST') { const body=req.postDataJSON(); fixtureState.userCreates++; fixtureState.users.push({username:body.username,role:'user',must_change_password:true,last_login_at:null,first_login_at:1780000000,password_reset_at:null}); return route.fulfill({status:201,json:{username:body.username}}); }
|
||||
const resetMatch=p.match(/^\/admin\/users\/([^/]+)\/reset-password$/);
|
||||
@@ -38,14 +29,14 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
const deleteMatch=p.match(/^\/admin\/users\/([^/]+)$/);
|
||||
if(deleteMatch && req.method()==='DELETE') { fixtureState.userDeletes++; const username=decodeURIComponent(deleteMatch[1]); fixtureState.users=fixtureState.users.filter((candidate)=>candidate.username!==username); return route.fulfill({json:{}}); }
|
||||
if(p==='/search') {
|
||||
if(url.searchParams.has('page_size')&&!url.searchParams.has('sort')) return route.fulfill({json:{results:reviewDocs,has_next:false,review_token:'fixture-review-token'}});
|
||||
if(url.searchParams.has('page_size')&&!url.searchParams.has('sort')) { if(delayNextReviewSearch){delayNextReviewSearch=false;await new Promise(resolve=>setTimeout(resolve,300));} return route.fulfill({json:{results:reviewDocs,has_next:false,review_token:'fixture-review-token'}}); }
|
||||
return route.fulfill(url.searchParams.get('q')==='service-error' ? {status:503,json:{error:'Fixture search error'}} : {json:{results:url.searchParams.get('q')==='not-found'?[]:docs,has_next:false,review_token:'fixture-review-token'}});
|
||||
}
|
||||
if(p==='/documents/doc-2/editions') return route.fulfill({json:{available_languages:[],editions:[]}});
|
||||
if(p==='/documents/doc-3/editions') return route.fulfill({status:503,json:{error:'Fixture editions error'}});
|
||||
if(p==='/documents/doc-1/editions') return route.fulfill({json:{available_languages:['ru','ky'],editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']}]}});
|
||||
if(p==='/documents/doc-1/editions') { if(delayNextPublicMetadata){delayNextPublicMetadata=false;await new Promise(resolve=>setTimeout(resolve,250));} return route.fulfill({json:{available_languages:['ru','ky'],editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']}]}}); }
|
||||
if(p==='/documents/doc-1/editions/2023') return route.fulfill({json:{content:{ru:{html:'<h2>Russian-only edition</h2><p>Regression fixture.</p>'}}}});
|
||||
if(p==='/documents/doc-1/editions/2024') { if(delayNextEdition){delayNextEdition=false;await new Promise(resolve=>setTimeout(resolve,200));} if(failNextEdition){failNextEdition=false;await new Promise(resolve=>setTimeout(resolve,120));return route.fulfill({status:503,json:{error:'Fixture edition error'}});} return route.fulfill({json:{content:{ru:{html:article},ky:{html:article}}}}); }
|
||||
if(p==='/documents/doc-1/editions/2024') { if(delayNextEdition){delayNextEdition=false;await new Promise(resolve=>setTimeout(resolve,200));} if(failNextEdition){failNextEdition=false;await new Promise(resolve=>setTimeout(resolve,120));return route.fulfill({status:503,json:{error:'Fixture edition error'}});} return route.fulfill({json:{content:{ru:{html:article},ky:{html:articleKy}}}}); }
|
||||
if(p==='/documents/review-a/editions/2026') { if(delayReviewDocumentA){delayReviewDocumentA=false;await new Promise(resolve=>setTimeout(resolve,350));} return route.fulfill({json:{content:{ru:{html:'<h2>Fixture document A</h2><p>Content for fixture A only.</p>'}}}}); }
|
||||
if(p==='/documents/review-b/editions/2025') { if(failReviewDocumentB) return route.fulfill({status:503,json:{error:'Fixture document B unavailable'}}); return route.fulfill({json:{content:{ru:{html:'<h2>Fixture document B</h2><p>Content for fixture B only.</p>'}}}}); }
|
||||
if(p==='/static/favicon.svg') return route.fulfill({status:200,contentType:'image/svg+xml',body:fs.readFileSync(path.join(root,'../favicon.svg'))});
|
||||
@@ -53,21 +44,31 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
if(p.startsWith('/static/fonts/')) { const f=path.join(root,path.basename(p)); return route.fulfill({status:200,contentType:'font/woff2',body:fs.readFileSync(f)}); }
|
||||
return route.fulfill({status:404,contentType:'application/json',body:'{}'});
|
||||
});
|
||||
await page.goto('https://fixture.invalid/'); await page.locator('#search-results-heading').waitFor();
|
||||
await page.waitForFunction(()=>document.querySelector('#search-splitter')?.getAttribute('aria-valuenow')!=='36');
|
||||
const freshSplitter=await page.evaluate(()=>{const r=s=>document.querySelector(s).getBoundingClientRect(),tracks=getComputedStyle(document.querySelector('#search-layout')).gridTemplateColumns.split(' ');return {filters:r('#search-filters').width,results:r('.search__results').width,gutter:parseFloat(tracks[2]),document:r('#public-document-panel').width,brand:r('.search__brand').width,descriptor:getComputedStyle(document.querySelector('.search__brand-description')).display,brandLabel:document.querySelector('.search__brand').getAttribute('aria-label')};});
|
||||
await page.setViewportSize({width:1280,height:800});
|
||||
const initialFooterCount=await page.evaluate(()=>[...document.querySelectorAll('body > footer')].filter(el=>getComputedStyle(el).display!=='none'&&el.getBoundingClientRect().height>0).length); const initialSearch=await page.evaluate(()=>({state:document.querySelector('#public-results').dataset.state,list:document.querySelector('#public-results').textContent.trim(),count:document.querySelector('#result-count').textContent,paginationHidden:document.querySelector('.search__pagination').hidden,breadcrumbHidden:document.querySelector('.search__breadcrumbs').hidden,documentText:document.querySelector('#document-facts').textContent,headingHidden:getComputedStyle(document.querySelector('#public-document-heading')).display==='none',opened:document.querySelectorAll('.search__opened').length}));
|
||||
await page.goto('https://fixture.invalid/?q=%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B8%D0%B1%D1%8B%D0%BB%D1%8C&status=active');
|
||||
const favicons=await page.evaluate(async()=>Promise.all([...document.querySelectorAll('link[rel="icon"]')].map(async link=>({type:link.type,status:(await fetch(link.href)).status}))));
|
||||
await page.evaluate(()=>document.fonts.ready);
|
||||
const labNavColor=await page.locator('#search-review-nav').evaluate(el=>getComputedStyle(el).color);
|
||||
await page.locator('.search__result-title').first().click();
|
||||
await page.locator('#public-document-body h2').first().waitFor();
|
||||
const tocState=await page.evaluate(()=>{const root=document.querySelector('#document-toc-list'),links=[...root.querySelectorAll('a')];return {titles:links.map(link=>link.textContent),nested:root.querySelector('ol ol')!==null,targetsUnique:new Set(links.map(link=>link.hash)).size===links.length,anchorsExist:links.every(link=>document.querySelector(link.hash)),ordinaryMentionIncluded:links.some(link=>link.textContent.includes('обычное упоминание')),languageSelectorHidden:document.querySelector('.search__document-language').hidden,splitter:{role:document.querySelector('#search-splitter').getAttribute('role'),orientation:document.querySelector('#search-splitter').getAttribute('aria-orientation'),value:document.querySelector('#search-splitter').getAttribute('aria-valuenow')}};});
|
||||
const safeLinks=await page.evaluate(()=>{const body=document.querySelector('#public-document-body'),official=[...body.querySelectorAll('a')].find(a=>a.textContent.includes('Official')),privateLink=[...body.querySelectorAll('a')].find(a=>a.textContent.includes('Private address'));return {relative:body.querySelector('a[href*=old]')?.getAttribute('href')||null,legacy:[...body.querySelectorAll('a')].find(a=>a.textContent.includes('Legacy'))?.getAttribute('href')||null,official:official?.href||null,ping:official?.getAttribute('ping')||null,privateHref:privateLink?.getAttribute('href')||null,image:body.querySelector('img')?.getAttribute('src')||null,srcset:body.querySelector('img')?.getAttribute('srcset')||null,privateImage:[...body.querySelectorAll('img')].find(image=>image.alt==='Private address image')?.getAttribute('src')||null};});
|
||||
await page.evaluate(()=>document.fonts.ready);
|
||||
await page.locator('#document-find').fill('налог на прибыль');
|
||||
await page.waitForTimeout(200);
|
||||
await page.addStyleTag({content:'.search__fixture-label{display:inline-block;margin-inline-start:0;padding-inline-start:12px;border-inline-start:1px solid #ded5cd;color:#786469;font-size:13px}' });
|
||||
await page.evaluate(()=>{const n=document.createElement('span');n.className='search__fixture-label';n.textContent='Демонстрационные данные';document.querySelector('#active-filters').after(n);const note=document.querySelector('#document-note');note.textContent='Текст приведён для примера оформления';note.hidden=false});
|
||||
console.log('subnavBoxes',await page.evaluate(()=>[...document.querySelector('.search__subnav').children].map(el=>({className:el.className||el.id,text:el.innerText,rect:(()=>{const r=el.getBoundingClientRect();return {left:r.left,right:r.right,width:r.width}})()})))); const navGeometry=await page.evaluate(()=>{const box=s=>{const r=document.querySelector(s).getBoundingClientRect();return {left:r.left,right:r.right}};const label=document.querySelector('.search__fixture-label'),range=document.createRange();range.selectNodeContents(label);const text=range.getBoundingClientRect();return {search:box('#search-nav'),sources:box('#sources-open'),language:box('.search__language-chip'),status:box('#active-filters .search__chip'),account:box('#search-account-open'),accountContentFits:(()=>{const e=document.querySelector('#search-account-open');return e.scrollWidth<=e.clientWidth})(),demoText:{left:text.left,right:text.right}}}); console.log('navGeometry',navGeometry); const resultHighlight=await page.locator('.search__result--selected .search__result-snippet mark').first().textContent(); const openedCount=await page.locator('.search__opened').count(); await page.locator('#public-document-panel').evaluate(el=>el.scrollTop=0); await page.evaluate(()=>document.activeElement.blur()); console.log('desktopBoxes', await page.evaluate(()=>Object.fromEntries(['.search__chrome','.search__layout','.search__footer','.search__document'].map(s=>[s,(()=>{const r=document.querySelector(s).getBoundingClientRect();return {top:r.top,bottom:r.bottom,height:r.height}})()])))); console.log('docElements',await page.evaluate(()=>Object.fromEntries(['.search__document-head','#public-document-heading','#public-document-meta','.search__document-toolbar','.search__find','#document-note','#public-document-body h2'].map(s=>[s,(()=>{const r=document.querySelector(s).getBoundingClientRect();return {top:r.top,bottom:r.bottom,height:r.height}})()])))); await page.screenshot({path:path.join(artifacts,'desktop-1280x800.png'),fullPage:false});
|
||||
const chipsBefore=await page.locator('#active-filters .search__chip').count(); await page.locator('input[name="filter-document_type"][value="code"]').check(); await page.waitForFunction(()=>new URL(location.href).searchParams.get('document_type')==='code'); const chipsWithTwo=await page.locator('#active-filters .search__chip').count(); await page.locator('#active-filters button').first().click(); await page.waitForFunction(()=>new URL(location.href).searchParams.get('status')===null); const preservedFilters=await page.evaluate(()=>({status:new URL(location.href).searchParams.get('status'),documentType:new URL(location.href).searchParams.get('document_type')})); await page.locator('#active-filters button').first().click(); const urlFilters=await page.evaluate(()=>({status:new URL(location.href).searchParams.get('status'),documentType:new URL(location.href).searchParams.get('document_type')})); const firstFindCount=await page.locator('#document-find-count').textContent(); await page.locator('#document-find-next').click(); const nextFindCount=await page.locator('#document-find-count').textContent(); await page.locator('input[name="filter-status"][value="active"]').check(); await page.locator('.search__result-title').first().click(); await page.locator('#document-find').fill('налог на прибыль'); await page.locator('#document-find-next').click(); await page.locator('#ui-ky').click(); const documentLanguage=await page.locator('#document-language').inputValue(); const kyrgyzUi=await page.evaluate(()=>({htmlLang:document.documentElement.lang,queryLabel:document.querySelector('label[for=public-query]').textContent,filterHeading:document.querySelectorAll('#filter-fields h3')[1].textContent,statusHeading:document.querySelectorAll('#filter-fields h3')[0].textContent,authority:document.querySelector('#filter-authority option').textContent,activeStatus:document.querySelector('#active-filters .search__chip').textContent.trim(),queryPlaceholder:document.querySelector('#public-query').placeholder,resultCount:document.querySelector('#result-count').textContent,findCount:document.querySelector('#document-find-count').textContent,opened:document.querySelector('.search__opened').textContent,statusValues:[...document.querySelectorAll('input[name="filter-status"]')].map(input=>{const spans=input.parentElement.querySelectorAll('span');return `${spans[0].textContent} (${spans[1].textContent})`}),documentTypes:[...document.querySelectorAll('input[name="filter-document_type"]')].map(input=>{const spans=input.parentElement.querySelectorAll('span');return `${spans[0].textContent} (${spans[1].textContent})`})})); await page.locator('#ui-ru').click(); await page.locator('#document-expand').click(); const expanded=await page.locator('#search-layout').evaluate(e=>e.classList.contains('is-expanded')); await page.keyboard.press('Escape'); const expandedEscapeClosed=await page.locator('#search-layout').evaluate(e=>!e.classList.contains('is-expanded')); const expandedFocusRestored=await page.evaluate(()=>document.activeElement.id); await page.locator('#search-account-open').click(); const accountActions=await page.locator('#account-dialog').evaluate(d=>({open:d.open,reviewVisible:!d.querySelector('#review-nav').hidden,usersVisible:!d.querySelector('#search-users-open').hidden,logoutVisible:!d.querySelector('#search-logout').hidden})); await page.locator('#account-dialog').evaluate(d=>d.close()); await page.locator('#public-query').fill('not-found'); await page.locator('#public-search-form button[type=submit]').click(); await page.waitForFunction(()=>document.querySelector('#result-count').textContent.startsWith('0 ')); await page.locator('#ui-ky').click(); const kyrgyzEmpty=await page.evaluate(()=>({count:document.querySelector('#result-count').textContent,heading:document.querySelector('#public-results .review__empty strong').textContent})); await page.locator('#ui-ru').click(); await page.goto('https://fixture.invalid/?q=%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3+%D0%BD%D0%B0+%D0%BF%D1%80%D0%B8%D0%B1%D1%8B%D0%BB%D1%8C&status=active'); await page.locator('.search__result-title').first().waitFor(); await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor(); await page.evaluate(()=>document.fonts.ready); await page.locator('#document-find').fill('налог на прибыль'); await page.addStyleTag({content:'.search__fixture-label{display:inline-block;margin-inline-start:12px;padding:5px 10px;border:1px solid #A37B32;border-radius:6px;color:#786469;font-size:14px}'}); await page.evaluate(()=>{const n=document.createElement('span');n.className='search__fixture-label';n.textContent='Демонстрационные данные';document.querySelector('.search__subnav').append(n);const note=document.querySelector('#document-note');note.textContent='Текст приведён для примера оформления';note.hidden=false;document.querySelector('#public-docuLine truncated
|
||||
console.log('subnavBoxes',await page.evaluate(()=>[...document.querySelector('.search__subnav').children].map(el=>({className:el.className||el.id,text:el.innerText,rect:(()=>{const r=el.getBoundingClientRect();return {left:r.left,right:r.right,width:r.width}})()})))); const navGeometry=await page.evaluate(()=>{const box=s=>{const r=document.querySelector(s).getBoundingClientRect();return {left:r.left,right:r.right}};const language=document.querySelector('.search__filter-language');const select=language.querySelector('select');const r=language.getBoundingClientRect();const filterHeader=document.querySelector('.search__filters .review__panel-heading').getBoundingClientRect(),filterHeading=document.querySelector('#filters-heading').getBoundingClientRect(),filterReset=document.querySelector('#clear-filters').getBoundingClientRect();return {search:box('#search-nav'),sources:box('#sources-open'),lab:box('#search-review-nav'),labNavVisible:!document.querySelector('#search-review-nav').hidden,filterHeadingSameRow:filterHeading.top<filterReset.bottom&&filterHeading.bottom>filterReset.top,filterLanguageGap:Math.round(language.getBoundingClientRect().top-filterHeader.bottom),splitterWidth:document.querySelector('#search-splitter').getBoundingClientRect().width,filterHeadingSize:parseFloat(getComputedStyle(document.querySelector('#filters-heading')).fontSize),resultsHeadingSize:parseFloat(getComputedStyle(document.querySelector('#search-results-heading')).fontSize),languageInFilters:document.querySelector('#search-filters').contains(language),languageWidth:r.width,languageSelectWidth:select.getBoundingClientRect().width,searchTextAlign:getComputedStyle(document.querySelector('#search-nav')).justifyContent,status:box('#active-filters .search__chip'),account:box('#search-account-open'),accountContentFits:(()=>{const e=document.querySelector('#search-account-open');return e.scrollWidth<=e.clientWidth})()}}); console.log('navGeometry',navGeometry); const documentTitleStyle=await page.locator('#public-document-heading').evaluate(el=>({fontSize:parseFloat(getComputedStyle(el).fontSize),lineHeight:parseFloat(getComputedStyle(el).lineHeight),fontFamily:getComputedStyle(el).fontFamily})); const resultHighlight=await page.locator('.search__result--selected .search__result-snippet mark').first().textContent(); const openedCount=await page.locator('.search__opened').count(); await page.locator('#public-document-panel').evaluate(el=>el.scrollTop=0); await page.evaluate(()=>document.activeElement.blur()); console.log('desktopBoxes', await page.evaluate(()=>Object.fromEntries(['.search__chrome','.search__layout','.search__footer','.search__document'].map(s=>[s,(()=>{const r=document.querySelector(s).getBoundingClientRect();return {top:r.top,bottom:r.bottom,height:r.height}})()])))); console.log('docElements',await page.evaluate(()=>Object.fromEntries(['.search__document-head','#public-document-heading','#public-document-meta','.search__document-toolbar','.search__find','#document-note','#public-document-body h2'].map(s=>[s,(()=>{const r=document.querySelector(s).getBoundingClientRect();return {top:r.top,bottom:r.bottom,height:r.height}})()])))); await page.screenshot({path:path.join(artifacts,'desktop-1280x800.png'),fullPage:false});
|
||||
const splitterDefault=await page.evaluate(()=>{const r=s=>document.querySelector(s).getBoundingClientRect();return {filters:r('#search-filters').width,results:r('.search__results').width,document:r('#public-document-panel').width};}); const splitter=page.locator('#search-splitter'); const splitterStart=Number(await splitter.getAttribute('aria-valuenow')); await splitter.focus(); await page.keyboard.press('ArrowRight'); const splitterKeyboard=Number(await splitter.getAttribute('aria-valuenow')); const keyboardMin=Number(await splitter.getAttribute('aria-valuemin')),keyboardMax=Number(await splitter.getAttribute('aria-valuemax')); await page.keyboard.press('Home'); const splitterHome=Number(await splitter.getAttribute('aria-valuenow')); await page.keyboard.press('End'); const splitterEnd=Number(await splitter.getAttribute('aria-valuenow')); const drag=async x=>{const box=await splitter.boundingBox();await page.mouse.move(box.x+6,box.y+box.height/2);await page.mouse.down();await page.mouse.move(x,box.y+box.height/2,{steps:5});await page.mouse.up();}; await drag(0); const splitterLeft=await page.evaluate(()=>({value:Number(document.querySelector('#search-splitter').getAttribute('aria-valuenow')),filters:document.querySelector('#search-filters').getBoundingClientRect().width,results:document.querySelector('.search__results').getBoundingClientRect().width,document:document.querySelector('#public-document-panel').getBoundingClientRect().width})); await drag(1280); const splitterRight=await page.evaluate(()=>({value:Number(document.querySelector('#search-splitter').getAttribute('aria-valuenow')),filters:document.querySelector('#search-filters').getBoundingClientRect().width,results:document.querySelector('.search__results').getBoundingClientRect().width,document:document.querySelector('#public-document-panel').getBoundingClientRect().width})); const splitterPointer=splitterLeft.value; const splitterStored=await page.evaluate(()=>localStorage.getItem('akyldash-search-results-share'));
|
||||
delayNextPublicMetadata=true; const delayedPublicRequest=page.waitForRequest(request=>new URL(request.url()).pathname==='/documents/doc-1/editions'); await page.locator('.search__result-title').first().click(); await delayedPublicRequest; await page.locator('.search__result-title').nth(2).click(); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Fixture editions error'); await page.waitForTimeout(300); const stalePublicSelection=await page.evaluate(()=>({selected:document.querySelector('.search__result--selected').dataset.code,markers:document.querySelectorAll('.search__opened').length})); await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor(); const markerAfterReload=await page.locator('.search__opened').count();
|
||||
await page.evaluate(()=>{localStorage.setItem('akyldash-search-results-share','36');}); await page.reload(); await page.locator('#search-results-heading').waitFor(); await page.locator('.search__result-title').first().waitFor(); const splitterRestored=await page.locator('#search-splitter').evaluate(el=>({value:Number(el.getAttribute('aria-valuenow')),min:Number(el.getAttribute('aria-valuemin')),max:Number(el.getAttribute('aria-valuemax'))})); await page.evaluate(()=>localStorage.setItem('akyldash-search-results-share','55')); await page.reload(); await page.locator('.search__result-title').first().waitFor(); await page.waitForFunction(()=>document.querySelector('#search-splitter')?.getAttribute('aria-valuenow')!=='36'); const splitterStoredMax=await page.locator('#search-splitter').evaluate(el=>({value:Number(el.getAttribute('aria-valuenow')),max:Number(el.getAttribute('aria-valuemax'))})); await page.setViewportSize({width:1440,height:800}); await page.evaluate(()=>window.dispatchEvent(new Event('resize'))); const splitterResize=await page.evaluate(()=>({results:document.querySelector('.search__results').getBoundingClientRect().width,document:document.querySelector('#public-document-panel').getBoundingClientRect().width})); await page.setViewportSize({width:1280,height:800}); await page.evaluate(()=>window.dispatchEvent(new Event('resize'))); await page.evaluate(()=>localStorage.setItem('akyldash-search-results-share','25')); await page.reload(); await page.locator('.search__result-title').first().waitFor(); await page.waitForFunction(()=>document.querySelector('#search-splitter')?.getAttribute('aria-valuenow')!=='36'); const splitterStoredMin=await page.locator('#search-splitter').evaluate(el=>({value:Number(el.getAttribute('aria-valuenow')),min:Number(el.getAttribute('aria-valuemin'))}));
|
||||
const chipsBefore=await page.locator('#active-filters .search__chip').count(); await page.locator('input[name="filter-document_type"][value="code"]').check(); await page.waitForFunction(()=>new URL(location.href).searchParams.get('document_type')==='code'); const chipsWithTwo=await page.locator('#active-filters .search__chip').count(); await page.locator('#active-filters button').first().click(); await page.waitForFunction(()=>new URL(location.href).searchParams.get('status')===null); const preservedFilters=await page.evaluate(()=>({status:new URL(location.href).searchParams.get('status'),documentType:new URL(location.href).searchParams.get('document_type')})); await page.locator('#active-filters button').first().click(); const urlFilters=await page.evaluate(()=>({status:new URL(location.href).searchParams.get('status'),documentType:new URL(location.href).searchParams.get('document_type')})); const firstFindCount=await page.locator('#document-find-count').textContent(); const findClearedAfterFilterChange=!(await page.locator('#document-find-next').isVisible()); await page.locator('input[name="filter-status"][value="active"]').check(); await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor(); await page.locator('#document-find').fill('налог на прибыль'); await page.waitForFunction(()=>!document.querySelector('#document-find-next').disabled); await page.locator('#document-find-next').click(); const nextFindCount=await page.locator('#document-find-count').textContent(); await page.locator('#ui-ky').click(); const documentLanguage=await page.locator('#document-language').inputValue(); const kyrgyzUi=await page.evaluate(()=>({htmlLang:document.documentElement.lang,queryLabel:document.querySelector('label[for=public-query]').textContent,filterHeading:document.querySelectorAll('#filter-fields h3')[1].textContent,statusHeading:document.querySelectorAll('#filter-fields h3')[0].textContent,authority:document.querySelector('#filter-authority option').textContent,activeStatus:document.querySelector('#active-filters .search__chip').textContent.trim(),queryPlaceholder:document.querySelector('#public-query').placeholder,resultCount:document.querySelector('#result-count').textContent,findCount:document.querySelector('#document-find-count').textContent,opened:document.querySelector('.search__opened').textContent,statusValues:[...document.querySelectorAll('input[name="filter-status"]')].map(input=>{const spans=input.parentElement.querySelectorAll('span');return `${spans[0].textContent} (${spans[1].textContent})`}),documentTypes:[...document.querySelectorAll('input[name="filter-document_type"]')].map(input=>{const spans=input.parentElement.querySelectorAll('span');return `${spans[0].textContent} (${spans[1].textContent})`})})); await page.locator('#ui-ru').click(); await page.locator('#document-expand').click(); const expanded=await page.locator('#search-layout').evaluate(e=>e.classList.contains('is-expanded')); await page.keyboard.press('Escape'); const expandedEscapeClosed=await page.locator('#search-layout').evaluate(e=>!e.classList.contains('is-expanded')); const expandedFocusRestored=await page.evaluate(()=>document.activeElement.id); await page.locator('#search-account-open').click(); const accountActions=await page.locator('#account-dialog').evaluate(d=>{const close=d.querySelector('.review__dialog-heading button'),profile=d.querySelector('dl');return {open:d.open,heading:d.querySelector('#account-heading').textContent,reviewVisible:!d.querySelector('#review-nav').hidden,reviewHref:d.querySelector('#review-nav').getAttribute('href'),usersVisible:!d.querySelector('#search-users-open').hidden,usersHref:d.querySelector('#search-users-open').getAttribute('href'),usersLabel:d.querySelector('#search-users-open').textContent,logoutVisible:!d.querySelector('#search-logout').hidden,closeIcon:Boolean(close.querySelector('svg')),closeText:close.textContent.trim(),closeLabel:close.getAttribute('aria-label'),profileGrid:getComputedStyle(profile).display,profileRows:profile.children.length,headingHeight:d.querySelector('.review__dialog-heading').getBoundingClientRect().height,headingFontSize:parseFloat(getComputedStyle(d.querySelector('.review__dialog-heading h2')).fontSize),headingFontFamily:getComputedStyle(d.querySelector('.review__dialog-heading h2')).fontFamily,dataBeforeActions:Boolean(profile.compareDocumentPosition(d.querySelector('.search__account-actions'))&Node.DOCUMENT_POSITION_FOLLOWING),dialogFits:d.scrollWidth<=d.clientWidth};}); const accountGeometry=await page.locator('#account-dialog').evaluate(d=>{const actions=d.querySelector('.search__account-actions'),logout=d.querySelector('#search-logout'),first=actions.querySelector('a').getBoundingClientRect(),out=logout.getBoundingClientRect();return {width:d.getBoundingClientRect().width,logoutSeparate:out.top>=first.bottom,logoutMuted:getComputedStyle(logout).backgroundColor==='rgba(0, 0Line truncated
|
||||
const fonts = await page.evaluate(async()=>({sans:document.fonts.check('400 16px "Noto Sans"'),serif:document.fonts.check('600 24px "Noto Serif"'),kyrgyzSans:(await document.fonts.load('400 16px "Noto Sans"','ӨөҮүҢң')).length>0,kyrgyzSerif:(await document.fonts.load('600 24px "Noto Serif"','ӨөҮүҢң')).length>0,ids:[...document.querySelectorAll('[id]')].map(x=>x.id).filter((id,i,a)=>a.indexOf(id)!==i)}));
|
||||
const widths={}; for(const width of [1440,1280,1024]){await page.setViewportSize({width,height:900});widths[width]=await page.evaluate(()=>({scrollWidth:document.documentElement.scrollWidth,viewport:innerWidth,layout:document.querySelector('#search-layout').getBoundingClientRect().width,columns:getComputedStyle(document.querySelector('#search-layout')).gridTemplateColumns.split(' ').map(parseFloat)}));await page.screenshot({path:path.join(artifacts,`desktop-${width}px.png`)});} await page.setViewportSize({width:320,height:800}); widths[320]=await page.evaluate(()=>({scrollWidth:document.documentElement.scrollWidth,viewport:innerWidth}));
|
||||
const widths={}; for(const width of [1440,1280,1024,1713]){await page.setViewportSize({width,height:900});widths[width]=await page.evaluate(()=>({scrollWidth:document.documentElement.scrollWidth,viewport:innerWidth,layout:document.querySelector('#search-layout').getBoundingClientRect().width,columns:getComputedStyle(document.querySelector('#search-layout')).gridTemplateColumns.split(' ').map(parseFloat)}));await page.screenshot({path:path.join(artifacts,`desktop-${width}px.png`)});} await page.setViewportSize({width:320,height:800}); widths[320]=await page.evaluate(()=>({scrollWidth:document.documentElement.scrollWidth,viewport:innerWidth}));
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.reload(); await page.evaluate(()=>document.fonts.ready);
|
||||
const view=await page.evaluate(()=>({mobileView:document.querySelector('#search-layout').dataset.mobileView,scrollWidth:document.documentElement.scrollWidth,width:innerWidth}));
|
||||
@@ -79,13 +80,14 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
await page.screenshot({path:path.join(artifacts,'mobile-390px.png'),fullPage:true});
|
||||
await page.locator('#document-back').click();
|
||||
const back=await page.locator('#search-layout').getAttribute('data-mobile-view'); await page.setViewportSize({width:1024,height:900}); await page.waitForFunction(()=>document.querySelector('#search-filters').getAttribute('aria-hidden')===null); const desktopFilters=await page.evaluate(()=>({visible:getComputedStyle(document.querySelector('#search-filters')).display!=='none',ariaHidden:document.querySelector('#search-filters').getAttribute('aria-hidden')}));
|
||||
await page.goto('https://fixture.invalid/review'); await page.locator('#review').waitFor(); const routes={searchHidden:await page.locator('#search-page').isHidden(),reviewVisible:await page.locator('#review').isVisible()}; const labLayout=await page.evaluate(()=>{const panel=document.querySelector('#document-panel'),body=document.querySelector('#document-body');for(let i=0;i<160;i++){const p=document.createElement('p');p.textContent='Эталонный текст длинной фиктивной редакции для проверки прокрутки панели документа. '.repeat(4);body.append(p);}const save=document.querySelector('#save'),footer=document.querySelector('body > footer.review__header'),r=panel.getBoundingClientRect();return {initialSaveDisabled:save.disabled,initialSaveText:save.textContent,initialDraft:document.querySelector('#draft-status').textContent,panelHeight:r.height,panelClient:panel.clientHeight,panelScroll:panel.scrollHeight,viewport:innerHeight,saveAfterPanel:Boolean(panel.compareDocumentPosition(save)&Node.DOCUMENT_POSITION_FOLLOWING),footerAfterSave:Boolean(save.compareDocumentPosition(footer)&Node.DOCUMENT_POSITION_FOLLOWING),footerVisible:getComputedStyle(footer).display!=='none',publicFooterVisible:getComputedStyle(document.querySelector('.search__footer')).display!=='none'};});
|
||||
const tutorialScreens={}; for(const [name,viewport] of [['desktop',{width:1280,height:800}],['mobile',{width:390,height:844}]]){await page.setViewportSize(viewport); await page.locator('#tutorial-open').click(); tutorialScreens[name]=[]; for(const target of ['#query','#results','#document-panel','#save']){const geometry=await page.evaluate((selector)=>{const dialog=document.querySelector('#tutorial-dialog'),target=document.querySelector(selector),d=dialog.getBoundingClientRect(),t=target.getBoundingClientRect(),style=getComputedStyle(dialog),targetStyle=getComputedStyle(target);return {step:document.querySelector('#tutorial-progress').textContent,width:d.width,height:d.height,overlaps:d.left<t.right&&d.right>t.left&&d.top<t.bottom&&d.bottom>t.top,font:style.fontFamily,titleFont:getComputedStyle(document.querySelector('#tutorial-heading')).fontFamily,background:style.backgroundColor,targetDisplay:targetStyle.display,targetInViewport:t.bottom>0&&t.top<innerHeight,target:{left:t.left,top:t.top,right:t.right,bottom:t.bottom}}},target);if(geometry.targetDisplay==='none'||geometry.target.right===geometry.target.left||geometry.target.bottom===geometry.target.top||!geometry.targetInViewport) throw new Error(`Tutorial target is not visible at ${name}: ${JSON.stringify(geometry)}`);if(geometry.overlaps) throw new Error(`Tutorial overlaps ${target} at ${name}`);if(geometry.width>320||!geometry.font.includes('Noto Sans')||!geometry.titleFont.includes('Noto Serif')||!geometry.background.includes('0.92')) throw new Error(`Tutorial style mismatch at ${name}: ${JSON.stringify(geometry)}`);tutorialScreens[name].push(geometry);if(target==='#query') await page.screenshot({path:path.join(artifacts,`review-tour-${name}.png`),fullPage:false});if(target!=='#save') await page.locator('#tutorial-next').press('Enter');}await page.locator('#tutorial-next').press('Enter');}
|
||||
await page.setViewportSize({width:1280,height:800}); await page.locator('#query').fill('налог на прибыль'); await page.locator('#search-form button[type=submit]').click(); await page.locator('.review__result').first().waitFor(); const reviewSaveEnabled=await page.locator('#save').isEnabled(); const commentDisclosure=page.locator('.review__comment-disclosure').first(); const commentStartsCollapsed=!(await commentDisclosure.evaluate(e=>e.open)); await commentDisclosure.locator('summary').click(); await commentDisclosure.locator('textarea').fill('Фиктивный комментарий для проверки черновика'); await page.locator('input[name="rating-0"][value="2"]').check(); await page.waitForFunction(()=>document.querySelector('#draft-status').textContent==='Черновик сохранён на этом устройстве.'); await page.locator('.review__result-title').first().click(); await page.locator('#document-body h2').first().waitFor(); await page.locator('#document-body').evaluate(body=>{for(let i=0;i<160;i++){const p=document.createElement('p');p.textContent='Эталонный длинный документ в безопасном browser fixture. '.repeat(5);body.append(p);}}); const reviewScroll=await page.locator('#document-panel').evaluate(panel=>({height:panel.getBoundingClientRect().height,client:panel.clientHeight,scroll:panel.scrollHeight,viewport:innerHeight,saveAfter:Boolean(panel.compareDocumentPosition(document.querySelector('#save'))&Node.DOCUMENT_POSITION_FOLLOWING),footerAfterSave:Boolean(document.querySelector('#save').compareDocumentPosition(document.querySelector('body > footer.review__header'))&Node.DOCUMENT_POSITION_FOLLOWING)})); await page.locator('#save').click(); await page.waitForFunction(()=>document.querySelector('#status').textContent.includes('Оценка сохранена')); const reviewFlow={reviewSaveEnabled,commentStartsCollapsed,commentExpanded:await commentDisclosure.evaluate(e=>e.open),draftStatus:await page.locator('#draft-status').textContent(),reviewScroll,reviewSaved:await page.locator('#status').textContent()};
|
||||
await page.setViewportSize({width:1440,height:900}); await page.goto('https://fixture.invalid/review'); await page.locator('#review').waitFor(); const routes={searchHidden:await page.locator('#search-page').isHidden(),reviewVisible:await page.locator('#review').isVisible(),visibleFooters:await page.evaluate(()=>[...document.querySelectorAll('body > footer')].filter(el=>getComputedStyle(el).display!=='none'&&el.getBoundingClientRect().height>0).length)}; const labLayout=await page.evaluate(()=>{const panel=document.querySelector('#document-panel'),body=document.querySelector('#document-body');for(let i=0;i<160;i++){const p=document.createElement('p');p.textContent='Эталонный текст длинной фиктивной редакции для проверки прокрутки панели документа. '.repeat(4);body.append(p);}const save=document.querySelector('#save'),footer=document.querySelector('body > footer.review__header'),r=panel.getBoundingClientRect();return {initialSaveDisabled:save.disabled,initialSaveText:save.textContent,initialDraft:document.querySelector('#draft-status').textContent,panelHeight:r.height,panelClient:panel.clientHeight,panelScroll:panel.scrollHeight,viewport:innerHeight,navHeight:document.querySelector('body > header.review__header .review__nav').getBoundingClientRect().height,titlebarHeight:document.querySelector('body > header.review__header .review__header-content').getBoundingClientRect().height,actionsHeight:document.querySelector('body > .review__actions').getBoundingClientRect().height,footerHeight:document.querySelector('body > footer.review__header').getBoundingClientRect().height,labTitleSize:parseFloat(getComputedStyle(document.querySelector('#route-heading')).fontSize),sectionHeadingSize:parseFloat(getComputedStyle(document.querySelector('.review__results .review__panel-heading h2')).fontSize),headerLeft:document.querySelector('body > header.review__header').getBoundingClientRect().left,headerRight:document.querySelector('body > header.review__header').getBoundingClientRect().right,workspaceLeft:document.querySelector('.review__workspace').getBoundingClientRect().left,workspaceRight:document.querySelector('.review__workspace').getBoundingClientRect().right,saveAfterPanel:Boolean(panel.compareDocumentPosition(save)&Node.DOCUMENT_POSITION_FOLLOWING),footerAfterSave:Boolean(save.compareDocumentPosition(footer)&Node.DOCUMENT_POSITION_FOLLOWING),footerVisible:getComputedStyle(footer).display!=='none',headerLeft:document.querySelector('body > header.review__header').getBoundingClientRect().left,headerRight:document.querySelector('body > header.review__header').getBoundingClientRect().right,workspaceLeft:document.querySelector('.review__workspace').getBoundingClientRect().left,workspaceRight:document.querySelector('.review__workspace').getBoundingClientRect().right,publicFooterVisible:getComputedStyle(document.querySelector('.search__footer')).display!=='none'};});
|
||||
const labGeometry=await page.evaluate(()=>{const rect=s=>document.querySelector(s).getBoundingClientRect(),action=rect('body > .review__actions'),workspace=rect('.review__workspace'),footer=rect('body > footer.review__header');return {headingLeft:rect('#route-heading').left,helpRight:rect('#tutorial-open').right,subtitleLeft:rect('#route-description').left,workspaceActionGap:action.top-workspace.bottom,actionFooterGap:footer.top-action.bottom,actionsHeight:action.height,footerHeight:footer.height};});
|
||||
const tutorialScreens={}; for(const [name,viewport] of [['desktop',{width:1280,height:800}],['mobile',{width:390,height:844}]]){await page.setViewportSize(viewport); await page.locator('#tutorial-open').click(); tutorialScreens[name]=[]; for(const target of ['#query','#results','#document-panel','#save']){const selector=name==='mobile'&&target==='#document-panel'?'#document-heading':target;const geometry=await page.evaluate((selector)=>{const dialog=document.querySelector('#tutorial-dialog'),target=document.querySelector(selector),d=dialog.getBoundingClientRect(),t=target.getBoundingClientRect(),style=getComputedStyle(dialog),targetStyle=getComputedStyle(target);return {step:document.querySelector('#tutorial-progress').textContent,width:d.width,height:d.height,overlaps:d.left<t.right&&d.right>t.left&&d.top<t.bottom&&d.bottom>t.top,font:style.fontFamily,titleFont:getComputedStyle(document.querySelector('#tutorial-heading')).fontFamily,background:style.backgroundColor,targetDisplay:targetStyle.display,targetInViewport:t.bottom>0&&t.top<innerHeight,target:{left:t.left,top:t.top,right:t.right,bottom:t.bottom}}},selector);if(geometry.targetDisplay==='none'||geometry.target.right===geometry.target.left||geometry.target.bottom===geometry.target.top||!geometry.targetInViewport) throw new Error(`Tutorial target is not visible at ${name}: ${JSON.stringify(geometry)}`);if(geometry.overlaps) throw new Error(`Tutorial overlaps ${target} at ${name}: ${JSON.stringify(geometry)}`);if(geometry.width>320||!geometry.font.includes('Noto Sans')||!geometry.titleFont.includes('Noto Serif')||!geometry.background.includes('0.92')) throw new Error(`Tutorial style mismatch at ${name}: ${JSON.stringify(geometry)}`);tutorialScreens[name].push(geometry);if(target==='#query') await page.screenshot({path:path.join(artifacts,`review-tour-${name}.png`),fullPage:false});if(target!=='#save') await page.locator('#tutorial-next').press('Enter');}await page.locator('#tutorial-next').press('Enter');}
|
||||
await page.setViewportSize({width:1280,height:800}); await page.locator('#query').fill('налог на прибыль'); delayNextReviewSearch=true; await page.locator('#search-form button[type=submit]').click(); await page.waitForFunction(()=>document.querySelector('#status').classList.contains('review__status--busy')); const labLoadingStatus=await page.locator('#status').evaluate(el=>({height:el.getBoundingClientRect().height,role:el.getAttribute('role'),busy:el.classList.contains('review__status--busy')})); await page.locator('.review__result').first().waitFor(); const successStatus=await page.locator('#status').evaluate(el=>({height:el.getBoundingClientRect().height,role:el.getAttribute('role'),live:el.getAttribute('aria-live'),success:el.classList.contains('review__status--success')})); await page.locator('.review__result-title').first().click(); await page.locator('#document-body h2').first().waitFor(); const compactResult=await page.locator('.review__result--selected').evaluate(el=>({padding:getComputedStyle(el).padding,titleTarget:el.querySelector('.review__result-title').getBoundingClientRect().height,ratingTarget:el.querySelector('.review__rating label').getBoundingClientRect().height,metaMargin:getComputedStyle(el.querySelector('.review__meta')).marginBlockStart})); const reviewSaveEnabled=await page.locator('#save').isEnabled(); const commentDisclosure=page.locator('.review__comment-disclosure').first(); const commentStartsCollapsed=!(await commentDisclosure.evaluate(e=>e.open)); await commentDisclosure.locator('summary').click(); await commentDisclosure.locator('textarea').fill('Фиктивный комментарий для проверки черновика'); await page.locator('input[name="rating-0"][value="2"]').check(); await page.waitForFunction(()=>document.querySelector('#draft-status').textContent==='Черновик сохранён на этом устройстве.'); await page.locator('.review__result-title').first().click(); await page.locator('#document-body h2').first().waitFor(); await page.locator('#document-body').evaluate(body=>{for(let i=0;i<160;i++){const p=document.createElement('p');p.textContent='Эталонный длинный документ в безопасном browser fixture. '.repeat(5);body.append(p);}}); await page.setViewportSize({width:1280,height:720}); const reviewScroll=await page.locator('#document-panel').evaluate(panel=>({height:panel.getBoundingClientRect().height,client:panel.clientHeight,scroll:panel.scrollHeight,viewport:innerHeight,internalScroll:panel.scrollHeight>panel.clientHeight,saveAfter:Boolean(panel.compareDocumentPosition(document.querySelector('#save'))&Node.DOCUMENT_POSITION_FOLLOWING),footerAfterSave:Boolean(document.querySelector('#save').compareDocumentPosition(document.querySelector('body > footer.review__header'))&Node.DOCUMENT_POSITION_FOLLOWING)})); await page.locator('#save').scrollIntoViewIfNeeded(); const saveViewport=await page.locator('#save').evaluate(el=>{const r=el.getBoundingClientRect();const footer=document.querySelector('body > footer.review__header').getBoundingClientRect();return {top:r.top,bottom:r.bottom,visible:r.top>=0&&r.bottom<=innerHeight,footerVisible:footer.top>=0&&footer.bottom<=innerHeight}}); await page.screenshot({path:path.join(artifacts,'lab-save-footer-1280x720.png'),fullPage:false}); await page.locator('#save').click(); await page.waitForFunction(()=>document.querySelector('#status').textContent.includes('Оценка сохранена')); const reviewFlow={reviewSaveEnabled,commentStartsCollapsed,commentExpanded:await commentDisclosure.evaluate(e=>e.open),draftStatus:await page.locator('#draft-status').textContent(),reviewScroll,saveViewport,reviewSaved:await page.locator('#status').textContent()};
|
||||
await page.locator('#query').fill('document-switch-fixture'); await page.locator('#search-form button[type=submit]').click(); await page.waitForFunction(()=>document.querySelector('.review__result-title span:last-child')?.textContent==='Fixture document A');
|
||||
await page.locator('.review__comment-disclosure').first().locator('summary').click(); await page.locator('.review__comment').first().fill('Fixture-only note for result A.'); const fixtureRating=page.locator('input[name="rating-0"][value="2"]'); await fixtureRating.check(); const ratingBeforeDocumentSwitch=await fixtureRating.isChecked();
|
||||
await page.locator('.review__result-title').nth(0).click(); await page.locator('#document-body h2').filter({hasText:'Fixture document A'}).waitFor();
|
||||
failReviewDocumentB=true; await page.locator('.review__result-title').nth(1).click(); await page.waitForFunction(()=>document.querySelector('#status').textContent==='Не удалось загрузить документ. Повторите попытку.');
|
||||
failReviewDocumentB=true; await page.locator('.review__result-title').nth(1).click(); await page.waitForFunction(()=>document.querySelector('#status').textContent==='Не удалось загрузить документ. Повторите попытку.'); const errorStatus=await page.locator('#status').evaluate(el=>({height:el.getBoundingClientRect().height,role:el.getAttribute('role'),live:el.getAttribute('aria-live')}));
|
||||
const failedDocumentB=await page.evaluate(()=>({selected:document.querySelector('.review__result--selected .review__result-title span:last-child').textContent,heading:document.querySelector('#dialog-heading').textContent,body:document.querySelector('#document-body').textContent,dialogBody:document.querySelector('#dialog-body').textContent,sourceCount:document.querySelectorAll('#document-meta a').length,rating:document.querySelector('input[name="rating-0"]:checked')?.value||null,comment:document.querySelector('.review__comment').value}));
|
||||
failReviewDocumentB=false; await page.locator('.review__result-title').nth(1).click(); await page.locator('#document-body h2').filter({hasText:'Fixture document B'}).waitFor();
|
||||
const successfulDocumentB=await page.evaluate(()=>({heading:document.querySelector('#dialog-heading').textContent,body:document.querySelector('#document-body').textContent,source:document.querySelector('#document-meta a')?.href||null,rating:document.querySelector('input[name="rating-0"]:checked')?.value||null,comment:document.querySelector('.review__comment').value}));
|
||||
@@ -95,7 +97,7 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
const documentSwitch={ratingBeforeDocumentSwitch,failedDocumentB,successfulDocumentB,staleDocumentA,lastReviewRatings:fixtureState.lastReviewRatings,reviewSaves:fixtureState.reviewSaves}; console.log('documentSwitchFixture',JSON.stringify(documentSwitch));
|
||||
if(!ratingBeforeDocumentSwitch||failedDocumentB.selected!=='Fixture document B'||failedDocumentB.heading!=='Fixture document B'||failedDocumentB.body||failedDocumentB.dialogBody||failedDocumentB.sourceCount||failedDocumentB.rating!=='2'||failedDocumentB.comment!=='Fixture-only note for result A.'||successfulDocumentB.heading!=='Fixture document B'||!successfulDocumentB.body.includes('Content for fixture B only.')||!successfulDocumentB.source.includes('/review-b/edition/2025/ru')||successfulDocumentB.rating!=='2'||successfulDocumentB.comment!=='Fixture-only note for result A.'||staleDocumentA.heading!=='Fixture document B'||!staleDocumentA.body.includes('Content for fixture B only.')||!staleDocumentA.source.includes('/review-b/edition/2025/ru')||staleDocumentA.selected!=='Fixture document B'||!fixtureState.lastReviewRatings.some((item)=>item.code==='review-a'&&item.rating===2)||fixtureState.reviewSaves<2) process.exit(1);
|
||||
await page.setViewportSize({width:1280,height:800}); await page.goto('https://fixture.invalid/?q=%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B8%D0%B1%D1%8B%D0%BB%D1%8C&status=active');
|
||||
await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor(); await page.locator('#document-language').selectOption('ky'); await page.locator('#document-edition').selectOption('2023'); await page.waitForFunction(()=>document.querySelector('#public-document-body h2')?.textContent==='Russian-only edition'); const languageFallback={language:await page.locator('#document-language').inputValue(),heading:await page.locator('#public-document-body h2').textContent()};
|
||||
await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor(); await page.locator('#document-language').selectOption('ky'); await page.locator('#document-edition').selectOption('2023'); await page.waitForFunction(()=>document.querySelector('#public-document-body h2')?.textContent==='Russian-only edition'); const languageFallback={language:await page.locator('#document-language').inputValue(),heading:await page.locator('#public-document-body h2').textContent(),selectorHidden:await page.locator('.search__document-language').evaluate(label=>label.hidden)};
|
||||
await page.locator('.search__result-title').nth(1).click(); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Для документа нет доступных редакций с текстом.'); const noEditionExpandedText=await page.locator('#public-document-body').textContent(); const noEditionExpandedHeading=await page.locator('#public-document-heading').textContent(); const noEditionExpandHidden=await page.locator('#document-expand').evaluate(e=>getComputedStyle(e).display==='none');
|
||||
await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor(); await page.locator('.search__result-title').nth(2).click(); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Fixture editions error'); const editionErrorExpandedText=await page.locator('#public-document-body').textContent(); const editionErrorExpandedHeading=await page.locator('#public-document-heading').textContent(); const editionErrorExpandHidden=await page.locator('#document-expand').evaluate(e=>getComputedStyle(e).display==='none');
|
||||
await page.goto('https://fixture.invalid/?q=%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B8%D0%B1%D1%8B%D0%BB%D1%8C&status=active');
|
||||
@@ -106,20 +108,18 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
const tableOverflow=await page.locator('#public-document-body').evaluate(body=>{const table=document.createElement('table');table.style.width='100%';table.innerHTML='<tbody><tr>'+Array.from({length:10},()=>'<td>'+('широкаятаблица'.repeat(20))+'</td>').join('')+'</tr></tbody>';body.append(table);const result={clientWidth:table.clientWidth,scrollWidth:table.scrollWidth,pageWidth:document.documentElement.scrollWidth,viewport:innerWidth};table.remove();return result});
|
||||
await page.emulateMedia({reducedMotion:'reduce'}); const reducedMotion=await page.evaluate(()=>({scrollBehavior:getComputedStyle(document.documentElement).scrollBehavior,transitionDuration:getComputedStyle(document.querySelector('#document-print')).transitionDuration})); await page.emulateMedia({reducedMotion:'no-preference'});
|
||||
await page.locator('#public-query').fill('service-error'); await page.locator('#public-search-form button[type=submit]').click(); await page.waitForFunction(()=>document.querySelector('#public-status').textContent==='Fixture search error'); const searchError={message:await page.locator('#public-status').textContent(),query:await page.locator('#public-query').inputValue(),role:await page.locator('#public-status').getAttribute('role')}; await page.locator('#public-query').fill('налог на прибыль'); await page.locator('#public-search-form button[type=submit]').click(); await page.locator('.search__result-title').first().waitFor(); await page.locator('.search__result-title').first().click(); await page.locator('#public-document-body h2').first().waitFor();
|
||||
await page.locator('#document-edition').selectOption('2023'); await page.waitForFunction(()=>document.querySelector('#public-document-body h2')?.textContent==='Russian-only edition'); const previousEditionSource=await page.locator('#document-source').getAttribute('href'); failNextEdition=true; await page.locator('#document-edition').selectOption('2024'); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Загрузка редакции…'); const sourceDuringEditionLoad=await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href')})); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Fixture edition error'); const editionError=await page.locator('#document-facts').textContent(); const sourceAfterEditionError=await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href')})); await page.locator('#document-edition').selectOption('2024'); await page.locator('#public-document-body h2').first().waitFor(); const editionRetry=await page.locator('#public-document-body h2').first().textContent(); const sourceAfterEditionRetry=await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href')}));
|
||||
await page.locator('.search__result-title').nth(1).click(); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Для документа нет доступных редакций с текстом.'); const noEditions={message:await page.locator('#document-facts').textContent(),bodyChildren:await page.locator('#public-document-body').locator(':scope > *').count(),source:await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href')}))};
|
||||
await page.locator('#document-edition').selectOption('2023'); await page.waitForFunction(()=>document.querySelector('#public-document-body h2')?.textContent==='Russian-only edition'); const previousEditionSource=await page.locator('#document-source').getAttribute('href'); failNextEdition=true; await page.locator('#document-edition').selectOption('2024'); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Загрузка редакции…'); const sourceDuringEditionLoad=await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href'),opened:document.querySelectorAll('.search__opened').length})); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Fixture edition error'); const editionError=await page.locator('#document-facts').textContent(); const sourceAfterEditionError=await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href'),opened:document.querySelectorAll('.search__opened').length})); await page.locator('#document-edition').selectOption('2024'); await page.locator('#public-document-body h2').first().waitFor(); const editionRetry=await page.locator('#public-document-body h2').first().textContent(); const sourceAfterEditionRetry=await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href'),opened:document.querySelectorAll('.search__opened').length}));
|
||||
await page.locator('.search__result-title').nth(1).click(); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Для документа нет доступных редакций с текстом.'); const noEditions={message:await page.locator('#document-facts').textContent(),bodyChildren:await page.locator('#public-document-body').locator(':scope > *').count(),source:await page.locator('#document-source').evaluate(link=>({hidden:link.hidden,href:link.getAttribute('href')})),languageSelectorHidden:await page.locator('.search__document-language').evaluate(label=>label.hidden)};
|
||||
delayNextEdition=true; await page.locator('.search__result-title').first().click(); await page.waitForFunction(()=>document.querySelector('#document-facts').textContent==='Загрузка редакции…'); const editionLoading=true; await page.locator('#public-document-body h2').first().waitFor();
|
||||
await page.setViewportSize({width:1280,height:800});
|
||||
await page.locator('#search-account-open').click(); await page.evaluate(()=>{const d=document.querySelector('#account-dialog');const controls=[...d.querySelectorAll('a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')].filter(e=>e.getClientRects().length&&getComputedStyle(e).visibility!=='hidden');controls.at(-1).focus();}); await page.keyboard.press('Tab'); const accountTabTarget=await page.evaluate(()=>({tag:document.activeElement.tagName,id:document.activeElement.id,dialog:document.querySelector('#account-dialog').contains(document.activeElement)})); const accountTabWrap=accountTabTarget.dialog; await page.keyboard.press('Shift+Tab'); const accountReverseTabWrap=await page.evaluate(()=>({id:document.activeElement.id,dialog:document.querySelector('#account-dialog').contains(document.activeElement)})); await page.keyboard.press('Escape');
|
||||
const viewportWidths=[]; for (const width of [320,390,640,1024,1280,1440]) { await page.setViewportSize({width,height:800}); viewportWidths.push(await page.evaluate(()=>({width:innerWidth,scrollWidth:document.documentElement.scrollWidth}))); } await page.setViewportSize({width:1280,height:800});
|
||||
const breakpointLayouts=[]; for (const width of [1101,1175,1176]) { await page.setViewportSize({width,height:800}); breakpointLayouts.push(await page.evaluate(()=>({width:innerWidth,scrollWidth:document.documentElement.scrollWidth,columns:getComputedStyle(document.querySelector('#search-layout')).gridTemplateColumns.split(' ').length,filtersHidden:false}))); }
|
||||
await page.evaluate(()=>{document.querySelector('#search-layout').dataset.filtersHidden='true';});
|
||||
for (const width of [1101,1175,1176]) { await page.setViewportSize({width,height:800}); breakpointLayouts.push(await page.evaluate(()=>({width:innerWidth,scrollWidth:document.documentElement.scrollWidth,columns:getComputedStyle(document.querySelector('#search-layout')).gridTemplateColumns.split(' ').length,filtersHidden:document.querySelector('#search-layout').dataset.filtersHidden==='true'}))); }
|
||||
await page.evaluate(()=>delete document.querySelector('#search-layout').dataset.filtersHidden); await page.setViewportSize({width:1280,height:800});
|
||||
const viewportWidths=[]; for (const width of [320,390,640,1024,1101,1175,1176,1280,1440,1713]) { await page.setViewportSize({width,height:800}); viewportWidths.push(await page.evaluate(()=>({width:innerWidth,scrollWidth:document.documentElement.scrollWidth}))); } await page.setViewportSize({width:1280,height:800});
|
||||
const breakpointLayouts=[]; for (const width of [1024,1101,1175,1191]) { await page.setViewportSize({width,height:800}); await page.evaluate(()=>window.dispatchEvent(new Event('resize'))); breakpointLayouts.push(await page.evaluate(()=>{const rect=(selector)=>document.querySelector(selector).getBoundingClientRect();return {width:innerWidth,scrollWidth:document.documentElement.scrollWidth,filtersWidth:rect('#search-filters').width,resultsWidth:rect('.search__results').width,splitterWidth:rect('#search-splitter').width,documentWidth:rect('#public-document-panel').width,filtersOpen:document.querySelector('#search-filters').classList.contains('is-open')}})); }
|
||||
await page.setViewportSize({width:1024,height:800}); await page.locator('#mobile-filters-open').click(); const filterDrawer=await page.evaluate(()=>({open:document.querySelector('#search-filters').classList.contains('is-open'),modal:document.querySelector('#search-filters').getAttribute('aria-modal'),overlay:getComputedStyle(document.querySelector('#filter-overlay')).display!=='none',results:document.querySelector('.search__results').getBoundingClientRect().width,document:document.querySelector('#public-document-panel').getBoundingClientRect().width})); const filterCloseVisible=await page.locator('#mobile-filters-close').isVisible(); await page.locator('#mobile-filters-close').click(); await page.locator('#mobile-filters-open').click(); await page.keyboard.press('Escape'); const filterDrawerEscape=await page.evaluate(()=>({closed:!document.querySelector('#search-filters').classList.contains('is-open'),focus:document.activeElement.id})); await page.setViewportSize({width:1280,height:800});
|
||||
const longContent=await page.evaluate(()=>{const result=document.querySelector('.search__result-title'),heading=document.querySelector('#public-document-heading'),oldResult=result.textContent,oldHeading=heading.textContent;const longName='Кыргызская Республика '.repeat(8);result.textContent=longName;heading.textContent=longName;const image=document.createElement('img');image.width=2200;image.height=100;image.src='data:image/svg+xml,'+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="2200" height="100"><rect width="2200" height="100" fill="gold"/></svg>');document.querySelector('#public-document-body').append(image);const titleWidths=[result,heading].map(el=>({client:el.clientWidth,scroll:el.scrollWidth}));const imageWidth=image.getBoundingClientRect().width,bodyWidth=document.querySelector('#public-document-body').clientWidth,pageWidth=document.documentElement.scrollWidth;result.textContent=oldResult;heading.textContent=oldHeading;image.remove();return {titleWidths,imageWidth,bodyWidth,pageWidth,viewport:innerWidth}});
|
||||
console.log('safeLinks',JSON.stringify(safeLinks)); console.log('viewportWidths',JSON.stringify(viewportWidths)); console.log('breakpointLayouts',JSON.stringify(breakpointLayouts));
|
||||
console.log('safeLinks',JSON.stringify(safeLinks)); console.log('initialSearch',JSON.stringify(initialSearch)); console.log('tocState',JSON.stringify(tocState)); console.log('splitterState',JSON.stringify({splitterStart,splitterKeyboard,keyboardMin,keyboardMax,splitterHome,splitterEnd,splitterLeft,splitterRight,splitterPointer,splitterStored,splitterRestored,splitterStoredMax,splitterStoredMin,splitterResize,stalePublicSelection,markerAfterReload})); console.log('freshSplitter',JSON.stringify(freshSplitter)); console.log('splitterDefault',JSON.stringify(splitterDefault)); console.log('filterDrawer',JSON.stringify({filterDrawer,filterCloseVisible,filterDrawerEscape})); console.log('visualDetails',JSON.stringify({successStatus,errorStatus,labLoadingStatus,compactResult,accountGeometry})); console.log('viewportWidths',JSON.stringify(viewportWidths)); console.log('breakpointLayouts',JSON.stringify(breakpointLayouts));
|
||||
console.log('subnavAcceptance',JSON.stringify({sourcesDialog,sourcesEscapeClosed,sourcesFocusRestored,accountDialogFocusInside,accountEscapeClosed,accountFocusRestored,printState,tableOverflow,reducedMotion,searchError,editionError,editionRetry,previousEditionSource,sourceDuringEditionLoad,sourceAfterEditionError,sourceAfterEditionRetry,noEditions,languageFallback,noEditionExpandedText,noEditionExpandedHeading,noEditionExpandHidden,editionErrorExpandedText,editionErrorExpandedHeading,editionErrorExpandHidden,expandedEscapeClosed,expandedFocusRestored,editionLoading,accountTabWrap,accountTabTarget,accountReverseTabWrap,longContent,tutorialScreens,viewportWidths,breakpointLayouts}));
|
||||
console.log(JSON.stringify({resultHighlight,fonts,favicons,widths,view,drawer,modalBackground,focusWrap,focusVisible,focusReverseWrap,focusRestored,back,chipsBefore,chipsWithTwo,preservedFilters,urlFilters,openedCount,firstFindCount,nextFindCount,documentLanguage,kyrgyzUi,kyrgyzEmpty,expanded,accountActions,desktopFilters,routes,errors},null,2));
|
||||
console.log(JSON.stringify({resultHighlight,fonts,favicons,widths,view,drawer,modalBackground,focusWrap,focusVisible,focusReverseWrap,focusRestored,back,chipsBefore,chipsWithTwo,preservedFilters,urlFilters,openedCount,firstFindCount,findClearedAfterFilterChange,nextFindCount,documentTitleStyle,documentLanguage,kyrgyzUi,kyrgyzEmpty,expanded,accountActions,desktopFilters,routes,errors},null,2));
|
||||
const referencePath=process.env.REFERENCE_IMAGE || path.join(repo, 'docs/design/tunduk-search-target.png');
|
||||
if(fs.existsSync(referencePath)) {
|
||||
const comparePage=await browser.newPage();
|
||||
@@ -154,17 +154,54 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
["safeLinks.privateImage!==null", safeLinks.privateImage!==null],
|
||||
["viewportWidths.some(item=>item.scrollWidth>item.width)", viewportWidths.some(item=>item.scrollWidth>item.width)],
|
||||
["breakpointLayouts.some(item=>item.scrollWidth>item.width)", breakpointLayouts.some(item=>item.scrollWidth>item.width)],
|
||||
["visible layouts do not switch before 1176px", breakpointLayouts.slice(0,3).some((item,index)=>item.columns!==(index===2?3:2))],
|
||||
["hidden filters are lost during resize", breakpointLayouts.slice(3).some(item=>item.columns!==2||!item.filtersHidden)],
|
||||
["compact filters stay behind the drawer while both panels fit", breakpointLayouts.some(item=>item.filtersWidth!==0||item.resultsWidth<360||item.splitterWidth!==0||item.documentWidth<560)],
|
||||
["compact filter drawer preserves access without replacing the two content panels", !filterDrawer.open||filterDrawer.modal!=="true"||!filterDrawer.overlay||filterDrawer.results<360||filterDrawer.document<560||!filterCloseVisible||!filterDrawerEscape.closed||filterDrawerEscape.focus!=='mobile-filters-open'],
|
||||
["resultHighlight!=='\u043d\u0430\u043b\u043e\u0433\u0435 \u043d\u0430 \u043f\u0440\u0438\u0431\u044b\u043b\u044c'", resultHighlight!=='налоге на прибыль'],
|
||||
["navGeometry.search.left!==26", navGeometry.search.left!==26],
|
||||
["navGeometry.search.right!==123", navGeometry.search.right!==123],
|
||||
["navGeometry.sources.left!==146", navGeometry.sources.left!==146],
|
||||
["Math.abs(navGeometry.sources.right-244)>3", Math.abs(navGeometry.sources.right-244)>3],
|
||||
["Math.abs(navGeometry.language.left-284)>2", Math.abs(navGeometry.language.left-284)>2],
|
||||
["Math.abs(navGeometry.language.right-372)>2", Math.abs(navGeometry.language.right-372)>2],
|
||||
["navGeometry.status.left!==381", navGeometry.status.left!==381],
|
||||
["Math.abs(navGeometry.demoText.left-510)>3", Math.abs(navGeometry.demoText.left-510)>3],
|
||||
["initialSearch.state!=='initial'", initialSearch.state!=='initial'],
|
||||
["initialSearch.count!==''", initialSearch.count!=='' ],
|
||||
["!initialSearch.paginationHidden", !initialSearch.paginationHidden],
|
||||
["!initialSearch.breadcrumbHidden", !initialSearch.breadcrumbHidden],
|
||||
["initialSearch.opened!==0", initialSearch.opened!==0],
|
||||
["!initialSearch.headingHidden", !initialSearch.headingHidden],
|
||||
["!tocState.nested", !tocState.nested],
|
||||
["documentTitleStyle.fontSize!==30", documentTitleStyle.fontSize!==30],
|
||||
["documentTitleStyle.lineHeight!==38", documentTitleStyle.lineHeight!==38],
|
||||
["!documentTitleStyle.fontFamily.includes('Noto Serif')", !documentTitleStyle.fontFamily.includes('Noto Serif')],
|
||||
["!tocState.targetsUnique", !tocState.targetsUnique],
|
||||
["!tocState.anchorsExist", !tocState.anchorsExist],
|
||||
["tocState.ordinaryMentionIncluded", tocState.ordinaryMentionIncluded],
|
||||
["tocState.languageSelectorHidden", tocState.languageSelectorHidden],
|
||||
["tocState.splitter.role!=='separator'", tocState.splitter.role!=='separator'],
|
||||
["navGeometry.languageInFilters!==true", navGeometry.languageInFilters!==true],
|
||||
["!navGeometry.labNavVisible", !navGeometry.labNavVisible],
|
||||
["labNavColor!=='rgb(157, 38, 51)'", labNavColor!=='rgb(157, 38, 51)'],
|
||||
["!navGeometry.filterHeadingSameRow", !navGeometry.filterHeadingSameRow],
|
||||
["navGeometry.filterLanguageGap>10", navGeometry.filterLanguageGap>10],
|
||||
["navGeometry.splitterWidth!==12", navGeometry.splitterWidth!==12],
|
||||
["navGeometry.filterHeadingSize!==20", navGeometry.filterHeadingSize!==20],
|
||||
["navGeometry.resultsHeadingSize!==20", navGeometry.resultsHeadingSize!==20],
|
||||
["navGeometry.languageSelectWidth<120", navGeometry.languageSelectWidth<120],
|
||||
["navGeometry.searchTextAlign!=='center'", navGeometry.searchTextAlign!=='center'],
|
||||
["splitterKeyboard<=splitterStart", splitterKeyboard<=splitterStart],
|
||||
["splitterDefault.filters!==256||Math.abs(splitterDefault.results-384)>1||Math.abs(splitterDefault.document-624)>1", splitterDefault.filters!==256||Math.abs(splitterDefault.results-384)>1||Math.abs(splitterDefault.document-624)>1],
|
||||
["successStatus.height>1||successStatus.role!=='status'||successStatus.live!=='polite'||!successStatus.success", successStatus.height>1||successStatus.role!=='status'||successStatus.live!=='polite'||!successStatus.success],
|
||||
["errorStatus.height<=1||errorStatus.role!=='alert'||errorStatus.live!=='assertive'", errorStatus.height<=1||errorStatus.role!=='alert'||errorStatus.live!=='assertive'],
|
||||
["labLoadingStatus.height<=1||labLoadingStatus.role!=='status'||!labLoadingStatus.busy", labLoadingStatus.height<=1||labLoadingStatus.role!=='status'||!labLoadingStatus.busy],
|
||||
["compactResult.padding!=='8px 10px'||compactResult.titleTarget<44||compactResult.ratingTarget<44", compactResult.padding!=='8px 10px'||compactResult.titleTarget<44||compactResult.ratingTarget<44],
|
||||
["accountGeometry.width!==560||!accountGeometry.logoutSeparate||!accountGeometry.logoutMuted", accountGeometry.width!==560||!accountGeometry.logoutSeparate||!accountGeometry.logoutMuted],
|
||||
["splitterHome!==keyboardMin", splitterHome!==keyboardMin],
|
||||
["splitterEnd!==keyboardMax", splitterEnd!==keyboardMax],
|
||||
["splitterPointer<25||splitterPointer>55", splitterPointer<25||splitterPointer>55],
|
||||
["splitterLeft.results<360||splitterLeft.document<560||splitterLeft.filters<256", splitterLeft.results<360||splitterLeft.document<560||splitterLeft.filters<256],
|
||||
["splitterRight.results<360||splitterRight.document<560||splitterRight.filters<256", splitterRight.results<360||splitterRight.document<560||splitterRight.filters<256],
|
||||
["Number(splitterStored)!==splitterRight.value", Number(splitterStored)!==splitterRight.value],
|
||||
["splitterRestored.value<splitterRestored.min||splitterRestored.value>splitterRestored.max", splitterRestored.value<splitterRestored.min||splitterRestored.value>splitterRestored.max],
|
||||
["splitterStoredMax.value!==splitterStoredMax.max||splitterStoredMin.value!==splitterStoredMin.min", splitterStoredMax.value!==splitterStoredMax.max||splitterStoredMin.value!==splitterStoredMin.min],
|
||||
["splitterResize.results<360||splitterResize.document<560", splitterResize.results<360||splitterResize.document<560],
|
||||
["freshSplitter.filters!==280||Math.abs(freshSplitter.results-408)>2||freshSplitter.gutter!==8||freshSplitter.document<560||freshSplitter.brand!==166||freshSplitter.descriptor!=='none'||freshSplitter.brandLabel!=='Акылдаш — поиск по правовой базе'", freshSplitter.filters!==280||Math.abs(freshSplitter.results-408)>2||freshSplitter.gutter!==8||freshSplitter.document<560||freshSplitter.brand!==166||freshSplitter.descriptor!=='none'||freshSplitter.brandLabel!=='Акылдаш — поиск по правовой базе'],
|
||||
["stalePublicSelection.selected!=='doc-3'", stalePublicSelection.selected!=='doc-3'],
|
||||
["stalePublicSelection.markers!==0", stalePublicSelection.markers!==0],
|
||||
["markerAfterReload!==1", markerAfterReload!==1],
|
||||
["errors.length", errors.length],
|
||||
["!fonts.sans", !fonts.sans],
|
||||
["!fonts.serif", !fonts.serif],
|
||||
@@ -189,7 +226,8 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
["preservedFilters.documentType!=='code'", preservedFilters.documentType!=='code'],
|
||||
["urlFilters.status!==null", urlFilters.status!==null],
|
||||
["urlFilters.documentType!==null", urlFilters.documentType!==null],
|
||||
["firstFindCount!=='1 \u0438\u0437 3'", firstFindCount!=='1 из 3'],
|
||||
["firstFindCount!==''", firstFindCount!==''],
|
||||
["!findClearedAfterFilterChange", !findClearedAfterFilterChange],
|
||||
["nextFindCount!=='2 \u0438\u0437 3'", nextFindCount!=='2 из 3'],
|
||||
["documentLanguage!=='ru'", documentLanguage!=='ru'],
|
||||
["kyrgyzUi.htmlLang!=='ky'", kyrgyzUi.htmlLang!=='ky'],
|
||||
@@ -204,18 +242,33 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
["kyrgyzUi.findCount!=='2 \u0438\u0447\u0438\u043d\u0435\u043d 3'", kyrgyzUi.findCount!=='2 ичинен 3'],
|
||||
["kyrgyzUi.opened!=='\u0410\u0447\u044b\u043b\u0434\u044b'", kyrgyzUi.opened!=='Ачылды'],
|
||||
["kyrgyzEmpty.count!=='0 \u043d\u0430\u0442\u044b\u0439\u0436\u0430 \u0431\u0435\u0442\u0442\u0435'", kyrgyzEmpty.count!=='0 натыйжа бетте'],
|
||||
["kyrgyzEmpty.heading!=='\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0442\u0435\u0440 \u0442\u0430\u0431\u044b\u043b\u0433\u0430\u043d \u0436\u043e\u043a'", kyrgyzEmpty.heading!=='Документтер табылган жок'],
|
||||
["kyrgyzEmpty.message!=='\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0442\u0435\u0440 \u0442\u0430\u0431\u044b\u043b\u0433\u0430\u043d \u0436\u043e\u043a'", kyrgyzEmpty.message!=='Документтер табылган жок'],
|
||||
["!expanded", !expanded],
|
||||
["!expandedEscapeClosed", !expandedEscapeClosed],
|
||||
["expandedFocusRestored!=='document-expand'", expandedFocusRestored!=='document-expand'],
|
||||
["!accountActions.open", !accountActions.open],
|
||||
["!accountActions.heading", !accountActions.heading],
|
||||
["!accountActions.reviewVisible", !accountActions.reviewVisible],
|
||||
["accountActions.reviewHref!=='/review'", accountActions.reviewHref!=='/review'],
|
||||
["!accountActions.usersVisible", !accountActions.usersVisible],
|
||||
["accountActions.usersHref!=='/users'", accountActions.usersHref!=='/users'],
|
||||
["!accountActions.usersLabel.includes('Управление пользователями')", !accountActions.usersLabel.includes('Управление пользователями')],
|
||||
["!accountActions.logoutVisible", !accountActions.logoutVisible],
|
||||
["desktopFilters.visible!==true", desktopFilters.visible!==true],
|
||||
["!accountActions.closeIcon", !accountActions.closeIcon],
|
||||
["accountActions.closeText!==''", accountActions.closeText!=='' ],
|
||||
["accountActions.closeLabel!=='Закрыть'", accountActions.closeLabel!=='Закрыть'],
|
||||
["accountActions.profileGrid!=='grid'", accountActions.profileGrid!=='grid'],
|
||||
["accountActions.profileRows!==6", accountActions.profileRows!==6],
|
||||
["accountActions.headingHeight!==44", accountActions.headingHeight!==44],
|
||||
["accountActions.headingFontSize!==20", accountActions.headingFontSize!==20],
|
||||
["!accountActions.headingFontFamily.includes('Noto Sans')", !accountActions.headingFontFamily.includes('Noto Sans')],
|
||||
["!accountActions.dataBeforeActions", !accountActions.dataBeforeActions],
|
||||
["!accountActions.dialogFits", !accountActions.dialogFits],
|
||||
["desktopFilters.visible!==false", desktopFilters.visible!==false],
|
||||
["desktopFilters.ariaHidden!==null", desktopFilters.ariaHidden!==null],
|
||||
["routes.searchHidden!==true", routes.searchHidden!==true],
|
||||
["routes.reviewVisible!==true", routes.reviewVisible!==true],
|
||||
["initialFooterCount!==1||routes.visibleFooters!==1", initialFooterCount!==1||routes.visibleFooters!==1],
|
||||
["!sourcesDialog.open", !sourcesDialog.open],
|
||||
["sourcesDialog.labelledBy!=='sources-heading'", sourcesDialog.labelledBy!=='sources-heading'],
|
||||
["!sourcesDialog.focusInside", !sourcesDialog.focusInside],
|
||||
@@ -243,16 +296,21 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
["previousEditionSource!=='https://cbd.minjust.gov.kg/doc-1/edition/2023/ru'", previousEditionSource!=='https://cbd.minjust.gov.kg/doc-1/edition/2023/ru'],
|
||||
["!sourceDuringEditionLoad.hidden", !sourceDuringEditionLoad.hidden],
|
||||
["sourceDuringEditionLoad.href!==null", sourceDuringEditionLoad.href!==null],
|
||||
["sourceDuringEditionLoad.opened!==0", sourceDuringEditionLoad.opened!==0],
|
||||
["!sourceAfterEditionError.hidden", !sourceAfterEditionError.hidden],
|
||||
["sourceAfterEditionError.href!==null", sourceAfterEditionError.href!==null],
|
||||
["sourceAfterEditionError.opened!==0", sourceAfterEditionError.opened!==0],
|
||||
["sourceAfterEditionRetry.hidden", sourceAfterEditionRetry.hidden],
|
||||
["sourceAfterEditionRetry.opened!==1", sourceAfterEditionRetry.opened!==1],
|
||||
["sourceAfterEditionRetry.href!=='https://cbd.minjust.gov.kg/doc-1/edition/2024/ru'", sourceAfterEditionRetry.href!=='https://cbd.minjust.gov.kg/doc-1/edition/2024/ru'],
|
||||
["noEditions.message!=='\u0414\u043b\u044f \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430 \u043d\u0435\u0442 \u0434\u043e\u0441\u0442\u0443\u043f\u043d\u044b\u0445 \u0440\u0435\u0434\u0430\u043a\u0446\u0438\u0439 \u0441 \u0442\u0435\u043a\u0441\u0442\u043e\u043c.'", noEditions.message!=='Для документа нет доступных редакций с текстом.'],
|
||||
["noEditions.bodyChildren!==0", noEditions.bodyChildren!==0],
|
||||
["!noEditions.source.hidden", !noEditions.source.hidden],
|
||||
["noEditions.source.href!==null", noEditions.source.href!==null],
|
||||
["!noEditions.languageSelectorHidden", !noEditions.languageSelectorHidden],
|
||||
["languageFallback.language!=='ru'", languageFallback.language!=='ru'],
|
||||
["languageFallback.heading!=='Russian-only edition'", languageFallback.heading!=='Russian-only edition'],
|
||||
["!languageFallback.selectorHidden", !languageFallback.selectorHidden],
|
||||
["noEditionExpandedText!==''", noEditionExpandedText!==''],
|
||||
["!noEditionExpandedHeading.includes('\u041e \u0432\u0432\u0435\u0434\u0435\u043d\u0438\u0438 \u0432 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435')", !noEditionExpandedHeading.includes('О введении в действие')],
|
||||
["!noEditionExpandHidden", !noEditionExpandHidden],
|
||||
@@ -264,27 +322,37 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
["!accountTabTarget.dialog", !accountTabTarget.dialog],
|
||||
["!accountReverseTabWrap.dialog", !accountReverseTabWrap.dialog],
|
||||
["longContent.titleWidths.some(item=>item.scroll>item.client)", longContent.titleWidths.some(item=>item.scroll>item.client)],
|
||||
["longContent.imageWidth>longContent.bodyWidth", longContent.imageWidth>longContent.bodyWidth],
|
||||
["longContent.imageWidth>longContent.bodyWidth+1", longContent.imageWidth>longContent.bodyWidth+1],
|
||||
["longContent.pageWidth>longContent.viewport", longContent.pageWidth>longContent.viewport],
|
||||
["!labInitial.saveDisabled", !labLayout.initialSaveDisabled],
|
||||
["!labLayout.initialSaveText.includes('Сначала выполните поиск')", !labLayout.initialSaveText.includes('Сначала выполните поиск')],
|
||||
["labLayout.panelScroll<=labLayout.panelClient", labLayout.panelScroll<=labLayout.panelClient],
|
||||
["labLayout.panelHeight>labLayout.viewport*0.69", labLayout.panelHeight>labLayout.viewport*0.69],
|
||||
["!labLayout.saveAfterPanel", !labLayout.saveAfterPanel],
|
||||
["!labLayout.footerAfterSave", !labLayout.footerAfterSave],
|
||||
["labGeometry.headingLeft!==24||labGeometry.subtitleLeft!==24||labGeometry.helpRight!==1416", labGeometry.headingLeft!==24||labGeometry.subtitleLeft!==24||labGeometry.helpRight!==1416],
|
||||
["labGeometry.workspaceActionGap>1||labGeometry.actionFooterGap>1", labGeometry.workspaceActionGap>1||labGeometry.actionFooterGap>1],
|
||||
["labGeometry.actionsHeight!==96||labGeometry.footerHeight!==44", labGeometry.actionsHeight!==96||labGeometry.footerHeight!==44],
|
||||
["!labLayout.footerVisible", !labLayout.footerVisible],
|
||||
["labLayout.publicFooterVisible", labLayout.publicFooterVisible],
|
||||
["labLayout.navHeight!==64", labLayout.navHeight!==64],
|
||||
["labLayout.titlebarHeight!==64", labLayout.titlebarHeight!==64],
|
||||
["labLayout.actionsHeight!==96", labLayout.actionsHeight!==96],
|
||||
["labLayout.footerHeight!==44", labLayout.footerHeight!==44],
|
||||
["labLayout.labTitleSize!==26", labLayout.labTitleSize!==26],
|
||||
["labLayout.sectionHeadingSize!==20", labLayout.sectionHeadingSize!==20],
|
||||
["Math.abs(labLayout.headerLeft-labLayout.workspaceLeft)>1", Math.abs(labLayout.headerLeft-labLayout.workspaceLeft)>1],
|
||||
["Math.abs(labLayout.headerRight-labLayout.workspaceRight)>1", Math.abs(labLayout.headerRight-labLayout.workspaceRight)>1],
|
||||
["!reviewFlow.reviewSaveEnabled", !reviewFlow.reviewSaveEnabled],
|
||||
["!reviewFlow.commentStartsCollapsed", !reviewFlow.commentStartsCollapsed],
|
||||
["!reviewFlow.commentExpanded", !reviewFlow.commentExpanded],
|
||||
["reviewFlow.draftStatus!=='Черновик сохранён на этом устройстве.'", reviewFlow.draftStatus!=='Черновик сохранён на этом устройстве.'],
|
||||
["reviewFlow.reviewScroll.scroll<=reviewFlow.reviewScroll.client", reviewFlow.reviewScroll.scroll<=reviewFlow.reviewScroll.client],
|
||||
["reviewFlow.reviewScroll.internalScroll", !reviewFlow.reviewScroll.internalScroll],
|
||||
["reviewFlow.reviewScroll.height>reviewFlow.reviewScroll.viewport*0.69", reviewFlow.reviewScroll.height>reviewFlow.reviewScroll.viewport*0.69],
|
||||
["!reviewFlow.saveViewport.visible", !reviewFlow.saveViewport.visible],
|
||||
["!reviewFlow.saveViewport.footerVisible", !reviewFlow.saveViewport.footerVisible],
|
||||
["!reviewFlow.reviewScroll.saveAfter", !reviewFlow.reviewScroll.saveAfter],
|
||||
["!reviewFlow.reviewScroll.footerAfterSave", !reviewFlow.reviewScroll.footerAfterSave],
|
||||
["!reviewFlow.reviewSaved.includes('Оценка сохранена')", !reviewFlow.reviewSaved.includes('Оценка сохранена')]
|
||||
].filter(([, failed]) => failed).map(([name]) => name); console.log('labLayout',JSON.stringify(labLayout)); console.log('reviewFlow',JSON.stringify(reviewFlow)); console.log('failedCoreChecks', JSON.stringify(failedCoreChecks)); if (failedCoreChecks.length) process.exit(1);
|
||||
const usersPage=page; await usersPage.setViewportSize({width:320,height:760}); await usersPage.goto('https://fixture.invalid/users'); await usersPage.locator('#user-list .review__user-row').waitFor(); const usersRoute=await usersPage.evaluate(()=>({visible:!document.querySelector('#users-page').hidden,admin:document.body.classList.contains('is-admin'),accountOpen:document.querySelector('#account-dialog').open,headerVisible:getComputedStyle(document.querySelector('body > header.review__header')).display!=='none',footerAfterMain:Boolean(document.querySelector('#users-page').compareDocumentPosition(document.querySelector('body > footer.review__header')) & Node.DOCUMENT_POSITION_FOLLOWING),overflow:document.documentElement.scrollWidth>innerWidth})); await usersPage.locator('#users-ui-ky').click(); const usersKy=await usersPage.evaluate(()=>({lang:document.documentElement.lang,heading:document.querySelector('#users-heading').textContent})); console.log('usersRouteCheck',JSON.stringify({usersRoute,usersKy,errors})); if(!usersRoute.visible||!usersRoute.admin||usersRoute.accountOpen||!usersRoute.headerVisible||!usersRoute.footerAfterMain||usersRoute.overflow||errors.length||usersKy.lang!=='ky'||usersKy.heading!=='Колдонуучулар') process.exit(1);
|
||||
const usersPage=page; await usersPage.setViewportSize({width:320,height:760}); await usersPage.goto('https://fixture.invalid/users'); await usersPage.locator('#user-list .review__user-row').waitFor(); const usersRoute=await usersPage.evaluate(()=>({visibleFooters:[...document.querySelectorAll('body > footer')].filter(el=>getComputedStyle(el).display!=='none'&&el.getBoundingClientRect().height>0).length,visible:!document.querySelector('#users-page').hidden,admin:document.body.classList.contains('is-admin'),accountOpen:document.querySelector('#account-dialog').open,headerVisible:getComputedStyle(document.querySelector('body > header.review__header')).display!=='none',footerAfterMain:Boolean(document.querySelector('#users-page').compareDocumentPosition(document.querySelector('body > footer.review__header')) & Node.DOCUMENT_POSITION_FOLLOWING),reviewActionsHidden:getComputedStyle(document.querySelector('body > .review__actions')).display==='none',footerAfterUsers:document.querySelector('body > footer.review__header').getBoundingClientRect().top>=document.querySelector('#user-list').getBoundingClientRect().bottom,overflow:document.documentElement.scrollWidth>innerWidth})); await usersPage.locator('#users-ui-ky').click(); const usersKy=await usersPage.evaluate(()=>({lang:document.documentElement.lang,heading:document.querySelector('#users-heading').textContent})); console.log('usersRouteCheck',JSON.stringify({usersRoute,usersKy,errors})); if(usersRoute.visibleFooters!==1||!usersRoute.visible||!usersRoute.admin||usersRoute.accountOpen||!usersRoute.headerVisible||!usersRoute.footerAfterMain||!usersRoute.reviewActionsHidden||!usersRoute.footerAfterUsers||usersRoute.overflow||errors.length||usersKy.lang!=='ky'||usersKy.heading!=='Колдонуучулар') process.exit(1);
|
||||
const reflowWidth=640; await usersPage.setViewportSize({width:reflowWidth,height:450});
|
||||
await usersPage.goto('https://fixture.invalid/?q=%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3'); await usersPage.locator('.search__result-title').first().waitFor();
|
||||
const search640=await usersPage.evaluate(()=>{const button=document.querySelector('#search-account-open'),r=button.getBoundingClientRect();return {documentWidth:document.documentElement.scrollWidth,accountVisible:r.width>0&&getComputedStyle(button).visibility!=='hidden',accountWithinViewport:r.left>=0&&r.right<=innerWidth};});
|
||||
@@ -299,10 +367,63 @@ let failNextEdition = false; let delayNextEdition = false; let failReviewDocumen
|
||||
if(search640.documentWidth>reflowWidth||!search640.accountVisible||!search640.accountWithinViewport||!accountDialog640.open||!accountDialog640.withinViewport||!accountDialog640.actionsVisible||review640.documentWidth>reflowWidth||!review640.accountWithinViewport||!review640.logoutVisible||!review640.logoutWithinViewport||users640.documentWidth>reflowWidth||!users640.accountWithinViewport||!users640.logoutVisible||!users640.logoutWithinViewport||!users640.createVisible||!users640.createWithinViewport) process.exit(1);
|
||||
await usersPage.locator('#create-user-open').click(); await usersPage.locator('#new-username').fill('fixture-created'); await usersPage.locator('#temporary-password').fill('Fixture-only-temporary-password-2026'); await usersPage.locator('#create-user-form button[type="submit"]').click(); await usersPage.waitForFunction(()=>!document.querySelector('#create-user-dialog').open); let createdRow=usersPage.locator('#user-list .review__user-row').filter({hasText:'fixture-created'}); await createdRow.waitFor();
|
||||
await createdRow.locator('.review__user-reset-disclosure summary').click(); await createdRow.locator('.review__user-reset input[type="password"]').fill('Fixture-only-reset-password-2026'); const resetResponse=usersPage.waitForResponse((response)=>new URL(response.url()).pathname==='/admin/users/fixture-created/reset-password'); await createdRow.locator('.review__user-reset button[type="submit"]').click(); await resetResponse;
|
||||
await usersPage.locator('#review-account-open').click(); await usersPage.locator('#security-tab').click(); await usersPage.locator('#profile-current-password').fill('Fixture-only-current-password-2026'); await usersPage.locator('#profile-new-password').fill('Fixture-only-new-password-2026'); await usersPage.locator('#profile-confirm-password').fill('Fixture-only-new-password-2026'); const passwordResponse=usersPage.waitForResponse((response)=>new URL(response.url()).pathname==='/auth/change-password'); await usersPage.locator('#profile-password-form button[type="submit"]').click(); await passwordResponse; await usersPage.waitForFunction(()=>!document.querySelector('#account-dialog').open);
|
||||
await usersPage.locator('#review-account-open').click(); await usersPage.locator('#security-tab').click(); const passwordToggle=usersPage.locator('#profile-password-form .review__password-toggle').first(); const securityCloseCount=await usersPage.locator('#security-panel [data-close="account-dialog"]').count(); await passwordToggle.click(); const passwordShown=await usersPage.locator('#profile-current-password').evaluate(input=>input.type==='text'&&input.parentElement.querySelector('.review__password-toggle').getAttribute('aria-pressed')==='true'); await passwordToggle.click(); const passwordHidden=await usersPage.locator('#profile-current-password').evaluate(input=>input.type==='password'&&input.parentElement.querySelector('.review__password-toggle').getAttribute('aria-pressed')==='false'); await usersPage.locator('#profile-current-password').fill('Fixture-only-current-password-2026'); await usersPage.locator('#profile-new-password').fill('Fixture-only-new-password-2026'); await usersPage.locator('#profile-confirm-password').fill('Fixture-only-new-password-2026'); const passwordResponse=usersPage.waitForResponse((response)=>new URL(response.url()).pathname==='/auth/change-password'); await usersPage.locator('#profile-password-form button[type="submit"]').click(); await passwordResponse; await usersPage.waitForFunction(()=>!document.querySelector('#account-dialog').open); if(securityCloseCount!==0||!passwordShown||!passwordHidden) process.exit(1); console.log('accountSecurity',JSON.stringify({securityCloseCount,passwordShown,passwordHidden}));
|
||||
const passwordAccountAfterChange=await usersPage.locator('#profile-username').textContent(); if(passwordAccountAfterChange!==passwordChangeAccount.username||!await usersPage.locator('#users-page').isVisible()) throw new Error('Fixture password change must return the account payload and restore the admin workspace.');
|
||||
createdRow=usersPage.locator('#user-list .review__user-row').filter({hasText:'fixture-created'}); await createdRow.waitFor(); await createdRow.locator('.review__user-actions > button').last().click(); await usersPage.locator('#delete-user-confirm').click(); await usersPage.waitForFunction(()=>![...document.querySelectorAll('#user-list .review__user-row')].some(row=>row.textContent.includes('fixture-created')));
|
||||
const safeFixtureOperations={passwordChanges:fixtureState.passwordChanges,userCreates:fixtureState.userCreates,passwordResets:fixtureState.passwordResets,userDeletes:fixtureState.userDeletes,reviewSaves:fixtureState.reviewSaves,createdUserRemoved:!fixtureState.users.some((user)=>user.username==='fixture-created')}; console.log('safeFixtureOperations',JSON.stringify(safeFixtureOperations));
|
||||
if(safeFixtureOperations.passwordChanges!==1||safeFixtureOperations.userCreates!==1||safeFixtureOperations.passwordResets!==1||safeFixtureOperations.userDeletes!==1||safeFixtureOperations.reviewSaves<2||!safeFixtureOperations.createdUserRemoved) process.exit(1);
|
||||
|
||||
const layoutRegressions={brand:{},mobile:{}};
|
||||
await usersPage.goto('https://fixture.invalid/'); await usersPage.locator('#search-results-heading').waitFor();
|
||||
for (const language of ['ru','ky']) {
|
||||
await usersPage.locator(`#ui-${language}`).click();
|
||||
await usersPage.waitForFunction(expected=>document.documentElement.lang===expected,language);
|
||||
for (const width of [1024,1280,1440]) {
|
||||
await usersPage.setViewportSize({width,height:900});
|
||||
await usersPage.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
|
||||
layoutRegressions.brand[`${language}-${width}`]=await usersPage.evaluate(()=>{
|
||||
const brand=document.querySelector('.search__brand'), name=document.querySelector('.search__brand-name'), form=document.querySelector('.search__query');
|
||||
const range=document.createRange(); range.selectNodeContents(name);
|
||||
const rects=[...range.getClientRects()];
|
||||
return {brandRight:brand.getBoundingClientRect().right,textLeft:Math.min(...rects.map(rect=>rect.left)),textRight:Math.max(...rects.map(rect=>rect.right)),formLeft:form.getBoundingClientRect().left,accessibleName:brand.getAttribute('aria-label')};
|
||||
});
|
||||
}
|
||||
}
|
||||
await usersPage.locator('#ui-ru').click();
|
||||
await usersPage.goto('https://fixture.invalid/review'); await usersPage.locator('#review').waitFor();
|
||||
layoutRegressions.reviewNav=await usersPage.evaluate(()=>{
|
||||
const read=id=>{const el=document.getElementById(id),s=getComputedStyle(el),r=el.getBoundingClientRect();return {tag:el.tagName,href:el.getAttribute('href'),active:el.classList.contains('is-active'),height:r.height,display:s.display,alignItems:s.alignItems,color:s.color,background:s.backgroundColor,borderColor:s.borderTopColor};};
|
||||
return {search:read('review-search-nav'),lab:read('review-review-nav')};
|
||||
});
|
||||
await usersPage.keyboard.press('Tab'); await usersPage.keyboard.press('Tab');
|
||||
layoutRegressions.reviewNav.focused=await usersPage.evaluate(()=>({id:document.activeElement.id,outline:getComputedStyle(document.activeElement).outlineWidth}));
|
||||
await usersPage.goto('https://fixture.invalid/'); await usersPage.locator('#search-results-heading').waitFor();
|
||||
layoutRegressions.publicNav=await usersPage.evaluate(()=>{
|
||||
const read=id=>{const el=document.getElementById(id),s=getComputedStyle(el),r=el.getBoundingClientRect();return {tag:el.tagName,href:el.getAttribute('href'),active:el.classList.contains('is-active'),height:r.height,display:s.display,alignItems:s.alignItems,color:s.color,background:s.backgroundColor,borderColor:s.borderTopColor};};
|
||||
return {search:read('search-nav'),lab:read('search-review-nav')};
|
||||
});
|
||||
await usersPage.setViewportSize({width:390,height:844});
|
||||
await usersPage.goto('https://fixture.invalid/?q=%D0%BD%D0%B0%D0%BB%D0%BE%D0%B3+%D0%BD%D0%B0+%D0%BF%D1%80%D0%B8%D0%B1%D1%8B%D0%BB%D1%8C');
|
||||
await usersPage.locator('.search__result-title').first().waitFor(); await usersPage.locator('.search__result-title').first().click(); await usersPage.locator('#public-document-heading').waitFor();
|
||||
for (const width of [390,320]) {
|
||||
await usersPage.setViewportSize({width,height:844});
|
||||
await usersPage.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
|
||||
layoutRegressions.mobile[width]=await usersPage.evaluate(()=>{
|
||||
const breadcrumb=document.querySelector('.search__breadcrumbs'),text=document.querySelector('#document-breadcrumb'),back=document.querySelector('#document-back'),range=document.createRange();
|
||||
range.selectNodeContents(text);
|
||||
const textRects=[...range.getClientRects()].map(({left,right,top,bottom})=>({left,right,top,bottom}));
|
||||
const backRect=back.getBoundingClientRect(),crumbRect=breadcrumb.getBoundingClientRect();
|
||||
const overlaps=textRects.some(rect=>rect.left<backRect.right&&rect.right>backRect.left&&rect.top<backRect.bottom&&rect.bottom>backRect.top);
|
||||
return {textRects,back:{left:backRect.left,right:backRect.right,top:backRect.top,bottom:backRect.bottom,height:backRect.height,tag:back.tagName,name:back.textContent.trim()},breadcrumb:{left:crumbRect.left,right:crumbRect.right,scrollWidth:breadcrumb.scrollWidth,clientWidth:breadcrumb.clientWidth},overlaps};
|
||||
});
|
||||
}
|
||||
console.log('layoutRegressions',JSON.stringify(layoutRegressions));
|
||||
const brandFailures=Object.entries(layoutRegressions.brand).filter(([,value])=>value.textRight>value.brandRight+0.5||value.formLeft-value.textRight<8||value.accessibleName!=='Акылдаш — поиск по правовой базе').map(([viewport])=>viewport);
|
||||
const navQuiet=value=>value.tag!=='A'||!value.href||value.active||value.height<44||value.display!=='flex'||value.alignItems!=='center'||value.color!=='rgb(157, 38, 51)'||value.background!=='rgb(255, 255, 255)'||value.borderColor!=='rgb(222, 211, 206)';
|
||||
const navPrimary=value=>value.tag!=='A'||!value.href||!value.active||value.height<44||value.display!=='flex'||value.alignItems!=='center'||value.color!=='rgb(255, 255, 255)'||value.background!=='rgb(157, 38, 51)'||value.borderColor!=='rgb(157, 38, 51)';
|
||||
const navFailures=navQuiet(layoutRegressions.reviewNav.search)||navPrimary(layoutRegressions.reviewNav.lab)||navQuiet(layoutRegressions.publicNav.lab)||navPrimary(layoutRegressions.publicNav.search)||layoutRegressions.reviewNav.focused.id!=='review-search-nav'||layoutRegressions.reviewNav.focused.outline!=='3px';
|
||||
const mobileFailures=Object.entries(layoutRegressions.mobile).filter(([,value])=>value.overlaps||value.back.tag!=='BUTTON'||value.back.name!=='К результатам'||value.back.height<44||value.textRects.some(rect=>rect.left<value.breadcrumb.left-1||rect.right>value.breadcrumb.right+1)).map(([viewport])=>viewport);
|
||||
if(brandFailures.length||navFailures||mobileFailures.length) throw new Error(JSON.stringify({brandFailures,navFailures,mobileFailures,layoutRegressions}));
|
||||
await browser.close();
|
||||
|
||||
})();
|
||||
@@ -0,0 +1,29 @@
|
||||
// Synthetic legal-interface examples. Shared by Playwright and the loopback preview.
|
||||
const docs = [
|
||||
{code:'doc-1',name:'Налоговый кодекс Кыргызской Республики',type:'Кодекс',status:'Действует',snippet:'… положения о налоге на прибыль и порядке его исчисления …',edition:'2024',editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']} ]},
|
||||
{code:'doc-2',name:'О введении в действие Налогового кодекса Кыргызской Республики',type:'Закон',status:'Действует',snippet:'… устанавливается порядок введения в действие Налогового кодекса Кыргызской Республики …'},
|
||||
{code:'doc-3',name:'Порядок заполнения налоговой отчётности',type:'Постановление',snippet:'… рекомендации по заполнению налоговой отчётности, включая показатели по налогу на прибыль …'}
|
||||
];
|
||||
const reviewDocs = [
|
||||
{code:'review-a',name:'Fixture document A',type:'fixture',status:'active',edition:'2026'},
|
||||
{code:'review-b',name:'Fixture document B',type:'fixture',status:'active',edition:'2025'}
|
||||
];
|
||||
const visualDocs = [
|
||||
{code:'doc-1',name:'Налоговый кодекс Кыргызской Республики · демонстрационная редакция',type:'Кодекс',status:'Действует',snippet:'Синтетический пример: общие положения о налоге на прибыль и порядке его расчёта.',edition:'2024'},
|
||||
{code:'doc-2',name:'Порядок расчёта налога на прибыль · учебный пример',type:'Методический материал',status:'Демонстрационный',snippet:'Иллюстративный материал для проверки отображения поисковой выдачи.',edition:'2023'}
|
||||
];
|
||||
const visualReviewDocs = [
|
||||
{code:'review-a',name:'Налог на прибыль: синтетический пример',type:'Демонстрационный документ',status:'Учебный пример',edition:'2026'},
|
||||
{code:'review-b',name:'Расчёт условной налоговой базы: синтетический пример',type:'Демонстрационный документ',status:'Учебный пример',edition:'2025'}
|
||||
];
|
||||
const visualArticle = '<h2>Налог на прибыль</h2><p>Синтетический текст для визуальной проверки интерфейса. Он не содержит ссылок на внешние адреса или загружаемые изображения.</p><p><b><span>Раздел I. Общие положения</span></b></p><p><b><span>Глава 1. Условный расчёт</span></b></p><p><b><span>Статья 1. Демонстрационный пример</span></b></p><p>Условная организация использует примерные данные, чтобы показать чтение текста и навигацию по структурным заголовкам.</p><h2>Порядок расчёта</h2><p>Все значения и формулировки в этом документе созданы только для интерфейсного preview.</p>';
|
||||
const visualReviewArticles = {
|
||||
'review-a':'<h2>Налог на прибыль: синтетический пример</h2><p>Демонстрационная редакция для проверки совместной работы результатов и панели документа.</p><p><b><span>Раздел I. Условные положения</span></b></p><p><b><span>Статья 1. Примерная расчётная база</span></b></p><p>Текст полностью вымышлен и используется только для локального fixture-preview.</p>',
|
||||
'review-b':'<h2>Расчёт условной налоговой базы</h2><p>Вымышленный текст для проверки панели чтения и элементов оценки.</p>'
|
||||
};
|
||||
const catalogs = {document_types:[{code:'code',labels:{ru:'Кодекс',ky:'Кодекс'},count:12},{code:'law',labels:{ru:'Закон',ky:'Мыйзам'},count:10},{code:'decree',labels:{ru:'Постановление',ky:'Токтом'},count:8}],statuses:[{code:'active',labels:{ru:'Действует',ky:'Күчүндө'},count:24},{code:'repealed',labels:{ru:'Утратил силу',ky:'Күчүн жоготту'},count:5}],authorities:[{code:'ministries_and_committees',labels:{ru:'Министерства и комитеты',ky:'Министрликтер'},count:5}],legal_forces:[]};
|
||||
const passwordChangeAccount = {username:'fixture-admin',role:'admin',created_at:1780000000,must_change_password:false};
|
||||
const article = '<h2>Налог на прибыль</h2><p><a href="../../tmp/old.html">Old local reference</a> <a href="http://cbd.minjust.gov.kg/old">Legacy HTTP reference</a> <a href="https://cbd.minjust.gov.kg/doc-1" ping="https://evil.invalid/ping">Official reference</a> <a href="https://127.0.0.1/private">Private address reference</a><img src="../../tmp/old.png" srcset="https://evil.invalid/pixel 1x, https://192.168.1.10/pixel 2x"><img alt="Private address image" src="https://192.168.1.10/pixel"></p><p><b><span>Раздел I. Общие положения</span></b></p><p><b><span>Глава 1. Основные положения</span></b></p><p><b><span>Статья 1. Основные понятия</span></b></p><p>Обычное упоминание статьи 9 не является заголовком.</p><p id="duplicate-heading"><b><span>Статья 1. Повторный номер</span></b></p><p id="duplicate-heading"><b><span>Раздел II. Налоговая отчётность</span></b></p><p>Текст документа приведён для примера оформления. Здесь будут отображаться положения выбранной редакции. По запросу налог на прибыль читатель найдёт нужный фрагмент.</p><h2>Налоговая отчётность</h2><p>В этом разделе отображается текст выбранной редакции. Поиск внутри документа помогает перейти к нужному фрагменту.</p><p>Далее приводятся положения о налоге на прибыль.</p><p>Упоминание запроса налог на прибыль в следующем разделе.</p>';
|
||||
const articleKy = '<h2>Киреше салыгы</h2><p><b><span>БӨЛҮМ 1. Жалпы жоболор</span></b></p><p><b><span>Глава 1. Негизги жоболор</span></b></p><p><b><span>Берене 1. Негизги түшүнүктөр</span></b></p><p>Текстте берене 9 жөнүндө кадимки эскерүү бар.</p>';
|
||||
|
||||
module.exports = {docs, reviewDocs, visualDocs, visualReviewDocs, visualArticle, visualReviewArticles, catalogs, passwordChangeAccount, article, articleKy};
|
||||
@@ -2,7 +2,8 @@
|
||||
"name": "akyldash-frontend-visual-review",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"test": "node check.cjs"
|
||||
"test": "node check.cjs",
|
||||
"preview": "node preview-server.cjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"playwright": "1.64.1"
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env node
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const {visualDocs, visualReviewDocs, visualReviewArticles, visualArticle, articleKy, catalogs, passwordChangeAccount} = require('./fixtures.cjs');
|
||||
|
||||
const repo = path.resolve(__dirname, '../..');
|
||||
const htmlPath = path.join(repo, 'backend/search/review.html');
|
||||
const staticRoot = path.join(repo, 'backend/search/static');
|
||||
const html = fs.readFileSync(htmlPath, 'utf8');
|
||||
const port = Number(process.argv[2] || 4173);
|
||||
let users = [{username:'fixture-user',role:'user',must_change_password:false,last_login_at:null,first_login_at:1780000000,password_reset_at:null}];
|
||||
|
||||
const warning = `<div style="position:relative;z-index:1000;padding:5px 12px;background:#38262a;color:#fff;font:600 12px/1.4 sans-serif;text-align:center;letter-spacing:.02em">ЛОКАЛЬНЫЙ PREVIEW · только синтетические данные · внешние ссылки отключены</div><script>document.addEventListener('click',event=>{const link=event.target.closest('a[href]');if(!link)return;const target=new URL(link.href,location.href);if(target.origin!==location.origin){event.preventDefault();event.stopImmediatePropagation();}},true);</script>`;
|
||||
const previewHtml = html.replace('<body>', `<body>${warning}`);
|
||||
const json = (response, status, value) => {
|
||||
response.writeHead(status, {'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});
|
||||
response.end(JSON.stringify(value));
|
||||
};
|
||||
const readBody = (request) => new Promise((resolve) => {
|
||||
let body = '';
|
||||
request.on('data', (chunk) => { body += chunk; if (body.length > 32768) request.destroy(); });
|
||||
request.on('end', () => { try { resolve(JSON.parse(body || '{}')); } catch { resolve({}); } });
|
||||
});
|
||||
const sendHtml = (response) => {
|
||||
response.writeHead(200, {
|
||||
'Content-Type':'text/html; charset=utf-8',
|
||||
'Cache-Control':'no-store',
|
||||
'X-Content-Type-Options':'nosniff',
|
||||
'Referrer-Policy':'no-referrer',
|
||||
'Content-Security-Policy':"default-src 'self' data:; connect-src 'self'; img-src 'self' data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; navigate-to 'self'"
|
||||
});
|
||||
response.end(previewHtml);
|
||||
};
|
||||
|
||||
const server = http.createServer(async (request, response) => {
|
||||
const url = new URL(request.url, 'http://127.0.0.1');
|
||||
const method = request.method || 'GET';
|
||||
if (method === 'GET' && ['/', '/review', '/users'].includes(url.pathname)) return sendHtml(response);
|
||||
if (method === 'GET' && url.pathname === '/auth/me') return json(response, 200, {account:passwordChangeAccount});
|
||||
if (method === 'POST' && url.pathname === '/auth/logout') return json(response, 200, {ok:true});
|
||||
if (method === 'POST' && url.pathname === '/auth/change-password') return json(response, 200, {account:passwordChangeAccount});
|
||||
if (method === 'GET' && url.pathname === '/search/filters') return json(response, 200, catalogs);
|
||||
if (method === 'GET' && url.pathname === '/search') {
|
||||
const query = url.searchParams.get('q') || '';
|
||||
const lab = url.searchParams.has('page_size') && !url.searchParams.has('sort');
|
||||
return json(response, 200, {results:query === 'not-found' ? [] : (lab ? visualReviewDocs : visualDocs),has_next:false,review_token:'fixture-only-token'});
|
||||
}
|
||||
if (method === 'GET' && url.pathname === '/documents/doc-2/editions') return json(response, 200, {available_languages:[],editions:[]});
|
||||
if (method === 'GET' && url.pathname === '/documents/doc-3/editions') return json(response, 503, {error:'Fixture editions error'});
|
||||
if (method === 'GET' && url.pathname === '/documents/doc-1/editions') return json(response, 200, {available_languages:['ru','ky'],editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года',ky:'2024-жылдын 12-январындагы редакция'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']}]});
|
||||
const visualReviewEdition = url.pathname.match(/^\/documents\/(review-a|review-b)\/editions\/(2026|2025)$/);
|
||||
if (method === 'GET' && visualReviewEdition) return json(response, 200, {content:{ru:{html:visualReviewArticles[visualReviewEdition[1]]}}});
|
||||
const edition = url.pathname.match(/^\/documents\/doc-1\/editions\/(2024|2023)$/);
|
||||
if (method === 'GET' && edition) {
|
||||
const language = url.searchParams.get('language') || 'ru';
|
||||
const content = edition[1] === '2023' ? '<h2>Russian-only edition</h2><p>Regression fixture.</p>' : language === 'ky' ? articleKy : visualArticle;
|
||||
return json(response, 200, {content:{[language]:{html:content}}});
|
||||
}
|
||||
if (method === 'GET' && url.pathname === '/admin/users') return json(response, 200, {users});
|
||||
if (method === 'POST' && url.pathname === '/admin/users') {
|
||||
const body = await readBody(request); const username = String(body.username || 'fixture-created');
|
||||
users.push({username,role:'user',must_change_password:true,last_login_at:null,first_login_at:1780000000,password_reset_at:null});
|
||||
return json(response, 201, {username});
|
||||
}
|
||||
if (method === 'POST' && /^\/admin\/users\/[^/]+\/reset-password$/.test(url.pathname)) return json(response, 200, {ok:true});
|
||||
if (method === 'DELETE' && /^\/admin\/users\/[^/]+$/.test(url.pathname)) return json(response, 200, {ok:true});
|
||||
if (method === 'POST' && url.pathname === '/search-reviews') return json(response, 200, {id:42});
|
||||
if (method === 'GET' && url.pathname.startsWith('/static/')) {
|
||||
const name = path.basename(url.pathname);
|
||||
const file = path.join(staticRoot, url.pathname.endsWith('.woff2') ? 'fonts' : '', name);
|
||||
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return json(response, 404, {error:'Not found'});
|
||||
const type = name.endsWith('.woff2') ? 'font/woff2' : name.endsWith('.svg') ? 'image/svg+xml' : 'image/png';
|
||||
response.writeHead(200, {'Content-Type':type,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});
|
||||
return fs.createReadStream(file).pipe(response);
|
||||
}
|
||||
return json(response, 404, {error:'Fixture route not found'});
|
||||
});
|
||||
|
||||
server.on('error', (error) => { process.stderr.write(`${error.code || error.name}\n`); process.exitCode = 1; });
|
||||
server.listen(port, '127.0.0.1', () => {
|
||||
process.stdout.write(`fixture preview listening at http://127.0.0.1:${port}/ (pid ${process.pid})\n`);
|
||||
});
|
||||
Reference in new issue
Block a user