Skip to main content

next_rust_ui/
script.rs

1//! Browser behavior of the interactive components, served at `/_next-rust/ui.js`.
2//!
3//! It exists twice: [`UI_JS`], readable (served in development), and
4//! [`UI_JS_MIN`], minified with Terser (production). After changing
5//! `UI_JS`, regenerate `UI_JS_MIN` (see CONTRIBUTING.md) and update
6//! `UI_JS_SOURCE_HASH` in the tests below.
7
8/// Readable source of the component script.
9pub const UI_JS: &str = r####"// Next Rust UI: browser behavior of the interactive components.
10//
11// Loaded as a module on pages that render an element with `data-nr-ui`.
12// Components work without it (native controls); this adds the custom
13// select, the calendar, the password toggle, `on_press`, the drawer, tab
14// panels, modals and closable alerts.
15
16const NR = () => window.nextRust || {};
17const html = document.documentElement;
18html.classList.add("nr-ui-js");
19
20const 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>';
21const 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>';
22const 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>';
23
24// ---- Popovers ---------------------------------------------------------------
25
26// Open popovers: component root → close function.
27const open = new Map();
28
29function closeAll(except) {
30  for (const [root, close] of open) if (root !== except) close();
31}
32
33document.addEventListener(
34  "pointerdown",
35  (e) => {
36    for (const [root, close] of open) if (!root.contains(e.target)) close();
37  },
38  true,
39);
40
41// Popovers are shown in the browser's top layer when it has one, so no
42// `overflow: hidden` container (a card, a dialog) can clip them; they are
43// then positioned against their anchor and follow it while scrolling.
44const topLayer = typeof HTMLElement.prototype.showPopover === "function";
45const anchors = new Map();
46
47// Below the anchor, or above it when there is no room below; kept inside
48// the viewport horizontally. `matchWidth`: as wide as the anchor.
49function position(pop, anchor, matchWidth) {
50  const r = anchor.getBoundingClientRect();
51  const gap = 6;
52  if (!topLayer) {
53    pop.removeAttribute("data-placement");
54    pop.removeAttribute("data-align");
55    const h = pop.offsetHeight;
56    if (r.bottom + h + gap * 2 > innerHeight && r.top - h - gap * 2 > 0) pop.dataset.placement = "top";
57    if (r.left + pop.offsetWidth + 8 > innerWidth && r.right - pop.offsetWidth > 0) pop.dataset.align = "end";
58    return;
59  }
60  const width = matchWidth ? r.width + 4 : pop.offsetWidth;
61  const left = Math.max(8, Math.min(r.left - 2, innerWidth - width - 8));
62  const h = pop.offsetHeight;
63  const below = r.bottom + gap + h <= innerHeight - 8 || r.top - gap - h < 8;
64  pop.dataset.placement = below ? "bottom" : "top";
65  Object.assign(pop.style, {
66    position: "fixed",
67    inset: "auto",
68    margin: "0",
69    left: `${left}px`,
70    top: `${below ? r.bottom + gap : r.top - gap - h}px`,
71    width: matchWidth ? `${width}px` : "",
72  });
73}
74
75function showPop(pop, anchor, matchWidth) {
76  pop.hidden = false;
77  if (topLayer) {
78    pop.popover = "manual";
79    pop.showPopover();
80    anchors.set(pop, [anchor, matchWidth]);
81  }
82  position(pop, anchor, matchWidth);
83}
84
85function hidePop(pop) {
86  if (topLayer && pop.matches(":popover-open")) pop.hidePopover();
87  anchors.delete(pop);
88  pop.hidden = true;
89}
90
91const follow = () => {
92  for (const [pop, [anchor, matchWidth]] of anchors) position(pop, anchor, matchWidth);
93};
94addEventListener("scroll", follow, { capture: true, passive: true });
95addEventListener("resize", follow, { passive: true });
96
97// ---- Mounting ---------------------------------------------------------------
98
99const mounted = new WeakSet();
100
101function mount(el) {
102  if (mounted.has(el)) return;
103  mounted.add(el);
104  const kind = el.dataset.nrUi;
105  if (kind === "select") setupSelect(el);
106  else if (kind === "datepicker") setupDatePicker(el);
107  else if (kind === "avatar") setupAvatar(el);
108  else if (kind === "tabs") setupTabs(el);
109  else if (kind === "modal") setupModal(el);
110}
111
112function mountAll(scope) {
113  if (scope.matches && scope.matches("[data-nr-ui]")) mount(scope);
114  for (const el of scope.querySelectorAll("[data-nr-ui]")) mount(el);
115}
116
117const fire = (el, name, detail) => el.dispatchEvent(new CustomEvent(name, { bubbles: true, detail }));
118const changed = (el) => {
119  el.dispatchEvent(new Event("input", { bubbles: true }));
120  el.dispatchEvent(new Event("change", { bubbles: true }));
121};
122
123// ---- on_press ---------------------------------------------------------------
124
125document.addEventListener("click", async (e) => {
126  const el = e.target.closest && e.target.closest("[data-nr-press]");
127  if (!el || el.matches(':disabled, [aria-disabled="true"], [data-loading]')) return;
128  const kind = el.dataset.nrPress;
129  const target = el.dataset.nrPressTarget || "";
130  if (kind === "navigate") {
131    e.preventDefault();
132    if (NR().navigate) NR().navigate(target);
133    else location.href = target;
134  } else if (kind === "modal") {
135    e.preventDefault();
136    openModal(document.getElementById(target));
137  } else if (kind === "close-modal") {
138    e.preventDefault();
139    const dialog = el.closest("dialog");
140    if (dialog) dialog.close();
141  } else if (kind === "emit") {
142    fire(el, "nr:" + target, null);
143  } else if (kind === "action") {
144    e.preventDefault();
145    let input = null;
146    try {
147      input = JSON.parse(el.dataset.nrPressInput || "null");
148    } catch {}
149    el.setAttribute("data-loading", "");
150    el.setAttribute("aria-busy", "true");
151    try {
152      const data = await NR().action(target, input);
153      fire(el, "nr:success", data);
154      if (el.dataset.nrPressRefresh !== "false" && NR().refresh) NR().refresh();
155    } catch (err) {
156      fire(el, "nr:error", err);
157      if (!el.hasAttribute("data-nr-quiet")) console.error("[next-rust] action failed:", err.message);
158    } finally {
159      el.removeAttribute("data-loading");
160      el.removeAttribute("aria-busy");
161    }
162  }
163});
164
165// Pressable elements that are not buttons (cards) react to Enter and Space.
166document.addEventListener("keydown", (e) => {
167  const el = e.target;
168  if ((e.key === "Enter" || e.key === " ") && el.matches && el.matches('[data-nr-press][role="button"]')) {
169    e.preventDefault();
170    el.click();
171  }
172});
173
174// ---- Text fields --------------------------------------------------------------
175
176document.addEventListener("click", (e) => {
177  const btn = e.target.closest && e.target.closest("[data-nr-field-action]");
178  if (btn) {
179    const input = btn.closest(".nr-field")?.querySelector("input.nr-field-input, textarea.nr-field-input");
180    const action = btn.dataset.nrFieldAction;
181    if (action === "toggle-password" && input) {
182      const show = input.type === "password";
183      input.type = show ? "text" : "password";
184      btn.setAttribute("aria-pressed", String(show));
185      btn.setAttribute("aria-label", show ? "Hide password" : "Show password");
186      input.focus({ preventScroll: true });
187      const end = input.value.length;
188      input.setSelectionRange(end, end);
189    } else if (action === "clear" && input) {
190      input.value = "";
191      changed(input);
192      input.focus();
193    }
194    return;
195  }
196  // A click anywhere in a text field's box focuses the input.
197  const wrap = e.target.closest && e.target.closest(".nr-input .nr-field-wrap, .nr-textarea .nr-field-wrap");
198  if (wrap && !e.target.closest("input, textarea, button, a, select")) {
199    wrap.querySelector(".nr-field-input")?.focus();
200  }
201});
202
203// ---- App shell drawer ---------------------------------------------------------
204
205function setShell(openIt) {
206  const shell = document.querySelector(".nr-shell");
207  if (!shell) return;
208  shell.toggleAttribute("data-open", openIt);
209  for (const b of document.querySelectorAll(".nr-navbar-menu")) b.setAttribute("aria-expanded", String(openIt));
210}
211
212document.addEventListener("click", (e) => {
213  if (e.target.closest && e.target.closest("[data-nr-shell-toggle]")) {
214    setShell(!document.querySelector(".nr-shell[data-open]"));
215  } else if (e.target.closest && e.target.closest(".nr-shell-sidebar a[href]")) {
216    setShell(false);
217  }
218});
219window.addEventListener("nr:navigate", () => setShell(false));
220document.addEventListener("keydown", (e) => {
221  if (e.key === "Escape" && document.querySelector(".nr-shell[data-open]")) setShell(false);
222});
223
224// ---- Tabs ---------------------------------------------------------------------
225
226function setupTabs(root) {
227  const list = root.querySelector('[role="tablist"]');
228  if (!list) return;
229  const tabs = () => [...list.querySelectorAll('[role="tab"]')];
230  function select(tab, focus) {
231    if (!tab || tab.disabled) return;
232    for (const t of tabs()) {
233      const on = t === tab;
234      t.classList.toggle("nr-tab-selected", on);
235      t.setAttribute("aria-selected", String(on));
236      t.tabIndex = on ? 0 : -1;
237      const panel = t.getAttribute("aria-controls") && document.getElementById(t.getAttribute("aria-controls"));
238      if (panel) panel.hidden = !on;
239    }
240    if (focus) tab.focus({ preventScroll: true });
241    fire(root, "nr:change", { key: tab.dataset.key });
242  }
243  list.addEventListener("click", (e) => {
244    const tab = e.target.closest('[role="tab"]');
245    if (tab && list.contains(tab)) select(tab);
246  });
247  list.addEventListener("keydown", (e) => {
248    const all = tabs().filter((t) => !t.disabled);
249    const i = all.indexOf(e.target.closest('[role="tab"]'));
250    if (i < 0) return;
251    const to = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: all.length - 1 }[e.key];
252    if (to === undefined) return;
253    e.preventDefault();
254    select(all[(to + all.length) % all.length], true);
255  });
256}
257
258// ---- Modal --------------------------------------------------------------------
259
260function openModal(dialog) {
261  if (!dialog || dialog.open) return;
262  dialog.showModal();
263  fire(dialog, "nr:open", null);
264}
265
266function setupModal(dialog) {
267  // Shown on load with `open`: reopen as a real modal (inert page, focus kept).
268  if (dialog.open) {
269    dialog.close();
270    openModal(dialog);
271  }
272  dialog.addEventListener("click", (e) => {
273    // A click on the backdrop lands on the dialog itself, not on its box.
274    if (e.target === dialog && dialog.hasAttribute("data-dismissable")) dialog.close();
275  });
276  dialog.addEventListener("close", () => fire(dialog, "nr:close", null));
277}
278
279// ---- Closable alerts ------------------------------------------------------------
280
281document.addEventListener("click", (e) => {
282  const btn = e.target.closest && e.target.closest("[data-nr-dismiss]");
283  const alert = btn && btn.closest('[data-nr-ui="alert"]');
284  if (alert) {
285    fire(alert, "nr:dismiss", null);
286    alert.remove();
287  }
288});
289
290// ---- Avatar -------------------------------------------------------------------
291
292function setupAvatar(el) {
293  const img = el.querySelector(".nr-avatar-img");
294  if (!img) return;
295  const fail = () => (img.hidden = true);
296  if (img.complete && img.naturalWidth === 0 && img.getAttribute("src")) fail();
297  else img.addEventListener("error", fail, { once: true });
298}
299
300// ---- Select -------------------------------------------------------------------
301
302function setupSelect(root) {
303  const native = root.querySelector(".nr-select-native");
304  const trigger = root.querySelector(".nr-select-trigger");
305  const list = root.querySelector(".nr-select-list");
306  const valueEl = root.querySelector(".nr-select-value");
307  const wrap = root.querySelector(".nr-field-wrap");
308  if (!native || !trigger || !list || !valueEl) return;
309  const multiple = native.multiple;
310  const blank = [...native.options].find((o) => o.value === "");
311  const placeholder = blank ? blank.textContent : "";
312  const options = () => [...list.querySelectorAll('[role="option"]')];
313  const usable = () => options().filter((o) => o.getAttribute("aria-disabled") !== "true");
314  let active = null;
315  let typed = "";
316  let typedAt = 0;
317
318  function sync() {
319    const values = new Set([...native.selectedOptions].map((o) => o.value).filter((v) => v !== ""));
320    const labels = [];
321    for (const o of options()) {
322      const on = values.has(o.dataset.value);
323      o.setAttribute("aria-selected", String(on));
324      if (on) labels.push(o.querySelector(".nr-select-option-label").textContent);
325    }
326    valueEl.textContent = labels.length ? labels.join(", ") : placeholder;
327    valueEl.toggleAttribute("data-placeholder", !labels.length);
328    root.toggleAttribute("data-filled", labels.length > 0);
329  }
330
331  function setActive(o, scroll = true) {
332    if (active) active.removeAttribute("data-active");
333    active = o || null;
334    if (active) {
335      active.setAttribute("data-active", "");
336      trigger.setAttribute("aria-activedescendant", active.id);
337      if (scroll) active.scrollIntoView({ block: "nearest" });
338    } else {
339      trigger.removeAttribute("aria-activedescendant");
340    }
341  }
342
343  function show() {
344    if (!list.hidden || native.disabled) return;
345    closeAll(root);
346    showPop(list, wrap, true);
347    root.setAttribute("data-open", "");
348    trigger.setAttribute("aria-expanded", "true");
349    setActive(usable().find((o) => o.getAttribute("aria-selected") === "true") || usable()[0]);
350    open.set(root, hide);
351  }
352
353  function hide(focus) {
354    if (list.hidden) return;
355    hidePop(list);
356    root.removeAttribute("data-open");
357    trigger.setAttribute("aria-expanded", "false");
358    setActive(null);
359    open.delete(root);
360    if (focus === true) trigger.focus();
361  }
362
363  function choose(o) {
364    if (!o || o.getAttribute("aria-disabled") === "true") return;
365    const option = [...native.options].find((x) => x.value === o.dataset.value);
366    if (!option) return;
367    option.selected = multiple ? !option.selected : true;
368    changed(native);
369    sync();
370    if (!multiple) hide(true);
371  }
372
373  trigger.addEventListener("click", () => (list.hidden ? show() : hide()));
374  wrap.addEventListener("click", (e) => {
375    if (e.target.closest(".nr-select-list, .nr-select-trigger")) return;
376    trigger.focus();
377    if (list.hidden) show();
378    else hide();
379  });
380  list.addEventListener("mousedown", (e) => e.preventDefault());
381  list.addEventListener("pointermove", (e) => {
382    const o = e.target.closest('[role="option"]');
383    if (o && o !== active && o.getAttribute("aria-disabled") !== "true") setActive(o, false);
384  });
385  list.addEventListener("click", (e) => {
386    e.stopPropagation();
387    choose(e.target.closest('[role="option"]'));
388  });
389  // Space activates a button on key up: that would reopen the list.
390  trigger.addEventListener("keyup", (e) => {
391    if (e.key === " ") e.preventDefault();
392  });
393  trigger.addEventListener("keydown", (e) => {
394    const items = usable();
395    const i = items.indexOf(active);
396    switch (e.key) {
397      case "ArrowDown":
398        e.preventDefault();
399        if (list.hidden) show();
400        else setActive(items[Math.min(i + 1, items.length - 1)] || items[0]);
401        break;
402      case "ArrowUp":
403        e.preventDefault();
404        if (list.hidden) show();
405        else setActive(items[Math.max(i - 1, 0)]);
406        break;
407      case "Home":
408      case "End":
409        if (!list.hidden) {
410          e.preventDefault();
411          setActive(e.key === "Home" ? items[0] : items[items.length - 1]);
412        }
413        break;
414      case "Enter":
415      case " ":
416        e.preventDefault();
417        if (list.hidden) show();
418        else choose(active);
419        break;
420      case "Escape":
421        if (!list.hidden) {
422          e.preventDefault();
423          hide(true);
424        }
425        break;
426      case "Tab":
427        hide();
428        break;
429      default:
430        if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
431          const now = Date.now();
432          typed = now - typedAt > 700 ? e.key : typed + e.key;
433          typedAt = now;
434          const query = typed.toLowerCase();
435          const match = items.find((o) => o.textContent.trim().toLowerCase().startsWith(query));
436          if (match) {
437            if (list.hidden) show();
438            setActive(match);
439          }
440        }
441    }
442  });
443  root.querySelector(".nr-field-label")?.addEventListener("click", (e) => {
444    e.preventDefault();
445    trigger.focus();
446  });
447  native.addEventListener("change", sync);
448  if (native.form) native.form.addEventListener("reset", () => setTimeout(sync));
449  sync();
450}
451
452// ---- Date picker --------------------------------------------------------------
453
454const pad = (n, w = 2) => String(n).padStart(w, "0");
455const iso = (d) => `${pad(d.getFullYear(), 4)}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
456const sameDay = (a, b) => !!a && !!b && iso(a) === iso(b);
457const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
458const monthStart = (d) => new Date(d.getFullYear(), d.getMonth(), 1);
459
460function parseDate(s) {
461  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s || "");
462  if (!m) return null;
463  const d = new Date(+m[1], +m[2] - 1, +m[3]);
464  return d.getMonth() === +m[2] - 1 ? d : null;
465}
466
467// Same month and year as `d`, on the closest valid day.
468function addMonths(d, n) {
469  const target = new Date(d.getFullYear(), d.getMonth() + n, 1);
470  const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
471  return new Date(target.getFullYear(), target.getMonth(), Math.min(d.getDate(), last));
472}
473
474function setupDatePicker(root) {
475  const input = root.querySelector(".nr-datepicker-input");
476  const cal = root.querySelector(".nr-calendar");
477  const wrap = root.querySelector(".nr-field-wrap");
478  if (!input || !cal || !wrap) return;
479  const locale = root.dataset.locale || html.lang || undefined;
480  const firstDay = +(root.dataset.firstDay || 0);
481  const min = parseDate(input.min);
482  const max = parseDate(input.max);
483  const today = () => {
484    const n = new Date();
485    return new Date(n.getFullYear(), n.getMonth(), n.getDate());
486  };
487  const allowed = (d) => (!min || d >= min) && (!max || d <= max);
488  const dateFmt = new Intl.DateTimeFormat(locale, { dateStyle: "medium" });
489  const longFmt = new Intl.DateTimeFormat(locale, { dateStyle: "full" });
490  const titleFmt = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" });
491  const monthFmt = new Intl.DateTimeFormat(locale, { month: "short" });
492  const weekdayFmt = new Intl.DateTimeFormat(locale, { weekday: "short" });
493
494  // The visible input shows the date in the visitor's locale; a hidden
495  // input submits it as YYYY-MM-DD under the field's name.
496  const hidden = document.createElement("input");
497  hidden.type = "hidden";
498  hidden.name = input.name;
499  input.removeAttribute("name");
500  input.after(hidden);
501  let value = parseDate(input.value);
502  input.type = "text";
503  input.autocomplete = "off";
504  input.setAttribute("inputmode", "none");
505  input.setAttribute("aria-haspopup", "dialog");
506  input.addEventListener("beforeinput", (e) => e.preventDefault());
507
508  const write = () => {
509    input.value = value ? dateFmt.format(value) : "";
510    hidden.value = value ? iso(value) : "";
511  };
512  write();
513
514  let view = "days";
515  let focus = value || today();
516
517  function button(cls, attrs, content) {
518    const b = document.createElement("button");
519    b.type = "button";
520    b.className = cls;
521    for (const [k, v] of Object.entries(attrs)) if (v !== false && v != null) b.setAttribute(k, v === true ? "" : v);
522    b.innerHTML = content;
523    return b;
524  }
525
526  function render(moveFocus) {
527    cal.textContent = "";
528    cal.dataset.view = view;
529    const header = document.createElement("div");
530    header.className = "nr-cal-header";
531    const inDays = view === "days";
532    const prevTarget = inDays ? addMonths(monthStart(focus), -1) : new Date(focus.getFullYear() - 1, 11, 31);
533    const nextTarget = inDays ? addMonths(monthStart(focus), 1) : new Date(focus.getFullYear() + 1, 0, 1);
534    const prevLast = inDays ? new Date(prevTarget.getFullYear(), prevTarget.getMonth() + 1, 0) : prevTarget;
535    header.append(
536      button("nr-cal-nav", { "data-cal": "prev", "aria-label": inDays ? "Previous month" : "Previous year", disabled: !!min && prevLast < min }, CHEVRON_LEFT),
537      button("nr-cal-title", { "data-cal": "view", "aria-live": "polite" }, `<span>${inDays ? titleFmt.format(focus) : focus.getFullYear()}</span>${CHEVRON_DOWN}`),
538      button("nr-cal-nav", { "data-cal": "next", "aria-label": inDays ? "Next month" : "Next year", disabled: !!max && nextTarget > max }, CHEVRON_RIGHT),
539    );
540    cal.append(header);
541
542    if (inDays) {
543      const grid = document.createElement("div");
544      grid.className = "nr-cal-grid";
545      grid.setAttribute("role", "grid");
546      for (let i = 0; i < 7; i++) {
547        const w = document.createElement("div");
548        w.className = "nr-cal-weekday";
549        w.setAttribute("role", "columnheader");
550        w.textContent = weekdayFmt.format(new Date(2023, 0, 1 + ((i + firstDay) % 7)));
551        grid.append(w);
552      }
553      const start = monthStart(focus);
554      const lead = (start.getDay() - firstDay + 7) % 7;
555      const now = today();
556      for (let i = 0; i < 42; i++) {
557        const d = addDays(start, i - lead);
558        grid.append(
559          button(
560            "nr-cal-day",
561            {
562              role: "gridcell",
563              "data-date": iso(d),
564              "aria-label": longFmt.format(d),
565              "aria-selected": sameDay(d, value) ? "true" : "false",
566              "data-today": sameDay(d, now),
567              "data-outside": d.getMonth() !== focus.getMonth(),
568              tabindex: sameDay(d, focus) ? "0" : "-1",
569              disabled: !allowed(d),
570            },
571            String(d.getDate()),
572          ),
573        );
574      }
575      cal.append(grid);
576    } else {
577      const months = document.createElement("div");
578      months.className = "nr-cal-months";
579      for (let m = 0; m < 12; m++) {
580        const first = new Date(focus.getFullYear(), m, 1);
581        const last = new Date(focus.getFullYear(), m + 1, 0);
582        months.append(
583          button(
584            "nr-cal-month",
585            {
586              "data-month": String(m),
587              "aria-selected": value && value.getFullYear() === focus.getFullYear() && value.getMonth() === m ? "true" : "false",
588              "data-current": m === focus.getMonth(),
589              tabindex: m === focus.getMonth() ? "0" : "-1",
590              disabled: (!!min && last < min) || (!!max && first > max),
591            },
592            monthFmt.format(first),
593          ),
594        );
595      }
596      cal.append(months);
597    }
598
599    const footer = document.createElement("div");
600    footer.className = "nr-cal-footer";
601    footer.append(
602      button("nr-cal-link", { "data-cal": "today", disabled: !allowed(today()) }, "Today"),
603      button("nr-cal-link", { "data-cal": "clear" }, "Clear"),
604    );
605    cal.append(footer);
606    // Month and day views differ in height.
607    if (!cal.hidden) position(cal, wrap, false);
608    if (moveFocus) cal.querySelector('[tabindex="0"]:not(:disabled)')?.focus({ preventScroll: true });
609  }
610
611  function show() {
612    if (!cal.hidden || input.disabled || input.readOnly) return;
613    closeAll(root);
614    view = "days";
615    focus = value || (allowed(today()) ? today() : min || max || today());
616    render(false);
617    showPop(cal, wrap, false);
618    root.setAttribute("data-open", "");
619    root.querySelector(".nr-datepicker-toggle")?.setAttribute("aria-expanded", "true");
620    cal.querySelector('[tabindex="0"]:not(:disabled)')?.focus({ preventScroll: true });
621    open.set(root, hide);
622  }
623
624  function hide(returnFocus) {
625    if (cal.hidden) return;
626    hidePop(cal);
627    root.removeAttribute("data-open");
628    root.querySelector(".nr-datepicker-toggle")?.setAttribute("aria-expanded", "false");
629    open.delete(root);
630    if (returnFocus === true) input.focus({ preventScroll: true });
631  }
632
633  function select(d) {
634    value = d;
635    write();
636    changed(hidden);
637    hide(true);
638  }
639
640  function move(d) {
641    if (min && d < min) d = min;
642    if (max && d > max) d = max;
643    focus = d;
644    render(true);
645  }
646
647  cal.addEventListener("click", (e) => {
648    const b = e.target.closest("button");
649    if (!b || b.disabled) return;
650    if (b.dataset.date) select(parseDate(b.dataset.date));
651    else if (b.dataset.month) {
652      focus = new Date(focus.getFullYear(), +b.dataset.month, Math.min(focus.getDate(), 28));
653      view = "days";
654      render(true);
655    } else if (b.dataset.cal === "prev") {
656      focus = view === "days" ? addMonths(focus, -1) : new Date(focus.getFullYear() - 1, focus.getMonth(), 1);
657      render(false);
658    } else if (b.dataset.cal === "next") {
659      focus = view === "days" ? addMonths(focus, 1) : new Date(focus.getFullYear() + 1, focus.getMonth(), 1);
660      render(false);
661    } else if (b.dataset.cal === "view") {
662      view = view === "days" ? "months" : "days";
663      render(true);
664    } else if (b.dataset.cal === "today") select(today());
665    else if (b.dataset.cal === "clear") {
666      value = null;
667      write();
668      changed(hidden);
669      hide(true);
670    }
671  });
672
673  cal.addEventListener("keydown", (e) => {
674    if (e.key === "Escape") {
675      e.preventDefault();
676      hide(true);
677      return;
678    }
679    const onDay = e.target.dataset && e.target.dataset.date;
680    const onMonth = e.target.dataset && e.target.dataset.month != null;
681    if (!onDay && !onMonth) return;
682    // Days: a week per row. Months: three per row.
683    const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: onDay ? -7 : -3, ArrowDown: onDay ? 7 : 3 }[e.key];
684    if (step != null) {
685      e.preventDefault();
686      if (onDay) move(addDays(focus, step));
687      else {
688        const m = Math.min(11, Math.max(0, focus.getMonth() + step));
689        focus = new Date(focus.getFullYear(), m, 1);
690        render(true);
691      }
692    } else if (onDay && (e.key === "PageUp" || e.key === "PageDown")) {
693      e.preventDefault();
694      move(addMonths(focus, (e.key === "PageUp" ? -1 : 1) * (e.shiftKey ? 12 : 1)));
695    } else if (onDay && (e.key === "Home" || e.key === "End")) {
696      e.preventDefault();
697      const offset = (focus.getDay() - firstDay + 7) % 7;
698      move(addDays(focus, e.key === "Home" ? -offset : 6 - offset));
699    }
700  });
701
702  // Leaving the picker with Tab closes it.
703  root.addEventListener("focusout", (e) => {
704    if (!cal.hidden && e.relatedTarget && !root.contains(e.relatedTarget)) hide();
705  });
706
707  input.addEventListener("click", show);
708  input.addEventListener("keydown", (e) => {
709    if (e.key === "Enter" || e.key === " " || e.key === "ArrowDown") {
710      e.preventDefault();
711      show();
712    } else if ((e.key === "Backspace" || e.key === "Delete") && value && !input.required) {
713      e.preventDefault();
714      value = null;
715      write();
716      changed(hidden);
717    }
718  });
719  wrap.addEventListener("click", (e) => {
720    if (e.target.closest(".nr-calendar")) return;
721    if (e.target.closest(".nr-datepicker-toggle") && !cal.hidden) hide(true);
722    else show();
723  });
724  if (input.form) {
725    input.form.addEventListener("reset", () =>
726      setTimeout(() => {
727        value = parseDate(input.defaultValue);
728        write();
729      }),
730    );
731  }
732}
733
734// ---- Start ------------------------------------------------------------------
735
736// Last, so every helper above is initialized.
737mountAll(document);
738// Streamed content and client-side navigations add components later.
739new MutationObserver((records) => {
740  for (const r of records) for (const n of r.addedNodes) if (n.nodeType === 1) mountAll(n);
741}).observe(html, { childList: true, subtree: true });
742"####;
743
744/// [`UI_JS`], minified.
745pub const UI_JS_MIN: &str = r####"const e=()=>window.nextRust||{},t=document.documentElement;t.classList.add("nr-ui-js");const n=new Map;function a(e){for(const[t,a]of n)t!==e&&a()}document.addEventListener("pointerdown",e=>{for(const[t,a]of n)t.contains(e.target)||a()},!0);const r="function"==typeof HTMLElement.prototype.showPopover,o=new Map;function s(e,t,n){const a=t.getBoundingClientRect();if(!r){e.removeAttribute("data-placement"),e.removeAttribute("data-align");const t=e.offsetHeight;return a.bottom+t+12>innerHeight&&a.top-t-12>0&&(e.dataset.placement="top"),void(a.left+e.offsetWidth+8>innerWidth&&a.right-e.offsetWidth>0&&(e.dataset.align="end"))}const o=n?a.width+4:e.offsetWidth,s=Math.max(8,Math.min(a.left-2,innerWidth-o-8)),l=e.offsetHeight,i=a.bottom+6+l<=innerHeight-8||a.top-6-l<8;e.dataset.placement=i?"bottom":"top",Object.assign(e.style,{position:"fixed",inset:"auto",margin:"0",left:`${s}px`,top:`${i?a.bottom+6:a.top-6-l}px`,width:n?`${o}px`:""})}function l(e,t,n){e.hidden=!1,r&&(e.popover="manual",e.showPopover(),o.set(e,[t,n])),s(e,t,n)}function i(e){r&&e.matches(":popover-open")&&e.hidePopover(),o.delete(e),e.hidden=!0}const d=()=>{for(const[e,[t,n]]of o)s(e,t,n)};addEventListener("scroll",d,{capture:!0,passive:!0}),addEventListener("resize",d,{passive:!0});const c=new WeakSet;function u(e){if(c.has(e))return;c.add(e);const r=e.dataset.nrUi;var o;"select"===r?function(e){const t=e.querySelector(".nr-select-native"),r=e.querySelector(".nr-select-trigger"),o=e.querySelector(".nr-select-list"),s=e.querySelector(".nr-select-value"),d=e.querySelector(".nr-field-wrap");if(!(t&&r&&o&&s))return;const c=t.multiple,u=[...t.options].find(e=>""===e.value),f=u?u.textContent:"",p=()=>[...o.querySelectorAll('[role="option"]')],m=()=>p().filter(e=>"true"!==e.getAttribute("aria-disabled"));let v=null,h="",b=0;function y(){const n=new Set([...t.selectedOptions].map(e=>e.value).filter(e=>""!==e)),a=[];for(const e of p()){const t=n.has(e.dataset.value);e.setAttribute("aria-selected",String(t)),t&&a.push(e.querySelector(".nr-select-option-label").textContent)}s.textContent=a.length?a.join(", "):f,s.toggleAttribute("data-placeholder",!a.length),e.toggleAttribute("data-filled",a.length>0)}function w(e,t=!0){v&&v.removeAttribute("data-active"),v=e||null,v?(v.setAttribute("data-active",""),r.setAttribute("aria-activedescendant",v.id),t&&v.scrollIntoView({block:"nearest"})):r.removeAttribute("aria-activedescendant")}function k(){o.hidden&&!t.disabled&&(a(e),l(o,d,!0),e.setAttribute("data-open",""),r.setAttribute("aria-expanded","true"),w(m().find(e=>"true"===e.getAttribute("aria-selected"))||m()[0]),n.set(e,D))}function D(t){o.hidden||(i(o),e.removeAttribute("data-open"),r.setAttribute("aria-expanded","false"),w(null),n.delete(e),!0===t&&r.focus())}function E(e){if(!e||"true"===e.getAttribute("aria-disabled"))return;const n=[...t.options].find(t=>t.value===e.dataset.value);n&&(n.selected=!c||!n.selected,g(t),y(),c||D(!0))}r.addEventListener("click",()=>o.hidden?k():D()),d.addEventListener("click",e=>{e.target.closest(".nr-select-list, .nr-select-trigger")||(r.focus(),o.hidden?k():D())}),o.addEventListener("mousedown",e=>e.preventDefault()),o.addEventListener("pointermove",e=>{const t=e.target.closest('[role="option"]');t&&t!==v&&"true"!==t.getAttribute("aria-disabled")&&w(t,!1)}),o.addEventListener("click",e=>{e.stopPropagation(),E(e.target.closest('[role="option"]'))}),r.addEventListener("keyup",e=>{" "===e.key&&e.preventDefault()}),r.addEventListener("keydown",e=>{const t=m(),n=t.indexOf(v);switch(e.key){case"ArrowDown":e.preventDefault(),o.hidden?k():w(t[Math.min(n+1,t.length-1)]||t[0]);break;case"ArrowUp":e.preventDefault(),o.hidden?k():w(t[Math.max(n-1,0)]);break;case"Home":case"End":o.hidden||(e.preventDefault(),w("Home"===e.key?t[0]:t[t.length-1]));break;case"Enter":case" ":e.preventDefault(),o.hidden?k():E(v);break;case"Escape":o.hidden||(e.preventDefault(),D(!0));break;case"Tab":D();break;default:if(1===e.key.length&&!e.ctrlKey&&!e.metaKey&&!e.altKey){const n=Date.now();h=n-b>700?e.key:h+e.key,b=n;const a=h.toLowerCase(),r=t.find(e=>e.textContent.trim().toLowerCase().startsWith(a));r&&(o.hidden&&k(),w(r))}}}),e.querySelector(".nr-field-label")?.addEventListener("click",e=>{e.preventDefault(),r.focus()}),t.addEventListener("change",y),t.form&&t.form.addEventListener("reset",()=>setTimeout(y)),y()}(e):"datepicker"===r?function(e){const r=e.querySelector(".nr-datepicker-input"),o=e.querySelector(".nr-calendar"),d=e.querySelector(".nr-field-wrap");if(!r||!o||!d)return;const c=e.dataset.locale||t.lang||void 0,u=+(e.dataset.firstDay||0),f=D(r.min),p=D(r.max),m=()=>{const e=new Date;return new Date(e.getFullYear(),e.getMonth(),e.getDate())},v=e=>(!f||e>=f)&&(!p||e<=p),h=new Intl.DateTimeFormat(c,{dateStyle:"medium"}),A=new Intl.DateTimeFormat(c,{dateStyle:"full"}),S=new Intl.DateTimeFormat(c,{month:"long",year:"numeric"}),L=new Intl.DateTimeFormat(c,{month:"short"}),x=new Intl.DateTimeFormat(c,{weekday:"short"}),M=document.createElement("input");M.type="hidden",M.name=r.name,r.removeAttribute("name"),r.after(M);let q=D(r.value);r.type="text",r.autocomplete="off",r.setAttribute("inputmode","none"),r.setAttribute("aria-haspopup","dialog"),r.addEventListener("beforeinput",e=>e.preventDefault());const F=()=>{r.value=q?h.format(q):"",M.value=q?b(q):""};F();let Y="days",T=q||m();function C(e,t,n){const a=document.createElement("button");a.type="button",a.className=e;for(const[e,n]of Object.entries(t))!1!==n&&null!=n&&a.setAttribute(e,!0===n?"":n);return a.innerHTML=n,a}function P(e){o.textContent="",o.dataset.view=Y;const t=document.createElement("div");t.className="nr-cal-header";const n="days"===Y,a=n?E(k(T),-1):new Date(T.getFullYear()-1,11,31),r=n?E(k(T),1):new Date(T.getFullYear()+1,0,1),l=n?new Date(a.getFullYear(),a.getMonth()+1,0):a;if(t.append(C("nr-cal-nav",{"data-cal":"prev","aria-label":n?"Previous month":"Previous year",disabled:!!f&&l<f},'<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>'),C("nr-cal-title",{"data-cal":"view","aria-live":"polite"},`<span>${n?S.format(T):T.getFullYear()}</span><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>`),C("nr-cal-nav",{"data-cal":"next","aria-label":n?"Next month":"Next year",disabled:!!p&&r>p},'<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>')),o.append(t),n){const e=document.createElement("div");e.className="nr-cal-grid",e.setAttribute("role","grid");for(let t=0;t<7;t++){const n=document.createElement("div");n.className="nr-cal-weekday",n.setAttribute("role","columnheader"),n.textContent=x.format(new Date(2023,0,1+(t+u)%7)),e.append(n)}const t=k(T),n=(t.getDay()-u+7)%7,a=m();for(let r=0;r<42;r++){const o=w(t,r-n);e.append(C("nr-cal-day",{role:"gridcell","data-date":b(o),"aria-label":A.format(o),"aria-selected":y(o,q)?"true":"false","data-today":y(o,a),"data-outside":o.getMonth()!==T.getMonth(),tabindex:y(o,T)?"0":"-1",disabled:!v(o)},String(o.getDate())))}o.append(e)}else{const e=document.createElement("div");e.className="nr-cal-months";for(let t=0;t<12;t++){const n=new Date(T.getFullYear(),t,1),a=new Date(T.getFullYear(),t+1,0);e.append(C("nr-cal-month",{"data-month":String(t),"aria-selected":q&&q.getFullYear()===T.getFullYear()&&q.getMonth()===t?"true":"false","data-current":t===T.getMonth(),tabindex:t===T.getMonth()?"0":"-1",disabled:!!f&&a<f||!!p&&n>p},L.format(n)))}o.append(e)}const i=document.createElement("div");i.className="nr-cal-footer",i.append(C("nr-cal-link",{"data-cal":"today",disabled:!v(m())},"Today"),C("nr-cal-link",{"data-cal":"clear"},"Clear")),o.append(i),o.hidden||s(o,d,!1),e&&o.querySelector('[tabindex="0"]:not(:disabled)')?.focus({preventScroll:!0})}function H(){!o.hidden||r.disabled||r.readOnly||(a(e),Y="days",T=q||(v(m())?m():f||p||m()),P(!1),l(o,d,!1),e.setAttribute("data-open",""),e.querySelector(".nr-datepicker-toggle")?.setAttribute("aria-expanded","true"),o.querySelector('[tabindex="0"]:not(:disabled)')?.focus({preventScroll:!0}),n.set(e,I))}function I(t){o.hidden||(i(o),e.removeAttribute("data-open"),e.querySelector(".nr-datepicker-toggle")?.setAttribute("aria-expanded","false"),n.delete(e),!0===t&&r.focus({preventScroll:!0}))}function N(e){q=e,F(),g(M),I(!0)}function O(e){f&&e<f&&(e=f),p&&e>p&&(e=p),T=e,P(!0)}o.addEventListener("click",e=>{const t=e.target.closest("button");t&&!t.disabled&&(t.dataset.date?N(D(t.dataset.date)):t.dataset.month?(T=new Date(T.getFullYear(),+t.dataset.month,Math.min(T.getDate(),28)),Y="days",P(!0)):"prev"===t.dataset.cal?(T="days"===Y?E(T,-1):new Date(T.getFullYear()-1,T.getMonth(),1),P(!1)):"next"===t.dataset.cal?(T="days"===Y?E(T,1):new Date(T.getFullYear()+1,T.getMonth(),1),P(!1)):"view"===t.dataset.cal?(Y="days"===Y?"months":"days",P(!0)):"today"===t.dataset.cal?N(m()):"clear"===t.dataset.cal&&(q=null,F(),g(M),I(!0)))}),o.addEventListener("keydown",e=>{if("Escape"===e.key)return e.preventDefault(),void I(!0);const t=e.target.dataset&&e.target.dataset.date,n=e.target.dataset&&null!=e.target.dataset.month;if(!t&&!n)return;const a={ArrowLeft:-1,ArrowRight:1,ArrowUp:t?-7:-3,ArrowDown:t?7:3}[e.key];if(null!=a)if(e.preventDefault(),t)O(w(T,a));else{const e=Math.min(11,Math.max(0,T.getMonth()+a));T=new Date(T.getFullYear(),e,1),P(!0)}else if(!t||"PageUp"!==e.key&&"PageDown"!==e.key){if(t&&("Home"===e.key||"End"===e.key)){e.preventDefault();const t=(T.getDay()-u+7)%7;O(w(T,"Home"===e.key?-t:6-t))}}else e.preventDefault(),O(E(T,("PageUp"===e.key?-1:1)*(e.shiftKey?12:1)))}),e.addEventListener("focusout",t=>{o.hidden||!t.relatedTarget||e.contains(t.relatedTarget)||I()}),r.addEventListener("click",H),r.addEventListener("keydown",e=>{"Enter"===e.key||" "===e.key||"ArrowDown"===e.key?(e.preventDefault(),H()):"Backspace"!==e.key&&"Delete"!==e.key||!q||r.required||(e.preventDefault(),q=null,F(),g(M))}),d.addEventListener("click",e=>{e.target.closest(".nr-calendar")||(e.target.closest(".nr-datepicker-toggle")&&!o.hidden?I(!0):H())}),r.form&&r.form.addEventListener("reset",()=>setTimeout(()=>{q=D(r.defaultValue),F()}))}(e):"avatar"===r?function(e){const t=e.querySelector(".nr-avatar-img");if(!t)return;const n=()=>t.hidden=!0;t.complete&&0===t.naturalWidth&&t.getAttribute("src")?n():t.addEventListener("error",n,{once:!0})}(e):"tabs"===r?function(e){const t=e.querySelector('[role="tablist"]');if(!t)return;const n=()=>[...t.querySelectorAll('[role="tab"]')];function a(t,a){if(t&&!t.disabled){for(const e of n()){const n=e===t;e.classList.toggle("nr-tab-selected",n),e.setAttribute("aria-selected",String(n)),e.tabIndex=n?0:-1;const a=e.getAttribute("aria-controls")&&document.getElementById(e.getAttribute("aria-controls"));a&&(a.hidden=!n)}a&&t.focus({preventScroll:!0}),p(e,"nr:change",{key:t.dataset.key})}}t.addEventListener("click",e=>{const n=e.target.closest('[role="tab"]');n&&t.contains(n)&&a(n)}),t.addEventListener("keydown",e=>{const t=n().filter(e=>!e.disabled),r=t.indexOf(e.target.closest('[role="tab"]'));if(r<0)return;const o={ArrowRight:r+1,ArrowLeft:r-1,Home:0,End:t.length-1}[e.key];void 0!==o&&(e.preventDefault(),a(t[(o+t.length)%t.length],!0))})}(e):"modal"===r&&((o=e).open&&(o.close(),v(o)),o.addEventListener("click",e=>{e.target===o&&o.hasAttribute("data-dismissable")&&o.close()}),o.addEventListener("close",()=>p(o,"nr:close",null)))}function f(e){e.matches&&e.matches("[data-nr-ui]")&&u(e);for(const t of e.querySelectorAll("[data-nr-ui]"))u(t)}const p=(e,t,n)=>e.dispatchEvent(new CustomEvent(t,{bubbles:!0,detail:n})),g=e=>{e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))};function m(e){const t=document.querySelector(".nr-shell");if(t){t.toggleAttribute("data-open",e);for(const t of document.querySelectorAll(".nr-navbar-menu"))t.setAttribute("aria-expanded",String(e))}}function v(e){e&&!e.open&&(e.showModal(),p(e,"nr:open",null))}document.addEventListener("click",async t=>{const n=t.target.closest&&t.target.closest("[data-nr-press]");if(!n||n.matches(':disabled, [aria-disabled="true"], [data-loading]'))return;const a=n.dataset.nrPress,r=n.dataset.nrPressTarget||"";if("navigate"===a)t.preventDefault(),e().navigate?e().navigate(r):location.href=r;else if("modal"===a)t.preventDefault(),v(document.getElementById(r));else if("close-modal"===a){t.preventDefault();const e=n.closest("dialog");e&&e.close()}else if("emit"===a)p(n,"nr:"+r,null);else if("action"===a){t.preventDefault();let a=null;try{a=JSON.parse(n.dataset.nrPressInput||"null")}catch{}n.setAttribute("data-loading",""),n.setAttribute("aria-busy","true");try{const t=await e().action(r,a);p(n,"nr:success",t),"false"!==n.dataset.nrPressRefresh&&e().refresh&&e().refresh()}catch(e){p(n,"nr:error",e),n.hasAttribute("data-nr-quiet")||console.error("[next-rust] action failed:",e.message)}finally{n.removeAttribute("data-loading"),n.removeAttribute("aria-busy")}}}),document.addEventListener("keydown",e=>{const t=e.target;("Enter"===e.key||" "===e.key)&&t.matches&&t.matches('[data-nr-press][role="button"]')&&(e.preventDefault(),t.click())}),document.addEventListener("click",e=>{const t=e.target.closest&&e.target.closest("[data-nr-field-action]");if(t){const e=t.closest(".nr-field")?.querySelector("input.nr-field-input, textarea.nr-field-input"),n=t.dataset.nrFieldAction;if("toggle-password"===n&&e){const n="password"===e.type;e.type=n?"text":"password",t.setAttribute("aria-pressed",String(n)),t.setAttribute("aria-label",n?"Hide password":"Show password"),e.focus({preventScroll:!0});const a=e.value.length;e.setSelectionRange(a,a)}else"clear"===n&&e&&(e.value="",g(e),e.focus());return}const n=e.target.closest&&e.target.closest(".nr-input .nr-field-wrap, .nr-textarea .nr-field-wrap");n&&!e.target.closest("input, textarea, button, a, select")&&n.querySelector(".nr-field-input")?.focus()}),document.addEventListener("click",e=>{e.target.closest&&e.target.closest("[data-nr-shell-toggle]")?m(!document.querySelector(".nr-shell[data-open]")):e.target.closest&&e.target.closest(".nr-shell-sidebar a[href]")&&m(!1)}),window.addEventListener("nr:navigate",()=>m(!1)),document.addEventListener("keydown",e=>{"Escape"===e.key&&document.querySelector(".nr-shell[data-open]")&&m(!1)}),document.addEventListener("click",e=>{const t=e.target.closest&&e.target.closest("[data-nr-dismiss]"),n=t&&t.closest('[data-nr-ui="alert"]');n&&(p(n,"nr:dismiss",null),n.remove())});const h=(e,t=2)=>String(e).padStart(t,"0"),b=e=>`${h(e.getFullYear(),4)}-${h(e.getMonth()+1)}-${h(e.getDate())}`,y=(e,t)=>!!e&&!!t&&b(e)===b(t),w=(e,t)=>new Date(e.getFullYear(),e.getMonth(),e.getDate()+t),k=e=>new Date(e.getFullYear(),e.getMonth(),1);function D(e){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e||"");if(!t)return null;const n=new Date(+t[1],+t[2]-1,+t[3]);return n.getMonth()===+t[2]-1?n:null}function E(e,t){const n=new Date(e.getFullYear(),e.getMonth()+t,1),a=new Date(n.getFullYear(),n.getMonth()+1,0).getDate();return new Date(n.getFullYear(),n.getMonth(),Math.min(e.getDate(),a))}f(document),new MutationObserver(e=>{for(const t of e)for(const e of t.addedNodes)1===e.nodeType&&f(e)}).observe(t,{childList:!0,subtree:!0});"####;
746
747/// `script` with every `nr-*` class name replaced through `rename`, for
748/// release builds that give the component classes short names. A class name
749/// is a whole `nr-…` token (so `data-nr-ui` is left alone).
750pub fn rename_classes(script: &str, rename: &dyn Fn(&str) -> Option<String>) -> String {
751    let part = |b: u8| b.is_ascii_alphanumeric() || b == b'-' || b == b'_';
752    let bytes = script.as_bytes();
753    let mut out = String::with_capacity(script.len());
754    let mut last = 0;
755    let mut i = 0;
756    while let Some(at) = script[i..].find("nr-").map(|at| i + at) {
757        let end =
758            at + bytes[at..].iter().take_while(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || **b == b'-').count();
759        if at > 0 && part(bytes[at - 1]) {
760            i = end;
761            continue;
762        }
763        if let Some(short) = rename(&script[at..end]) {
764            out.push_str(&script[last..at]);
765            out.push_str(&short);
766            last = end;
767        }
768        i = end;
769    }
770    out.push_str(&script[last..]);
771    out
772}
773
774#[cfg(test)]
775mod tests {
776    use super::*;
777
778    /// Content hash of [`UI_JS`] that [`UI_JS_MIN`] was generated from.
779    const UI_JS_SOURCE_HASH: &str = "7faa71b0c48d8972";
780
781    #[test]
782    fn minified_script_matches_source() {
783        assert_eq!(
784            next_rust_assets::content_hash(UI_JS.as_bytes()),
785            UI_JS_SOURCE_HASH,
786            "UI_JS changed: regenerate UI_JS_MIN and UI_JS_SOURCE_HASH (see CONTRIBUTING.md)"
787        );
788        assert!(!UI_JS_MIN.contains('\n'), "minified to one line");
789        assert!(UI_JS_MIN.len() < UI_JS.len() * 2 / 3);
790    }
791
792    #[test]
793    fn class_names_are_renamed_as_whole_tokens() {
794        let rename = |c: &str| match c {
795            "nr-field" => Some("a".to_owned()),
796            "nr-field-wrap" => Some("b".to_owned()),
797            "nr-ui-js" => Some("c".to_owned()),
798            _ => None,
799        };
800        let js = r#"x.querySelector(".nr-field .nr-field-wrap");h.classList.add("nr-ui-js");e.dataset.nrUi;"[data-nr-ui]";"nr-other""#;
801        assert_eq!(
802            rename_classes(js, &rename),
803            r#"x.querySelector(".a .b");h.classList.add("c");e.dataset.nrUi;"[data-nr-ui]";"nr-other""#
804        );
805    }
806
807    #[test]
808    fn minified_script_keeps_public_contract() {
809        for needle in
810            ["nr-ui-js", "data-nr-ui", "data-nr-press", "data-nr-field-action", "data-nr-shell-toggle", "nr:navigate"]
811        {
812            assert!(UI_JS_MIN.contains(needle), "minified script lost `{needle}`");
813        }
814    }
815}