| 1 | /* grid.js — editing in place (level-up spec §5), as progressive |
| 2 | * enhancement. Every screen works without it: a cell is a link to the edit |
| 3 | * form, the card is a form with one Save button, Undo is a one-button |
| 4 | * form, J and K are Next and Previous links. |
| 5 | * |
| 6 | * With it: |
| 7 | * - the table is an ARIA grid with one tab stop and Rejilla's keys (§5.6); |
| 8 | * - a cell edits in place and saves at once, one field per POST, carrying |
| 9 | * what the editor saw (was) and the page's locale (§5.2, §6.8); |
| 10 | * - each save gets a toast with Undo, and ⌘Z / ⇧⌘Z undo and redo this |
| 11 | * tab's own changes, newest first (§5.3); |
| 12 | * - the card's quiet inputs save when they lose focus; |
| 13 | * - J and K walk the list, only while focus is in the card pane or the |
| 14 | * narrowed list and not in an input (§5.4, WCAG 2.1.4); |
| 15 | * - on a phone a value opens a sheet with its editor and Save (§5.8). |
| 16 | * |
| 17 | * The server says what a value means: numbers are read in the locale the |
| 18 | * page was drawn in, which every post carries, and the server answers |
| 19 | * with the cell as it draws it. |
| 20 | */ |
| 21 | (function () { |
| 22 | "use strict"; |
| 23 | |
| 24 | var TOAST_MS = 10000; |
| 25 | var undoStack = []; // this tab's own changes: {card, event, label} |
| 26 | var redoStack = []; // this tab's Undo events, for ⇧⌘Z |
| 27 | var phone = window.matchMedia("(max-width: 799.98px)"); |
| 28 | |
| 29 | function locale() { return document.body.getAttribute("data-locale") || ""; } |
| 30 | |
| 31 | // ---- The save state in the bar's lead, and the live region. |
| 32 | |
| 33 | function saveState(state) { |
| 34 | var el = document.querySelector("[estilo-save-status]"); |
| 35 | if (!el) return; |
| 36 | el.setAttribute("data-state", state); |
| 37 | el.textContent = state === "idle" ? "" : (el.getAttribute("data-text-" + state) || ""); |
| 38 | } |
| 39 | |
| 40 | function announce(text) { |
| 41 | var live = document.querySelector("[fichas-live]"); |
| 42 | if (!live) return; |
| 43 | live.textContent = ""; |
| 44 | window.setTimeout(function () { live.textContent = text; }, 30); |
| 45 | } |
| 46 | |
| 47 | // ---- The toast: what happened, and Undo for 10 seconds. |
| 48 | |
| 49 | function toast(text, action) { |
| 50 | var host = document.querySelector("[fichas-toasts]"); |
| 51 | if (!host) return; |
| 52 | host.querySelectorAll("[fichas-toast]").forEach(function (t) { t.remove(); }); |
| 53 | var t = document.createElement("div"); |
| 54 | t.setAttribute("fichas-toast", ""); |
| 55 | var span = document.createElement("span"); |
| 56 | span.textContent = text; |
| 57 | t.appendChild(span); |
| 58 | if (action) { |
| 59 | var b = document.createElement("button"); |
| 60 | b.type = "button"; |
| 61 | b.textContent = action.label; |
| 62 | b.addEventListener("click", function () { t.remove(); action.run(); }); |
| 63 | t.appendChild(b); |
| 64 | } |
| 65 | host.appendChild(t); |
| 66 | announce(text + (action ? " " + action.label + " is available." : "")); |
| 67 | window.setTimeout(function () { t.remove(); }, TOAST_MS); |
| 68 | } |
| 69 | |
| 70 | // ---- Talking to the server: a form-encoded POST, JSON back. |
| 71 | |
| 72 | function post(url, fields) { |
| 73 | var body = new URLSearchParams(); |
| 74 | Object.keys(fields).forEach(function (k) { body.append(k, fields[k]); }); |
| 75 | return fetch(url, { |
| 76 | method: "POST", |
| 77 | credentials: "same-origin", |
| 78 | headers: { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded" }, |
| 79 | body: body |
| 80 | }).then(function (res) { |
| 81 | var type = res.headers.get("Content-Type") || ""; |
| 82 | if (type.indexOf("application/json") < 0) { |
| 83 | // Not ours to read (a sign-in door after the session ended, say): |
| 84 | // go and see what the server has to say. |
| 85 | if (res.redirected) { window.location.href = res.url; } |
| 86 | throw new Error("not json"); |
| 87 | } |
| 88 | return res.json().then(function (data) { return { status: res.status, data: data }; }); |
| 89 | }); |
| 90 | } |
| 91 | |
| 92 | // saveField writes one field. was is what the editor saw; the reply |
| 93 | // says what the field holds now. |
| 94 | function saveField(card, key, value, was, extra) { |
| 95 | var fields = { "return_to": location.pathname + location.search }; |
| 96 | fields[key] = value; |
| 97 | fields["was." + key] = was; |
| 98 | fields[key + ".locale"] = locale(); |
| 99 | if (extra) Object.keys(extra).forEach(function (k) { fields[k] = extra[k]; }); |
| 100 | saveState("saving"); |
| 101 | return post("/cards/" + card + "/fields/" + encodeURIComponent(key), fields).then(function (r) { |
| 102 | saveState(r.status === 200 ? "saved" : "idle"); |
| 103 | return r; |
| 104 | }, function (err) { |
| 105 | saveState("failed"); |
| 106 | throw err; |
| 107 | }); |
| 108 | } |
| 109 | |
| 110 | function remember(card, event, label) { |
| 111 | if (!event) return; |
| 112 | undoStack.push({ card: card, event: event, label: label }); |
| 113 | redoStack = []; |
| 114 | } |
| 115 | |
| 116 | function undo(entry, redo) { |
| 117 | saveState("saving"); |
| 118 | return post("/cards/" + entry.card + "/undo", { event: entry.event, locale: locale() }).then(function (r) { |
| 119 | if (r.status !== 200) { saveState("idle"); toast("That change can no longer be undone."); return; } |
| 120 | saveState("saved"); |
| 121 | var d = r.data; |
| 122 | Object.keys(d.cells || {}).forEach(function (key) { applyValue(entry.card, key, d.cells[key]); }); |
| 123 | if (d.event) { |
| 124 | if (redo) { undoStack.push({ card: entry.card, event: d.event }); } |
| 125 | else { redoStack.push({ card: entry.card, event: d.event }); } |
| 126 | } |
| 127 | toast(d.message); |
| 128 | }, function () { toast("Couldn't reach Fichas, so nothing was undone."); }); |
| 129 | } |
| 130 | |
| 131 | // undoFromToast is the toast's Undo: the event leaves this tab's ⌘Z |
| 132 | // stack too, so a later ⌘Z does not ask for it again. |
| 133 | function undoFromToast(card, event) { |
| 134 | var i = undoStack.map(function (u) { return u.event; }).indexOf(event); |
| 135 | if (i >= 0) undoStack.splice(i, 1); |
| 136 | undo({ card: card, event: event }, false); |
| 137 | } |
| 138 | |
| 139 | function undoLast() { |
| 140 | var e = undoStack.pop(); |
| 141 | if (e) { undo(e, false); } else { toast("Nothing to undo in this tab."); } |
| 142 | } |
| 143 | |
| 144 | function redoLast() { |
| 145 | var e = redoStack.pop(); |
| 146 | if (e) { undo(e, true); } else { toast("Nothing to redo."); } |
| 147 | } |
| 148 | |
| 149 | // applyValue draws a field's new value wherever this page shows it: its |
| 150 | // table cell, and the card's quiet input. |
| 151 | function applyValue(card, key, v) { |
| 152 | document.querySelectorAll('tr[data-card="' + card + '"] td[data-field="' + key + '"]').forEach(function (td) { |
| 153 | td.setAttribute("data-was", v.value); |
| 154 | td.setAttribute("data-seed", v.seed); |
| 155 | var link = td.querySelector("[fichas-cell-link]"); |
| 156 | if (link) { |
| 157 | var sr = link.querySelector(".rst-sr-only"); |
| 158 | link.innerHTML = v.cell; |
| 159 | if (sr) link.appendChild(sr); |
| 160 | } |
| 161 | }); |
| 162 | document.querySelectorAll('[fichas-card-form][data-card="' + card + '"]').forEach(function (form) { |
| 163 | var wasInput = form.querySelector('input[name="was.' + cssEscape(key) + '"]'); |
| 164 | if (wasInput) wasInput.value = v.value; |
| 165 | var input = form.querySelector('[name="' + cssEscape(key) + '"]:not([type="hidden"])'); |
| 166 | if (input && document.activeElement !== input) input.value = v.seed; |
| 167 | }); |
| 168 | } |
| 169 | |
| 170 | function cssEscape(s) { return window.CSS && CSS.escape ? CSS.escape(s) : s.replace(/"/g, '\\"'); } |
| 171 | |
| 172 | // ---- The grid (§5.6). |
| 173 | |
| 174 | function cellsOf(row) { return Array.prototype.filter.call(row.children, function (c) { return c.tagName === "TD" || c.tagName === "TH"; }); } |
| 175 | |
| 176 | function setupGrid(table) { |
| 177 | if (table.hasAttribute("data-grid-ready")) return; |
| 178 | table.setAttribute("data-grid-ready", ""); |
| 179 | table.setAttribute("role", "grid"); |
| 180 | var first = null; |
| 181 | table.querySelectorAll("tr").forEach(function (tr) { |
| 182 | cellsOf(tr).forEach(function (cell) { |
| 183 | cell.setAttribute("tabindex", "-1"); |
| 184 | if (tr.parentElement.tagName === "TBODY" && !first) first = cell; |
| 185 | cell.querySelectorAll("a").forEach(function (a) { a.setAttribute("tabindex", "-1"); }); |
| 186 | }); |
| 187 | }); |
| 188 | if (first) first.setAttribute("tabindex", "0"); |
| 189 | table.addEventListener("keydown", function (e) { gridKey(table, e); }); |
| 190 | table.addEventListener("click", function (e) { gridClick(table, e); }); |
| 191 | table.addEventListener("focusin", function (e) { |
| 192 | var cell = e.target.closest("td, th"); |
| 193 | if (cell && table.contains(cell) && !cell.querySelector("[fichas-editor]")) activate(table, cell, false); |
| 194 | }); |
| 195 | } |
| 196 | |
| 197 | function activate(table, cell, focus) { |
| 198 | table.querySelectorAll('[tabindex="0"]').forEach(function (c) { if (c !== cell && (c.tagName === "TD" || c.tagName === "TH")) c.setAttribute("tabindex", "-1"); }); |
| 199 | cell.setAttribute("tabindex", "0"); |
| 200 | if (focus) cell.focus(); |
| 201 | } |
| 202 | |
| 203 | function position(table, cell) { |
| 204 | var rows = Array.prototype.slice.call(table.querySelectorAll("tr")); |
| 205 | var r = rows.indexOf(cell.parentElement); |
| 206 | return { rows: rows, r: r, c: cellsOf(cell.parentElement).indexOf(cell) }; |
| 207 | } |
| 208 | |
| 209 | function move(table, cell, dr, dc, abs) { |
| 210 | var p = position(table, cell); |
| 211 | var r = abs && abs.row !== undefined ? abs.row : p.r + dr; |
| 212 | // Row 0 is the header: ArrowUp from the first row reaches it, and |
| 213 | // Enter there follows its sort link. |
| 214 | r = Math.max(0, Math.min(p.rows.length - 1, r)); |
| 215 | var row = cellsOf(p.rows[r]); |
| 216 | var c = abs && abs.col !== undefined ? abs.col : p.c + dc; |
| 217 | c = Math.max(0, Math.min(row.length - 1, c)); |
| 218 | activate(table, row[c], true); |
| 219 | return row[c]; |
| 220 | } |
| 221 | |
| 222 | function editable(cell) { return cell && cell.tagName === "TD" && cell.hasAttribute("data-field"); } |
| 223 | |
| 224 | function gridKey(table, e) { |
| 225 | var cell = e.target.closest("td, th"); |
| 226 | if (!cell || e.target !== cell) return; // an editor handles its own keys |
| 227 | var mod = e.metaKey || e.ctrlKey; |
| 228 | var p = position(table, cell); |
| 229 | switch (e.key) { |
| 230 | case "ArrowUp": e.preventDefault(); if (mod) move(table, cell, 0, 0, { row: 1 }); else move(table, cell, -1, 0); return; |
| 231 | case "ArrowDown": e.preventDefault(); if (mod) move(table, cell, 0, 0, { row: p.rows.length - 1 }); else move(table, cell, 1, 0); return; |
| 232 | case "ArrowLeft": e.preventDefault(); move(table, cell, 0, -1); return; |
| 233 | case "ArrowRight": e.preventDefault(); move(table, cell, 0, 1); return; |
| 234 | case "Home": e.preventDefault(); move(table, cell, 0, 0, { col: 0 }); return; |
| 235 | case "End": e.preventDefault(); move(table, cell, 0, 0, { col: 99 }); return; |
| 236 | case "Escape": e.preventDefault(); var q = document.querySelector('[data-live-search] input[name="q"]'); if (q) q.focus(); return; |
| 237 | case "Enter": |
| 238 | e.preventDefault(); |
| 239 | if (editable(cell)) { openEditor(table, cell, null); return; } |
| 240 | var link = cell.querySelector("a[href]"); |
| 241 | if (link) link.click(); // the name opens the card; a header sorts |
| 242 | return; |
| 243 | case " ": |
| 244 | if (editable(cell)) { e.preventDefault(); openEditor(table, cell, null); } |
| 245 | return; |
| 246 | case "Delete": |
| 247 | case "Backspace": |
| 248 | if (editable(cell)) { e.preventDefault(); commit(table, cell, "", { stay: true }); } |
| 249 | return; |
| 250 | } |
| 251 | if (mod && (e.key === "c" || e.key === "C") && !e.shiftKey) { |
| 252 | if (navigator.clipboard) { e.preventDefault(); navigator.clipboard.writeText(cellText(cell)); } |
| 253 | return; |
| 254 | } |
| 255 | if (mod && (e.key === "v" || e.key === "V") && editable(cell) && navigator.clipboard && navigator.clipboard.readText) { |
| 256 | e.preventDefault(); |
| 257 | navigator.clipboard.readText().then(function (text) { commit(table, cell, text.trim(), { stay: true, typed: true }); }); |
| 258 | return; |
| 259 | } |
| 260 | // A printable key starts an edit, replacing the value with what is |
| 261 | // typed. It never opens anything else (§5.4: typing "Oslo" edits). |
| 262 | // The key is not swallowed: the editor opens empty and takes focus |
| 263 | // during the keydown, so the browser types the character into it, |
| 264 | // composition and dead keys included. |
| 265 | if (!mod && !e.altKey && e.key.length === 1 && editable(cell)) { |
| 266 | if (phone.matches) { e.preventDefault(); openSheet(cell, e.key); return; } |
| 267 | openEditor(table, cell, ""); |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | function cellText(cell) { |
| 272 | var clone = cell.cloneNode(true); |
| 273 | clone.querySelectorAll(".rst-sr-only").forEach(function (n) { n.remove(); }); |
| 274 | return clone.textContent.replace(/\s+/g, " ").trim(); |
| 275 | } |
| 276 | |
| 277 | function gridClick(table, e) { |
| 278 | var cell = e.target.closest("td, th"); |
| 279 | if (!cell || !table.contains(cell) || e.target.closest("[fichas-editor], [fichas-picker], [fichas-editor-error]")) return; |
| 280 | if (!editable(cell)) return; // the name, a header, Last call: their links work as links |
| 281 | if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; // a new tab still opens the edit form |
| 282 | e.preventDefault(); |
| 283 | activate(table, cell, false); |
| 284 | if (phone.matches) { openSheet(cell); return; } |
| 285 | openEditor(table, cell, null); |
| 286 | } |
| 287 | |
| 288 | // ---- A cell's editor. |
| 289 | |
| 290 | function openEditor(table, cell, typed) { |
| 291 | if (phone.matches) { openSheet(cell, typed); return; } |
| 292 | closeEditors(); |
| 293 | var kind = cell.getAttribute("data-kind"); |
| 294 | var box = document.createElement("div"); |
| 295 | box.setAttribute("fichas-editor", ""); |
| 296 | var input; |
| 297 | if (kind === "enum") { |
| 298 | cell.appendChild(box); |
| 299 | openPicker(table, cell, box, typed); |
| 300 | return; |
| 301 | } |
| 302 | input = document.createElement("input"); |
| 303 | input.setAttribute("aria-label", cell.getAttribute("data-label") || "Value"); |
| 304 | if (kind === "date") { input.type = "date"; input.value = cell.getAttribute("data-was") || ""; } |
| 305 | else { |
| 306 | input.type = kind === "email" ? "email" : kind === "phone" ? "tel" : "text"; |
| 307 | input.inputMode = { number: "decimal", email: "email", phone: "tel", url: "url" }[kind] || "text"; |
| 308 | input.autocomplete = "off"; |
| 309 | input.spellcheck = kind === "text"; |
| 310 | input.value = typed !== null ? typed : (cell.getAttribute("data-seed") || ""); |
| 311 | } |
| 312 | box.appendChild(input); |
| 313 | cell.appendChild(box); |
| 314 | input.focus(); |
| 315 | if (typed === null && input.select) input.select(); |
| 316 | input.addEventListener("keydown", function (e) { |
| 317 | if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeEditor(cell, true); } |
| 318 | else if (e.key === "Enter") { e.preventDefault(); commit(table, cell, input.value, { next: [e.shiftKey ? -1 : 1, 0] }); } |
| 319 | else if (e.key === "Tab") { e.preventDefault(); commit(table, cell, input.value, { next: [0, e.shiftKey ? -1 : 1] }); } |
| 320 | }); |
| 321 | input.addEventListener("blur", function () { |
| 322 | window.setTimeout(function () { |
| 323 | if (box.isConnected && !box.contains(document.activeElement) && !cell.querySelector("[fichas-editor-error]")) commit(table, cell, input.value, { quiet: true }); |
| 324 | }, 0); |
| 325 | }); |
| 326 | } |
| 327 | |
| 328 | // place pins a popup under its cell in the viewport's coordinates, so |
| 329 | // the table's own scrolling box never clips it. |
| 330 | function place(popup, cell) { |
| 331 | var r = cell.getBoundingClientRect(); |
| 332 | popup.style.position = "fixed"; |
| 333 | popup.style.top = Math.round(r.bottom + 4) + "px"; |
| 334 | popup.style.left = Math.round(Math.min(r.left, window.innerWidth - 240)) + "px"; |
| 335 | } |
| 336 | |
| 337 | function closeEditors() { document.querySelectorAll("[fichas-editor], [fichas-picker], [fichas-editor-error]").forEach(function (n) { n.remove(); }); } |
| 338 | |
| 339 | function closeEditor(cell, refocus) { |
| 340 | cell.querySelectorAll("[fichas-editor], [fichas-picker], [fichas-editor-error]").forEach(function (n) { n.remove(); }); |
| 341 | if (refocus) cell.focus(); |
| 342 | } |
| 343 | |
| 344 | // A choice opens a listbox with a search box (§6.5). |
| 345 | function openPicker(table, cell, box, typed) { |
| 346 | var options = (cell.getAttribute("data-options") || "").split("\n").filter(Boolean); |
| 347 | var current = cell.getAttribute("data-was") || ""; |
| 348 | var pick = document.createElement("div"); |
| 349 | pick.setAttribute("fichas-picker", ""); |
| 350 | var search = document.createElement("input"); |
| 351 | search.type = "text"; |
| 352 | search.setAttribute("role", "combobox"); |
| 353 | search.setAttribute("aria-label", "Find " + (cell.getAttribute("data-label") || "an option")); |
| 354 | search.setAttribute("aria-expanded", "true"); |
| 355 | var list = document.createElement("ul"); |
| 356 | list.setAttribute("role", "listbox"); |
| 357 | list.id = "fichas-picker-list"; |
| 358 | search.setAttribute("aria-controls", list.id); |
| 359 | pick.appendChild(search); |
| 360 | pick.appendChild(list); |
| 361 | box.appendChild(pick); |
| 362 | place(pick, cell); |
| 363 | var active = 0; |
| 364 | function draw() { |
| 365 | var q = search.value.toLowerCase(); |
| 366 | list.innerHTML = ""; |
| 367 | var shown = [""].concat(options).filter(function (o) { return o === "" ? q === "" : o.toLowerCase().indexOf(q) >= 0; }); |
| 368 | active = Math.min(active, shown.length - 1); |
| 369 | shown.forEach(function (o, i) { |
| 370 | var li = document.createElement("li"); |
| 371 | li.setAttribute("role", "option"); |
| 372 | li.id = "fichas-opt-" + i; |
| 373 | li.textContent = o === "" ? "No " + (cell.getAttribute("data-label") || "value").toLowerCase() : o; |
| 374 | li.setAttribute("aria-selected", i === active ? "true" : "false"); |
| 375 | if (o === current) li.setAttribute("data-current", ""); |
| 376 | li.addEventListener("mousedown", function (e) { e.preventDefault(); commit(table, cell, o, {}); }); |
| 377 | list.appendChild(li); |
| 378 | }); |
| 379 | search.setAttribute("aria-activedescendant", shown.length ? "fichas-opt-" + active : ""); |
| 380 | return shown; |
| 381 | } |
| 382 | var shown = draw(); |
| 383 | search.focus(); |
| 384 | search.addEventListener("input", function () { active = 0; shown = draw(); }); |
| 385 | search.addEventListener("keydown", function (e) { |
| 386 | if (e.key === "ArrowDown") { e.preventDefault(); active = Math.min(shown.length - 1, active + 1); shown = draw(); } |
| 387 | else if (e.key === "ArrowUp") { e.preventDefault(); active = Math.max(0, active - 1); shown = draw(); } |
| 388 | else if (e.key === "Enter" || e.key === "Tab") { |
| 389 | e.preventDefault(); |
| 390 | if (shown.length) commit(table, cell, shown[active], { next: e.key === "Tab" ? [0, e.shiftKey ? -1 : 1] : [1, 0] }); |
| 391 | } else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeEditor(cell, true); } |
| 392 | }); |
| 393 | search.addEventListener("blur", function () { |
| 394 | window.setTimeout(function () { if (box.isConnected && !box.contains(document.activeElement)) closeEditor(cell, false); }, 0); |
| 395 | }); |
| 396 | } |
| 397 | |
| 398 | // commit saves a cell's value. Nothing typed that differs from the seed |
| 399 | // is not a change, and is not sent. |
| 400 | function commit(table, cell, value, how) { |
| 401 | var card = cell.parentElement.getAttribute("data-card"); |
| 402 | var key = cell.getAttribute("data-field"); |
| 403 | var was = cell.getAttribute("data-was") || ""; |
| 404 | var seed = cell.getAttribute("data-seed") || ""; |
| 405 | var unchanged = cell.getAttribute("data-kind") === "date" ? value === was : value === seed; |
| 406 | if (unchanged && !how.typed) { closeEditor(cell, !how.quiet); if (how.next) move(table, cell, how.next[0], how.next[1]); return; } |
| 407 | closeEditor(cell, false); |
| 408 | var label = cell.getAttribute("data-label") || ""; |
| 409 | saveField(card, key, value, was, { list: table.getAttribute("data-list") || "" }).then(function (r) { |
| 410 | var d = r.data; |
| 411 | if (r.status === 200) { |
| 412 | applyValue(card, key, d); |
| 413 | if (d.event) { |
| 414 | remember(card, d.event, label); |
| 415 | toast(d.message, { label: "Undo", run: function () { undoFromToast(card, d.event); } }); |
| 416 | } |
| 417 | if (d.outOfView) markOutOfView(cell.parentElement); |
| 418 | if (!how.quiet) { |
| 419 | if (how.next) move(table, cell, how.next[0], how.next[1]); else cell.focus(); |
| 420 | } |
| 421 | } else if (r.status === 409) { |
| 422 | conflictBubble(table, cell, value, d); |
| 423 | } else if (r.status === 422) { |
| 424 | reopenWithError(table, cell, value, d.error); |
| 425 | } else { |
| 426 | toast("This change couldn't be saved."); |
| 427 | } |
| 428 | }, function () { |
| 429 | reopenWithError(table, cell, value, "Couldn't save. Check your connection, then press Enter to try again."); |
| 430 | }); |
| 431 | } |
| 432 | |
| 433 | // A refused value stays in the editor with the message beside it. |
| 434 | function reopenWithError(table, cell, value, message) { |
| 435 | openEditor(table, cell, cell.getAttribute("data-kind") === "enum" ? null : value); |
| 436 | var input = cell.querySelector("[fichas-editor] input"); |
| 437 | var err = document.createElement("p"); |
| 438 | err.setAttribute("fichas-editor-error", ""); |
| 439 | err.setAttribute("role", "alert"); |
| 440 | err.id = "fichas-editor-error"; |
| 441 | err.textContent = message; |
| 442 | cell.appendChild(err); |
| 443 | place(err, cell); |
| 444 | if (input) { input.setAttribute("aria-invalid", "true"); input.setAttribute("aria-describedby", err.id); } |
| 445 | } |
| 446 | |
| 447 | // Someone changed it first: say who and to what, with Keep theirs and |
| 448 | // Use mine (§5.2). Use mine is a second POST with theirs as was. |
| 449 | function conflictBubble(table, cell, mine, d) { |
| 450 | var card = cell.parentElement.getAttribute("data-card"); |
| 451 | var key = cell.getAttribute("data-field"); |
| 452 | applyValue(card, key, { value: d.theirs, seed: d.seed, cell: d.cell }); |
| 453 | var err = document.createElement("div"); |
| 454 | err.setAttribute("fichas-editor-error", ""); |
| 455 | err.setAttribute("role", "alert"); |
| 456 | err.textContent = d.message; |
| 457 | var keep = document.createElement("button"); |
| 458 | keep.type = "button"; keep.setAttribute("rst-btn", "sm"); keep.textContent = "Keep theirs"; |
| 459 | keep.addEventListener("click", function () { err.remove(); cell.focus(); }); |
| 460 | var use = document.createElement("button"); |
| 461 | use.type = "button"; use.setAttribute("rst-btn", "sm"); use.textContent = "Use mine"; |
| 462 | use.addEventListener("click", function () { err.remove(); commit(table, cell, mine, { typed: true }); }); |
| 463 | err.appendChild(keep); |
| 464 | err.appendChild(use); |
| 465 | cell.appendChild(err); |
| 466 | place(err, cell); |
| 467 | keep.focus(); |
| 468 | } |
| 469 | |
| 470 | // An edit that takes a card out of the view does not move or hide its |
| 471 | // row: it says so, in words and with an icon (§5.1). |
| 472 | function markOutOfView(tr) { |
| 473 | if (tr.hasAttribute("data-out-of-view")) return; |
| 474 | tr.setAttribute("data-out-of-view", ""); |
| 475 | var name = tr.querySelector("[fichas-title-cell]"); |
| 476 | if (name) { |
| 477 | var tag = document.createElement("span"); |
| 478 | tag.setAttribute("fichas-out-of-view", ""); |
| 479 | tag.innerHTML = '<svg class="icon" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>No longer in this view'; |
| 480 | name.appendChild(tag); |
| 481 | } |
| 482 | announce("No longer in this view."); |
| 483 | } |
| 484 | |
| 485 | // ---- The phone's sheet (§5.8): the field's editor, Save at its foot. |
| 486 | |
| 487 | function openSheet(cell, typed) { |
| 488 | var kind = cell.getAttribute("data-kind"); |
| 489 | var dialog = document.createElement("dialog"); |
| 490 | dialog.setAttribute("fichas-sheet", ""); |
| 491 | dialog.setAttribute("aria-label", cell.getAttribute("data-label") || "Change"); |
| 492 | var form = document.createElement("form"); |
| 493 | var label = document.createElement("label"); |
| 494 | label.textContent = cell.getAttribute("data-label") || "Value"; |
| 495 | label.htmlFor = "fichas-sheet-input"; |
| 496 | var input; |
| 497 | if (kind === "enum") { |
| 498 | input = document.createElement("select"); |
| 499 | [""].concat((cell.getAttribute("data-options") || "").split("\n").filter(Boolean)).forEach(function (o) { |
| 500 | var opt = document.createElement("option"); |
| 501 | opt.value = o; opt.textContent = o || "—"; |
| 502 | if (o === (cell.getAttribute("data-was") || "")) opt.selected = true; |
| 503 | input.appendChild(opt); |
| 504 | }); |
| 505 | } else { |
| 506 | input = document.createElement("input"); |
| 507 | input.type = kind === "date" ? "date" : kind === "email" ? "email" : kind === "phone" ? "tel" : "text"; |
| 508 | input.inputMode = { number: "decimal", email: "email", phone: "tel", url: "url" }[kind] || "text"; |
| 509 | input.value = kind === "date" ? (cell.getAttribute("data-was") || "") : (typed || cell.getAttribute("data-seed") || ""); |
| 510 | } |
| 511 | input.id = "fichas-sheet-input"; |
| 512 | var error = document.createElement("p"); |
| 513 | error.setAttribute("fichas-sheet-error", ""); |
| 514 | error.setAttribute("role", "alert"); |
| 515 | var foot = document.createElement("div"); |
| 516 | foot.setAttribute("fichas-sheet-foot", ""); |
| 517 | var cancel = document.createElement("button"); |
| 518 | cancel.type = "button"; cancel.setAttribute("rst-btn", ""); cancel.textContent = "Cancel"; |
| 519 | cancel.addEventListener("click", function () { dialog.close(); }); |
| 520 | var save = document.createElement("button"); |
| 521 | save.type = "submit"; save.setAttribute("rst-btn", "primary"); save.textContent = "Save"; |
| 522 | foot.appendChild(cancel); foot.appendChild(save); |
| 523 | form.appendChild(label); form.appendChild(input); form.appendChild(error); form.appendChild(foot); |
| 524 | dialog.appendChild(form); |
| 525 | document.body.appendChild(dialog); |
| 526 | dialog.addEventListener("close", function () { dialog.remove(); cell.focus(); }); |
| 527 | form.addEventListener("submit", function (e) { |
| 528 | e.preventDefault(); |
| 529 | var card = cell.parentElement.getAttribute("data-card"); |
| 530 | var key = cell.getAttribute("data-field"); |
| 531 | var table = cell.closest("table"); |
| 532 | saveField(card, key, input.value, cell.getAttribute("data-was") || "", { list: (table && table.getAttribute("data-list")) || "" }).then(function (r) { |
| 533 | var d = r.data; |
| 534 | if (r.status === 200) { |
| 535 | applyValue(card, key, d); |
| 536 | dialog.close(); |
| 537 | if (d.outOfView) markOutOfView(cell.parentElement); |
| 538 | if (d.event) { |
| 539 | remember(card, d.event, key); |
| 540 | toast(d.message, { label: "Undo", run: function () { undoFromToast(card, d.event); } }); |
| 541 | } |
| 542 | } else if (r.status === 409) { |
| 543 | applyValue(card, key, { value: d.theirs, seed: d.seed, cell: d.cell }); |
| 544 | error.textContent = d.message + " Save again to use yours."; |
| 545 | cell.setAttribute("data-was", d.theirs); |
| 546 | } else { |
| 547 | error.textContent = d.error || "This change couldn't be saved."; |
| 548 | } |
| 549 | }, function () { error.textContent = "Couldn't save. Check your connection and try again."; }); |
| 550 | }); |
| 551 | dialog.showModal(); |
| 552 | input.focus(); |
| 553 | } |
| 554 | |
| 555 | // ---- The card's quiet inputs: each saves when it loses focus. |
| 556 | |
| 557 | function setupCard(form) { |
| 558 | if (form.hasAttribute("data-card-ready")) return; |
| 559 | form.setAttribute("data-card-ready", ""); |
| 560 | document.body.setAttribute("data-fichas-live", ""); |
| 561 | var card = form.getAttribute("data-card"); |
| 562 | form.addEventListener("change", function (e) { |
| 563 | var input = e.target; |
| 564 | if (!input.name || input.type === "hidden" || input.name.indexOf("was.") === 0) return; |
| 565 | var key = input.name; |
| 566 | var wasInput = form.querySelector('input[name="was.' + cssEscape(key) + '"]'); |
| 567 | var was = wasInput ? wasInput.value : ""; |
| 568 | var holder = input.closest("[fichas-quiet-field]") || input.parentElement; |
| 569 | var old = holder.querySelector("[rst-field-error]"); |
| 570 | if (old) old.remove(); |
| 571 | input.removeAttribute("aria-invalid"); |
| 572 | saveField(card, key, input.value, was, {}).then(function (r) { |
| 573 | var d = r.data; |
| 574 | if (r.status === 200) { |
| 575 | if (wasInput) wasInput.value = d.value; |
| 576 | if (document.activeElement !== input) input.value = d.seed; |
| 577 | applyValue(card, key, d); |
| 578 | if (d.event) { |
| 579 | remember(card, d.event, key); |
| 580 | toast(d.message, { label: "Undo", run: function () { undoFromToast(card, d.event); } }); |
| 581 | } |
| 582 | } else { |
| 583 | var msg = r.status === 409 ? d.message : (d.error || "This change couldn't be saved."); |
| 584 | var p = document.createElement("p"); |
| 585 | p.setAttribute("rst-field-error", ""); |
| 586 | p.id = "fichas-err-" + key; |
| 587 | p.textContent = msg; |
| 588 | if (r.status === 409) { |
| 589 | if (wasInput) wasInput.value = d.theirs; |
| 590 | var useMine = document.createElement("button"); |
| 591 | useMine.type = "button"; useMine.setAttribute("rst-btn", "sm"); useMine.textContent = "Use mine"; |
| 592 | useMine.addEventListener("click", function () { p.remove(); input.dispatchEvent(new Event("change", { bubbles: true })); }); |
| 593 | var keep = document.createElement("button"); |
| 594 | keep.type = "button"; keep.setAttribute("rst-btn", "sm"); keep.textContent = "Keep theirs"; |
| 595 | keep.addEventListener("click", function () { p.remove(); input.value = d.seed; }); |
| 596 | p.appendChild(document.createTextNode(" ")); |
| 597 | p.appendChild(keep); p.appendChild(useMine); |
| 598 | } |
| 599 | holder.appendChild(p); |
| 600 | input.setAttribute("aria-invalid", "true"); |
| 601 | input.setAttribute("aria-describedby", p.id); |
| 602 | announce(msg); |
| 603 | } |
| 604 | }, function () { announce("Couldn't save."); }); |
| 605 | }); |
| 606 | } |
| 607 | |
| 608 | // ---- Keys that are not the grid's. |
| 609 | |
| 610 | function inField(el) { |
| 611 | return el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)); |
| 612 | } |
| 613 | |
| 614 | document.addEventListener("keydown", function (e) { |
| 615 | var mod = e.metaKey || e.ctrlKey; |
| 616 | var t = e.target; |
| 617 | if (mod && (e.key === "z" || e.key === "Z")) { |
| 618 | // Inside a text input ⌘Z is the browser's own until it is saved. |
| 619 | if (inField(t)) return; |
| 620 | e.preventDefault(); |
| 621 | if (e.shiftKey) redoLast(); else undoLast(); |
| 622 | return; |
| 623 | } |
| 624 | if (mod && (e.key === "k" || e.key === "K")) { |
| 625 | var q = document.querySelector('[data-live-search] input[name="q"]'); |
| 626 | if (q) { e.preventDefault(); q.focus(); q.select(); return; } |
| 627 | // No Find box here (a card, History): go where the rail's Search |
| 628 | // goes, the list's Find box (the link is there below 800px too, |
| 629 | // where the rail is not drawn). Never from inside a field, where |
| 630 | // it would leave typing unsaved. |
| 631 | var search = document.querySelector("a[data-fichas-search]"); |
| 632 | if (search && !inField(t) && search.pathname !== location.pathname) { e.preventDefault(); location.assign(search.href); } |
| 633 | return; |
| 634 | } |
| 635 | if (mod && e.key === "\\") { |
| 636 | var fold = document.querySelector("[fichas-rail-foot]"); |
| 637 | if (fold) { |
| 638 | e.preventDefault(); |
| 639 | var visible = Array.prototype.find.call(fold.querySelectorAll("button"), function (b) { return b.offsetParent !== null; }); |
| 640 | if (visible) visible.click(); |
| 641 | } |
| 642 | return; |
| 643 | } |
| 644 | if (mod || e.altKey || inField(t)) return; |
| 645 | // J and K act only in the card pane or the narrowed list (§5.4). |
| 646 | var scope = t.closest && t.closest("[fichas-pane], [fichas-narrow]"); |
| 647 | if (!scope) return; |
| 648 | if (e.key === "j" || e.key === "J" || e.key === "k" || e.key === "K") { |
| 649 | var rel = (e.key === "j" || e.key === "J") ? "next" : "prev"; |
| 650 | var link = document.querySelector('[fichas-pane] a[rel="' + rel + '"]'); |
| 651 | if (link) { e.preventDefault(); keepFocus(scope); window.location.href = link.href; } |
| 652 | } else if (e.key === "Escape") { |
| 653 | var close = document.querySelector("[data-fichas-close]"); |
| 654 | if (close) { e.preventDefault(); window.location.href = close.href; } |
| 655 | } |
| 656 | }); |
| 657 | |
| 658 | // After J or K the new page puts focus back where it was: in the pane |
| 659 | // or the list, so the keys go on working. |
| 660 | function keepFocus(scope) { |
| 661 | try { sessionStorage.setItem("fichas-focus", scope.hasAttribute("fichas-narrow") ? "narrow" : "pane"); } catch (err) { /* private mode */ } |
| 662 | keepScroll(); |
| 663 | } |
| 664 | |
| 665 | // The narrowed list keeps its scroll from card to card (§5.4): each |
| 666 | // step is a page load, so the position rides in this tab's storage. |
| 667 | function keepScroll() { |
| 668 | try { sessionStorage.setItem("fichas-scroll", String(window.scrollY)); } catch (err) { /* private mode */ } |
| 669 | } |
| 670 | |
| 671 | function restoreScroll() { |
| 672 | var y = null; |
| 673 | try { y = sessionStorage.getItem("fichas-scroll"); sessionStorage.removeItem("fichas-scroll"); } catch (err) { return; } |
| 674 | if (y === null || !document.querySelector("[fichas-narrow]")) return; |
| 675 | window.scrollTo(0, parseInt(y, 10) || 0); |
| 676 | var current = document.querySelector("[fichas-narrow] a[aria-current]"); |
| 677 | if (current && current.scrollIntoView) current.scrollIntoView({ block: "nearest" }); |
| 678 | } |
| 679 | |
| 680 | function restoreFocus() { |
| 681 | var where = null; |
| 682 | try { where = sessionStorage.getItem("fichas-focus"); sessionStorage.removeItem("fichas-focus"); } catch (err) { return; } |
| 683 | if (where === "narrow") { |
| 684 | var current = document.querySelector('[fichas-narrow] a[aria-current]'); |
| 685 | if (current) current.focus(); |
| 686 | } else if (where === "pane") { |
| 687 | var pane = document.querySelector("[fichas-pane]"); |
| 688 | if (pane) { pane.setAttribute("tabindex", "-1"); pane.focus(); } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | // ---- The menus' commands, bound now that there is a script. |
| 693 | |
| 694 | function bindCommands() { |
| 695 | document.querySelectorAll("[data-fichas-command]").forEach(function (b) { |
| 696 | b.disabled = false; |
| 697 | b.addEventListener("click", function () { |
| 698 | var menu = b.closest("details"); |
| 699 | if (menu) menu.open = false; |
| 700 | if (b.getAttribute("data-fichas-command") === "undo") undoLast(); else redoLast(); |
| 701 | }); |
| 702 | }); |
| 703 | document.querySelectorAll('a[href$="#find"]').forEach(function (a) { |
| 704 | a.addEventListener("click", function (e) { |
| 705 | var q = document.querySelector('[data-live-search] input[name="q"]'); |
| 706 | if (q && a.pathname === location.pathname) { e.preventDefault(); q.focus(); } |
| 707 | }); |
| 708 | }); |
| 709 | } |
| 710 | |
| 711 | function init() { |
| 712 | document.querySelectorAll("table[fichas-grid]").forEach(setupGrid); |
| 713 | document.querySelectorAll("form[fichas-card-form]").forEach(setupCard); |
| 714 | bindCommands(); |
| 715 | restoreScroll(); |
| 716 | restoreFocus(); |
| 717 | document.addEventListener("click", function (e) { |
| 718 | if (e.target.closest && e.target.closest("[fichas-narrow] a, [fichas-pane] a[rel]")) keepScroll(); |
| 719 | }); |
| 720 | // search.js swaps the results in place as a person types: a new |
| 721 | // table is set up as it arrives. |
| 722 | var results = document.getElementById("results"); |
| 723 | if (results && window.MutationObserver) { |
| 724 | new MutationObserver(function () { results.querySelectorAll("table[fichas-grid]").forEach(setupGrid); }) |
| 725 | .observe(results, { childList: true, subtree: true }); |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); |
| 730 | else init(); |
| 731 | })(); |
| 732 | |