Polish toasts and add searchable select and copy input
No files matched your search
@@ -32,7 +32,7 @@ node scripts/serve.mjs
|
||||
|
||||
Строки таблиц, сервисов, событий, сеансов, приложений и настроек имеют заметные hover/focus и состояния выбора. Полоса прокрутки оформлена под тему; место для неё резервируется, поэтому меню и диалоги не сдвигают контент.
|
||||
|
||||
В библиотеке компонентов показаны четыре состояния тостов, readonly-поле и подписанные радио/чекбоксы в капсулах. Для связанных чекбоксов добавлены общие горизонтальная и вертикальная капсулы с независимым выбором пунктов. Работают поиск, фильтры, пагинация, редактирование пользователей и доступов, диалоги, меню аккаунта и command palette. Панель раскрывается при наведении; a/ поддерживает клик, клавиатуру и touch.
|
||||
В библиотеке компонентов показаны четыре состояния компактных тостов, выпадающий список с поиском, строка с иконкой копирования слева, readonly-поле и подписанные радио/чекбоксы в капсулах. Для связанных чекбоксов добавлены общие горизонтальная и вертикальная капсулы с независимым выбором пунктов. Работают поиск, фильтры, пагинация, редактирование пользователей и доступов, диалоги, меню аккаунта и command palette. Панель раскрывается при наведении; a/ поддерживает клик, клавиатуру и touch.
|
||||
|
||||
Личный кабинет и состояния входа — демонстрации на тестовых данных. Сам SSO Service не изменяется; реальная авторизация, письма и Passkey не выполняются. Данные примера хранятся в sessionStorage вкладки; пароли и токены не сохраняются. Сброс — на экране состояний входа.
|
||||
|
||||
|
||||
@@ -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: общая капсула для нескольких связан
|
||||
</fieldset>
|
||||
```
|
||||
|
||||
Тосты: 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";
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 `<div class="search-select" id="${id}" data-search-select><span class="search-select-label" id="${id}-label">${escape(label)}</span><button type="button" class="search-select-trigger" aria-labelledby="${id}-label ${id}-value" aria-haspopup="listbox" aria-expanded="false" aria-controls="${id}-list" ${selected ? "" : "disabled"}><span id="${id}-value" data-search-value>${escape(selected?.label || t("Выберите значение", "Choose a value"))}</span>${iconSvg("chevron-down", { size: 16 })}</button><input type="hidden" name="${escape(name)}" value="${escape(selected?.value || "")}"><div class="search-select-popup" id="${id}-popup" popover="auto" data-search-popup><div class="search-select-search">${iconSvg("search", { size: 16 })}<input type="search" role="combobox" aria-label="${t("Поиск по списку", "Search options")}" aria-expanded="false" aria-autocomplete="list" aria-controls="${id}-list" placeholder="${t("Найти окружение…", "Find environment…")}" autocomplete="off" spellcheck="false"></div><div class="search-select-options" id="${id}-list" role="listbox" aria-labelledby="${id}-label"></div><div class="search-select-empty" hidden>${t("Ничего не найдено", "No results found")}</div><div class="search-select-count" role="status" aria-live="polite"></div></div></div>`;
|
||||
}
|
||||
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();
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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."), `<button data-action="command">${t("Команды", "Commands")} ${commandShortcut}</button>`)}<div class="page-body"><div class="library">
|
||||
<section class="specimen"><h2>Buttons</h2><div class="component-row"><button class="primary" data-action="demo-save">${t("Сохранить", "Save")}</button><button data-action="toast">${t("Вторичная", "Secondary")}</button><button class="danger" data-action="delete">${t("Удалить", "Delete")}</button><button disabled>Disabled</button><button aria-busy="true" disabled>${t("Загрузка…", "Loading…")}</button></div><small>Hover · active · focus · disabled · loading</small></section>
|
||||
<section class="specimen"><h2>Inputs & selects</h2><label class="field">${t("Имя проекта", "Project name")}<input placeholder="Anidev Production"></label><label class="field">Email<input aria-invalid="true" aria-describedby="sample-error" value="invalid-email"><small class="error-text" id="sample-error">${t("Введите корректный email", "Enter a valid email")}</small></label><div class="sample-control-row"><select aria-label="${t("Окружение", "Environment")}"><option>Production</option><option>Staging</option></select><input aria-label="${t("Только для чтения", "Read-only field")}" readonly value="Read only"></div></section>
|
||||
<section class="specimen"><h2>Inputs & selects</h2><label class="field">${t("Имя проекта", "Project name")}<input placeholder="Anidev Production"></label><label class="field">Email<input aria-invalid="true" aria-describedby="sample-error" value="invalid-email"><small class="error-text" id="sample-error">${t("Введите корректный email", "Enter a valid email")}</small></label><div class="sample-control-row"><select aria-label="${t("Окружение", "Environment")}"><option>Production</option><option>Staging</option></select><input aria-label="${t("Только для чтения", "Read-only field")}" readonly value="Read only"></div><div class="search-select-example">${searchSelectMarkup({ id: "environment-search", name: "searchEnvironment", label: t("Окружение — с поиском", "Environment — searchable"), options: environmentOptions, value: "production", t })}</div><div class="field copy-field-example"><label for="copy-input-example">${t("Строка с копированием", "Field with copy action")}</label><div class="copy-input"><button type="button" class="input-copy-action" data-copy-input aria-label="${t("Скопировать значение", "Copy field value")}" title="${t("Скопировать значение", "Copy field value")}">${iconSvg("copy", { size: 16 })}</button><input id="copy-input-example" name="copyExample" value="anidev-production" autocomplete="off"></div></div></section>
|
||||
<section class="specimen selection-specimen"><h2>Selection controls</h2><div class="form-row"><label class="choice-pill" for="check-demo"><input id="check-demo" type="checkbox" checked><span>${t("Email-уведомления", "Email notifications")}</span></label></div><fieldset style="border:0;padding:0"><legend>${t("Период хранения", "Retention period")}</legend><div class="component-row"><label class="choice-pill"><input type="radio" name="retention" value="30" checked><span>30 ${t("дней", "days")}</span></label><label class="choice-pill"><input type="radio" name="retention" value="90"><span>90 ${t("дней", "days")}</span></label></div></fieldset><div class="form-row"><label for="switch-demo">${t("Автообновление", "Auto refresh")}</label><input id="switch-demo" class="switch" role="switch" type="checkbox" checked></div></section>
|
||||
<section class="specimen grouped-choice-specimen"><h2>${t("Группы чекбоксов", "Checkbox groups")}</h2>${[
|
||||
"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"));
|
||||
|
||||
@@ -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.
|
||||
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 5.3 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 4.9 KiB |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 4.8 KiB |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 6.4 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
@@ -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();
|
||||
}
|
||||