Newer
Older
vmk-ui-kit / src / js / components / lists.js
/**
 * VMK UI Kit browser list helper.
 *
 * Mirrors gnexus-ui-kit list helpers:
 *   init(root), activate(item)
 */

const initializedRoots = new WeakSet();

function getItems(root) {
  return [...root.querySelectorAll(".list-item")];
}

function activate(item, options = {}) {
  if (!item || item.classList.contains("is-disabled")) return;

  const list = item.closest(".list");
  if (!list) return;

  getItems(list).forEach(i => i.classList.toggle("is-active", i === item));

  if (options.focus !== false) {
    item.focus?.();
  }
}

function handleClick(event) {
  const item = event.target.closest(".list-item");
  if (!item) return;
  activate(item, { focus: false });
}

function init(root = document) {
  if (initializedRoots.has(root)) return;
  root.addEventListener("click", handleClick);
  initializedRoots.add(root);
}

export default {
  init,
  activate
};