Files
anidev-design-system/components/search-select.js
T

304 lines
11 KiB
JavaScript

import { iconSvg } from "../icons/icons.js";
const escape = (value) =>
String(value).replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
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();
};
}