diff --git a/README.md b/README.md index a9792aa..b1afc70 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ node scripts/serve.mjs Строки таблиц, сервисов, событий, сеансов, приложений и настроек имеют заметные hover/focus и состояния выбора. Полоса прокрутки оформлена под тему; место для неё резервируется, поэтому меню и диалоги не сдвигают контент. -В библиотеке компонентов показаны четыре состояния тостов, readonly-поле и подписанные радио/чекбоксы в капсулах. Для связанных чекбоксов добавлены общие горизонтальная и вертикальная капсулы с независимым выбором пунктов. Работают поиск, фильтры, пагинация, редактирование пользователей и доступов, диалоги, меню аккаунта и command palette. Панель раскрывается при наведении; a/ поддерживает клик, клавиатуру и touch. +В библиотеке компонентов показаны четыре состояния компактных тостов, выпадающий список с поиском, строка с иконкой копирования слева, readonly-поле и подписанные радио/чекбоксы в капсулах. Для связанных чекбоксов добавлены общие горизонтальная и вертикальная капсулы с независимым выбором пунктов. Работают поиск, фильтры, пагинация, редактирование пользователей и доступов, диалоги, меню аккаунта и command palette. Панель раскрывается при наведении; a/ поддерживает клик, клавиатуру и touch. Личный кабинет и состояния входа — демонстрации на тестовых данных. Сам SSO Service не изменяется; реальная авторизация, письма и Passkey не выполняются. Данные примера хранятся в sessionStorage вкладки; пароли и токены не сохраняются. Сброс — на экране состояний входа. diff --git a/components/CONTRACT.md b/components/CONTRACT.md index 392e151..c396036 100644 --- a/components/CONTRACT.md +++ b/components/CONTRACT.md @@ -14,6 +14,10 @@ Поля: readonly остаётся фокусируемым и позволяет выделение/копирование, но не редактирование. Программный фокус #content не рисует рамку вокруг всей страницы. В sample-control-row зазор 12px и общая высота контролов; на мобильном они стоят друг под другом. +Строка с копированием: `.copy-input` содержит подписанный input и кнопку `.input-copy-action[data-copy-input]` с иконкой слева внутри поля. Копируется текущее значение, включая изменения пользователя. Кнопка имеет доступное имя; результат или ошибка Clipboard API показываются тостом. + +Select с поиском: `searchSelectMarkup` и `mountSearchSelect` из `search-select.js`. Настройки: уникальный id, name, label, options ({value, label, disabled}), value и t; mount принимает onChange и возвращает cleanup. Native select остаётся отдельной разновидностью. Поиск фильтрует подписи без учёта регистра; пустой результат показан явно. ArrowUp/Down перемещают активный пункт, Enter выбирает, Escape закрывает с возвратом фокуса, Tab продолжает обход формы. Ctrl/Cmd+Home/End переходят к краям списка; disabled пропускаются. Выбор обновляет hidden input и отправляет input/change только при смене значения. Выпадающая панель использует auto popover, ограничена viewport и закрывается при раскрытии Dock или модального окна. + Choice pill: подписанные checkbox/radio помещаются внутрь label.choice-pill со span текста. Вся капсула кликабельна; native input сохраняет поведение и клавиатуру. Контрол и подпись центрированы, checked меняет фон/рамку/цвет, focus-visible обводит капсулу; минимальная высота 40px, на мобильном 44px. Табличные checkbox остаются компактными. Choice group: общая капсула для нескольких связанных checkbox. Fieldset/legend задают название группы, div.choice-group — одну внешнюю поверхность, label.choice-group-option — пункты без отдельных пузырьков. По умолчанию расположение горизонтальное; choice-group--vertical ставит пункты столбцом. Нативные checkbox сохраняют независимый множественный выбор, клики по подписям и Space. Разделители нарисованы псевдоэлементами и не смещают центры контролов. Focus-visible меняет фон пункта без прямоугольной рамки. Минимальная высота пункта — 44px. @@ -34,7 +38,7 @@ Choice group: общая капсула для нескольких связан ``` -Тосты: createNotifier из toast.js, типы success/info/warning/error. Иконка, заголовок, текст, семантический акцент и закрытие. Таймеры: 4/5/8 секунд, ошибка без автоматического скрытия. Hover и фокус приостанавливают таймер. Повторный вызов заменяет активное уведомление. Error использует role=alert/assertive; остальные status/polite. Текст вставляется через textContent. Тост помещается в активный dialog и показывается в верхнем слое: затемнение не перекрывает его, закрытие доступно мышью и клавиатурой, фокус возвращается инициатору. +Тосты: createNotifier из toast.js, типы success/info/warning/error. Компактная поверхность без цветной боковой полосы: иконка и закрытие центрированы, основной текст приглушён, акцент сосредоточен на иконке. Таймеры: 4/5/8 секунд, ошибка без автоматического скрытия. Hover и фокус приостанавливают таймер. Повторный вызов заменяет активное уведомление. Error использует role=alert/assertive; остальные status/polite. Текст вставляется через textContent. Тост помещается в активный dialog и показывается в верхнем слое: затемнение не перекрывает его, закрытие доступно мышью и клавиатурой, фокус возвращается инициатору. ```js import { createNotifier } from "./components/toast.js"; diff --git a/components/export-system.js b/components/export-system.js index f3251c9..87da17f 100644 --- a/components/export-system.js +++ b/components/export-system.js @@ -106,6 +106,7 @@ export async function exportSystem( ...iconNames.map((name) => `icons/svg/${name}.svg`), "components/system.css", "components/toast.js", + "components/search-select.js", "components/workspaces.css", "components/ssh-console.js", "components/log-reader.js", diff --git a/components/search-select.js b/components/search-select.js new file mode 100644 index 0000000..0e6e8ec --- /dev/null +++ b/components/search-select.js @@ -0,0 +1,303 @@ +import { iconSvg } from "../icons/icons.js"; +const escape = (value) => + String(value).replace( + /[&<>"']/g, + (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ + c + ], + ); +export const environmentOptions = [ + ["production", "Production"], + ["staging", "Staging"], + ["development", "Development"], + ["testing", "Testing"], + ["sandbox", "Sandbox"], + ["preview", "Preview"], + ["canary", "Canary"], + ["performance", "Performance"], + ["production-eu", "Production · EU Central"], + ["production-us", "Production · US East"], + ["production-asia", "Production · Asia Pacific"], + ["staging-eu", "Staging · EU Central"], + ["staging-us", "Staging · US East"], + ["development-team", "Development · Team"], + ["development-local", "Development · Local"], + ["preview-pr", "Preview · Pull requests"], + ["preview-release", "Preview · Release"], + ["disaster-recovery", "Disaster recovery"], + ["integration", "Integration"], + ["qa", "Quality assurance"], + ["legacy", "Legacy", true], +].map(([value, label, disabled = false]) => ({ value, label, disabled })); +export function searchSelectMarkup({ id, name, label, options, value, t }) { + if (!/^[a-z][\w-]*$/i.test(id)) + throw Error("Search select needs a valid unique id"); + const selected = + options.find((o) => o.value === value && !o.disabled) || + options.find((o) => !o.disabled); + return `
${escape(label)}
`; +} +export function mountSearchSelect(root, { options, t, onChange = () => {} }) { + const trigger = root.querySelector(".search-select-trigger"), + popup = root.querySelector("[data-search-popup]"), + input = popup.querySelector("input"), + list = popup.querySelector("[role=listbox]"), + hidden = root.querySelector("input[type=hidden]"), + valueNode = root.querySelector("[data-search-value]"), + empty = popup.querySelector(".search-select-empty"), + count = popup.querySelector("[role=status]"); + const abort = new AbortController(), + signal = abort.signal; + let matches = [], + active = -1, + frame = 0, + disposed = false, + wasOpenOnPointerDown = false; + function opened() { + return popup.matches(":popover-open"); + } + function position() { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { + if (disposed || !opened() || !root.isConnected) return; + const rect = trigger.getBoundingClientRect(), + width = document.documentElement.clientWidth, + viewport = window.visualViewport, + height = viewport?.height || innerHeight, + offset = viewport?.offsetTop || 0; + const actualWidth = Math.min(Math.max(rect.width, 240), width - 24); + popup.style.width = actualWidth + "px"; + popup.style.left = + Math.max(12, Math.min(rect.left, width - actualWidth - 12)) + "px"; + const below = height + offset - rect.bottom - 8, + above = rect.top - offset - 8; + const preferBelow = + below >= Math.min(popup.scrollHeight, 280) || below >= above; + const available = Math.max( + 80, + Math.min(height - 24, (preferBelow ? below : above) - 12), + ); + popup.style.maxHeight = Math.min(360, available) + "px"; + const popupHeight = popup.getBoundingClientRect().height; + const targetTop = preferBelow + ? rect.bottom + 6 + : rect.top - popupHeight - 6; + popup.style.top = + Math.max( + offset + 12, + Math.min(targetTop, offset + height - popupHeight - 12), + ) + "px"; + }); + } + function paintActive(scroll = true) { + [...list.children].forEach((node, i) => + node.classList.toggle("is-active", i === active), + ); + const node = list.children[active]; + if (node) { + input.setAttribute("aria-activedescendant", node.id); + if (scroll) node.scrollIntoView({ block: "nearest" }); + } else input.removeAttribute("aria-activedescendant"); + } + function render() { + const query = input.value.trim().toLocaleLowerCase(); + matches = options + .map((option, index) => ({ ...option, index })) + .filter((o) => o.label.toLocaleLowerCase().includes(query)); + list.replaceChildren(); + for (const option of matches) { + const node = document.createElement("div"); + node.className = "search-select-option"; + node.id = `${root.id}-option-${option.index}`; + node.setAttribute("role", "option"); + node.setAttribute("aria-selected", String(option.value === hidden.value)); + node.setAttribute("aria-disabled", String(Boolean(option.disabled))); + node.dataset.index = String(option.index); + const label = document.createElement("span"); + label.textContent = option.label; + node.append(label); + const mark = document.createElement("span"); + mark.className = "search-select-mark"; + mark.innerHTML = + option.value === hidden.value ? iconSvg("check", { size: 16 }) : ""; + node.append(mark); + list.append(node); + } + active = matches.findIndex((o) => o.value === hidden.value && !o.disabled); + if (active < 0) active = matches.findIndex((o) => !o.disabled); + empty.hidden = matches.length > 0; + count.textContent = t( + `Найдено: ${matches.length}`, + `${matches.length} options`, + ); + paintActive(false); + position(); + } + function close(restore = true) { + if (opened()) popup.hidePopover(); + trigger.setAttribute("aria-expanded", "false"); + input.setAttribute("aria-expanded", "false"); + input.removeAttribute("aria-activedescendant"); + if (restore && root.isConnected) trigger.focus({ preventScroll: true }); + } + function open() { + if (disposed || trigger.disabled) return; + input.value = ""; + render(); + if (!opened()) popup.showPopover(); + trigger.setAttribute("aria-expanded", "true"); + input.setAttribute("aria-expanded", "true"); + input.focus({ preventScroll: true }); + position(); + requestAnimationFrame(() => paintActive()); + } + function choose(option) { + if (!option || option.disabled) return; + const changed = hidden.value !== option.value; + hidden.value = option.value; + valueNode.textContent = option.label; + close(); + if (changed) { + hidden.dispatchEvent(new Event("input", { bubbles: true })); + hidden.dispatchEvent(new Event("change", { bubbles: true })); + onChange(option.value, option); + } + } + function move(direction) { + if (!matches.some((o) => !o.disabled)) return; + let candidate = active; + for (let i = 0; i < matches.length; i++) { + candidate = (candidate + direction + matches.length) % matches.length; + if (!matches[candidate].disabled) { + active = candidate; + break; + } + } + paintActive(); + } + trigger.addEventListener( + "pointerdown", + () => { + wasOpenOnPointerDown = opened(); + }, + { signal }, + ); + trigger.addEventListener( + "click", + () => { + if (wasOpenOnPointerDown || opened()) close(); + else open(); + wasOpenOnPointerDown = false; + }, + { signal }, + ); + trigger.addEventListener( + "keydown", + (event) => { + if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) { + event.preventDefault(); + event.stopPropagation(); + open(); + if (event.key === "ArrowUp" || event.key === "End") { + active = matches.findLastIndex((o) => !o.disabled); + paintActive(); + } + if (event.key === "Home") { + active = matches.findIndex((o) => !o.disabled); + paintActive(); + } + } + }, + { signal }, + ); + input.addEventListener("input", render, { signal }); + input.addEventListener( + "keydown", + (event) => { + if (event.isComposing) return; + const handled = + ["ArrowDown", "ArrowUp", "Enter", "Escape", "Tab"].includes( + event.key, + ) || + ((event.ctrlKey || event.metaKey) && + ["Home", "End"].includes(event.key)); + if (handled) event.stopPropagation(); + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + event.preventDefault(); + move(event.key === "ArrowDown" ? 1 : -1); + } + if (event.key === "Enter") { + event.preventDefault(); + choose(matches[active]); + } + if (event.key === "Escape") { + event.preventDefault(); + close(); + } + if (event.key === "Tab") { + close(false); + trigger.focus({ preventScroll: true }); + } + if ((event.ctrlKey || event.metaKey) && event.key === "Home") { + event.preventDefault(); + active = matches.findIndex((o) => !o.disabled); + paintActive(); + } + if ((event.ctrlKey || event.metaKey) && event.key === "End") { + event.preventDefault(); + active = matches.findLastIndex((o) => !o.disabled); + paintActive(); + } + }, + { signal }, + ); + list.addEventListener( + "pointerdown", + (event) => { + if (event.target.closest("[role=option]")) event.preventDefault(); + }, + { signal }, + ); + list.addEventListener( + "pointermove", + (event) => { + const node = event.target.closest("[role=option]"); + if (!node) return; + const i = [...list.children].indexOf(node); + if (i >= 0 && !matches[i].disabled) { + active = i; + paintActive(false); + } + }, + { signal }, + ); + list.addEventListener( + "click", + (event) => { + const node = event.target.closest("[role=option]"); + if (node) choose(options[Number(node.dataset.index)]); + }, + { signal }, + ); + popup.addEventListener( + "toggle", + (event) => { + const open = event.newState === "open"; + trigger.setAttribute("aria-expanded", String(open)); + input.setAttribute("aria-expanded", String(open)); + if (!open) input.removeAttribute("aria-activedescendant"); + }, + { signal }, + ); + window.addEventListener("resize", position, { signal }); + window.addEventListener("scroll", position, { signal, capture: true }); + window.visualViewport?.addEventListener("resize", position, { signal }); + window.visualViewport?.addEventListener("scroll", position, { signal }); + return () => { + disposed = true; + abort.abort(); + cancelAnimationFrame(frame); + if (opened()) popup.hidePopover(); + }; +} diff --git a/components/system.css b/components/system.css index 3876556..b4c8885 100644 --- a/components/system.css +++ b/components/system.css @@ -231,8 +231,8 @@ small { min-height: 32px; } .avatar { - width: 30px; - height: 30px; + width: 32px; + height: 32px; border-radius: 50%; background: var(--color-text); color: var(--color-bg); @@ -982,16 +982,17 @@ dialog > p { bottom: 24px; left: 50%; transform: translateX(-50%); - width: min(420px, calc(100% - 32px)); + width: min(380px, calc(100% - 32px)); max-width: calc(100% - 32px); background: var(--color-surface); color: var(--color-text); border: 1px solid - color-mix(in srgb, var(--toast-tone) 30%, var(--color-border)); - border-left: 3px solid var(--toast-tone); + color-mix(in srgb, var(--toast-tone) 18%, var(--color-border)); border-radius: var(--radius-control); - box-shadow: 0 8px 32px #0003; - padding: 14px; + box-shadow: + 0 10px 28px #07181f30, + 0 2px 6px #07181f18; + padding: 14px 16px; font-size: 13px; z-index: 100; display: none; @@ -1007,32 +1008,35 @@ dialog > p { } :is(#toast, .anidev-toast):popover-open { display: flex; - align-items: flex-start; + align-items: center; gap: 12px; - animation: toast-enter 180ms ease-out; + animation: toast-enter 140ms ease-out; } .toast-symbol { display: grid; place-items: center; flex-shrink: 0; - width: 30px; - height: 30px; + width: 32px; + height: 32px; border-radius: 50%; background: color-mix(in srgb, var(--toast-tone) 12%, var(--color-surface)); color: var(--toast-tone); } .toast-content { display: grid; - gap: 4px; + gap: 2px; flex: 1; min-width: 0; } .toast-title { + font-weight: 600; font-size: 14px; line-height: 20px; } .toast-message { - line-height: 1.5; + color: var(--color-muted); + font-weight: 400; + line-height: 20px; overflow-wrap: anywhere; } :is(#toast, .anidev-toast) .toast-dismiss { @@ -1050,7 +1054,7 @@ dialog > p { @keyframes toast-enter { from { opacity: 0; - translate: 0 6px; + translate: 0 4px; } to { opacity: 1; @@ -2928,3 +2932,188 @@ body[data-concept="dock"].dock-open border-left: 0; border-top: 1px solid var(--color-border); } + +.search-select-example { + margin-top: 20px; +} +.search-select { + max-width: 320px; + min-width: 0; +} +.search-select-label { + display: block; + margin-bottom: 6px; + font-size: 14px; +} +.search-select-trigger { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + width: 100%; + height: calc(var(--size-control) + 8px); + padding: 8px 10px; + text-align: left; +} +.search-select-trigger > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.search-select-trigger > svg { + flex-shrink: 0; + color: var(--color-muted); + transition: transform 140ms ease; +} +.search-select-trigger[aria-expanded="true"] > svg { + transform: rotate(180deg); +} +.search-select-popup { + position: fixed; + inset: auto; + margin: 0; + padding: 0; + max-height: 360px; + background: var(--color-surface); + color: var(--color-text); + border: 1px solid var(--color-border); + border-radius: 12px; + box-shadow: 0 10px 30px #07181f30; + overflow: hidden; +} +.search-select-popup:popover-open { + display: flex; + flex-direction: column; + animation: search-select-enter 140ms ease-out; +} +.search-select-search { + position: relative; + padding: 10px; + border-bottom: 1px solid var(--color-border); + flex-shrink: 0; +} +.search-select-search > svg { + position: absolute; + left: 21px; + top: 50%; + translate: 0 -50%; + color: var(--color-muted); + pointer-events: none; +} +.search-select-search input { + width: 100%; + height: 38px; + min-height: 38px; + padding: 7px 10px 7px 34px; + font-size: 13px; +} +.search-select-search input:focus-visible { + outline: 2px solid var(--color-accent); + outline-offset: 0; +} +.search-select-options { + min-height: 0; + overflow-y: auto; + padding: 4px; + scrollbar-gutter: stable; +} +.search-select-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 9px 10px; + min-height: 38px; + border-radius: 6px; + font-size: 13px; + line-height: 20px; + cursor: pointer; +} +.search-select-option > span:first-child { + min-width: 0; + overflow-wrap: anywhere; +} +.search-select-option[aria-selected="true"] { + color: var(--color-accent); + font-weight: 600; +} +.search-select-option.is-active { + background: var(--color-row-hover); +} +.search-select-option[aria-disabled="true"] { + opacity: 0.45; + cursor: not-allowed; +} +.search-select-mark { + display: flex; + align-items: center; + flex-shrink: 0; + width: 16px; +} +.search-select-empty { + padding: 24px 14px; + text-align: center; + font-size: 13px; + color: var(--color-muted); +} +.search-select-empty[hidden] { + display: none; +} +.search-select-count { + padding: 7px 14px; + border-top: 1px solid var(--color-border); + font-size: 11px; + color: var(--color-muted); + flex-shrink: 0; +} +@keyframes search-select-enter { + from { + opacity: 0; + translate: 0 -3px; + } + to { + opacity: 1; + translate: 0 0; + } +} +.copy-field-example { + margin-top: 20px; +} +.copy-input { + position: relative; + min-width: 0; +} +.copy-input > input { + width: 100%; + height: calc(var(--size-control) + 8px); + padding-left: 44px; +} +.copy-input .input-copy-action { + position: absolute; + left: 6px; + top: 0; + bottom: 0; + margin-block: auto; + display: flex; + align-items: center; + justify-content: center; + width: 30px; + height: 30px; + min-height: 30px; + padding: 7px; + border: 0; + background: transparent; + color: var(--color-muted); +} +.copy-input .input-copy-action:hover { + background: var(--color-row-hover); + color: var(--color-text); +} +.copy-input .input-copy-action:focus-visible { + outline: 2px solid var(--color-accent); + outline-offset: 0; +} +body[data-concept="dock"] .copy-input .input-copy-action:active { + transform: none; +} diff --git a/playground/frame.js b/playground/frame.js index 6ada74c..e45ce0d 100644 --- a/playground/frame.js +++ b/playground/frame.js @@ -1,3 +1,8 @@ +import { + searchSelectMarkup, + mountSearchSelect, + environmentOptions, +} from "../components/search-select.js"; import { createNotifier } from "../components/toast.js"; import { sshScreen, mountSsh } from "../components/ssh-console.js"; import { logsScreen, mountLogs } from "../components/log-reader.js"; @@ -337,6 +342,10 @@ function setDockOpen(open, returnFocus = true) { : t("Развернуть меню", "Expand navigation"), ); toggle.title = toggle.getAttribute("aria-label"); + if (open) + document + .querySelectorAll("[data-search-popup]:popover-open") + .forEach((popup) => popup.hidePopover()); $(".main-column").inert = open; syncAdministration(); if (open) { @@ -357,11 +366,14 @@ function savePreferences() { ); } catch {} } +let selectCleanups = []; let workspaceCleanup = () => {}, workspaceRender = 0; let initialRender = true; function render({ preserveDock = false } = {}) { workspaceCleanup(); + selectCleanups.forEach((cleanup) => cleanup()); + selectCleanups = []; workspaceCleanup = () => {}; const workspaceVersion = ++workspaceRender; const dockWasOpen = @@ -418,6 +430,13 @@ function render({ preserveDock = false } = {}) { bindDockHover(); if (dockWasOpen) setDockOpen(true, false); bindCharts(); + document + .querySelectorAll("[data-search-select]") + .forEach((root) => + selectCleanups.push( + mountSearchSelect(root, { options: environmentOptions, t }), + ), + ); if ($("#log-workspace")) workspaceCleanup = mountLogs($("#log-workspace"), { t, @@ -655,7 +674,7 @@ function auth() { function componentScreen() { return `${heading(t("Библиотека компонентов", "Component library"), t("Единые компоненты и состояния Dock.", "Shared Dock components and states."), ``)}

Buttons

Hover · active · focus · disabled · loading
-

Inputs & selects

+

Inputs & selects

${searchSelectMarkup({ id: "environment-search", name: "searchEnvironment", label: t("Окружение — с поиском", "Environment — searchable"), options: environmentOptions, value: "production", t })}

Selection controls

${t("Период хранения", "Retention period")}

${t("Группы чекбоксов", "Checkbox groups")}

${[ "horizontal", @@ -708,6 +727,9 @@ function tokenScreen() { let dialogInitiator = null; function openDialog(title, body, cls = "") { if (document.body.classList.contains("dock-open")) setDockOpen(false, false); + document + .querySelectorAll("[data-search-popup]:popover-open") + .forEach((popup) => popup.hidePopover()); const d = $("#dialog"); if (d.open) d.close(); dialogInitiator = document.activeElement; @@ -894,6 +916,25 @@ function contextMenu(x, y) { } document.addEventListener("click", async (e) => { if (await accountUI.handleClick(e)) return; + const copyButton = e.target.closest("[data-copy-input]"); + if (copyButton) { + const field = copyButton.closest(".copy-input").querySelector("input"); + try { + await navigator.clipboard.writeText(field.value); + toast(t("Значение поля скопировано.", "Field value copied."), { + type: "success", + }); + } catch { + toast( + t( + "Не удалось скопировать значение.", + "Could not copy the field value.", + ), + { type: "error" }, + ); + } + return; + } const pageButton = e.target.closest("[data-page]"); if (pageButton) { const fromDock = Boolean(pageButton.closest(".navigation")); diff --git a/references/QA.md b/references/QA.md index b34c198..6d26be0 100644 --- a/references/QA.md +++ b/references/QA.md @@ -139,3 +139,11 @@ Log reader: фильтры уровня/сервиса/текста, подсв В компоненты добавлен образец «Группы чекбоксов»: по три связанных checkbox в одной общей поверхности, горизонтально и вертикально. У пунктов нет собственных пузырьков; разделители не участвуют в расчёте геометрии, поэтому контролы и подписи остаются на одной оси. Яркая прямоугольная рамка фокуса убрана по уточнению пользователя; клавиатурный фокус обозначается фоном. Проверены 12 сочетаний light/dark × RU/EN × 1440/768/390: количество и ориентация пунктов, ровно одна общая рамка, отсутствие индивидуальных скруглений, центры input/текста/строки, высота >=44px, независимый выбор нескольких значений, клик по подписи и Space, fieldset/legend, отсутствие горизонтального переполнения и ошибок JavaScript. Общая browser suite: 50/50. npm run check проходит. Скриншоты: references/checkbox-groups. + +## Select с поиском, копирование и тосты / 01.12.2026 + +Сохранён native select и добавлен отдельный вариант с поиском по 21 окружению. Проверены фильтрация, пустой результат, выбор стрелками/Enter, пропуск disabled, Escape/Tab, повторный клик по триггеру, границы панели и закрытие перед command palette. В новом поле кнопка копирования находится слева внутри строки и копирует текущее изменённое значение. Результат подтверждается success-тостом; ошибка Clipboard API обрабатывается error-тостом. + +Тосты уплотнены: убрана тяжёлая боковая полоса, иконка и закрытие центрированы, основной текст приглушён, уменьшены ширина и дистанция анимации. Все четыре состояния просмотрены в light/dark. Поведение таймеров, пауза при наведении, постоянная ошибка, верхний слой в dialog и reduced motion сохранились. + +Проверки: search-select — 6 сочетаний тем/ширин, browser — 50/50, navigation-feedback — 79/79, без ошибок JavaScript; scripts/check.mjs проходит. ZIP экспорт содержит новый модуль, CRC проверен. Скриншоты: references/search-select и references/navigation-feedback/toast-*.png. diff --git a/references/navigation-feedback/toast-error-dark.png b/references/navigation-feedback/toast-error-dark.png index c5e50d6..9dfc0aa 100644 Binary files a/references/navigation-feedback/toast-error-dark.png and b/references/navigation-feedback/toast-error-dark.png differ diff --git a/references/navigation-feedback/toast-error-light.png b/references/navigation-feedback/toast-error-light.png index 79c3e3b..25afd4b 100644 Binary files a/references/navigation-feedback/toast-error-light.png and b/references/navigation-feedback/toast-error-light.png differ diff --git a/references/navigation-feedback/toast-info-dark.png b/references/navigation-feedback/toast-info-dark.png index 0feb7d1..e6f89bb 100644 Binary files a/references/navigation-feedback/toast-info-dark.png and b/references/navigation-feedback/toast-info-dark.png differ diff --git a/references/navigation-feedback/toast-info-light.png b/references/navigation-feedback/toast-info-light.png index 4635121..0935edd 100644 Binary files a/references/navigation-feedback/toast-info-light.png and b/references/navigation-feedback/toast-info-light.png differ diff --git a/references/navigation-feedback/toast-success-dark.png b/references/navigation-feedback/toast-success-dark.png index 3487683..aca09eb 100644 Binary files a/references/navigation-feedback/toast-success-dark.png and b/references/navigation-feedback/toast-success-dark.png differ diff --git a/references/navigation-feedback/toast-success-light.png b/references/navigation-feedback/toast-success-light.png index d98ce5a..a15bdac 100644 Binary files a/references/navigation-feedback/toast-success-light.png and b/references/navigation-feedback/toast-success-light.png differ diff --git a/references/navigation-feedback/toast-warning-dark.png b/references/navigation-feedback/toast-warning-dark.png index cb98d52..6b776e4 100644 Binary files a/references/navigation-feedback/toast-warning-dark.png and b/references/navigation-feedback/toast-warning-dark.png differ diff --git a/references/navigation-feedback/toast-warning-light.png b/references/navigation-feedback/toast-warning-light.png index a3499d5..a0467ec 100644 Binary files a/references/navigation-feedback/toast-warning-light.png and b/references/navigation-feedback/toast-warning-light.png differ diff --git a/references/search-select/copy-dark-1440.png b/references/search-select/copy-dark-1440.png new file mode 100644 index 0000000..0dbf612 Binary files /dev/null and b/references/search-select/copy-dark-1440.png differ diff --git a/references/search-select/copy-dark-390.png b/references/search-select/copy-dark-390.png new file mode 100644 index 0000000..617be22 Binary files /dev/null and b/references/search-select/copy-dark-390.png differ diff --git a/references/search-select/copy-dark-768.png b/references/search-select/copy-dark-768.png new file mode 100644 index 0000000..69836d2 Binary files /dev/null and b/references/search-select/copy-dark-768.png differ diff --git a/references/search-select/copy-light-1440.png b/references/search-select/copy-light-1440.png new file mode 100644 index 0000000..1ae76e4 Binary files /dev/null and b/references/search-select/copy-light-1440.png differ diff --git a/references/search-select/copy-light-390.png b/references/search-select/copy-light-390.png new file mode 100644 index 0000000..0329ae8 Binary files /dev/null and b/references/search-select/copy-light-390.png differ diff --git a/references/search-select/copy-light-768.png b/references/search-select/copy-light-768.png new file mode 100644 index 0000000..f176e46 Binary files /dev/null and b/references/search-select/copy-light-768.png differ diff --git a/references/search-select/dark-1440.png b/references/search-select/dark-1440.png new file mode 100644 index 0000000..294b91e Binary files /dev/null and b/references/search-select/dark-1440.png differ diff --git a/references/search-select/dark-390.png b/references/search-select/dark-390.png new file mode 100644 index 0000000..aee2713 Binary files /dev/null and b/references/search-select/dark-390.png differ diff --git a/references/search-select/dark-768.png b/references/search-select/dark-768.png new file mode 100644 index 0000000..c38a83f Binary files /dev/null and b/references/search-select/dark-768.png differ diff --git a/references/search-select/light-1440.png b/references/search-select/light-1440.png new file mode 100644 index 0000000..1ecf859 Binary files /dev/null and b/references/search-select/light-1440.png differ diff --git a/references/search-select/light-390.png b/references/search-select/light-390.png new file mode 100644 index 0000000..7ed9b79 Binary files /dev/null and b/references/search-select/light-390.png differ diff --git a/references/search-select/light-768.png b/references/search-select/light-768.png new file mode 100644 index 0000000..49f0244 Binary files /dev/null and b/references/search-select/light-768.png differ diff --git a/tests/search-select.mjs b/tests/search-select.mjs new file mode 100644 index 0000000..836d153 --- /dev/null +++ b/tests/search-select.mjs @@ -0,0 +1,108 @@ +import { chromium } from "playwright"; +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; + +const browser = await chromium.launch({ + executablePath: + process.env.PLAYWRIGHT_EXECUTABLE_PATH || + "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe", + headless: true, +}); +const page = await browser.newPage({ + permissions: ["clipboard-read", "clipboard-write"], +}); +const errors = []; +page.on("pageerror", (e) => errors.push(e.message)); +const base = process.env.BASE_URL || "http://127.0.0.1:4173"; +await mkdir("references/search-select", { recursive: true }); +let passed = 0; +try { + for (const theme of ["dark", "light"]) + for (const width of [1440, 768, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.goto(`${base}/?page=components&theme=${theme}&locale=ru`); + const root = page.locator("#environment-search"); + const trigger = root.locator(".search-select-trigger"); + const popup = root.locator("[data-search-popup]"); + const search = popup.locator("input"); + await trigger.click(); + await search.fill("staging"); + assert.equal(await popup.locator("[role=option]").count(), 3); + await page.keyboard.press("ArrowDown"); + await page.keyboard.press("Enter"); + assert.equal( + await root.locator("input[type=hidden]").inputValue(), + "staging-eu", + ); + assert.equal( + await trigger.evaluate((e) => e === document.activeElement), + true, + ); + await trigger.click(); + await search.fill("unfindable"); + assert.equal( + await popup.locator(".search-select-empty").isVisible(), + true, + ); + await page.keyboard.press("Enter"); + assert.equal(await popup.isVisible(), true); + await page.keyboard.press("Escape"); + assert.equal(await trigger.getAttribute("aria-expanded"), "false"); + await trigger.press("End"); + const activeId = await search.getAttribute("aria-activedescendant"); + assert.equal( + await page.locator(`#${activeId}`).innerText(), + "Quality assurance", + ); + await page.keyboard.press("Escape"); + await trigger.click(); + await page.waitForTimeout(180); + const rect = await popup.boundingBox(); + assert.ok(rect.x >= 0 && rect.x + rect.width <= width + 1); + assert.ok(rect.y >= 0 && rect.y + rect.height <= 901); + await popup.screenshot({ + path: `references/search-select/${theme}-${width}.png`, + }); + await trigger.click(); + assert.equal(await popup.isVisible(), false); + await trigger.click(); + await page.keyboard.press("Tab"); + assert.equal(await popup.isVisible(), false); + const copyInput = page.locator("#copy-input-example"); + await copyInput.fill("current-value-✓"); + const copyButton = page.locator("[data-copy-input]"); + await copyButton.click(); + assert.equal( + await page.evaluate(() => navigator.clipboard.readText()), + "current-value-✓", + ); + assert.equal( + await page.locator("#toast").getAttribute("data-type"), + "success", + ); + await page.locator("[data-toast-dismiss]").click(); + await page + .locator(".copy-field-example") + .screenshot({ + path: `references/search-select/copy-${theme}-${width}.png`, + }); + await trigger.click(); + await page.keyboard.press("Control+k"); + await page.locator("dialog[open]").waitFor(); + assert.equal(await popup.isVisible(), false); + await page.keyboard.press("Escape"); + assert.equal( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + true, + ); + passed++; + } + assert.deepEqual(errors, []); + console.log( + `PASS: ${passed} searchable-select/copy variants; filtering, empty state, keyboard selection, disabled skip, dismissal, viewport bounds, clipboard, modal integration.`, + ); +} finally { + await browser.close(); +}