Skip to main content

UI_JS

Constant UI_JS 

Source
pub const UI_JS: &str = r####"// Next Rust UI: browser behavior of the interactive components.
//
// Loaded as a module on pages that render an element with `data-nr-ui`.
// Components work without it (native controls); this adds the custom
// select, the calendar, the password toggle, `on_press`, the drawer, tab
// panels, modals and closable alerts.

const NR = () => window.nextRust || {};
const html = document.documentElement;
html.classList.add("nr-ui-js");

const CHEVRON_LEFT = '<svg class="nr-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>';
const CHEVRON_RIGHT = '<svg class="nr-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg>';
const CHEVRON_DOWN = '<svg class="nr-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';

// ---- Popovers ---------------------------------------------------------------

// Open popovers: component root → close function.
const open = new Map();

function closeAll(except) {
  for (const [root, close] of open) if (root !== except) close();
}

document.addEventListener(
  "pointerdown",
  (e) => {
    for (const [root, close] of open) if (!root.contains(e.target)) close();
  },
  true,
);

// Popovers are shown in the browser's top layer when it has one, so no
// `overflow: hidden` container (a card, a dialog) can clip them; they are
// then positioned against their anchor and follow it while scrolling.
const topLayer = typeof HTMLElement.prototype.showPopover === "function";
const anchors = new Map();

// Below the anchor, or above it when there is no room below; kept inside
// the viewport horizontally. `matchWidth`: as wide as the anchor.
function position(pop, anchor, matchWidth) {
  const r = anchor.getBoundingClientRect();
  const gap = 6;
  if (!topLayer) {
    pop.removeAttribute("data-placement");
    pop.removeAttribute("data-align");
    const h = pop.offsetHeight;
    if (r.bottom + h + gap * 2 > innerHeight && r.top - h - gap * 2 > 0) pop.dataset.placement = "top";
    if (r.left + pop.offsetWidth + 8 > innerWidth && r.right - pop.offsetWidth > 0) pop.dataset.align = "end";
    return;
  }
  const width = matchWidth ? r.width + 4 : pop.offsetWidth;
  const left = Math.max(8, Math.min(r.left - 2, innerWidth - width - 8));
  const h = pop.offsetHeight;
  const below = r.bottom + gap + h <= innerHeight - 8 || r.top - gap - h < 8;
  pop.dataset.placement = below ? "bottom" : "top";
  Object.assign(pop.style, {
    position: "fixed",
    inset: "auto",
    margin: "0",
    left: `${left}px`,
    top: `${below ? r.bottom + gap : r.top - gap - h}px`,
    width: matchWidth ? `${width}px` : "",
  });
}

function showPop(pop, anchor, matchWidth) {
  pop.hidden = false;
  if (topLayer) {
    pop.popover = "manual";
    pop.showPopover();
    anchors.set(pop, [anchor, matchWidth]);
  }
  position(pop, anchor, matchWidth);
}

function hidePop(pop) {
  if (topLayer && pop.matches(":popover-open")) pop.hidePopover();
  anchors.delete(pop);
  pop.hidden = true;
}

const follow = () => {
  for (const [pop, [anchor, matchWidth]] of anchors) position(pop, anchor, matchWidth);
};
addEventListener("scroll", follow, { capture: true, passive: true });
addEventListener("resize", follow, { passive: true });

// ---- Mounting ---------------------------------------------------------------

const mounted = new WeakSet();

function mount(el) {
  if (mounted.has(el)) return;
  mounted.add(el);
  const kind = el.dataset.nrUi;
  if (kind === "select") setupSelect(el);
  else if (kind === "datepicker") setupDatePicker(el);
  else if (kind === "avatar") setupAvatar(el);
  else if (kind === "tabs") setupTabs(el);
  else if (kind === "modal") setupModal(el);
}

function mountAll(scope) {
  if (scope.matches && scope.matches("[data-nr-ui]")) mount(scope);
  for (const el of scope.querySelectorAll("[data-nr-ui]")) mount(el);
}

const fire = (el, name, detail) => el.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
const changed = (el) => {
  el.dispatchEvent(new Event("input", { bubbles: true }));
  el.dispatchEvent(new Event("change", { bubbles: true }));
};

// ---- on_press ---------------------------------------------------------------

document.addEventListener("click", async (e) => {
  const el = e.target.closest && e.target.closest("[data-nr-press]");
  if (!el || el.matches(':disabled, [aria-disabled="true"], [data-loading]')) return;
  const kind = el.dataset.nrPress;
  const target = el.dataset.nrPressTarget || "";
  if (kind === "navigate") {
    e.preventDefault();
    if (NR().navigate) NR().navigate(target);
    else location.href = target;
  } else if (kind === "modal") {
    e.preventDefault();
    openModal(document.getElementById(target));
  } else if (kind === "close-modal") {
    e.preventDefault();
    const dialog = el.closest("dialog");
    if (dialog) dialog.close();
  } else if (kind === "emit") {
    fire(el, "nr:" + target, null);
  } else if (kind === "action") {
    e.preventDefault();
    let input = null;
    try {
      input = JSON.parse(el.dataset.nrPressInput || "null");
    } catch {}
    el.setAttribute("data-loading", "");
    el.setAttribute("aria-busy", "true");
    try {
      const data = await NR().action(target, input);
      fire(el, "nr:success", data);
      if (el.dataset.nrPressRefresh !== "false" && NR().refresh) NR().refresh();
    } catch (err) {
      fire(el, "nr:error", err);
      if (!el.hasAttribute("data-nr-quiet")) console.error("[next-rust] action failed:", err.message);
    } finally {
      el.removeAttribute("data-loading");
      el.removeAttribute("aria-busy");
    }
  }
});

// Pressable elements that are not buttons (cards) react to Enter and Space.
document.addEventListener("keydown", (e) => {
  const el = e.target;
  if ((e.key === "Enter" || e.key === " ") && el.matches && el.matches('[data-nr-press][role="button"]')) {
    e.preventDefault();
    el.click();
  }
});

// ---- Text fields --------------------------------------------------------------

document.addEventListener("click", (e) => {
  const btn = e.target.closest && e.target.closest("[data-nr-field-action]");
  if (btn) {
    const input = btn.closest(".nr-field")?.querySelector("input.nr-field-input, textarea.nr-field-input");
    const action = btn.dataset.nrFieldAction;
    if (action === "toggle-password" && input) {
      const show = input.type === "password";
      input.type = show ? "text" : "password";
      btn.setAttribute("aria-pressed", String(show));
      btn.setAttribute("aria-label", show ? "Hide password" : "Show password");
      input.focus({ preventScroll: true });
      const end = input.value.length;
      input.setSelectionRange(end, end);
    } else if (action === "clear" && input) {
      input.value = "";
      changed(input);
      input.focus();
    }
    return;
  }
  // A click anywhere in a text field's box focuses the input.
  const wrap = e.target.closest && e.target.closest(".nr-input .nr-field-wrap, .nr-textarea .nr-field-wrap");
  if (wrap && !e.target.closest("input, textarea, button, a, select")) {
    wrap.querySelector(".nr-field-input")?.focus();
  }
});

// ---- App shell drawer ---------------------------------------------------------

function setShell(openIt) {
  const shell = document.querySelector(".nr-shell");
  if (!shell) return;
  shell.toggleAttribute("data-open", openIt);
  for (const b of document.querySelectorAll(".nr-navbar-menu")) b.setAttribute("aria-expanded", String(openIt));
}

document.addEventListener("click", (e) => {
  if (e.target.closest && e.target.closest("[data-nr-shell-toggle]")) {
    setShell(!document.querySelector(".nr-shell[data-open]"));
  } else if (e.target.closest && e.target.closest(".nr-shell-sidebar a[href]")) {
    setShell(false);
  }
});
window.addEventListener("nr:navigate", () => setShell(false));
document.addEventListener("keydown", (e) => {
  if (e.key === "Escape" && document.querySelector(".nr-shell[data-open]")) setShell(false);
});

// ---- Tabs ---------------------------------------------------------------------

function setupTabs(root) {
  const list = root.querySelector('[role="tablist"]');
  if (!list) return;
  const tabs = () => [...list.querySelectorAll('[role="tab"]')];
  function select(tab, focus) {
    if (!tab || tab.disabled) return;
    for (const t of tabs()) {
      const on = t === tab;
      t.classList.toggle("nr-tab-selected", on);
      t.setAttribute("aria-selected", String(on));
      t.tabIndex = on ? 0 : -1;
      const panel = t.getAttribute("aria-controls") && document.getElementById(t.getAttribute("aria-controls"));
      if (panel) panel.hidden = !on;
    }
    if (focus) tab.focus({ preventScroll: true });
    fire(root, "nr:change", { key: tab.dataset.key });
  }
  list.addEventListener("click", (e) => {
    const tab = e.target.closest('[role="tab"]');
    if (tab && list.contains(tab)) select(tab);
  });
  list.addEventListener("keydown", (e) => {
    const all = tabs().filter((t) => !t.disabled);
    const i = all.indexOf(e.target.closest('[role="tab"]'));
    if (i < 0) return;
    const to = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: all.length - 1 }[e.key];
    if (to === undefined) return;
    e.preventDefault();
    select(all[(to + all.length) % all.length], true);
  });
}

// ---- Modal --------------------------------------------------------------------

function openModal(dialog) {
  if (!dialog || dialog.open) return;
  dialog.showModal();
  fire(dialog, "nr:open", null);
}

function setupModal(dialog) {
  // Shown on load with `open`: reopen as a real modal (inert page, focus kept).
  if (dialog.open) {
    dialog.close();
    openModal(dialog);
  }
  dialog.addEventListener("click", (e) => {
    // A click on the backdrop lands on the dialog itself, not on its box.
    if (e.target === dialog && dialog.hasAttribute("data-dismissable")) dialog.close();
  });
  dialog.addEventListener("close", () => fire(dialog, "nr:close", null));
}

// ---- Closable alerts ------------------------------------------------------------

document.addEventListener("click", (e) => {
  const btn = e.target.closest && e.target.closest("[data-nr-dismiss]");
  const alert = btn && btn.closest('[data-nr-ui="alert"]');
  if (alert) {
    fire(alert, "nr:dismiss", null);
    alert.remove();
  }
});

// ---- Avatar -------------------------------------------------------------------

function setupAvatar(el) {
  const img = el.querySelector(".nr-avatar-img");
  if (!img) return;
  const fail = () => (img.hidden = true);
  if (img.complete && img.naturalWidth === 0 && img.getAttribute("src")) fail();
  else img.addEventListener("error", fail, { once: true });
}

// ---- Select -------------------------------------------------------------------

function setupSelect(root) {
  const native = root.querySelector(".nr-select-native");
  const trigger = root.querySelector(".nr-select-trigger");
  const list = root.querySelector(".nr-select-list");
  const valueEl = root.querySelector(".nr-select-value");
  const wrap = root.querySelector(".nr-field-wrap");
  if (!native || !trigger || !list || !valueEl) return;
  const multiple = native.multiple;
  const blank = [...native.options].find((o) => o.value === "");
  const placeholder = blank ? blank.textContent : "";
  const options = () => [...list.querySelectorAll('[role="option"]')];
  const usable = () => options().filter((o) => o.getAttribute("aria-disabled") !== "true");
  let active = null;
  let typed = "";
  let typedAt = 0;

  function sync() {
    const values = new Set([...native.selectedOptions].map((o) => o.value).filter((v) => v !== ""));
    const labels = [];
    for (const o of options()) {
      const on = values.has(o.dataset.value);
      o.setAttribute("aria-selected", String(on));
      if (on) labels.push(o.querySelector(".nr-select-option-label").textContent);
    }
    valueEl.textContent = labels.length ? labels.join(", ") : placeholder;
    valueEl.toggleAttribute("data-placeholder", !labels.length);
    root.toggleAttribute("data-filled", labels.length > 0);
  }

  function setActive(o, scroll = true) {
    if (active) active.removeAttribute("data-active");
    active = o || null;
    if (active) {
      active.setAttribute("data-active", "");
      trigger.setAttribute("aria-activedescendant", active.id);
      if (scroll) active.scrollIntoView({ block: "nearest" });
    } else {
      trigger.removeAttribute("aria-activedescendant");
    }
  }

  function show() {
    if (!list.hidden || native.disabled) return;
    closeAll(root);
    showPop(list, wrap, true);
    root.setAttribute("data-open", "");
    trigger.setAttribute("aria-expanded", "true");
    setActive(usable().find((o) => o.getAttribute("aria-selected") === "true") || usable()[0]);
    open.set(root, hide);
  }

  function hide(focus) {
    if (list.hidden) return;
    hidePop(list);
    root.removeAttribute("data-open");
    trigger.setAttribute("aria-expanded", "false");
    setActive(null);
    open.delete(root);
    if (focus === true) trigger.focus();
  }

  function choose(o) {
    if (!o || o.getAttribute("aria-disabled") === "true") return;
    const option = [...native.options].find((x) => x.value === o.dataset.value);
    if (!option) return;
    option.selected = multiple ? !option.selected : true;
    changed(native);
    sync();
    if (!multiple) hide(true);
  }

  trigger.addEventListener("click", () => (list.hidden ? show() : hide()));
  wrap.addEventListener("click", (e) => {
    if (e.target.closest(".nr-select-list, .nr-select-trigger")) return;
    trigger.focus();
    if (list.hidden) show();
    else hide();
  });
  list.addEventListener("mousedown", (e) => e.preventDefault());
  list.addEventListener("pointermove", (e) => {
    const o = e.target.closest('[role="option"]');
    if (o && o !== active && o.getAttribute("aria-disabled") !== "true") setActive(o, false);
  });
  list.addEventListener("click", (e) => {
    e.stopPropagation();
    choose(e.target.closest('[role="option"]'));
  });
  // Space activates a button on key up: that would reopen the list.
  trigger.addEventListener("keyup", (e) => {
    if (e.key === " ") e.preventDefault();
  });
  trigger.addEventListener("keydown", (e) => {
    const items = usable();
    const i = items.indexOf(active);
    switch (e.key) {
      case "ArrowDown":
        e.preventDefault();
        if (list.hidden) show();
        else setActive(items[Math.min(i + 1, items.length - 1)] || items[0]);
        break;
      case "ArrowUp":
        e.preventDefault();
        if (list.hidden) show();
        else setActive(items[Math.max(i - 1, 0)]);
        break;
      case "Home":
      case "End":
        if (!list.hidden) {
          e.preventDefault();
          setActive(e.key === "Home" ? items[0] : items[items.length - 1]);
        }
        break;
      case "Enter":
      case " ":
        e.preventDefault();
        if (list.hidden) show();
        else choose(active);
        break;
      case "Escape":
        if (!list.hidden) {
          e.preventDefault();
          hide(true);
        }
        break;
      case "Tab":
        hide();
        break;
      default:
        if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
          const now = Date.now();
          typed = now - typedAt > 700 ? e.key : typed + e.key;
          typedAt = now;
          const query = typed.toLowerCase();
          const match = items.find((o) => o.textContent.trim().toLowerCase().startsWith(query));
          if (match) {
            if (list.hidden) show();
            setActive(match);
          }
        }
    }
  });
  root.querySelector(".nr-field-label")?.addEventListener("click", (e) => {
    e.preventDefault();
    trigger.focus();
  });
  native.addEventListener("change", sync);
  if (native.form) native.form.addEventListener("reset", () => setTimeout(sync));
  sync();
}

// ---- Date picker --------------------------------------------------------------

const pad = (n, w = 2) => String(n).padStart(w, "0");
const iso = (d) => `${pad(d.getFullYear(), 4)}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
const sameDay = (a, b) => !!a && !!b && iso(a) === iso(b);
const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
const monthStart = (d) => new Date(d.getFullYear(), d.getMonth(), 1);

function parseDate(s) {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s || "");
  if (!m) return null;
  const d = new Date(+m[1], +m[2] - 1, +m[3]);
  return d.getMonth() === +m[2] - 1 ? d : null;
}

// Same month and year as `d`, on the closest valid day.
function addMonths(d, n) {
  const target = new Date(d.getFullYear(), d.getMonth() + n, 1);
  const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
  return new Date(target.getFullYear(), target.getMonth(), Math.min(d.getDate(), last));
}

function setupDatePicker(root) {
  const input = root.querySelector(".nr-datepicker-input");
  const cal = root.querySelector(".nr-calendar");
  const wrap = root.querySelector(".nr-field-wrap");
  if (!input || !cal || !wrap) return;
  const locale = root.dataset.locale || html.lang || undefined;
  const firstDay = +(root.dataset.firstDay || 0);
  const min = parseDate(input.min);
  const max = parseDate(input.max);
  const today = () => {
    const n = new Date();
    return new Date(n.getFullYear(), n.getMonth(), n.getDate());
  };
  const allowed = (d) => (!min || d >= min) && (!max || d <= max);
  const dateFmt = new Intl.DateTimeFormat(locale, { dateStyle: "medium" });
  const longFmt = new Intl.DateTimeFormat(locale, { dateStyle: "full" });
  const titleFmt = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" });
  const monthFmt = new Intl.DateTimeFormat(locale, { month: "short" });
  const weekdayFmt = new Intl.DateTimeFormat(locale, { weekday: "short" });

  // The visible input shows the date in the visitor's locale; a hidden
  // input submits it as YYYY-MM-DD under the field's name.
  const hidden = document.createElement("input");
  hidden.type = "hidden";
  hidden.name = input.name;
  input.removeAttribute("name");
  input.after(hidden);
  let value = parseDate(input.value);
  input.type = "text";
  input.autocomplete = "off";
  input.setAttribute("inputmode", "none");
  input.setAttribute("aria-haspopup", "dialog");
  input.addEventListener("beforeinput", (e) => e.preventDefault());

  const write = () => {
    input.value = value ? dateFmt.format(value) : "";
    hidden.value = value ? iso(value) : "";
  };
  write();

  let view = "days";
  let focus = value || today();

  function button(cls, attrs, content) {
    const b = document.createElement("button");
    b.type = "button";
    b.className = cls;
    for (const [k, v] of Object.entries(attrs)) if (v !== false && v != null) b.setAttribute(k, v === true ? "" : v);
    b.innerHTML = content;
    return b;
  }

  function render(moveFocus) {
    cal.textContent = "";
    cal.dataset.view = view;
    const header = document.createElement("div");
    header.className = "nr-cal-header";
    const inDays = view === "days";
    const prevTarget = inDays ? addMonths(monthStart(focus), -1) : new Date(focus.getFullYear() - 1, 11, 31);
    const nextTarget = inDays ? addMonths(monthStart(focus), 1) : new Date(focus.getFullYear() + 1, 0, 1);
    const prevLast = inDays ? new Date(prevTarget.getFullYear(), prevTarget.getMonth() + 1, 0) : prevTarget;
    header.append(
      button("nr-cal-nav", { "data-cal": "prev", "aria-label": inDays ? "Previous month" : "Previous year", disabled: !!min && prevLast < min }, CHEVRON_LEFT),
      button("nr-cal-title", { "data-cal": "view", "aria-live": "polite" }, `<span>${inDays ? titleFmt.format(focus) : focus.getFullYear()}</span>${CHEVRON_DOWN}`),
      button("nr-cal-nav", { "data-cal": "next", "aria-label": inDays ? "Next month" : "Next year", disabled: !!max && nextTarget > max }, CHEVRON_RIGHT),
    );
    cal.append(header);

    if (inDays) {
      const grid = document.createElement("div");
      grid.className = "nr-cal-grid";
      grid.setAttribute("role", "grid");
      for (let i = 0; i < 7; i++) {
        const w = document.createElement("div");
        w.className = "nr-cal-weekday";
        w.setAttribute("role", "columnheader");
        w.textContent = weekdayFmt.format(new Date(2023, 0, 1 + ((i + firstDay) % 7)));
        grid.append(w);
      }
      const start = monthStart(focus);
      const lead = (start.getDay() - firstDay + 7) % 7;
      const now = today();
      for (let i = 0; i < 42; i++) {
        const d = addDays(start, i - lead);
        grid.append(
          button(
            "nr-cal-day",
            {
              role: "gridcell",
              "data-date": iso(d),
              "aria-label": longFmt.format(d),
              "aria-selected": sameDay(d, value) ? "true" : "false",
              "data-today": sameDay(d, now),
              "data-outside": d.getMonth() !== focus.getMonth(),
              tabindex: sameDay(d, focus) ? "0" : "-1",
              disabled: !allowed(d),
            },
            String(d.getDate()),
          ),
        );
      }
      cal.append(grid);
    } else {
      const months = document.createElement("div");
      months.className = "nr-cal-months";
      for (let m = 0; m < 12; m++) {
        const first = new Date(focus.getFullYear(), m, 1);
        const last = new Date(focus.getFullYear(), m + 1, 0);
        months.append(
          button(
            "nr-cal-month",
            {
              "data-month": String(m),
              "aria-selected": value && value.getFullYear() === focus.getFullYear() && value.getMonth() === m ? "true" : "false",
              "data-current": m === focus.getMonth(),
              tabindex: m === focus.getMonth() ? "0" : "-1",
              disabled: (!!min && last < min) || (!!max && first > max),
            },
            monthFmt.format(first),
          ),
        );
      }
      cal.append(months);
    }

    const footer = document.createElement("div");
    footer.className = "nr-cal-footer";
    footer.append(
      button("nr-cal-link", { "data-cal": "today", disabled: !allowed(today()) }, "Today"),
      button("nr-cal-link", { "data-cal": "clear" }, "Clear"),
    );
    cal.append(footer);
    // Month and day views differ in height.
    if (!cal.hidden) position(cal, wrap, false);
    if (moveFocus) cal.querySelector('[tabindex="0"]:not(:disabled)')?.focus({ preventScroll: true });
  }

  function show() {
    if (!cal.hidden || input.disabled || input.readOnly) return;
    closeAll(root);
    view = "days";
    focus = value || (allowed(today()) ? today() : min || max || today());
    render(false);
    showPop(cal, wrap, false);
    root.setAttribute("data-open", "");
    root.querySelector(".nr-datepicker-toggle")?.setAttribute("aria-expanded", "true");
    cal.querySelector('[tabindex="0"]:not(:disabled)')?.focus({ preventScroll: true });
    open.set(root, hide);
  }

  function hide(returnFocus) {
    if (cal.hidden) return;
    hidePop(cal);
    root.removeAttribute("data-open");
    root.querySelector(".nr-datepicker-toggle")?.setAttribute("aria-expanded", "false");
    open.delete(root);
    if (returnFocus === true) input.focus({ preventScroll: true });
  }

  function select(d) {
    value = d;
    write();
    changed(hidden);
    hide(true);
  }

  function move(d) {
    if (min && d < min) d = min;
    if (max && d > max) d = max;
    focus = d;
    render(true);
  }

  cal.addEventListener("click", (e) => {
    const b = e.target.closest("button");
    if (!b || b.disabled) return;
    if (b.dataset.date) select(parseDate(b.dataset.date));
    else if (b.dataset.month) {
      focus = new Date(focus.getFullYear(), +b.dataset.month, Math.min(focus.getDate(), 28));
      view = "days";
      render(true);
    } else if (b.dataset.cal === "prev") {
      focus = view === "days" ? addMonths(focus, -1) : new Date(focus.getFullYear() - 1, focus.getMonth(), 1);
      render(false);
    } else if (b.dataset.cal === "next") {
      focus = view === "days" ? addMonths(focus, 1) : new Date(focus.getFullYear() + 1, focus.getMonth(), 1);
      render(false);
    } else if (b.dataset.cal === "view") {
      view = view === "days" ? "months" : "days";
      render(true);
    } else if (b.dataset.cal === "today") select(today());
    else if (b.dataset.cal === "clear") {
      value = null;
      write();
      changed(hidden);
      hide(true);
    }
  });

  cal.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      e.preventDefault();
      hide(true);
      return;
    }
    const onDay = e.target.dataset && e.target.dataset.date;
    const onMonth = e.target.dataset && e.target.dataset.month != null;
    if (!onDay && !onMonth) return;
    // Days: a week per row. Months: three per row.
    const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: onDay ? -7 : -3, ArrowDown: onDay ? 7 : 3 }[e.key];
    if (step != null) {
      e.preventDefault();
      if (onDay) move(addDays(focus, step));
      else {
        const m = Math.min(11, Math.max(0, focus.getMonth() + step));
        focus = new Date(focus.getFullYear(), m, 1);
        render(true);
      }
    } else if (onDay && (e.key === "PageUp" || e.key === "PageDown")) {
      e.preventDefault();
      move(addMonths(focus, (e.key === "PageUp" ? -1 : 1) * (e.shiftKey ? 12 : 1)));
    } else if (onDay && (e.key === "Home" || e.key === "End")) {
      e.preventDefault();
      const offset = (focus.getDay() - firstDay + 7) % 7;
      move(addDays(focus, e.key === "Home" ? -offset : 6 - offset));
    }
  });

  // Leaving the picker with Tab closes it.
  root.addEventListener("focusout", (e) => {
    if (!cal.hidden && e.relatedTarget && !root.contains(e.relatedTarget)) hide();
  });

  input.addEventListener("click", show);
  input.addEventListener("keydown", (e) => {
    if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") {
      e.preventDefault();
      show();
    } else if ((e.key === "Backspace" || e.key === "Delete") && value && !input.required) {
      e.preventDefault();
      value = null;
      write();
      changed(hidden);
    }
  });
  wrap.addEventListener("click", (e) => {
    if (e.target.closest(".nr-calendar")) return;
    if (e.target.closest(".nr-datepicker-toggle") && !cal.hidden) hide(true);
    else show();
  });
  if (input.form) {
    input.form.addEventListener("reset", () =>
      setTimeout(() => {
        value = parseDate(input.defaultValue);
        write();
      }),
    );
  }
}

// ---- Start ------------------------------------------------------------------

// Last, so every helper above is initialized.
mountAll(document);
// Streamed content and client-side navigations add components later.
new MutationObserver((records) => {
  for (const r of records) for (const n of r.addedNodes) if (n.nodeType === 1) mountAll(n);
}).observe(html, { childList: true, subtree: true });
"####;
Expand description

Readable source of the component script.