// Khaemhat browser interop (SPEC ยง1.1: JavaScript only as minimal interop, no framework, no bundler). // Everything lives under window.khaemhat; .NET calls these functions through IJSRuntime. (function () { "use strict"; let shortcutTarget = null; let shortcutCombos = new Set(); let unloadGuard = false; // The combination of a key event in the form used by KeyboardShortcuts.cs: "Ctrl+Shift+K", "F9", "Alt+1", "Escape". function comboOf(e) { let key; if (/^Key[A-Z]$/.test(e.code)) key = e.code.substring(3); else if (/^Digit[0-9]$/.test(e.code)) key = e.code.substring(5); else if (e.key === " ") key = "Space"; else key = e.key; if (key === "Control" || key === "Alt" || key === "Shift" || key === "Meta") return null; let combo = ""; if (e.ctrlKey || e.metaKey) combo += "Ctrl+"; if (e.altKey) combo += "Alt+"; if (e.shiftKey) combo += "Shift+"; return combo + key; } // The keys an element handles itself (data-kh-prevent="ArrowDown F4"): the page shortcuts leave them alone. function preventedBy(element, combo) { const list = element && element.getAttribute ? element.getAttribute("data-kh-prevent") : null; return !!list && list.split(" ").indexOf(combo) >= 0; } function onKeyDown(e) { if (!shortcutTarget || e.isComposing) return; const combo = comboOf(e); if (!combo || !shortcutCombos.has(combo) || preventedBy(e.target, combo)) return; // A modal window is open: the page behind it does not react (Ctrl+Canc in a search box must not delete the record). if (document.querySelector(".overlay")) return; e.preventDefault(); e.stopPropagation(); shortcutTarget.invokeMethodAsync("OnShortcut", combo).catch(function () { /* circuit gone */ }); } // Escape closes the topmost dialog even when the focus fell out of it (after a re-render, a click on the page). // Inside the dialog its own handler already does it. document.addEventListener("keydown", function (e) { if (e.key !== "Escape" || e.defaultPrevented) return; const overlays = document.querySelectorAll(".overlay"); if (overlays.length === 0 || (e.target.closest && e.target.closest(".overlay"))) return; const close = overlays[overlays.length - 1].querySelector(".kh-close"); if (close) close.click(); }); // Dashboard widgets being customized can be dragged: Firefox starts a drag only when some data is set. document.addEventListener("dragstart", function (e) { const widget = e.target.closest && e.target.closest("[data-kh-drag]"); if (!widget || !e.dataTransfer) return; e.dataTransfer.effectAllowed = "move"; e.dataTransfer.setData("text/plain", widget.getAttribute("data-widget") || ""); }); function onBeforeUnload(e) { if (!unloadGuard) return; e.preventDefault(); e.returnValue = ""; } window.khaemhat = { // Sets (or removes, with null) attributes of the root element: data-theme, data-accent, data-density... applyRoot: function (attributes) { const root = document.documentElement; for (const name in attributes) { const value = attributes[name]; if (value === null || value === undefined) root.removeAttribute(name); else root.setAttribute(name, value); } }, // Registers the .NET object that receives the shortcuts, and the combinations it wants. startShortcuts: function (target, combos) { shortcutTarget = target; shortcutCombos = new Set(combos); document.removeEventListener("keydown", onKeyDown, true); document.addEventListener("keydown", onKeyDown, true); }, stopShortcuts: function () { shortcutTarget = null; document.removeEventListener("keydown", onKeyDown, true); }, // Asks the browser to confirm leaving the page while a tab has unsaved changes. setUnloadGuard: function (on) { unloadGuard = !!on; window.removeEventListener("beforeunload", onBeforeUnload); if (unloadGuard) window.addEventListener("beforeunload", onBeforeUnload); }, // The window width, to collapse the menu under 1100 px when the user never chose. viewportWidth: function () { return window.innerWidth; }, // Round trip for the latency shown in the status bar. ping: function () { return true; }, // Moves the focus to the first element matching a selector. focus: function (selector) { const element = document.querySelector(selector); if (element) { element.focus(); if (typeof element.select === "function") element.select(); } }, // Stops the browser default of the keys listed in data-kh-prevent (read at each key, so Blazor can change it): // arrows and Enter in an open hotlink list, + and - in a date field. preventKeys: function (element) { if (!element || element.khPrevent) return; element.khPrevent = true; element.addEventListener("keydown", function (e) { // Date fields: + and - move one day when the field holds a whole date, and are typed otherwise (5-3-26, +30). if ((e.key === "+" || e.key === "-") && !e.ctrlKey && !e.altKey && element.hasAttribute("data-kh-datestep") && /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(element.value)) { e.preventDefault(); e.stopPropagation(); element.dispatchEvent(new KeyboardEvent("keydown", { key: e.key === "+" ? "ArrowUp" : "ArrowDown", bubbles: true })); return; } // Keys typed in a field inside the element (a cell being edited) are the field's own. if (e.target !== element && e.target.matches && e.target.matches("input, textarea, select, [contenteditable]")) return; const combo = comboOf(e); if (combo && preventedBy(element, combo)) e.preventDefault(); }); }, // Places a drop-down menu under its button with fixed coordinates, aligned right, shorter when the window is. placeMenu: function (menu) { const anchor = menu && menu.parentElement; if (!anchor) return; const r = anchor.getBoundingClientRect(); const below = window.innerHeight - r.bottom - 12; const above = r.top - 12; menu.style.position = "fixed"; menu.style.right = Math.max(8, window.innerWidth - r.right) + "px"; menu.style.left = "auto"; if (below >= 200 || below >= above) { menu.style.top = (r.bottom + 6) + "px"; menu.style.bottom = "auto"; menu.style.maxHeight = below + "px"; } else { menu.style.bottom = (window.innerHeight - r.top + 6) + "px"; menu.style.top = "auto"; menu.style.maxHeight = above + "px"; } menu.style.overflowY = "auto"; }, // Brings a row of a grid into view: the row when it is rendered, otherwise its estimated place (virtual rows). scrollGridRow: function (wrap, index) { if (!wrap) return; const row = wrap.querySelector('tr[data-i="' + index + '"]'); if (row) { const head = wrap.querySelector("thead"); const top = row.offsetTop - (head ? head.offsetHeight : 0); if (top < wrap.scrollTop) wrap.scrollTop = top; else if (row.offsetTop + row.offsetHeight > wrap.scrollTop + wrap.clientHeight) wrap.scrollTop = row.offsetTop + row.offsetHeight - wrap.clientHeight; return; } const sample = wrap.querySelector("tbody tr[data-i]"); const height = sample ? sample.offsetHeight : 30; wrap.scrollTop = Math.max(0, index * height - wrap.clientHeight / 2); }, // Moves a fixed menu back inside the window when it would come out of the right or bottom edge. keepInWindow: function (element) { if (!element) return; const r = element.getBoundingClientRect(); if (r.right > window.innerWidth - 8) element.style.left = Math.max(8, window.innerWidth - r.width - 8) + "px"; if (r.bottom > window.innerHeight - 8) element.style.top = Math.max(8, window.innerHeight - r.height - 8) + "px"; }, // Hands a file written by the server to the browser as a download. download: async function (fileName, mediaType, streamReference) { const buffer = await streamReference.arrayBuffer(); const url = URL.createObjectURL(new Blob([buffer], { type: mediaType })); const link = document.createElement("a"); link.href = url; link.download = fileName; document.body.appendChild(link); link.click(); link.remove(); setTimeout(function () { URL.revokeObjectURL(url); }, 2000); }, // The keyboard of the lines of a document: Enter next cell, Shift+Enter previous, arrows the same cell of the line // above or below, Ctrl+Down new line, Ctrl+Canc removes the line, F4 lookup. Rows and cells are data-r and data-c. linesGrid: function (table, target) { if (!table || table.khLines) return; table.khLines = true; const cellOf = function (r, c) { return table.querySelector('input.kh-cell[data-r="' + r + '"][data-c="' + c + '"]'); }; const focusCell = function (r, c) { let tries = 0; (function attempt() { const el = cellOf(r, c) || table.querySelector('input.kh-cell[data-r="' + r + '"]'); if (el) { el.focus(); el.select(); } else if (tries++ < 20) setTimeout(attempt, 40); })(); }; table.khFocus = focusCell; const flush = function (el) { if (el.khDirty) { el.khDirty = false; el.dispatchEvent(new Event("change", { bubbles: true })); } }; table.addEventListener("input", function (e) { if (e.target.classList.contains("kh-cell")) e.target.khDirty = true; }); table.addEventListener("change", function (e) { if (e.target.classList.contains("kh-cell")) e.target.khDirty = false; }, true); table.addEventListener("keydown", function (e) { const el = e.target; if (!el.classList || !el.classList.contains("kh-cell") || e.isComposing) return; const r = Number(el.dataset.r), c = Number(el.dataset.c); const combo = comboOf(e); const call = function (method, args, then) { e.preventDefault(); e.stopPropagation(); flush(el); target.invokeMethodAsync.apply(target, [method].concat(args)).then(then).catch(function () { /* circuit gone */ }); }; if (combo === "Enter" || combo === "Shift+Enter") { e.preventDefault(); const cells = Array.prototype.slice.call(table.querySelectorAll("input.kh-cell:not([readonly])")); const next = cells[cells.indexOf(el) + (combo === "Enter" ? 1 : -1)]; if (next) { next.focus(); next.select(); } } else if (combo === "ArrowDown" || combo === "ArrowUp") { const other = cellOf(r + (combo === "ArrowDown" ? 1 : -1), c); if (other) { e.preventDefault(); other.focus(); other.select(); } } else if (combo === "Ctrl+ArrowDown") { call("InsertAfterAsync", [r], function () { focusCell(r + 1, 0); }); } else if (combo === "Ctrl+Delete") { call("RemoveAtAsync", [r], function () { focusCell(r, c); }); } else if (combo === "F4") { call("LookupAsync", [r, c], function () { }); } }); }, // Moves the focus to a cell of the lines of a document. focusLineCell: function (table, r, c) { if (table && table.khFocus) table.khFocus(r, Math.max(0, c)); }, // Moves the focus to the first field or button inside an element (dialogs, side panels). focusFirst: function (element) { if (!element) return; const target = element.querySelector("[autofocus], input:not([type=hidden]):not([disabled]):not([readonly]), select:not([disabled]), textarea:not([disabled]):not([readonly]), .db button:not([disabled]), .df button:not([disabled])") || element.querySelector("button:not([disabled])"); if (target) target.focus(); }, // Keeps a toolbar on one line: the commands with the highest data-ovf move out (data-ovf-hidden) until the bar // fits, then .NET is told which ones, to list them in the "..." menu. watchToolbar: function (element, target) { if (!element) return; element.khToolbar = target; element.khObserver = new ResizeObserver(function () { window.khaemhat.fitToolbar(element); }); element.khObserver.observe(element); window.khaemhat.fitToolbar(element); }, fitToolbar: function (element) { if (!element || !element.khToolbar || element.clientWidth === 0) return; const items = Array.prototype.slice.call(element.querySelectorAll("[data-ovf]")); const groups = element.querySelectorAll("[data-ovf-group]"); items.forEach(function (item) { item.removeAttribute("data-ovf-hidden"); }); groups.forEach(function (group) { group.removeAttribute("data-ovf-hidden"); }); const order = items.map(function (item, index) { return { item: item, index: index, priority: Number(item.getAttribute("data-ovf")) || 0 }; }) .sort(function (a, b) { return b.priority - a.priority || b.index - a.index; }); const hidden = []; for (let i = 0; i < order.length && element.scrollWidth > element.clientWidth; i++) { order[i].item.setAttribute("data-ovf-hidden", ""); hidden.push(order[i].item.getAttribute("data-id")); } groups.forEach(function (group) { const children = group.querySelectorAll("[data-ovf]"); if (children.length > 0 && Array.prototype.every.call(children, function (c) { return c.hasAttribute("data-ovf-hidden"); })) { group.setAttribute("data-ovf-hidden", ""); } }); element.querySelectorAll(".sep").forEach(function (sep) { const next = sep.nextElementSibling; if (next && next.hasAttribute("data-ovf-hidden")) sep.setAttribute("data-ovf-hidden", ""); else sep.removeAttribute("data-ovf-hidden"); }); const key = hidden.join(","); if (element.khOverflow !== key) { element.khOverflow = key; element.khToolbar.invokeMethodAsync("SetOverflow", hidden).catch(function () { /* circuit gone */ }); } }, unwatchToolbar: function (element) { if (!element) return; if (element.khObserver) element.khObserver.disconnect(); element.khObserver = null; element.khToolbar = null; }, print: function () { window.print(); }, // Opens an address (the wiki help) in a new window, without giving it access to this one. openWindow: function (url) { window.open(url, "_blank", "noopener"); } }; })();