// Shared client behaviour: theme toggle and focus management after HTMX swaps. (function () { const THEME_KEY = "theme"; window.setTheme = function (theme) { document.documentElement.setAttribute("data-theme", theme); localStorage.setItem(THEME_KEY, theme); }; // Forms answer validation errors with 422; HTMX must swap those too so errors are shown. if (window.htmx) { window.htmx.config.responseHandling = [ { code: "204", swap: false }, { code: "[23]..", swap: true }, { code: "422", swap: true }, { code: "[45]..", swap: false, error: true }, { code: "...", swap: true }, ]; } // After a swap: focus the first invalid field, else an element marked data-autofocus. document.addEventListener("htmx:afterSettle", function (event) { const target = event.detail.target; if (!target || !target.isConnected) return; const focusable = target.querySelector("[aria-invalid='true']") || target.querySelector("[data-autofocus]"); if (focusable) { focusable.focus(); } }); // Announce HX-Trigger "notify" events in the live region and as a toast. document.body.addEventListener("notify", function (event) { window.notify(event.detail.value || event.detail.message || ""); }); // A dialog form saved: the server re-rendered the section (HX-Trigger-After-Settle "itemSaved"). document.body.addEventListener("itemSaved", function (event) { const detail = event.detail || {}; document.querySelectorAll("dialog[open]").forEach(function (d) { d.close(); }); if (detail.focus) { const el = document.querySelector(detail.focus); if (el) el.focus(); } if (detail.message) window.notify(detail.message); }); window.notify = function (message) { const live = document.getElementById("live-region"); if (live) { live.textContent = ""; window.setTimeout(function () { live.textContent = message; }, 50); } }; })();