oficina / fichas Public

Phase 1 review, round 1: Fable's High, Mediums and Lows

- H1: values are stored with LF line endings and compared newline-blind,
  so a form's CRLF and a script's LF never conflict; gated both ways.
- M1: ArrowUp from the first row reaches the grid's header, and Enter
  sorts (a WCAG 2.1.1 regression); gated in the browser.
- M2: LU17's template check: every locale call names the reader's
  localizer, commas is gone, and no handler formats a date by hand.
- Lows: an untouched web address and a Choice no longer offered are kept
  by the forms; a refused number on the New form comes back as typed;
  Sync rebuilds rather than stalls on a group event or a gone field; a
  partial scriptless Undo says so; the toast's Undo leaves the ⌘Z stack;
  Undo answers in the page's locale; the phone sheet posts its list; the
  conflict line says You in another tab; the narrowed list keeps its
  scroll; the email link is guarded; dead DetailItems removed. Build notes
  16 to 19.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 68feb3db364a1d5042f00e3e561ee9ab95e38250 parent 781f47c
18 files changed, +330 −78
  • docs/superpowers/specs/2026-11-17-fichas-level-up.md +5 −1
  • internal/fichas/card_handlers.go +2 −2
  • internal/fichas/edit.go +3 −3
  • internal/fichas/edit_handlers.go +37 −10
  • internal/fichas/edit_test.go +30 −0
  • internal/fichas/handlers.go +1 −0
  • internal/fichas/index.go +22 −2
  • internal/fichas/kinds_test.go +4 −6
  • internal/fichas/pane.go +7 −3
  • internal/fichas/read.go +0 −41
  • internal/fichas/render.go +18 −1
  • internal/fichas/static/grid.js +38 −6
  • internal/fichas/store.go +15 −0
  • internal/fichas/sync_kinds_test.go +1 −1
  • internal/fichas/templates/partials.html +1 −1
  • internal/fichastest/browser_edit_test.go +25 −0
  • internal/fichastest/edit_routes_test.go +66 −1
  • internal/fichastest/formats_markup_test.go +55 −0

CI passed — run details

CI log
=== vet ===
go vet ./...
go vet -tags browser ./internal/fichastest/
=== fmt ===
=== test ===
go test ./...
?   	amadan.net/oficina/fichas/cmd/fichas	[no test files]
ok  	amadan.net/oficina/fichas/internal/fichas	2.464s
?   	amadan.net/oficina/fichas/internal/fichas/icons	[no test files]
ok  	amadan.net/oficina/fichas/internal/fichas/locale	0.008s
ok  	amadan.net/oficina/fichas/internal/fichas/seal	(cached)
ok  	amadan.net/oficina/fichas/internal/fichastest	1.812s
?   	amadan.net/oficina/fichas/scripts/mockups	[no test files]
?   	amadan.net/oficina/fichas/scripts/preview	[no test files]
?   	amadan.net/oficina/fichas/scripts/writeestilo	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
diff --git a/docs/superpowers/specs/2026-11-17-fichas-level-up.md b/docs/superpowers/specs/2026-11-17-fichas-level-up.md
index 33536ab..14cb121 100644
--- a/docs/superpowers/specs/2026-11-17-fichas-level-up.md
+++ b/docs/superpowers/specs/2026-11-17-fichas-level-up.md
@@ -1089,10 +1089,14 @@ Choices made while building, where this spec was silent or the build chose diffe
9. **A scriptless save comes back with a flag, never with text:** `?saved=<event>`, `?undone=<event>`, `?refused=1`, `?conflict=1`. The notice's words are Fichas' own, and its Undo form posts to the card the event is on, looked up from the event. A crafted link cannot put words on the page.
10. **An edit form posted without `was.<key>`** (a client older than this form) is checked against the value as the handler loaded it. Fichas' own forms always send `was`.
11. **The value window's sweep** runs from `main`, once at start and then hourly, off the boot path; a failure is logged and tried again.
-12. **Numbers** follow §6.8's Phase 1 rules: drawn ungrouped with the pack's decimal mark, read by the interim strict reading in `numberread.go`, with the echo and the unchanged-seed rule. Counts go through rastrillo's `{{number}}`.
+12. **Numbers and dates** follow §6.8's Phase 1 rules, as aligned with Mapa's build note 85: the six offered locales, negotiated from `Accept-Language` alone; numbers drawn ungrouped with the pack's decimal mark and read by the interim strict reading in `numberread.go`, with the echo and the unchanged-seed rule; counts through rastrillo's `{{number}}`; dates by Mapa's patterns and formatter, copied into `internal/fichas/locale` and pinned to Mapa's by sha256. A number stored before the grammar in a non-canonical form (`1.500`) is drawn as stored until Phase 2's reconcile rewrites it.
13. **estilo hides the brand's name in a stacked bar,** which leaves its link with no accessible name (axe-core's `link-name`). `frame.css` keeps the name for screen readers; the fix belongs in estilo.
14. **The scriptless browser gate (LU9) turns page scripts off with `Emulation.setScriptExecutionDisabled`** and reads the DOM through DevTools' DOM domain only, because chromedp's visibility checks need script.
15. **The phone's list of rows** shows the title, the first Choice as its pill, and the first two other values, rather than "the next two face fields": face fields are a Cards-layout setting, and the table's columns are what the reader chose to see.
+16. **Line endings are normalised to LF** for every value written, and compared newline-blind, because a form posts CRLF, script LF, and Notes written before hold CRLF (Fable's Phase 1 review, H1).
+17. **`Index.Sync` rebuilds on a `group` event** (no group is written before Phase 6, which will say which types a folder change touches) and when a field event's field is gone; `reloadType` reloads the type's cards as well as its labels, where §9 says metadata, because a field's rename or options change how every card of the type is drawn.
+18. **With a card open beside the list, the bar's title is the card's,** as on its full page: the card is the open object.
+19. **The conflict line says "You changed this … in another tab."** when the last change was the person's own, and never "a moment ago", which the event's time does not back.
---
diff --git a/internal/fichas/card_handlers.go b/internal/fichas/card_handlers.go
index da86c02..0844aeb 100644
--- a/internal/fichas/card_handlers.go
+++ b/internal/fichas/card_handlers.go
@@ -124,7 +124,7 @@ func formEdit(r *http.Request, card CardView) (values, was, typed map[string]str
w, sent := r.PostForm["was."+key]
was[key] = f.Value
if sent {
- was[key] = w[0]
+ was[key] = lf(w[0])
}
typed[key] = r.PostForm.Get(key)
v, problem := postedValue(r, f.Def, was[key])
@@ -132,7 +132,7 @@ func formEdit(r *http.Request, card CardView) (values, was, typed map[string]str
problems[key] = problem
continue
}
- if normaliseValue(f.Def, v) != was[key] {
+ if !sameText(normaliseValue(f.Def, v), was[key]) {
values[key] = v
}
}
diff --git a/internal/fichas/edit.go b/internal/fichas/edit.go
index cee49c5..addce5f 100644
--- a/internal/fichas/edit.go
+++ b/internal/fichas/edit.go
@@ -158,8 +158,8 @@ func EditFields(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64,
}
res.Values[key] = before
switch {
- case before == after:
- case before == was[key]:
+ case sameText(before, after):
+ case sameText(before, was[key]):
res.Changes = append(res.Changes, change{Field: key, Before: before, After: after})
changed = append(changed, def.ID)
res.Values[key] = after
@@ -315,7 +315,7 @@ func Undo(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor
if err != nil {
return err
}
- if now != c.After {
+ if !sameText(now, c.After) {
by, err := lastEditor(tx, s, cardID, def.ID)
if err != nil {
return err
diff --git a/internal/fichas/edit_handlers.go b/internal/fichas/edit_handlers.go
index 43f4f7e..e927fcd 100644
--- a/internal/fichas/edit_handlers.go
+++ b/internal/fichas/edit_handlers.go
@@ -47,7 +47,12 @@ func echoedLocale(r *http.Request, key string) string {
// postedValue is one field's posted value, read in the page's locale and
// made canonical; or a message saying what to fix.
func postedValue(r *http.Request, def FieldDef, was string) (string, string) {
- raw := strings.TrimSpace(r.PostForm.Get(def.Key))
+ raw := lf(strings.TrimSpace(r.PostForm.Get(def.Key)))
+ // A web address is drawn without its scheme; drawn back untouched it
+ // is the value the editor saw, not a change to https:// (§5.2).
+ if def.Kind == KindURL && was != "" && raw == displayURL(was) {
+ return was, ""
+ }
if def.Kind != KindNumber {
return raw, ""
}
@@ -86,7 +91,7 @@ func (a *app) setFieldValue(w http.ResponseWriter, r *http.Request) {
notFound(w, r)
return
}
- was := r.PostForm.Get("was." + key)
+ was := lf(r.PostForm.Get("was." + key))
value, problem := postedValue(r, f.Def, was)
if problem != "" {
a.refuseField(w, r, card, key, problem)
@@ -106,7 +111,8 @@ func (a *app) answerFieldEdit(w http.ResponseWriter, r *http.Request, card CardV
}
if c, ok := IsConflict(err); ok {
theirs := c.Fields[f.Def.Key]
- msg := conflictLine(L, f, theirs)
+ me, _ := a.identity(r)
+ msg := conflictLine(L, f, theirs, me)
if !wantsJSON(r) {
a.backWith(w, r, card.Card.ID, "conflict", "1")
return
@@ -224,16 +230,25 @@ func changedLine(L *ui.Localizer, f FieldView, now string) string {
return f.Label + " changed to " + showValue(L, f.Def.Kind, now) + "."
}
-// conflictLine is §5.2's "Niamh changed this to Contacted a moment ago."
-func conflictLine(L *ui.Localizer, f FieldView, c Conflict) string {
+// conflictLine is §5.2's "Niamh changed this to Contacted." When the
+// last change was this person's own, from another tab or window, it says
+// so rather than naming them to themselves.
+func conflictLine(L *ui.Localizer, f FieldView, c Conflict, me string) string {
who := "Someone"
- if c.By != "" {
+ switch {
+ case c.By != "" && c.By == me:
+ who = "You"
+ case c.By != "":
who = personName(c.By)
}
+ where := "."
+ if who == "You" {
+ where = " in another tab."
+ }
if c.Theirs == "" {
- return who + " cleared this a moment ago."
+ return who + " cleared this" + where
}
- return who + " changed this to " + showValue(L, f.Def.Kind, c.Theirs) + " a moment ago."
+ return who + " changed this to " + showValue(L, f.Def.Kind, c.Theirs) + where
}
// cellHTML draws one table cell's contents as the list draws it.
@@ -298,10 +313,13 @@ func (a *app) undoEdit(w http.ResponseWriter, r *http.Request) {
a.notFoundOrFail(w, r, err)
return
}
- L := a.readerL(r)
+ L := localizerFor(r.PostForm.Get("locale"))
+ if L == nil {
+ L = a.readerL(r)
+ }
msg := undoLine(card, res)
if !wantsJSON(r) {
- a.backWith(w, r, id, "undone", strconv.FormatInt(res.EventID, 10))
+ a.backWith(w, r, id, "undone", strconv.FormatInt(res.EventID, 10)+leftMark(res))
return
}
cells := map[string]map[string]string{}
@@ -312,6 +330,15 @@ func (a *app) undoEdit(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"event": res.EventID, "redo": res.Redo, "message": msg, "cells": cells})
}
+// leftMark tells the scriptless notice that an Undo left some fields:
+// "-left" after the event id, never their names in a URL.
+func leftMark(res UndoResult) string {
+ if len(res.Left) > 0 {
+ return "-left"
+ }
+ return ""
+}
+
// undoLine says what an Undo did, naming each field it left (§5.3).
func undoLine(card CardView, res UndoResult) string {
var parts []string
diff --git a/internal/fichas/edit_test.go b/internal/fichas/edit_test.go
index 9db72ea..499ae4f 100644
--- a/internal/fichas/edit_test.go
+++ b/internal/fichas/edit_test.go
@@ -278,3 +278,33 @@ func memberID(t *testing.T, g *gorm.DB, s *seal.Sealer, address string) int64 {
}
return m.ID
}
+
+// Multi-line text compares by its lines, not its line endings: Notes
+// written before were stored with a form's CRLF, a script sends LF, and a
+// form sends CRLF again (Fable, Phase 1 review, H1). LU4.
+//
+// Mutation, 2026-11-17: comparing before and was byte for byte failed
+// both halves.
+func TestLineEndingsAreNotAConflict(t *testing.T) {
+ g, s := seeded(t)
+ ana := memberID(t, g, s, "ana@example.com")
+ card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc"})
+ defs, _ := fieldsFor(g, card.CardTypeID)
+ // A legacy row, as the New form stored it before this rule.
+ if err := writeValue(g, s, card.ID, defs[FieldNotes], "line one\r\nline two"); err != nil {
+ t.Fatal(err)
+ }
+ // Script after a form: was arrives with LF.
+ if _, err := SetField(ctx(), g, s, card.ID, Person(ana), FieldNotes, "line one\nline two\nline three", "line one\nline two"); err != nil {
+ t.Fatalf("a script's edit of CRLF notes: %v", err)
+ }
+ // A form after script: was arrives with CRLF over the stored LF.
+ if _, err := EditFields(ctx(), g, s, card.ID, Person(ana),
+ map[string]string{FieldNotes: "line one\r\nline four"},
+ map[string]string{FieldNotes: "line one\r\nline two\r\nline three"}); err != nil {
+ t.Fatalf("a form's edit of LF notes: %v", err)
+ }
+ if got := valueOf(t, g, s, card.ID, FieldNotes); got != "line one\nline four" {
+ t.Fatalf("notes are %q; want LF line endings", got)
+ }
+}
diff --git a/internal/fichas/handlers.go b/internal/fichas/handlers.go
index d76e913..162f231 100644
--- a/internal/fichas/handlers.go
+++ b/internal/fichas/handlers.go
@@ -364,6 +364,7 @@ func (a *app) createCard(w http.ResponseWriter, r *http.Request) {
v, problem := postedValue(r, f.Def, "")
if problem != "" {
problems[f.Def.Key] = problem
+ continue // what was typed is drawn again as typed
}
values[f.Def.Key] = v
}
diff --git a/internal/fichas/index.go b/internal/fichas/index.go
index 9a7ff38..63c1642 100644
--- a/internal/fichas/index.go
+++ b/internal/fichas/index.go
@@ -111,6 +111,7 @@ func (ix *Index) Sync(ctx context.Context) error {
}
cards := map[int64]bool{}
types := map[int64]bool{}
+ full := false
for _, e := range events {
// Each object kind is named, with what it reloads (level-up §9):
// a kind this switch does not name rebuilds everything, the safe
@@ -125,14 +126,25 @@ func (ix *Index) Sync(ctx context.Context) error {
case ObjectView, ObjectFile, ObjectDraft, ObjectMember:
// Nothing the index holds: views are read per request; files,
// drafts and a person's own format are not in it.
- case ObjectType, ObjectGroup:
+ case ObjectType:
types[e.ObjectID] = true
case ObjectField:
var fd FieldDef
- if err := g.Select("card_type_id").First(&fd, e.ObjectID).Error; err != nil {
+ err := g.Select("card_type_id").First(&fd, e.ObjectID).Error
+ if err == gorm.ErrRecordNotFound {
+ // A field gone from under its event: rebuild, never stall.
+ full = true
+ continue
+ }
+ if err != nil {
return fmt.Errorf("fichas: finding field %d's type: %w", e.ObjectID, err)
}
types[fd.CardTypeID] = true
+ case ObjectGroup:
+ // A folder names types by its own id, not theirs; until Phase 6
+ // writes folders and says which types a change touches, a
+ // folder event rebuilds the index.
+ full = true
default:
ix.fullLoads++
if err := ix.loadAll(g); err != nil {
@@ -142,6 +154,14 @@ func (ix *Index) Sync(ctx context.Context) error {
return nil
}
}
+ if full {
+ ix.fullLoads++
+ if err := ix.loadAll(g); err != nil {
+ return err
+ }
+ ix.seen = latest
+ return nil
+ }
for id := range types {
if err := ix.reloadType(g, id); err != nil {
return err
diff --git a/internal/fichas/kinds_test.go b/internal/fichas/kinds_test.go
index ca9c833..a2d6301 100644
--- a/internal/fichas/kinds_test.go
+++ b/internal/fichas/kinds_test.go
@@ -1,7 +1,6 @@
package fichas
import (
- "fmt"
"testing"
"amadan.net/oficina/fichas/internal/fichas/seal"
@@ -92,12 +91,11 @@ func TestEmailAndPhoneAreCheckedAndTidied(t *testing.T) {
if got := view.Field(FieldPhone).Value; got != "+353 1 555 0100" {
t.Errorf("phone stored as %q", got)
}
- links := map[string]string{}
- for _, d := range view.DetailItems() {
- links[d["Label"].(string)] = fmt.Sprint(d["Href"])
+ if mailHref(view.Field(FieldEmail).Value) != "mailto:Ana.Ni@cnoc.example" || telHref(view.Field(FieldPhone).Value) != "tel:+35315550100" {
+ t.Errorf("the card does not link them")
}
- if links["Email"] != "mailto:Ana.Ni@cnoc.example" || links["Phone"] != "tel:+35315550100" {
- t.Errorf("the card does not link them: %v", links)
+ if mailHref("ana@example.com?subject=hi") != "" {
+ t.Error("an email value with mailto: parameters is linked")
}
}
diff --git a/internal/fichas/pane.go b/internal/fichas/pane.go
index 3d90f9d..c79637a 100644
--- a/internal/fichas/pane.go
+++ b/internal/fichas/pane.go
@@ -190,9 +190,13 @@ func noticeFrom(r *http.Request) *notice {
case q.Get("saved") != "":
return &notice{Kind: "saved", Text: "Saved.", EventID: digits(q.Get("saved"))}
case q.Get("undone") != "":
- id := digits(q.Get("undone"))
- if id == "" || id == "0" {
- return &notice{Kind: "undone", Text: "Nothing to undo: it was changed again since."}
+ raw, left := strings.CutSuffix(q.Get("undone"), "-left")
+ id := digits(raw)
+ switch {
+ case id == "" || id == "0":
+ return &notice{Kind: "undone", Text: "Nothing was undone: it was changed again since. History shows who changed it."}
+ case left:
+ return &notice{Kind: "undone", Text: "Undone, except where it was changed again since. History shows what was left.", EventID: id}
}
return &notice{Kind: "undone", Text: "Undone.", EventID: id}
// Refusals come back as a flag, never as text from the URL, so a
diff --git a/internal/fichas/read.go b/internal/fichas/read.go
index f27f9af..5bf0fb9 100644
--- a/internal/fichas/read.go
+++ b/internal/fichas/read.go
@@ -3,10 +3,8 @@ package fichas
import (
"context"
"fmt"
- "html/template"
"sort"
"strings"
- "time"
"amadan.net/oficina/fichas/internal/fichas/seal"
"gorm.io/gorm"
@@ -376,45 +374,6 @@ func memberByAddress(ctx context.Context, db *gorm.DB, s *seal.Sealer, address s
return m, nil
}
-// DetailItems is the read view's fact list: every field except the title
-// and long text, in order, with "—" for an empty one so the shape of the
-// card does not change as it fills in.
-func (c CardView) DetailItems() []map[string]any {
- var out []map[string]any
- for _, f := range c.Fields {
- if c.IsTitle(f.Def.Key) || isLong(f.Def) {
- continue
- }
- v, external := f.Value, false
- var href any = ""
- switch {
- case v == "":
- v = "—"
- case f.Def.Kind == KindDate:
- v = displayDate(v)
- case f.Def.Kind == KindURL:
- href, v, external = safeHref(v), displayURL(v), true
- case f.Def.Kind == KindEmail && looksLikeAnEmail(v):
- href = "mailto:" + v // html/template allows mailto: and escapes it
- case f.Def.Kind == KindPhone && telDigits(v) != "" && looksLikeAPhoneNumber(v):
- // html/template refuses tel: unless told it is safe. It is: only
- // ASCII digits and a leading + survive telDigits.
- href = template.URL("tel:" + telDigits(v))
- }
- out = append(out, map[string]any{"Label": f.Label, "Value": v, "Href": href, "External": external})
- }
- return out
-}
-
-// displayDate shows a stored "2026-10-02" as "2 October 2026".
-func displayDate(v string) string {
- d, err := time.Parse("2006-01-02", v)
- if err != nil {
- return v
- }
- return d.Format("2 January 2006")
-}
-
// EnsureMember is memberByAddress for callers outside the package — the
// preview server, which needs a real member to attribute its seed data to.
func EnsureMember(ctx context.Context, db *gorm.DB, s *seal.Sealer, address string) (Member, error) {
diff --git a/internal/fichas/render.go b/internal/fichas/render.go
index 35bcb09..9e71cbd 100644
--- a/internal/fichas/render.go
+++ b/internal/fichas/render.go
@@ -63,6 +63,7 @@ func init() {
"personName": personName,
"editField": editField,
"telHref": telHref,
+ "mailHref": mailHref,
"errFor": errFor,
"yesNo": yesNo,
"displayURL": displayURL,
@@ -119,6 +120,15 @@ func notFound(w http.ResponseWriter, r *http.Request) {
// system. Every page draws it, so the scheme is right in the first paint.
func themeAttr(r *http.Request) string { return chrome.ThemeAttr(chrome.Appearance(r)) }
+// mailHref is an email value's mailto: link, or nothing when it is not
+// an address: a value cannot carry mailto: parameters into the link.
+func mailHref(v string) string {
+ if looksLikeAnEmail(v) {
+ return "mailto:" + v
+ }
+ return ""
+}
+
// telHref is a phone number's tel: link, or nothing when it is not one.
func telHref(v string) template.URL {
if d := telDigits(v); d != "" && looksLikeAPhoneNumber(v) {
@@ -144,10 +154,17 @@ func editField(f FieldView, typed bool, L *ui.Localizer) FieldView {
// no empty choice silently submits its first value for a card nobody has
// set a stage on yet, which writes a value a person never chose.
func selectOptions(values []string, current string) []map[string]any {
- out := make([]map[string]any, 0, len(values)+1)
+ out := make([]map[string]any, 0, len(values)+2)
out = append(out, map[string]any{"Value": "", "Label": "—", "Selected": current == ""})
+ known := current == ""
for _, v := range values {
out = append(out, map[string]any{"Value": v, "Label": v, "Selected": v == current})
+ known = known || v == current
+ }
+ // A stored value the field no longer offers is still the card's: it
+ // is shown and kept, so saving another field never clears it (§5.2).
+ if !known {
+ out = append(out, map[string]any{"Value": current, "Label": current + " (no longer offered)", "Selected": true})
}
return out
}
diff --git a/internal/fichas/static/grid.js b/internal/fichas/static/grid.js
index 4b2a747..7ae3da5 100644
--- a/internal/fichas/static/grid.js
+++ b/internal/fichas/static/grid.js
@@ -115,7 +115,7 @@
function undo(entry, redo) {
saveState("saving");
- return post("/cards/" + entry.card + "/undo", { event: entry.event }).then(function (r) {
+ return post("/cards/" + entry.card + "/undo", { event: entry.event, locale: locale() }).then(function (r) {
if (r.status !== 200) { saveState("idle"); toast("That can no longer be undone."); return; }
saveState("saved");
var d = r.data;
@@ -128,6 +128,14 @@
}, function () { toast("Couldn't reach Fichas, so nothing was undone."); });
}
+ // undoFromToast is the toast's Undo: the event leaves this tab's ⌘Z
+ // stack too, so a later ⌘Z does not ask for it again.
+ function undoFromToast(card, event) {
+ var i = undoStack.map(function (u) { return u.event; }).indexOf(event);
+ if (i >= 0) undoStack.splice(i, 1);
+ undo({ card: card, event: event }, false);
+ }
+
function undoLast() {
var e = undoStack.pop();
if (e) { undo(e, false); } else { toast("Nothing to undo in this tab."); }
@@ -201,7 +209,9 @@
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
+ // Row 0 is the header: ArrowUp from the first row reaches it, and
+ // Enter there follows its sort link.
+ r = Math.max(0, Math.min(p.rows.length - 1, r));
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));
@@ -402,7 +412,7 @@
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); } });
+ toast(d.message, { label: "Undo", run: function () { undoFromToast(card, d.event); } });
}
if (d.outOfView) markOutOfView(cell.parentElement);
if (!how.quiet) {
@@ -518,14 +528,16 @@
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 table = cell.closest("table");
+ saveField(card, key, input.value, cell.getAttribute("data-was") || "", { list: (table && table.getAttribute("data-list")) || "" }).then(function (r) {
var d = r.data;
if (r.status === 200) {
applyValue(card, key, d);
dialog.close();
+ if (d.outOfView) markOutOfView(cell.parentElement);
if (d.event) {
remember(card, d.event, key);
- toast(d.message, { label: "Undo", run: function () { undo({ card: card, event: d.event }, false); } });
+ toast(d.message, { label: "Undo", run: function () { undoFromToast(card, d.event); } });
}
} else if (r.status === 409) {
applyValue(card, key, { value: d.theirs, seed: d.seed, cell: d.cell });
@@ -565,7 +577,7 @@
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); } });
+ toast(d.message, { label: "Undo", run: function () { undoFromToast(card, d.event); } });
}
} else {
var msg = r.status === 409 ? d.message : (d.error || "That can't be changed any more.");
@@ -641,6 +653,22 @@
// 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 */ }
+ keepScroll();
+ }
+
+ // The narrowed list keeps its scroll from card to card (§5.4): each
+ // step is a page load, so the position rides in this tab's storage.
+ function keepScroll() {
+ try { sessionStorage.setItem("fichas-scroll", String(window.scrollY)); } catch (err) { /* private mode */ }
+ }
+
+ function restoreScroll() {
+ var y = null;
+ try { y = sessionStorage.getItem("fichas-scroll"); sessionStorage.removeItem("fichas-scroll"); } catch (err) { return; }
+ if (y === null || !document.querySelector("[fichas-narrow]")) return;
+ window.scrollTo(0, parseInt(y, 10) || 0);
+ var current = document.querySelector("[fichas-narrow] a[aria-current]");
+ if (current && current.scrollIntoView) current.scrollIntoView({ block: "nearest" });
}
function restoreFocus() {
@@ -678,7 +706,11 @@
document.querySelectorAll("table[fichas-grid]").forEach(setupGrid);
document.querySelectorAll("form[fichas-card-form]").forEach(setupCard);
bindCommands();
+ restoreScroll();
restoreFocus();
+ document.addEventListener("click", function (e) {
+ if (e.target.closest && e.target.closest("[fichas-narrow] a, [fichas-pane] a[rel]")) keepScroll();
+ });
// 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");
diff --git a/internal/fichas/store.go b/internal/fichas/store.go
index d47f39e..5dd7d07 100644
--- a/internal/fichas/store.go
+++ b/internal/fichas/store.go
@@ -208,6 +208,7 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel
// (A form reads numbers in the reader's locale first, §6.8; this keeps
// the store's own callers, which pass canonical text, as they were.)
func normaliseValue(def FieldDef, v string) string {
+ v = lf(v)
switch def.Kind {
case KindNumber:
v = strings.ReplaceAll(strings.TrimSpace(v), ",", "")
@@ -229,6 +230,20 @@ func normaliseValue(def FieldDef, v string) string {
return v
}
+// lf is text with every line ending a line feed. A browser posts a
+// textarea's and a hidden field's lines with CRLF, the DOM hands script
+// LF, and Notes written before this rule hold CRLF; compared byte for
+// byte, each would conflict with the other (Fable, Phase 1 review, H1).
+func lf(s string) string {
+ if !strings.Contains(s, "\r") {
+ return s
+ }
+ return strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\r", "\n")
+}
+
+// sameText reports whether two values are the same but for line endings.
+func sameText(a, b string) bool { return lf(a) == lf(b) }
+
// checkValues normalises values and refuses, with a FormError, any a
// person must fix: a bad value for its kind, an empty title, a choice
// that is not an option. A key that is not a field is a programming
diff --git a/internal/fichas/sync_kinds_test.go b/internal/fichas/sync_kinds_test.go
index fd634cb..5641697 100644
--- a/internal/fichas/sync_kinds_test.go
+++ b/internal/fichas/sync_kinds_test.go
@@ -29,7 +29,7 @@ func TestEveryObjectKindIsNamedInSync(t *testing.T) {
if err := UpdateField(ctx(), g, s, fd.Key, Person(1), "Budget (EUR)", nil); err != nil {
t.Fatal(err)
}
- for _, kind := range []string{ObjectView, ObjectFile, ObjectDraft, ObjectGroup, ObjectMember} {
+ for _, kind := range []string{ObjectView, ObjectFile, ObjectDraft, ObjectMember} {
if err := g.Create(&Event{Kind: EventUpdated, ObjectKind: kind, ObjectID: ct.ID, ChangedFields: "[]", Nonce: 1}).Error; err != nil {
t.Fatal(err)
}
diff --git a/internal/fichas/templates/partials.html b/internal/fichas/templates/partials.html
index 85d33d3..b5d6e48 100644
--- a/internal/fichas/templates/partials.html
+++ b/internal/fichas/templates/partials.html
@@ -136,7 +136,7 @@
{{- else}} type="text"{{end}}{{if .Error}} aria-invalid="true" aria-describedby="{{$id}}-error"{{end}}>
{{- with $f.Value}}
{{- if eq $f.Def.Kind "url"}}{{with safeHref .}}<a fichas-quiet-open href="{{.}}" target="_blank" rel="noopener noreferrer">{{icon "maximize-2"}}<span class="rst-sr-only">Visit {{displayURL $f.Value}}</span></a>{{end}}
- {{- else if eq $f.Def.Kind "email"}}<a fichas-quiet-open href="mailto:{{.}}">{{icon "maximize-2"}}<span class="rst-sr-only">Write to {{.}}</span></a>
+ {{- else if eq $f.Def.Kind "email"}}{{with mailHref .}}<a fichas-quiet-open href="{{.}}">{{icon "maximize-2"}}<span class="rst-sr-only">Write to {{$f.Value}}</span></a>{{end}}
{{- else if eq $f.Def.Kind "phone"}}{{with telHref .}}<a fichas-quiet-open href="{{.}}">{{icon "phone"}}<span class="rst-sr-only">Call {{$f.Value}}</span></a>{{end}}{{end}}
{{- end}}
{{- end}}
diff --git a/internal/fichastest/browser_edit_test.go b/internal/fichastest/browser_edit_test.go
index d2a6d68..40311f3 100644
--- a/internal/fichastest/browser_edit_test.go
+++ b/internal/fichastest/browser_edit_test.go
@@ -342,3 +342,28 @@ func TestPhones(t *testing.T) {
t.Errorf("the card on a phone: its own screen %v, a Next of 44px %v", narrowHidden, hasNext)
}
}
+
+// The grid's header is reachable by keyboard (Fable, Phase 1 review,
+// M1): ArrowUp from the first row reaches it, and Enter sorts.
+//
+// Mutation, 2026-11-17: clamping the grid's rows to the body again
+// failed it.
+func TestTheHeaderSortsByKeyboard(t *testing.T) {
+ s := seedCards(t, 2)
+ var onHeader bool
+ var search string
+ s.rig.Run(
+ wide(),
+ chromedp.Navigate(s.rig.Origin+"/t/t_customer"),
+ chromedp.WaitVisible(`[fichas-grid][role="grid"]`),
+ chromedp.Evaluate[chromedp.Void](`document.querySelector('[fichas-grid] tbody [fichas-title-cell]').focus()`),
+ chromedp.KeyEvent(kb.ArrowUp),
+ harness.Into(&onHeader, chromedp.Evaluate[bool](`document.activeElement.tagName === 'TH' && document.activeElement.closest('thead') !== null`)),
+ chromedp.KeyEvent("\r"),
+ chromedp.Sleep(500*time.Millisecond),
+ harness.Into(&search, chromedp.Evaluate[string](`location.search`)),
+ )
+ if !onHeader || !strings.Contains(search, "sort=") {
+ t.Fatalf("the header by keyboard: reached %v, sorted %q", onHeader, search)
+ }
+}
diff --git a/internal/fichastest/edit_routes_test.go b/internal/fichastest/edit_routes_test.go
index 5af3cac..4b6a7a5 100644
--- a/internal/fichastest/edit_routes_test.go
+++ b/internal/fichastest/edit_routes_test.go
@@ -117,7 +117,7 @@ func TestAFieldSavesAtOnceWithScript(t *testing.T) {
code, out = postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{
fichas.FieldStage: {"Lost"}, "was." + fichas.FieldStage: {"Lead"},
})
- if code != http.StatusConflict || out["message"] != "ana changed this to Won a moment ago." || out["theirs"] != "Won" {
+ if code != http.StatusConflict || out["message"] != "You changed this to Won in another tab." || out["theirs"] != "Won" {
t.Fatalf("a stale edit: %d %v", code, out)
}
// Unknown fields and cards are the app's 404.
@@ -446,3 +446,68 @@ func TestDatesAreWrittenInTheReadersLocale(t *testing.T) {
}
}
}
+
+// The scriptless forms change only what a person changed (§5.2): an
+// untouched web address drawn without its scheme, and a Choice the field
+// no longer offers, are kept, not rewritten or cleared (Fable, Phase 1
+// review, L1 and L2).
+func TestTheFormKeepsWhatWasNotTouched(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldDomain: "http://cnoc.example", fichas.FieldStage: "Lead"})
+ m, _ := fichas.EnsureMember(t.Context(), r.d.G, r.cfg.Sealer, TestOwner)
+ if err := fichas.UpdateField(t.Context(), r.d.G, r.cfg.Sealer, fichas.FieldStage, fichas.Person(m.ID), "Stage", []string{"Contacted", "Won"}); err != nil {
+ t.Fatal(err)
+ }
+ form := get(t, r.h, cardPath(id)+"/edit").Body.String()
+ if !strings.Contains(form, `<option value="Lead" selected>Lead (no longer offered)</option>`) {
+ t.Fatal("the form does not keep a Choice the field no longer offers")
+ }
+ // The form as drawn, with only the email typed.
+ rec := post(t, r.h, cardPath(id), url.Values{
+ fichas.FieldName: {"Cnoc"}, "was." + fichas.FieldName: {"Cnoc"},
+ fichas.FieldDomain: {"http://cnoc.example"}, "was." + fichas.FieldDomain: {"http://cnoc.example"},
+ fichas.FieldStage: {"Lead"}, "was." + fichas.FieldStage: {"Lead"},
+ fichas.FieldEmail: {"a@b.example"}, "was." + fichas.FieldEmail: {""},
+ })
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("saving the form: %d", rec.Code)
+ }
+ if r.value(t, id, fichas.FieldDomain) != "http://cnoc.example" || r.value(t, id, fichas.FieldStage) != "Lead" {
+ t.Fatalf("an untouched field changed: domain %q, stage %q", r.value(t, id, fichas.FieldDomain), r.value(t, id, fichas.FieldStage))
+ }
+ // The address as the field draws it, without its scheme, is no change.
+ if code, out := postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldDomain, url.Values{
+ fichas.FieldDomain: {"cnoc.example"}, "was." + fichas.FieldDomain: {"http://cnoc.example"},
+ }); code != 200 || out["event"].(float64) != 0 {
+ t.Fatalf("an untouched address: %d %v", code, out)
+ }
+}
+
+// A refused number on the New form comes back as typed (L3).
+func TestARefusedNumberComesBackAsTyped(t *testing.T) {
+ r := newEditRig(t)
+ rec := post(t, r.h, "/cards", url.Values{"type": {"t_customer"}, fichas.FieldName: {"Cnoc"}, r.budget: {"1,5"}, r.budget + ".locale": {"en-IE"}})
+ if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `value="1,5"`) {
+ t.Fatalf("a refused number: %d, typed value kept %v", rec.Code, strings.Contains(rec.Body.String(), `value="1,5"`))
+ }
+}
+
+// A scriptless Undo that left a field says so (§5.3; L5).
+func TestAPartialUndoSaysWhatItLeft(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldStage: "Lead"})
+ rec := post(t, r.h, cardPath(id), url.Values{
+ fichas.FieldStage: {"Won"}, "was." + fichas.FieldStage: {"Lead"},
+ fichas.FieldEmail: {"a@b.example"}, "was." + fichas.FieldEmail: {""},
+ })
+ event := strings.TrimPrefix(rec.Header().Get("Location"), cardPath(id)+"?saved=")
+ m, _ := fichas.EnsureMember(t.Context(), r.d.G, r.cfg.Sealer, "niamh@example.com")
+ if _, err := fichas.SetField(t.Context(), r.d.G, r.cfg.Sealer, id, fichas.Person(m.ID), fichas.FieldStage, "Lost", "Won"); err != nil {
+ t.Fatal(err)
+ }
+ undo := post(t, r.h, cardPath(id)+"/undo", url.Values{"event": {event}})
+ page := get(t, r.h, undo.Header().Get("Location")).Body.String()
+ if !strings.Contains(page, "Undone, except where it was changed again since.") {
+ t.Fatalf("a partial Undo does not say what it left (%s)", undo.Header().Get("Location"))
+ }
+}
diff --git a/internal/fichastest/formats_markup_test.go b/internal/fichastest/formats_markup_test.go
new file mode 100644
index 0000000..c2eddb3
--- /dev/null
+++ b/internal/fichastest/formats_markup_test.go
@@ -0,0 +1,55 @@
+package fichastest
+
+import (
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+// LU17's template check (§6.8): Fichas renders through ui.Funcs, where a
+// locale function called without the reader's localizer silently formats
+// in English. So every call of one names L first, and commas is gone.
+//
+// Mutation, 2026-11-17: {{number .Result.Total}} in index.html failed it.
+func TestEveryLocaleCallNamesTheReadersLocalizer(t *testing.T) {
+ call := regexp.MustCompile(`[{(]-?\s*(number|money|showNumber|showValue|seed|count|ago|dateAgo|stamp|longDate|editField)\s+(\S+)`)
+ paths, _ := filepath.Glob(filepath.Join("..", "fichas", "templates", "*.html"))
+ for _, path := range paths {
+ body := read(t, path)
+ if strings.Contains(body, "commas") {
+ t.Errorf("%s still calls commas", filepath.Base(path))
+ }
+ for _, m := range call.FindAllStringSubmatch(body, -1) {
+ fn, arg := m[1], strings.TrimRight(m[2], ")}")
+ if fn == "editField" {
+ continue // its localizer is its third argument, checked below
+ }
+ if arg != "$.L" && arg != ".L" && arg != "$L" {
+ t.Errorf("%s: {{%s %s}} does not name the reader's localizer first", filepath.Base(path), fn, arg)
+ }
+ }
+ for _, m := range regexp.MustCompile(`editField \S+ \S+ (\S+?)\)`).FindAllStringSubmatch(body, -1) {
+ if m[1] != "$L" && m[1] != "$.L" && m[1] != ".L" {
+ t.Errorf("%s: editField's localizer is %s", filepath.Base(path), m[1])
+ }
+ }
+ }
+ // And no handler writes a date for a person with time.Format: dates
+ // go through the reader's locale (render.go's ago, stamp, longDate).
+ gos, _ := filepath.Glob(filepath.Join("..", "fichas", "*.go"))
+ people := regexp.MustCompile(`\.Format\("2 January|\.Format\("Jan`)
+ for _, path := range gos {
+ if strings.HasSuffix(path, "_test.go") {
+ continue
+ }
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if people.Match(b) {
+ t.Errorf("%s formats a date for a person outside the reader's locale", filepath.Base(path))
+ }
+ }
+}