Files
anidev-design-system/components/navigation.js
T

226 lines
7.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { iconSvg, iconNames } from "../icons/icons.js";
let sequence = 0;
const escape = (value) =>
String(value).replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
/** Validate before replacing an existing menu; malformed API data leaves it intact. */
export function validateNavigation(items) {
if (!Array.isArray(items) || items.length > 100)
throw new TypeError("Navigation must contain at most 100 items");
const ids = new Set();
function visit(nodes, level) {
return nodes.map((item) => {
if (
!item ||
typeof item.id !== "string" ||
!/^[a-z][\w-]{0,63}$/i.test(item.id) ||
ids.has(item.id)
)
throw new TypeError("Navigation ids must be unique and valid");
ids.add(item.id);
if (
typeof item.label !== "string" ||
!item.label.trim() ||
item.label.length > 160
)
throw new TypeError("Navigation needs a label of 1–160 characters");
if (!iconNames.includes(item.icon))
throw new TypeError("Unknown navigation icon");
if (
item.children !== undefined &&
(level || !Array.isArray(item.children) || item.children.length > 100)
)
throw new TypeError("Navigation supports one group level");
return {
id: item.id,
label: item.label,
icon: item.icon,
disabled: Boolean(item.disabled),
...(item.children
? {
children: visit(item.children, level + 1).map((child) => ({
...child,
disabled: Boolean(item.disabled) || child.disabled,
})),
}
: {}),
};
});
}
const result = visit(items, 0);
if (ids.size > 100)
throw new TypeError(
"Navigation must contain at most 100 entries including groups",
);
return result;
}
export function mountNavigation(
root,
{
items = [],
activeId = null,
onSelect = () => {},
onActiveChange = () => {},
t = (ru) => ru,
} = {},
) {
const shell = root.closest(".navigation"),
prefix = `anidev-nav-${++sequence}`;
const abort = new AbortController(),
{ signal } = abort;
let model = [],
active = null,
expanded = document.body.classList.contains("dock-open"),
disposed = false;
const groups = new Set();
const leaves = () =>
model
.flatMap((item) =>
item.children ? (item.disabled ? [] : item.children) : [item],
)
.filter((item) => !item.disabled);
function button(item) {
return `<button type="button" data-nav-id="${item.id}" ${item.disabled ? "disabled" : ""} ${active === item.id ? 'aria-current="page"' : ""} aria-label="${escape(item.label)}" title="${escape(item.label)}">${iconSvg(item.icon, { className: "nav-icon" })}<span>${escape(item.label)}</span></button>`;
}
function sync() {
root.querySelectorAll("[data-nav-group]").forEach((group) => {
const open = expanded && groups.has(group.dataset.navGroup);
group.classList.toggle("is-expanded", open);
group
.querySelector(".nav-group-toggle")
.setAttribute("aria-expanded", String(open));
const submenu = group.querySelector(".nav-submenu-container");
submenu.inert = !open;
submenu.setAttribute("aria-hidden", String(!open));
});
}
function render() {
const focused = root.contains(document.activeElement)
? document.activeElement.dataset.navId ||
document.activeElement.dataset.navToggle
: null;
root.innerHTML = model
.map((item) => {
if (!item.children) return button(item);
return `<div class="nav-group" data-nav-group="${item.id}"><button type="button" class="nav-group-toggle" data-nav-toggle="${item.id}" ${item.disabled ? "disabled" : ""} data-active="${item.children.some((child) => child.id === active)}" aria-label="${escape(item.label)}" title="${escape(item.label)}" aria-expanded="false" aria-controls="${prefix}-${item.id}">${iconSvg(item.icon, { className: "nav-icon" })}<span class="nav-group-label">${escape(item.label)}${iconSvg("chevron-down", { size: 16, className: "nav-chevron" })}</span></button><div class="nav-submenu-container" id="${prefix}-${item.id}" aria-hidden="true" inert><div class="nav-submenu-clip"><div class="nav-submenu-list">${item.children.map(button).join("")}</div></div></div></div>`;
})
.join("");
if (!model.length) {
const message = document.createElement("p");
message.className = "nav-empty muted";
message.textContent = t(
"Нет доступных разделов",
"No available sections",
);
root.append(message);
}
sync();
if (focused) {
const candidate = [...root.querySelectorAll("button")].find(
(e) =>
(e.dataset.navId || e.dataset.navToggle) === focused &&
!e.disabled &&
!e.closest("[inert]"),
);
(
candidate ||
root.querySelector("button:not(:disabled)") ||
shell?.querySelector(".dock-brand")
)?.focus({ preventScroll: true });
}
}
function setItems(next, { activeId: requested = active } = {}) {
if (disposed) return;
const valid = validateNavigation(next);
const previous = active;
model = valid;
active = leaves().some((item) => item.id === requested)
? requested
: leaves()[0]?.id || null;
for (const id of groups)
if (!model.some((item) => item.id === id)) groups.delete(id);
model
.filter((item) => item.children?.some((child) => child.id === active))
.forEach((item) => groups.add(item.id));
render();
if (previous !== active) onActiveChange(active);
}
function setActive(id) {
if (disposed) return;
if (!leaves().some((item) => item.id === id))
throw new TypeError("Active section is not available");
setItems(model, { activeId: id });
}
root.addEventListener(
"click",
(event) => {
const toggle = event.target.closest("[data-nav-toggle]");
if (toggle && !toggle.disabled) {
groups.has(toggle.dataset.navToggle)
? groups.delete(toggle.dataset.navToggle)
: groups.add(toggle.dataset.navToggle);
sync();
return;
}
const target = event.target.closest("[data-nav-id]");
if (target && !target.disabled && !target.closest("[inert]")) {
setActive(target.dataset.navId);
onSelect(active);
}
},
{ signal },
);
root.addEventListener(
"keydown",
(event) => {
const group = event.target.closest("[data-nav-group]");
if (!group || !["ArrowRight", "ArrowLeft"].includes(event.key)) return;
event.preventDefault();
if (event.key === "ArrowRight") {
groups.add(group.dataset.navGroup);
sync();
group.querySelector(".nav-submenu-list button:not(:disabled)")?.focus();
} else {
groups.delete(group.dataset.navGroup);
sync();
group.querySelector(".nav-group-toggle").focus();
}
},
{ signal },
);
shell?.addEventListener(
"anidev:dockchange",
(event) => {
expanded = event.detail.open;
sync();
},
{ signal },
);
setItems(items, { activeId });
return {
setItems,
setActive,
clearActive() {
if (disposed) return;
const previous = active;
active = null;
render();
if (previous !== null) onActiveChange(null);
},
get activeId() {
return active;
},
dispose() {
disposed = true;
abort.abort();
},
};
}