oficina / fichas Public

grid.js: click to edit, Rejilla's keys, the toast with Undo, ⌘Z and ⇧⌘Z, J and K, the card's quiet inputs, and the phone's sheet (level-up §5)

Progressive enhancement over the scriptless floor: the table becomes an
ARIA grid with one tab stop; a cell edits in place and saves at once,
carrying was and the page's locale; a refusal stays in the editor, a
conflict offers Keep theirs and Use mine; an edit that takes a card out
of the view marks its row in words; J and K act only in the pane and the
narrowed list. Browser tests follow the new frame.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev be90f2e13ffd67ad76d8108db355a001732ed866 parent 6eabb6f
4 files changed, +724 −78
  • internal/fichas/frame.go +1 −1
  • internal/fichas/static/grid.js +679 −1
  • internal/fichas/templates/index.html +1 −1
  • internal/fichastest/browser_test.go +43 −75
diff --git a/internal/fichas/frame.go b/internal/fichas/frame.go
index 4471055..936b9db 100644
--- a/internal/fichas/frame.go
+++ b/internal/fichas/frame.go
@@ -205,7 +205,7 @@ func orText(s, def string) string {
func barActions(f frameFacts) []chrome.Action {
search := "/"
if f.TypeKey != "" {
- search = typeHref(f.TypeKey) + "#q"
+ search = typeHref(f.TypeKey) + "#find"
}
actions := []chrome.Action{{Item: menu.Item{Href: search, Label: "Search", Key: "⌘K"}, Icon: icons.Icon("search")}}
if f.CardID != 0 {
diff --git a/internal/fichas/static/grid.js b/internal/fichas/static/grid.js
index d79ae12..6a7028d 100644
--- a/internal/fichas/static/grid.js
+++ b/internal/fichas/static/grid.js
@@ -1 +1,679 @@
-(function () { "use strict"; })();
+/* grid.js — editing in place (level-up spec §5), as progressive
+ * enhancement. Every screen works without it: a cell is a link to the edit
+ * form, the card is a form with one Save button, Undo is a one-button
+ * form, J and K are Next and Previous links.
+ *
+ * With it:
+ * - the table is an ARIA grid with one tab stop and Rejilla's keys (§5.6);
+ * - a cell edits in place and saves at once, one field per POST, carrying
+ * what the editor saw (was) and the page's locale (§5.2, §6.8);
+ * - each save gets a toast with Undo, and ⌘Z / ⇧⌘Z undo and redo this
+ * tab's own changes, newest first (§5.3);
+ * - the card's quiet inputs save when they lose focus;
+ * - J and K walk the list, only while focus is in the card pane or the
+ * narrowed list and not in an input (§5.4, WCAG 2.1.4);
+ * - on a phone a value opens a sheet with its editor and Save (§5.8).
+ *
+ * The server says what a value means: numbers are read in the locale the
+ * page was drawn in, which every post carries, and the server answers
+ * with the cell as it draws it.
+ */
+(function () {
+ "use strict";
+
+ var TOAST_MS = 10000;
+ var undoStack = []; // this tab's own changes: {card, event, label}
+ var redoStack = []; // this tab's Undo events, for ⇧⌘Z
+ var phone = window.matchMedia("(max-width: 799.98px)");
+
+ function locale() { return document.body.getAttribute("data-locale") || ""; }
+
+ // ---- The save state in the bar's lead, and the live region.
+
+ function saveState(state) {
+ var el = document.querySelector("[estilo-save-status]");
+ if (!el) return;
+ el.setAttribute("data-state", state);
+ el.textContent = state === "idle" ? "" : (el.getAttribute("data-text-" + state) || "");
+ }
+
+ function announce(text) {
+ var live = document.querySelector("[fichas-live]");
+ if (!live) return;
+ live.textContent = "";
+ window.setTimeout(function () { live.textContent = text; }, 30);
+ }
+
+ // ---- The toast: what happened, and Undo for 10 seconds.
+
+ function toast(text, action) {
+ var host = document.querySelector("[fichas-toasts]");
+ if (!host) return;
+ host.querySelectorAll("[fichas-toast]").forEach(function (t) { t.remove(); });
+ var t = document.createElement("div");
+ t.setAttribute("fichas-toast", "");
+ var span = document.createElement("span");
+ span.textContent = text;
+ t.appendChild(span);
+ if (action) {
+ var b = document.createElement("button");
+ b.type = "button";
+ b.textContent = action.label;
+ b.addEventListener("click", function () { t.remove(); action.run(); });
+ t.appendChild(b);
+ }
+ host.appendChild(t);
+ announce(text + (action ? " " + action.label + " is available." : ""));
+ window.setTimeout(function () { t.remove(); }, TOAST_MS);
+ }
+
+ // ---- Talking to the server: a form-encoded POST, JSON back.
+
+ function post(url, fields) {
+ var body = new URLSearchParams();
+ Object.keys(fields).forEach(function (k) { body.append(k, fields[k]); });
+ return fetch(url, {
+ method: "POST",
+ credentials: "same-origin",
+ headers: { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded" },
+ body: body
+ }).then(function (res) {
+ var type = res.headers.get("Content-Type") || "";
+ if (type.indexOf("application/json") < 0) {
+ // Not ours to read (a sign-in door after the session ended, say):
+ // go and see what the server has to say.
+ if (res.redirected) { window.location.href = res.url; }
+ throw new Error("not json");
+ }
+ return res.json().then(function (data) { return { status: res.status, data: data }; });
+ });
+ }
+
+ // saveField writes one field. was is what the editor saw; the reply
+ // says what the field holds now.
+ function saveField(card, key, value, was, extra) {
+ var fields = { "return_to": location.pathname + location.search };
+ fields[key] = value;
+ fields["was." + key] = was;
+ fields[key + ".locale"] = locale();
+ if (extra) Object.keys(extra).forEach(function (k) { fields[k] = extra[k]; });
+ saveState("saving");
+ return post("/cards/" + card + "/fields/" + encodeURIComponent(key), fields).then(function (r) {
+ saveState(r.status === 200 ? "saved" : "idle");
+ return r;
+ }, function (err) {
+ saveState("failed");
+ throw err;
+ });
+ }
+
+ function remember(card, event, label) {
+ if (!event) return;
+ undoStack.push({ card: card, event: event, label: label });
+ redoStack = [];
+ }
+
+ function undo(entry, redo) {
+ saveState("saving");
+ return post("/cards/" + entry.card + "/undo", { event: entry.event }).then(function (r) {
+ if (r.status !== 200) { saveState("idle"); toast("That can no longer be undone."); return; }
+ saveState("saved");
+ var d = r.data;
+ Object.keys(d.cells || {}).forEach(function (key) { applyValue(entry.card, key, d.cells[key]); });
+ if (d.event) {
+ if (redo) { undoStack.push({ card: entry.card, event: d.event }); }
+ else { redoStack.push({ card: entry.card, event: d.event }); }
+ }
+ toast(d.message);
+ }, function () { toast("Couldn't reach Fichas, so nothing was undone."); });
+ }
+
+ function undoLast() {
+ var e = undoStack.pop();
+ if (e) { undo(e, false); } else { toast("Nothing to undo in this tab."); }
+ }
+
+ function redoLast() {
+ var e = redoStack.pop();
+ if (e) { undo(e, true); } else { toast("Nothing to redo."); }
+ }
+
+ // applyValue draws a field's new value wherever this page shows it: its
+ // table cell, and the card's quiet input.
+ function applyValue(card, key, v) {
+ document.querySelectorAll('tr[data-card="' + card + '"] td[data-field="' + key + '"]').forEach(function (td) {
+ td.setAttribute("data-was", v.value);
+ td.setAttribute("data-seed", v.seed);
+ var link = td.querySelector("[fichas-cell-link]");
+ if (link) {
+ var sr = link.querySelector(".rst-sr-only");
+ link.innerHTML = v.cell;
+ if (sr) link.appendChild(sr);
+ }
+ });
+ document.querySelectorAll('[fichas-card-form][data-card="' + card + '"]').forEach(function (form) {
+ var wasInput = form.querySelector('input[name="was.' + cssEscape(key) + '"]');
+ if (wasInput) wasInput.value = v.value;
+ var input = form.querySelector('[name="' + cssEscape(key) + '"]:not([type="hidden"])');
+ if (input && document.activeElement !== input) input.value = v.seed;
+ });
+ }
+
+ function cssEscape(s) { return window.CSS && CSS.escape ? CSS.escape(s) : s.replace(/"/g, '\\"'); }
+
+ // ---- The grid (§5.6).
+
+ function cellsOf(row) { return Array.prototype.filter.call(row.children, function (c) { return c.tagName === "TD" || c.tagName === "TH"; }); }
+
+ function setupGrid(table) {
+ if (table.hasAttribute("data-grid-ready")) return;
+ table.setAttribute("data-grid-ready", "");
+ table.setAttribute("role", "grid");
+ var first = null;
+ table.querySelectorAll("tr").forEach(function (tr) {
+ cellsOf(tr).forEach(function (cell) {
+ cell.setAttribute("tabindex", "-1");
+ if (tr.parentElement.tagName === "TBODY" && !first) first = cell;
+ cell.querySelectorAll("a").forEach(function (a) { a.setAttribute("tabindex", "-1"); });
+ });
+ });
+ if (first) first.setAttribute("tabindex", "0");
+ table.addEventListener("keydown", function (e) { gridKey(table, e); });
+ table.addEventListener("click", function (e) { gridClick(table, e); });
+ table.addEventListener("focusin", function (e) {
+ var cell = e.target.closest("td, th");
+ if (cell && table.contains(cell) && !cell.querySelector("[fichas-editor]")) activate(table, cell, false);
+ });
+ }
+
+ function activate(table, cell, focus) {
+ table.querySelectorAll('[tabindex="0"]').forEach(function (c) { if (c !== cell && (c.tagName === "TD" || c.tagName === "TH")) c.setAttribute("tabindex", "-1"); });
+ cell.setAttribute("tabindex", "0");
+ if (focus) cell.focus();
+ }
+
+ function position(table, cell) {
+ var rows = Array.prototype.slice.call(table.querySelectorAll("tr"));
+ var r = rows.indexOf(cell.parentElement);
+ return { rows: rows, r: r, c: cellsOf(cell.parentElement).indexOf(cell) };
+ }
+
+ function move(table, cell, dr, dc, abs) {
+ var p = position(table, cell);
+ var r = abs && abs.row !== undefined ? abs.row : p.r + dr;
+ r = Math.max(1, Math.min(p.rows.length - 1, r)); // row 0 is the header
+ var row = cellsOf(p.rows[r]);
+ var c = abs && abs.col !== undefined ? abs.col : p.c + dc;
+ c = Math.max(0, Math.min(row.length - 1, c));
+ activate(table, row[c], true);
+ return row[c];
+ }
+
+ function editable(cell) { return cell && cell.tagName === "TD" && cell.hasAttribute("data-field"); }
+
+ function gridKey(table, e) {
+ var cell = e.target.closest("td, th");
+ if (!cell || e.target !== cell) return; // an editor handles its own keys
+ var mod = e.metaKey || e.ctrlKey;
+ var p = position(table, cell);
+ switch (e.key) {
+ case "ArrowUp": e.preventDefault(); if (mod) move(table, cell, 0, 0, { row: 1 }); else move(table, cell, -1, 0); return;
+ case "ArrowDown": e.preventDefault(); if (mod) move(table, cell, 0, 0, { row: p.rows.length - 1 }); else move(table, cell, 1, 0); return;
+ case "ArrowLeft": e.preventDefault(); move(table, cell, 0, -1); return;
+ case "ArrowRight": e.preventDefault(); move(table, cell, 0, 1); return;
+ case "Home": e.preventDefault(); move(table, cell, 0, 0, { col: 0 }); return;
+ case "End": e.preventDefault(); move(table, cell, 0, 0, { col: 99 }); return;
+ case "Escape": e.preventDefault(); var q = document.querySelector('[data-live-search] input[name="q"]'); if (q) q.focus(); return;
+ case "Enter":
+ e.preventDefault();
+ if (editable(cell)) { openEditor(table, cell, null); return; }
+ var link = cell.querySelector("a[href]");
+ if (link) link.click(); // the name opens the card; a header sorts
+ return;
+ case " ":
+ if (editable(cell)) { e.preventDefault(); openEditor(table, cell, null); }
+ return;
+ case "Delete":
+ case "Backspace":
+ if (editable(cell)) { e.preventDefault(); commit(table, cell, "", { stay: true }); }
+ return;
+ }
+ if (mod && (e.key === "c" || e.key === "C") && !e.shiftKey) {
+ if (navigator.clipboard) { e.preventDefault(); navigator.clipboard.writeText(cellText(cell)); }
+ return;
+ }
+ if (mod && (e.key === "v" || e.key === "V") && editable(cell) && navigator.clipboard && navigator.clipboard.readText) {
+ e.preventDefault();
+ navigator.clipboard.readText().then(function (text) { commit(table, cell, text.trim(), { stay: true, typed: true }); });
+ return;
+ }
+ // A printable key starts an edit, replacing the value with what is
+ // typed. It never opens anything else (§5.4: typing "Oslo" edits).
+ if (!mod && !e.altKey && e.key.length === 1 && editable(cell)) {
+ e.preventDefault();
+ openEditor(table, cell, e.key);
+ }
+ }
+
+ function cellText(cell) {
+ var clone = cell.cloneNode(true);
+ clone.querySelectorAll(".rst-sr-only").forEach(function (n) { n.remove(); });
+ return clone.textContent.replace(/\s+/g, " ").trim();
+ }
+
+ function gridClick(table, e) {
+ var cell = e.target.closest("td, th");
+ if (!cell || !table.contains(cell) || e.target.closest("[fichas-editor], [fichas-picker], [fichas-editor-error]")) return;
+ if (!editable(cell)) return; // the name, a header, Last call: their links work as links
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return; // a new tab still opens the edit form
+ e.preventDefault();
+ activate(table, cell, false);
+ if (phone.matches) { openSheet(cell); return; }
+ openEditor(table, cell, null);
+ }
+
+ // ---- A cell's editor.
+
+ function openEditor(table, cell, typed) {
+ if (phone.matches) { openSheet(cell, typed); return; }
+ closeEditors();
+ var kind = cell.getAttribute("data-kind");
+ var box = document.createElement("div");
+ box.setAttribute("fichas-editor", "");
+ var input;
+ if (kind === "enum") {
+ cell.appendChild(box);
+ openPicker(table, cell, box, typed);
+ return;
+ }
+ input = document.createElement("input");
+ input.setAttribute("aria-label", cell.getAttribute("data-label") || "Value");
+ if (kind === "date") { input.type = "date"; input.value = cell.getAttribute("data-was") || ""; }
+ else {
+ input.type = kind === "email" ? "email" : kind === "phone" ? "tel" : "text";
+ input.inputMode = { number: "decimal", email: "email", phone: "tel", url: "url" }[kind] || "text";
+ input.autocomplete = "off";
+ input.spellcheck = kind === "text";
+ input.value = typed !== null ? typed : (cell.getAttribute("data-seed") || "");
+ }
+ box.appendChild(input);
+ cell.appendChild(box);
+ input.focus();
+ if (typed === null && input.select) input.select();
+ input.addEventListener("keydown", function (e) {
+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeEditor(cell, true); }
+ else if (e.key === "Enter") { e.preventDefault(); commit(table, cell, input.value, { next: [e.shiftKey ? -1 : 1, 0] }); }
+ else if (e.key === "Tab") { e.preventDefault(); commit(table, cell, input.value, { next: [0, e.shiftKey ? -1 : 1] }); }
+ });
+ input.addEventListener("blur", function () {
+ window.setTimeout(function () {
+ if (box.isConnected && !box.contains(document.activeElement) && !cell.querySelector("[fichas-editor-error]")) commit(table, cell, input.value, { quiet: true });
+ }, 0);
+ });
+ }
+
+ function closeEditors() { document.querySelectorAll("[fichas-editor], [fichas-picker], [fichas-editor-error]").forEach(function (n) { n.remove(); }); }
+
+ function closeEditor(cell, refocus) {
+ cell.querySelectorAll("[fichas-editor], [fichas-picker], [fichas-editor-error]").forEach(function (n) { n.remove(); });
+ if (refocus) cell.focus();
+ }
+
+ // A choice opens a listbox with a search box (§6.5).
+ function openPicker(table, cell, box, typed) {
+ var options = (cell.getAttribute("data-options") || "").split("\n").filter(Boolean);
+ var current = cell.getAttribute("data-was") || "";
+ var pick = document.createElement("div");
+ pick.setAttribute("fichas-picker", "");
+ var search = document.createElement("input");
+ search.type = "text";
+ search.setAttribute("role", "combobox");
+ search.setAttribute("aria-label", "Find " + (cell.getAttribute("data-label") || "an option"));
+ search.setAttribute("aria-expanded", "true");
+ var list = document.createElement("ul");
+ list.setAttribute("role", "listbox");
+ list.id = "fichas-picker-list";
+ search.setAttribute("aria-controls", list.id);
+ pick.appendChild(search);
+ pick.appendChild(list);
+ box.appendChild(pick);
+ var active = 0;
+ function draw() {
+ var q = search.value.toLowerCase();
+ list.innerHTML = "";
+ var shown = [""].concat(options).filter(function (o) { return o === "" ? q === "" : o.toLowerCase().indexOf(q) >= 0; });
+ active = Math.min(active, shown.length - 1);
+ shown.forEach(function (o, i) {
+ var li = document.createElement("li");
+ li.setAttribute("role", "option");
+ li.id = "fichas-opt-" + i;
+ li.textContent = o === "" ? "No " + (cell.getAttribute("data-label") || "value").toLowerCase() : o;
+ li.setAttribute("aria-selected", i === active ? "true" : "false");
+ if (o === current) li.setAttribute("data-current", "");
+ li.addEventListener("mousedown", function (e) { e.preventDefault(); commit(table, cell, o, {}); });
+ list.appendChild(li);
+ });
+ search.setAttribute("aria-activedescendant", shown.length ? "fichas-opt-" + active : "");
+ return shown;
+ }
+ if (typed) search.value = typed;
+ var shown = draw();
+ search.focus();
+ search.addEventListener("input", function () { active = 0; shown = draw(); });
+ search.addEventListener("keydown", function (e) {
+ if (e.key === "ArrowDown") { e.preventDefault(); active = Math.min(shown.length - 1, active + 1); shown = draw(); }
+ else if (e.key === "ArrowUp") { e.preventDefault(); active = Math.max(0, active - 1); shown = draw(); }
+ else if (e.key === "Enter" || e.key === "Tab") {
+ e.preventDefault();
+ if (shown.length) commit(table, cell, shown[active], { next: e.key === "Tab" ? [0, e.shiftKey ? -1 : 1] : [1, 0] });
+ } else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeEditor(cell, true); }
+ });
+ search.addEventListener("blur", function () {
+ window.setTimeout(function () { if (box.isConnected && !box.contains(document.activeElement)) closeEditor(cell, false); }, 0);
+ });
+ }
+
+ // commit saves a cell's value. Nothing typed that differs from the seed
+ // is not a change, and is not sent.
+ function commit(table, cell, value, how) {
+ var card = cell.parentElement.getAttribute("data-card");
+ var key = cell.getAttribute("data-field");
+ var was = cell.getAttribute("data-was") || "";
+ var seed = cell.getAttribute("data-seed") || "";
+ var unchanged = cell.getAttribute("data-kind") === "date" ? value === was : value === seed;
+ if (unchanged && !how.typed) { closeEditor(cell, !how.quiet); if (how.next) move(table, cell, how.next[0], how.next[1]); return; }
+ closeEditor(cell, false);
+ var label = cell.getAttribute("data-label") || "";
+ saveField(card, key, value, was, { list: table.getAttribute("data-list") || "" }).then(function (r) {
+ var d = r.data;
+ if (r.status === 200) {
+ applyValue(card, key, d);
+ if (d.event) {
+ remember(card, d.event, label);
+ toast(d.message, { label: "Undo", run: function () { var i = undoStack.map(function (u) { return u.event; }).indexOf(d.event); if (i >= 0) undoStack.splice(i, 1); undo({ card: card, event: d.event }, false); } });
+ }
+ if (d.outOfView) markOutOfView(cell.parentElement);
+ if (!how.quiet) {
+ if (how.next) move(table, cell, how.next[0], how.next[1]); else cell.focus();
+ }
+ } else if (r.status === 409) {
+ conflictBubble(table, cell, value, d);
+ } else if (r.status === 422) {
+ reopenWithError(table, cell, value, d.error);
+ } else {
+ toast("That can't be changed any more.");
+ }
+ }, function () {
+ reopenWithError(table, cell, value, "Couldn't save. Check your connection, then press Enter to try again.");
+ });
+ }
+
+ // A refused value stays in the editor with the message beside it.
+ function reopenWithError(table, cell, value, message) {
+ openEditor(table, cell, cell.getAttribute("data-kind") === "enum" ? null : value);
+ var input = cell.querySelector("[fichas-editor] input");
+ var err = document.createElement("p");
+ err.setAttribute("fichas-editor-error", "");
+ err.setAttribute("role", "alert");
+ err.id = "fichas-editor-error";
+ err.textContent = message;
+ cell.appendChild(err);
+ if (input) { input.setAttribute("aria-invalid", "true"); input.setAttribute("aria-describedby", err.id); }
+ }
+
+ // Someone changed it first: say who and to what, with Keep theirs and
+ // Use mine (§5.2). Use mine is a second POST with theirs as was.
+ function conflictBubble(table, cell, mine, d) {
+ var card = cell.parentElement.getAttribute("data-card");
+ var key = cell.getAttribute("data-field");
+ applyValue(card, key, { value: d.theirs, seed: d.seed, cell: d.cell });
+ var err = document.createElement("div");
+ err.setAttribute("fichas-editor-error", "");
+ err.setAttribute("role", "alert");
+ err.textContent = d.message;
+ var keep = document.createElement("button");
+ keep.type = "button"; keep.setAttribute("rst-btn", "sm"); keep.textContent = "Keep theirs";
+ keep.addEventListener("click", function () { err.remove(); cell.focus(); });
+ var use = document.createElement("button");
+ use.type = "button"; use.setAttribute("rst-btn", "sm"); use.textContent = "Use mine";
+ use.addEventListener("click", function () { err.remove(); commit(table, cell, mine, { typed: true }); });
+ err.appendChild(keep);
+ err.appendChild(use);
+ cell.appendChild(err);
+ keep.focus();
+ }
+
+ // An edit that takes a card out of the view does not move or hide its
+ // row: it says so, in words and with an icon (§5.1).
+ function markOutOfView(tr) {
+ if (tr.hasAttribute("data-out-of-view")) return;
+ tr.setAttribute("data-out-of-view", "");
+ var name = tr.querySelector("[fichas-title-cell]");
+ if (name) {
+ var tag = document.createElement("span");
+ tag.setAttribute("fichas-out-of-view", "");
+ 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';
+ name.appendChild(tag);
+ }
+ announce("No longer in this view.");
+ }
+
+ // ---- The phone's sheet (§5.8): the field's editor, Save at its foot.
+
+ function openSheet(cell, typed) {
+ var kind = cell.getAttribute("data-kind");
+ var dialog = document.createElement("dialog");
+ dialog.setAttribute("fichas-sheet", "");
+ dialog.setAttribute("aria-label", cell.getAttribute("data-label") || "Change");
+ var form = document.createElement("form");
+ var label = document.createElement("label");
+ label.textContent = cell.getAttribute("data-label") || "Value";
+ label.htmlFor = "fichas-sheet-input";
+ var input;
+ if (kind === "enum") {
+ input = document.createElement("select");
+ [""].concat((cell.getAttribute("data-options") || "").split("\n").filter(Boolean)).forEach(function (o) {
+ var opt = document.createElement("option");
+ opt.value = o; opt.textContent = o || "—";
+ if (o === (cell.getAttribute("data-was") || "")) opt.selected = true;
+ input.appendChild(opt);
+ });
+ } else {
+ input = document.createElement("input");
+ input.type = kind === "date" ? "date" : kind === "email" ? "email" : kind === "phone" ? "tel" : "text";
+ input.inputMode = { number: "decimal", email: "email", phone: "tel", url: "url" }[kind] || "text";
+ input.value = kind === "date" ? (cell.getAttribute("data-was") || "") : (typed || cell.getAttribute("data-seed") || "");
+ }
+ input.id = "fichas-sheet-input";
+ var error = document.createElement("p");
+ error.setAttribute("fichas-sheet-error", "");
+ error.setAttribute("role", "alert");
+ var foot = document.createElement("div");
+ foot.setAttribute("fichas-sheet-foot", "");
+ var cancel = document.createElement("button");
+ cancel.type = "button"; cancel.setAttribute("rst-btn", ""); cancel.textContent = "Cancel";
+ cancel.addEventListener("click", function () { dialog.close(); });
+ var save = document.createElement("button");
+ save.type = "submit"; save.setAttribute("rst-btn", "primary"); save.textContent = "Save";
+ foot.appendChild(cancel); foot.appendChild(save);
+ form.appendChild(label); form.appendChild(input); form.appendChild(error); form.appendChild(foot);
+ dialog.appendChild(form);
+ document.body.appendChild(dialog);
+ dialog.addEventListener("close", function () { dialog.remove(); cell.focus(); });
+ form.addEventListener("submit", function (e) {
+ e.preventDefault();
+ var card = cell.parentElement.getAttribute("data-card");
+ var key = cell.getAttribute("data-field");
+ saveField(card, key, input.value, cell.getAttribute("data-was") || "", {}).then(function (r) {
+ var d = r.data;
+ if (r.status === 200) {
+ applyValue(card, key, d);
+ dialog.close();
+ if (d.event) {
+ remember(card, d.event, key);
+ toast(d.message, { label: "Undo", run: function () { undo({ card: card, event: d.event }, false); } });
+ }
+ } else if (r.status === 409) {
+ applyValue(card, key, { value: d.theirs, seed: d.seed, cell: d.cell });
+ error.textContent = d.message + " Save again to use yours.";
+ cell.setAttribute("data-was", d.theirs);
+ } else {
+ error.textContent = d.error || "That can't be changed any more.";
+ }
+ }, function () { error.textContent = "Couldn't save. Check your connection and try again."; });
+ });
+ dialog.showModal();
+ input.focus();
+ }
+
+ // ---- The card's quiet inputs: each saves when it loses focus.
+
+ function setupCard(form) {
+ if (form.hasAttribute("data-card-ready")) return;
+ form.setAttribute("data-card-ready", "");
+ document.body.setAttribute("data-fichas-live", "");
+ var card = form.getAttribute("data-card");
+ form.addEventListener("change", function (e) {
+ var input = e.target;
+ if (!input.name || input.type === "hidden" || input.name.indexOf("was.") === 0) return;
+ var key = input.name;
+ var wasInput = form.querySelector('input[name="was.' + cssEscape(key) + '"]');
+ var was = wasInput ? wasInput.value : "";
+ var holder = input.closest("[fichas-quiet-field]") || input.parentElement;
+ var old = holder.querySelector("[rst-field-error]");
+ if (old) old.remove();
+ input.removeAttribute("aria-invalid");
+ saveField(card, key, input.value, was, {}).then(function (r) {
+ var d = r.data;
+ if (r.status === 200) {
+ if (wasInput) wasInput.value = d.value;
+ if (document.activeElement !== input) input.value = d.seed;
+ applyValue(card, key, d);
+ if (d.event) {
+ remember(card, d.event, key);
+ toast(d.message, { label: "Undo", run: function () { undo({ card: card, event: d.event }, false); } });
+ }
+ } else {
+ var msg = r.status === 409 ? d.message : (d.error || "That can't be changed any more.");
+ var p = document.createElement("p");
+ p.setAttribute("rst-field-error", "");
+ p.id = "fichas-err-" + key;
+ p.textContent = msg;
+ if (r.status === 409) {
+ if (wasInput) wasInput.value = d.theirs;
+ var useMine = document.createElement("button");
+ useMine.type = "button"; useMine.setAttribute("rst-btn", "sm"); useMine.textContent = "Use mine";
+ useMine.addEventListener("click", function () { p.remove(); input.dispatchEvent(new Event("change", { bubbles: true })); });
+ var keep = document.createElement("button");
+ keep.type = "button"; keep.setAttribute("rst-btn", "sm"); keep.textContent = "Keep theirs";
+ keep.addEventListener("click", function () { p.remove(); input.value = d.seed; });
+ p.appendChild(document.createTextNode(" "));
+ p.appendChild(keep); p.appendChild(useMine);
+ }
+ holder.appendChild(p);
+ input.setAttribute("aria-invalid", "true");
+ input.setAttribute("aria-describedby", p.id);
+ announce(msg);
+ }
+ }, function () { announce("Couldn't save."); });
+ });
+ }
+
+ // ---- Keys that are not the grid's.
+
+ function inField(el) {
+ return el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
+ }
+
+ document.addEventListener("keydown", function (e) {
+ var mod = e.metaKey || e.ctrlKey;
+ var t = e.target;
+ if (mod && (e.key === "z" || e.key === "Z")) {
+ // Inside a text input ⌘Z is the browser's own until it is saved.
+ if (inField(t)) return;
+ e.preventDefault();
+ if (e.shiftKey) redoLast(); else undoLast();
+ return;
+ }
+ if (mod && (e.key === "k" || e.key === "K")) {
+ var q = document.querySelector('[data-live-search] input[name="q"]');
+ if (q) { e.preventDefault(); q.focus(); q.select(); }
+ return;
+ }
+ if (mod && e.key === "\\") {
+ var fold = document.querySelector("[fichas-rail-foot]");
+ if (fold) {
+ e.preventDefault();
+ var visible = Array.prototype.find.call(fold.querySelectorAll("button"), function (b) { return b.offsetParent !== null; });
+ if (visible) visible.click();
+ }
+ return;
+ }
+ if (mod || e.altKey || inField(t)) return;
+ // J and K act only in the card pane or the narrowed list (§5.4).
+ var scope = t.closest && t.closest("[fichas-pane], [fichas-narrow]");
+ if (!scope) return;
+ if (e.key === "j" || e.key === "J" || e.key === "k" || e.key === "K") {
+ var rel = (e.key === "j" || e.key === "J") ? "next" : "prev";
+ var link = document.querySelector('[fichas-pane] a[rel="' + rel + '"]');
+ if (link) { e.preventDefault(); keepFocus(scope); window.location.href = link.href; }
+ } else if (e.key === "Escape") {
+ var close = document.querySelector("[data-fichas-close]");
+ if (close) { e.preventDefault(); window.location.href = close.href; }
+ }
+ });
+
+ // After J or K the new page puts focus back where it was: in the pane
+ // or the list, so the keys go on working.
+ function keepFocus(scope) {
+ try { sessionStorage.setItem("fichas-focus", scope.hasAttribute("fichas-narrow") ? "narrow" : "pane"); } catch (err) { /* private mode */ }
+ }
+
+ function restoreFocus() {
+ var where = null;
+ try { where = sessionStorage.getItem("fichas-focus"); sessionStorage.removeItem("fichas-focus"); } catch (err) { return; }
+ if (where === "narrow") {
+ var current = document.querySelector('[fichas-narrow] a[aria-current]');
+ if (current) current.focus();
+ } else if (where === "pane") {
+ var pane = document.querySelector("[fichas-pane]");
+ if (pane) { pane.setAttribute("tabindex", "-1"); pane.focus(); }
+ }
+ }
+
+ // ---- The menus' commands, bound now that there is a script.
+
+ function bindCommands() {
+ document.querySelectorAll("[data-fichas-command]").forEach(function (b) {
+ b.disabled = false;
+ b.addEventListener("click", function () {
+ var menu = b.closest("details");
+ if (menu) menu.open = false;
+ if (b.getAttribute("data-fichas-command") === "undo") undoLast(); else redoLast();
+ });
+ });
+ document.querySelectorAll('a[href$="#find"]').forEach(function (a) {
+ a.addEventListener("click", function (e) {
+ var q = document.querySelector('[data-live-search] input[name="q"]');
+ if (q && a.pathname === location.pathname) { e.preventDefault(); q.focus(); }
+ });
+ });
+ }
+
+ function init() {
+ document.querySelectorAll("table[fichas-grid]").forEach(setupGrid);
+ document.querySelectorAll("form[fichas-card-form]").forEach(setupCard);
+ bindCommands();
+ restoreFocus();
+ // search.js swaps the results in place as a person types: a new
+ // table is set up as it arrives.
+ var results = document.getElementById("results");
+ if (results && window.MutationObserver) {
+ new MutationObserver(function () { results.querySelectorAll("table[fichas-grid]").forEach(setupGrid); })
+ .observe(results, { childList: true, subtree: true });
+ }
+ }
+
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
+ else init();
+})();
diff --git a/internal/fichas/templates/index.html b/internal/fichas/templates/index.html
index 97a920b..6c2e518 100644
--- a/internal/fichas/templates/index.html
+++ b/internal/fichas/templates/index.html
@@ -41,7 +41,7 @@
</div>{{end}}
</div>
-<div rst-lbar data-live-search>
+<div rst-lbar data-live-search id="find">
{{template "list-bar-search" (dict "Action" .Base "Query" .Q "Placeholder" (printf "Search %s" (lower .Result.Plural)) "Hidden" .Hidden "ClearHref" .ClearHref)}}
<div id="list-filters" data-live-region>{{range .Filters}}{{template "dropdown" .}}{{end}}</div>
</div>
diff --git a/internal/fichastest/browser_test.go b/internal/fichastest/browser_test.go
index 58d33b6..b1ae05f 100644
--- a/internal/fichastest/browser_test.go
+++ b/internal/fichastest/browser_test.go
@@ -242,82 +242,51 @@ func TestNoZoomOnTap(t *testing.T) {
}
}
-// TestTheAccountMenuOpensUpward: the account at the rail's foot opens
-// upward where the rail is the viewport's height, and inside the narrow
-// Menu disclosure it opens downward; at every width the whole panel is on
-// screen and its Sign out is the thing a tap at its centre reaches. Escape
-// closes it and gives focus back to its trigger; a click outside closes
-// it. The panel floats, so it is rounded; the trigger is in the rail's
-// flow, so it is square.
-func TestTheAccountMenuOpensUpward(t *testing.T) {
+// TestTheAccountMenuInTheBar: the account sits at the bar's end (level-up
+// §3.1), at every width the whole panel is on screen and its Sign out is
+// the thing a tap at its centre reaches; Escape closes it and gives focus
+// back to its trigger, and a click outside closes it.
+func TestTheAccountMenuInTheBar(t *testing.T) {
type facts struct {
Open bool
- PanelTop, PanelBot float64
- PanelLeft, PanelRite float64
- TrigTop, TrigBot float64
- VW float64
- SignOutHit bool
- EdgesHit bool
- PanelRadius string
- TrigRadius string
+ PanelTop, PanelLeft float64
+ PanelRite, VW float64
+ SignOutHit, EdgesHit bool
}
const measure = `(() => {
- const d = document.querySelector('[estilo-account]'), s = d.querySelector('summary'), p = d.querySelector('[estilo-account-panel]')
- const pr = p.getBoundingClientRect(), tr = s.getBoundingClientRect()
+ const d = document.querySelector('[estilo-bar] [estilo-account]'), p = d.querySelector('[estilo-account-panel]')
const out = d.querySelector('form[action="/signout"] button')
out.scrollIntoView({block: 'nearest'})
const or = out.getBoundingClientRect(), hit = document.elementFromPoint(or.left + or.width / 2, or.top + or.height / 2)
- const pr2 = p.getBoundingClientRect(), tr2 = s.getBoundingClientRect()
- // Not clipped: a point just inside each side edge is the panel's own,
- // not whatever is beside it (the rail scrolls, so it clips).
- const mid = (pr2.top + pr2.bottom) / 2, inP = (x) => { const h = document.elementFromPoint(x, mid); return !!h && p.contains(h) }
- return {Open: d.open, PanelTop: pr2.top, PanelBot: pr2.bottom, PanelLeft: pr2.left, PanelRite: pr2.right,
- TrigTop: tr2.top, TrigBot: tr2.bottom, VW: document.documentElement.clientWidth,
- SignOutHit: !!hit && out.contains(hit), EdgesHit: inP(pr2.left + 2) && inP(pr2.right - 2), PanelRadius: getComputedStyle(p).borderRadius, TrigRadius: getComputedStyle(s).borderRadius}
+ const pr = p.getBoundingClientRect(), mid = (pr.top + pr.bottom) / 2
+ const inP = (x) => { const h = document.elementFromPoint(x, mid); return !!h && p.contains(h) }
+ return {Open: d.open, PanelTop: pr.top, PanelLeft: pr.left, PanelRite: pr.right, VW: document.documentElement.clientWidth,
+ SignOutHit: !!hit && out.contains(hit), EdgesHit: inP(pr.left + 2) && inP(pr.right - 2)}
})()`
for _, w := range []int64{1440, 390, 320} {
rig := browserApp(t, nil)
var f facts
var closedByEscape, focusBack, closedByOutside bool
- actions := []chromedp.Action[chromedp.Void]{
+ rig.Run(
send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: w, Height: 800, DeviceScaleFactor: 1}),
- chromedp.Navigate(rig.Origin + "/"),
- chromedp.WaitReady(`[rst-shell-rail-foot]`),
- }
- if w < 800 {
- actions = append(actions, chromedp.Click(`[rst-shell-chrome] > summary`), chromedp.Sleep(100*time.Millisecond))
- }
- var present bool
- rig.Run(append(actions, harness.Into(&present, chromedp.Evaluate[bool](`!!document.querySelector('[rst-shell-rail-foot] [estilo-account] > summary')`)))...)
- if !present {
- t.Fatalf("%dpx: the rail's foot has no account menu", w)
- }
- actions = append(actions,
- chromedp.Click(`[estilo-account] > summary`),
+ chromedp.Navigate(rig.Origin+"/"),
+ chromedp.WaitVisible(`[estilo-bar] [estilo-account] > summary`),
+ chromedp.Click(`[estilo-bar] [estilo-account] > summary`),
chromedp.Sleep(150*time.Millisecond),
harness.Into(&f, chromedp.Evaluate[facts](measure)),
chromedp.KeyEvent("\x1b"),
chromedp.Sleep(100*time.Millisecond),
harness.Into(&closedByEscape, chromedp.Evaluate[bool](`!document.querySelector('[estilo-account]').open`)),
harness.Into(&focusBack, chromedp.Evaluate[bool](`document.activeElement === document.querySelector('[estilo-account] > summary')`)),
- chromedp.Click(`[estilo-account] > summary`),
+ chromedp.Click(`[estilo-bar] [estilo-account] > summary`),
chromedp.Sleep(100*time.Millisecond),
- // The window's top corner, outside the panel at every width (at
- // 390 the downward panel covers the page's heading).
- chromedp.MouseClickXY(float64(w)-8, 8),
+ chromedp.MouseClickXY(20, 700),
chromedp.Sleep(100*time.Millisecond),
harness.Into(&closedByOutside, chromedp.Evaluate[bool](`!document.querySelector('[estilo-account]').open`)),
)
- rig.Run(actions...)
if !f.Open {
t.Fatalf("%dpx: the account menu did not open", w)
}
- if w >= 800 && f.PanelBot > f.TrigTop+0.5 {
- t.Errorf("%dpx: the panel (%.0f..%.0f) does not open upward from its trigger at %.0f", w, f.PanelTop, f.PanelBot, f.TrigTop)
- }
- if w < 800 && f.PanelTop < f.TrigBot-0.5 {
- t.Errorf("%dpx: inside the Menu disclosure the panel (%.0f..%.0f) should open downward from %.0f", w, f.PanelTop, f.PanelBot, f.TrigBot)
- }
if f.PanelTop < 0 || f.PanelLeft < 0 || f.PanelRite > f.VW+0.5 {
t.Errorf("%dpx: the panel is partly off screen: %+v", w, f)
}
@@ -327,9 +296,6 @@ func TestTheAccountMenuOpensUpward(t *testing.T) {
if !f.SignOutHit {
t.Errorf("%dpx: a tap at Sign out's centre does not reach it", w)
}
- if f.PanelRadius != "9px" || f.TrigRadius != "0px" {
- t.Errorf("%dpx: panel radius %s (want 9px, it floats), trigger radius %s (want 0px, it is in flow)", w, f.PanelRadius, f.TrigRadius)
- }
if !closedByEscape || !focusBack {
t.Errorf("%dpx: Escape closed it: %v; focus back on its trigger: %v", w, closedByEscape, focusBack)
}
@@ -348,9 +314,10 @@ func send[P any](command cdp.Command[P, cdp.Empty], params P) chromedp.Action[ch
})
}
-// TestARowOpensItsCard: a click anywhere on a row opens its card, and a
-// link of the row's own (the domain) is still what a click on it reaches.
-func TestARowOpensItsCard(t *testing.T) {
+// TestTheNameOpensTheCardAndACellEdits: the name opens the card beside
+// the list (level-up §5.4, D1), and a click on any other cell edits it in
+// place and opens nothing (Q10, ruled 2026-11-17).
+func TestTheNameOpensTheCardAndACellEdits(t *testing.T) {
var id int64
rig := browserApp(t, func(ctx context.Context, d *db.DB, cfg fichas.Config) {
m, _ := fichas.EnsureMember(ctx, d.G, cfg.Sealer, TestOwner)
@@ -361,25 +328,26 @@ func TestARowOpensItsCard(t *testing.T) {
}
id = c.ID
})
- var domainOnTop bool
- var path string
+ var editing bool
+ var before, search string
rig.Run(
+ send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 900, DeviceScaleFactor: 1}),
chromedp.Navigate(rig.Origin+"/"),
- chromedp.WaitVisible(`[fichas-grid] tbody tr`),
- harness.Into(&domainOnTop, chromedp.Evaluate[bool](`(() => {
- const a = document.querySelector('[fichas-grid] tbody a[fichas-link]'), r = a.getBoundingClientRect()
- return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === a
- })()`)),
- // The phone's cell: plain text, far from the title.
- chromedp.Click(`[fichas-grid] tbody tr td:nth-child(4)`),
- chromedp.WaitVisible(`textarea[name="f_body"]`),
- harness.Into(&path, chromedp.Evaluate[string](`location.pathname`)),
+ chromedp.WaitVisible(`[fichas-grid][role="grid"] tbody tr`),
+ harness.Into(&before, chromedp.Evaluate[string](`location.pathname + location.search`)),
+ chromedp.Click(`[fichas-grid] td[data-field="f_phone"]`),
+ chromedp.WaitVisible(`[fichas-editor] input`),
+ harness.Into(&editing, chromedp.Evaluate[bool](`document.activeElement === document.querySelector('[fichas-editor] input') && location.pathname + location.search === `+"`"+`/`+"`"+``)),
+ chromedp.KeyEvent("\x1b"),
+ chromedp.Click(`[fichas-title-link]`),
+ chromedp.WaitVisible(`[fichas-pane] [fichas-quiet-title]`),
+ harness.Into(&search, chromedp.Evaluate[string](`location.search`)),
)
- if !domainOnTop {
- t.Error("the row's link covers the domain link: a click on the domain would open the card")
+ if !editing {
+ t.Error("a click on the phone cell did not open its editor in place")
}
- if path != "/cards/"+itoa(id) {
- t.Fatalf("a click on the row's phone cell went to %q, want the card", path)
+ if search != "?card="+itoa(id) {
+ t.Fatalf("the name opened %q, want the card beside the list", search)
}
}
@@ -391,12 +359,12 @@ func TestRailIconsSitOnTheTextsCentreLine(t *testing.T) {
var offsets []float64
rig.Run(
// A desktop width: below 800px the rail folds behind Menu.
- send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 800, DeviceScaleFactor: 1}),
+ send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1440, Height: 800, DeviceScaleFactor: 1}),
chromedp.Navigate(rig.Origin+"/"),
- chromedp.WaitVisible(`[rst-shell-nav] a`),
- harness.Into(&offsets, chromedp.Evaluate[[]float64](`[...document.querySelectorAll('[rst-shell-nav] a')].map(a => {
+ chromedp.WaitVisible(`[fichas-rail] a[fichas-rail-item]`),
+ harness.Into(&offsets, chromedp.Evaluate[[]float64](`[...document.querySelectorAll('[fichas-rail] a[fichas-rail-item]')].map(a => {
const i = a.querySelector('svg').getBoundingClientRect()
- const r = document.createRange(); r.selectNodeContents(a.lastChild); const tx = r.getBoundingClientRect()
+ const r = document.createRange(); r.selectNodeContents(a.querySelector('[fichas-rail-label]')); const tx = r.getBoundingClientRect()
return (i.top + i.height / 2) - (tx.top + tx.height / 2)
})`)),
)