oficina / fichas Public

Formats: numbers and counts in the reader's locale through rastrillo (level-up §6.8)

Every pack linked (locales/modern); FICHAS_LOCALE (default en-IE)
refuses boot unless it resolves without falling back; the formatting
locale follows Accept-Language, a bare language matching the team's
yields the team's; English words through rastrillo's base catalog.
Counts go through rastrillo's {{number}}; number values are drawn
ungrouped from the pack's decimal mark, and read by the interim strict
reading on the same data, with the unchanged-seed rule. commas retires.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev aab94d8eef9068932b46692a3f2b03b05a1756df parent 25e21c8
9 files changed, +561 −20
  • internal/fichas/app.go +3 −0
  • internal/fichas/config.go +7 −0
  • internal/fichas/formats.go +190 −0
  • internal/fichas/formats_test.go +117 −0
  • internal/fichas/handlers.go +2 −1
  • internal/fichas/list.go +8 −14
  • internal/fichas/numberread.go +227 −0
  • internal/fichas/render.go +6 −4
  • internal/fichas/templates/index.html +1 −1
diff --git a/internal/fichas/app.go b/internal/fichas/app.go
index fa4911f..27ed89f 100644
--- a/internal/fichas/app.go
+++ b/internal/fichas/app.go
@@ -65,6 +65,9 @@ func App(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error
// is born covered. Origin-checking, not tokens — nothing to mint
// or forget in a form.
r.Use(csrf.Protect(cfg.Origin))
+ // Every page carries the reader's localizer: English words, their
+ // own formats (level-up §6.8).
+ r.Use(a.withFormats)
// A path nothing answers is the app's 404 page, not chi's plain text.
r.NotFound(notFound)
diff --git a/internal/fichas/config.go b/internal/fichas/config.go
index eb3b4b3..c463ec7 100644
--- a/internal/fichas/config.go
+++ b/internal/fichas/config.go
@@ -56,6 +56,10 @@ type Config struct {
// (spec §6.5), from FICHAS_SUITE_CONSUMERS. None, and the routes do
// not exist.
SuiteConsumers []server.Consumer
+ // Locale is the team's formatting locale (level-up §6.8), from
+ // FICHAS_LOCALE: the CLDR locale a reader's numbers and dates are
+ // written in when their browser names none Fichas can use.
+ Locale string
}
// ErrMissing is returned when required platform config is absent.
@@ -167,6 +171,9 @@ func LoadConfig(getenv func(string) string) (Config, error) {
if err != nil {
return Config{}, err
}
+ if c.Locale, err = teamLocale(getenv("FICHAS_LOCALE")); err != nil {
+ return Config{}, err
+ }
return c, nil
}
diff --git a/internal/fichas/formats.go b/internal/fichas/formats.go
new file mode 100644
index 0000000..1762b44
--- /dev/null
+++ b/internal/fichas/formats.go
@@ -0,0 +1,190 @@
+package fichas
+
+// Formats: the reader's locale (level-up spec §6.8). Values are stored
+// canonical and locale-free; the reader's locale applies only where a
+// value is drawn and where what a person typed is read. The interface
+// stays English: the localizer carries English words and the reader's
+// formatting locale.
+
+import (
+ "fmt"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+
+ "amadan.net/rastrillo/rastrillo"
+ "amadan.net/rastrillo/rastrillo/locales"
+ "amadan.net/rastrillo/rastrillo/ui"
+)
+
+// defaultLocale is FICHAS_LOCALE's default: Paul's teams are in Ireland.
+const defaultLocale = "en-IE"
+
+// teamLocale is FICHAS_LOCALE, checked as rastrillo checks a configured
+// identity, and resolved to the linked CLDR locale that formats it. A
+// value that only works by falling back is refused, as an unknown zone
+// would be: a team default that silently became another is a default
+// nobody chose.
+func teamLocale(v string) (string, error) {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ v = defaultLocale
+ }
+ canon, err := locales.CanonicalIdentity(v)
+ if err != nil {
+ return "", fmt.Errorf("fichas: FICHAS_LOCALE is %q: %w", v, err)
+ }
+ id, ok := usableLocale(canon)
+ if !ok {
+ return "", fmt.Errorf("fichas: FICHAS_LOCALE is %q, which names no locale "+
+ "Fichas can format in; write a CLDR locale such as en-IE or de-DE", v)
+ }
+ return id, nil
+}
+
+// usableLocale is the linked locale tag resolves to, when it resolves
+// without falling back to a default.
+func usableLocale(tag string) (string, bool) {
+ res := locales.Resolve(tag)
+ if res.Malformed || res.UsedDefault || res.MissingPack != "" || res.ID == "" || res.ID == "root" {
+ return "", false
+ }
+ return res.ID, true
+}
+
+// formatLocale is the request's formatting locale: the browser's
+// Accept-Language, in q order, the first tag that resolves without
+// falling back; else the team's. A bare language that is the team
+// default's language is the team default, so a browser saying only
+// "en" gets en-IE on Paul's teams rather than CLDR's American en.
+func formatLocale(r *http.Request, team string) string {
+ teamLang, _, _ := strings.Cut(team, "-")
+ for _, tag := range acceptedTags(r.Header.Get("Accept-Language")) {
+ if !strings.Contains(tag, "-") && strings.EqualFold(tag, teamLang) {
+ return team
+ }
+ if id, ok := usableLocale(tag); ok {
+ return id
+ }
+ }
+ return team
+}
+
+// acceptedTags are an Accept-Language header's tags, highest q first,
+// as rastrillo's locale middleware orders them. A q of 0, "*" and an
+// empty tag are left out.
+func acceptedTags(header string) []string {
+ type pref struct {
+ tag string
+ q float64
+ }
+ var prefs []pref
+ for _, part := range strings.Split(header, ",") {
+ tag, params, _ := strings.Cut(strings.TrimSpace(part), ";")
+ tag, q := strings.TrimSpace(tag), 1.0
+ for _, p := range strings.Split(params, ";") {
+ if v, ok := strings.CutPrefix(strings.TrimSpace(p), "q="); ok {
+ if f, err := strconv.ParseFloat(v, 64); err == nil {
+ q = f
+ }
+ }
+ }
+ if tag == "" || tag == "*" || q <= 0 {
+ continue
+ }
+ prefs = append(prefs, pref{tag, q})
+ }
+ sort.SliceStable(prefs, func(i, j int) bool { return prefs[i].q > prefs[j].q })
+ out := make([]string, len(prefs))
+ for i, p := range prefs {
+ out[i] = p.tag
+ }
+ return out
+}
+
+// english is the one language Fichas speaks: rastrillo's base catalog,
+// for the framework partials' own strings.
+var english = func() func(string, ...any) string {
+ l, err := rastrillo.NewLocales([]string{"en"}, "en", rastrillo.BaseCatalog(), nil)
+ if err != nil {
+ panic("fichas: rastrillo's English catalog: " + err.Error())
+ }
+ return func(key string, args ...any) string { return l.Tf("en", key, args...) }
+}()
+
+var localizers sync.Map // format -> *ui.Localizer
+
+// localizerFor is English words with format's numbers and dates. One
+// per format, made once: a localizer holds no request state.
+func localizerFor(format string) *ui.Localizer {
+ if l, ok := localizers.Load(format); ok {
+ return l.(*ui.Localizer)
+ }
+ l, _ := localizers.LoadOrStore(format, ui.NewLocalizer("en", format, english))
+ return l.(*ui.Localizer)
+}
+
+// withFormats puts the reader's localizer on every request.
+func (a *app) withFormats(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ next.ServeHTTP(w, ui.WithLocalizer(r, localizerFor(formatLocale(r, a.cfg.Locale))))
+ })
+}
+
+// readerL is the request's localizer, or the team's when the middleware
+// did not run (a test calling a handler directly).
+func (a *app) readerL(r *http.Request) *ui.Localizer {
+ if l := ui.LocalizerFrom(r); l != nil {
+ return l
+ }
+ return localizerFor(a.cfg.Locale)
+}
+
+// rastrilloNumber is rastrillo's {{number}}, called from Go for the
+// sentences Fichas builds in code ("7 of 10 customers").
+var rastrilloNumber = ui.Funcs()["number"].(func(...any) (any, error))
+
+// count writes n in L's format, through rastrillo.
+func count(L *ui.Localizer, n int) string {
+ v, err := rastrilloNumber(L, n)
+ if err != nil {
+ return strconv.Itoa(n)
+ }
+ return fmt.Sprint(v)
+}
+
+// showNumber is a stored number as L's reader sees it. Until rastrillo's
+// {{number}} reads the packs (§6.8, R1), a number value is drawn from
+// the pack's data alone, in the form the interim reading reads: the
+// canonical digits, the pack's decimal mark, no group marks. x/text's
+// older data disagrees with the packs on marks in dozens of locales, and
+// a value drawn by one and read by the other could come back a thousand
+// times wrong. A stored value that is not canonical shows as stored.
+func showNumber(L *ui.Localizer, v string) string { return seedNumber(L.Format(), v) }
+
+// canonicalNumber reports whether v is in §6.2's canonical form: an
+// optional minus, digits with no leading zero, and a fraction with no
+// trailing zero; never "-0".
+func canonicalNumber(v string) bool {
+ neg := strings.HasPrefix(v, "-")
+ body := strings.TrimPrefix(v, "-")
+ whole, frac, hasFrac := strings.Cut(body, ".")
+ if whole == "" || !allDigits(whole) || (len(whole) > 1 && whole[0] == '0') {
+ return false
+ }
+ if hasFrac && (frac == "" || !allDigits(frac) || strings.HasSuffix(frac, "0")) {
+ return false
+ }
+ return !(neg && whole == "0" && !hasFrac)
+}
+
+func allDigits(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] < '0' || s[i] > '9' {
+ return false
+ }
+ }
+ return s != ""
+}
diff --git a/internal/fichas/formats_test.go b/internal/fichas/formats_test.go
new file mode 100644
index 0000000..ecad35b
--- /dev/null
+++ b/internal/fichas/formats_test.go
@@ -0,0 +1,117 @@
+package fichas
+
+import (
+ "net/http/httptest"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/locales"
+)
+
+// TestEveryDrawnNumberReadsBack is LU17's round trip: for every linked
+// locale, every number Fichas draws, grouped or as an editor's seed,
+// reads back through the interim reading as the same value.
+func TestEveryDrawnNumberReadsBack(t *testing.T) {
+ values := []string{"0", "7", "-12.5", "1200.5", "1234567.125", "0.001", "987654321", "-1000000", "123456789012345678901234567.125"}
+ failed := 0
+ for _, id := range locales.LinkedIDs() {
+ if id == "root" {
+ continue
+ }
+ L := localizerFor(id)
+ for _, v := range values {
+ for _, shown := range []string{showNumber(L, v), seedNumber(id, v)} {
+ got, err := readNumber(id, shown)
+ if err != nil || got != v {
+ failed++
+ if failed < 40 {
+ t.Errorf("%s: %s drawn as %q reads back as %q, %v", id, v, shown, got, err)
+ }
+ }
+ }
+ }
+ }
+ if failed > 0 {
+ t.Errorf("%d failures in all", failed)
+ }
+}
+
+func TestTheFormatLocaleFollowsTheBrowser(t *testing.T) {
+ for _, c := range []struct{ header, want string }{
+ {"de-DE,de;q=0.9,en;q=0.8", "de"},
+ {"en", "en-IE"},
+ {"en-US,en;q=0.9", "en"},
+ {"xx-YY, fr-FR;q=0.5", "fr"},
+ {"en-GB;q=0.2, de-CH;q=0.9", "de-CH"},
+ {"*", "en-IE"},
+ {"", "en-IE"},
+ {"!!", "en-IE"},
+ } {
+ r := httptest.NewRequest("GET", "/", nil)
+ r.Header.Set("Accept-Language", c.header)
+ if got := formatLocale(r, "en-IE"); got != c.want {
+ t.Errorf("Accept-Language %q: got %q, want %q", c.header, got, c.want)
+ }
+ }
+}
+
+func TestAnUnusableTeamLocaleRefusesBoot(t *testing.T) {
+ for _, bad := range []string{"xx", "en_IE", "not a locale", "zz-ZZ"} {
+ if _, err := teamLocale(bad); err == nil {
+ t.Errorf("FICHAS_LOCALE=%q was accepted", bad)
+ }
+ }
+ for v, want := range map[string]string{"": "en-IE", "de-DE": "de", "en-US": "en", "pt-PT": "pt-PT"} {
+ if got, err := teamLocale(v); err != nil || got != want {
+ t.Errorf("FICHAS_LOCALE=%q: got %q, %v; want %q", v, got, err, want)
+ }
+ }
+}
+
+func TestTheInterimReadingIsTheLocalesOwnOnly(t *testing.T) {
+ for _, c := range []struct{ locale, in, want string }{
+ {"en-IE", "1,200.5", "1200.5"},
+ {"en-IE", "1200.50", "1200.5"},
+ {"en-IE", ".5", "0.5"},
+ {"en-IE", "-0", "0"},
+ {"en-IE", "007", "7"},
+ {"de", "1.200,5", "1200.5"},
+ {"de", "1200,5", "1200.5"},
+ {"de", "1.500", "1500"},
+ {"fr", "1 200,5", "1200.5"},
+ {"fr", "1 200,5", "1200.5"},
+ {"hi", "12,34,567", "1234567"},
+ {"de-CH", "1'200.5", "1200.5"},
+ {"de-CH", "1’200.5", "1200.5"},
+ {"en-IE", "", ""},
+ } {
+ got, err := readNumber(c.locale, c.in)
+ if err != nil || got != c.want {
+ t.Errorf("%s %q: got %q, %v; want %q", c.locale, c.in, got, err, c.want)
+ }
+ }
+ for _, c := range []struct{ locale, in string }{
+ {"en-IE", "1,5"}, {"en-IE", "1.200,50"}, {"en-IE", "1e3"}, {"en-IE", "NaN"},
+ {"en-IE", "Inf"}, {"en-IE", "0x10"}, {"en-IE", "+5"}, {"en-IE", "1.2.3"},
+ {"en-IE", "1,,200"}, {"en-IE", "12,.5"}, {"en-IE", "1,200,"}, {"en-IE", "-"},
+ {"de", "1200.5"}, {"de", "1,200.5"}, {"en-IE", "1234567890123456789012345678901"},
+ {"en-IE", "€5"}, {"en-IE", "1 200"},
+ } {
+ if got, err := readNumber(c.locale, c.in); err == nil {
+ t.Errorf("%s %q was read as %q; want a refusal", c.locale, c.in, got)
+ }
+ }
+ if _, err := readNumber("de", "abc"); err == nil || err.Error() != "Enter a number, like 1200,5." {
+ t.Errorf("a German refusal says %v; want the example in German", err)
+ }
+}
+
+func TestAnUnchangedSeedIsTheStoredValue(t *testing.T) {
+ // 1.234 in German is "1,234", which a grouping reader could take for
+ // 1234: the unchanged seed is never read at all.
+ if got, err := readNumberInput("de", "1,234", "1.234"); err != nil || got != "1.234" {
+ t.Errorf("an unchanged German seed: got %q, %v", got, err)
+ }
+ if got, err := readNumberInput("en-IE", "1,200", "1200"); err != nil || got != "1200" {
+ t.Errorf("a typed 1,200 over 1200: got %q, %v", got, err)
+ }
+}
diff --git a/internal/fichas/handlers.go b/internal/fichas/handlers.go
index 48852f2..cf6058c 100644
--- a/internal/fichas/handlers.go
+++ b/internal/fichas/handlers.go
@@ -219,6 +219,7 @@ func (a *app) pageStatus(w http.ResponseWriter, r *http.Request, status int, nam
me, _ := a.identity(r)
data["Account"] = a.account(r, me)
data["Theme"] = themeAttr(r)
+ data["L"] = a.readerL(r)
if status != http.StatusOK {
w.WriteHeader(status)
}
@@ -363,7 +364,7 @@ func (a *app) index(w http.ResponseWriter, r *http.Request) {
"Density": densityOf(r),
"Here": l.href(), // the list as shown: a dropped sort stays dropped
"Pages": l.pages(res),
- "Count": countLine(res, filtered),
+ "Count": countLine(a.readerL(r), res, filtered),
"Filtered": filtered,
"TableHref": l.with(func(s *listState) { s.View = "table" }).href(),
"CardsHref": l.with(func(s *listState) { s.View = "cards" }).href(),
diff --git a/internal/fichas/list.go b/internal/fichas/list.go
index c137c4a..37c440b 100644
--- a/internal/fichas/list.go
+++ b/internal/fichas/list.go
@@ -1,6 +1,7 @@
package fichas
import (
+ "amadan.net/rastrillo/rastrillo/ui"
"fmt"
"net/http"
"net/url"
@@ -225,7 +226,8 @@ func (l listState) pages(res Result) []map[string]any {
}
// countLine says what the list is showing, in words.
-func countLine(res Result, filtered bool) string {
+func countLine(L *ui.Localizer, res Result, filtered bool) string {
+ num := func(n int) string { return count(L, n) }
noun := res.Plural
if res.All == 1 && !filtered {
noun = res.Label // "1 customer", not "1 customers"
@@ -234,26 +236,18 @@ func countLine(res Result, filtered bool) string {
case res.All == 0:
return ""
case filtered && res.Total == 0:
- return fmt.Sprintf("No %s match. %s in all.", lower(noun), commas(res.All))
+ return fmt.Sprintf("No %s match. %s in all.", lower(noun), num(res.All))
case filtered && res.Pages > 1:
- return fmt.Sprintf("%s–%s of %s matching %s (%s in all)", commas(res.First), commas(res.Last), commas(res.Total), lower(noun), commas(res.All))
+ return fmt.Sprintf("%s–%s of %s matching %s (%s in all)", num(res.First), num(res.Last), num(res.Total), lower(noun), num(res.All))
case filtered:
- return fmt.Sprintf("%s of %s %s", commas(res.Total), commas(res.All), lower(noun))
+ return fmt.Sprintf("%s of %s %s", num(res.Total), num(res.All), lower(noun))
case res.Pages > 1:
- return fmt.Sprintf("%s–%s of %s %s", commas(res.First), commas(res.Last), commas(res.All), lower(noun))
+ return fmt.Sprintf("%s–%s of %s %s", num(res.First), num(res.Last), num(res.All), lower(noun))
default:
- return fmt.Sprintf("%s %s", commas(res.All), lower(noun))
+ return fmt.Sprintf("%s %s", num(res.All), lower(noun))
}
}
-func commas(n int) string {
- s := strconv.Itoa(n)
- for i := len(s) - 3; i > 0; i -= 3 {
- s = s[:i] + "," + s[i:]
- }
- return s
-}
-
func lower(s string) string {
if s == "" {
return s
diff --git a/internal/fichas/numberread.go b/internal/fichas/numberread.go
new file mode 100644
index 0000000..fed142f
--- /dev/null
+++ b/internal/fichas/numberread.go
@@ -0,0 +1,227 @@
+package fichas
+
+// The interim number reading (level-up spec §6.8, "Phase 1 reads
+// numbers without R2"): the reader's own convention only, as
+// rastrillo's Strict money fields read, built on rastrillo's locale
+// data. One convention means one reading, so it is never ambiguous; it
+// never rounds and it writes the canonical form. It is deleted when
+// rastrillo's plain number reading (R2) lands in Phase 2.
+
+import (
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "amadan.net/rastrillo/rastrillo/locales"
+)
+
+// maxDigits is §6.2's bound on a number's digits.
+const maxDigits = 30
+
+// numberMarks are one locale's marks for plain numbers.
+type numberMarks struct {
+ decimal, group rune
+ primary, secondary int
+ minus rune
+ digits []rune // the locale's own ten digits
+}
+
+func marksFor(format string) numberMarks {
+ d, _ := locales.Data(format)
+ m := numberMarks{decimal: '.', group: ',', primary: 3, secondary: 3, minus: '-'}
+ if r, _ := utf8.DecodeRuneInString(d.Decimal); r != utf8.RuneError {
+ m.decimal = r
+ }
+ // rastrillo's packs carry the currency group mark and not yet the
+ // plain one (R1). It is read as a group mark only where it can never
+ // also be a decimal mark in this locale (§6.8): not when it is the
+ // decimal mark, and not where money's decimal mark differs from the
+ // ordinary one (fr-CH). Phase 1 draws numbers ungrouped, so nothing
+ // it draws needs the group mark read.
+ m.group = 0
+ if r, _ := utf8.DecodeRuneInString(d.CurrencyGroup); r != utf8.RuneError &&
+ d.CurrencyGroup != d.Decimal && (d.CurrencyDecimal == "" || d.CurrencyDecimal == d.Decimal) {
+ m.group = foldSpaceRune(r)
+ }
+ if r, _ := utf8.DecodeRuneInString(d.Minus); r != utf8.RuneError {
+ m.minus = r
+ }
+ m.digits = []rune(d.Digits)
+ if p, s := patternGrouping(d.Standard); p > 0 {
+ m.primary, m.secondary = p, s
+ }
+ return m
+}
+
+// patternGrouping reads a CLDR pattern's group sizes: "#,##,##0.00" is
+// 3 then 2.
+func patternGrouping(pattern string) (int, int) {
+ pos, _, _ := strings.Cut(pattern, ";")
+ start := strings.IndexAny(pos, "#0,.")
+ end := strings.LastIndexAny(pos, "#0,.") + 1
+ if start < 0 || end <= start {
+ return 0, 0
+ }
+ intPart, _, _ := strings.Cut(pos[start:end], ".")
+ groups := strings.Split(intPart, ",")
+ if len(groups) < 2 {
+ return 0, 0
+ }
+ primary := len(groups[len(groups)-1])
+ secondary := primary
+ if len(groups) > 2 {
+ secondary = len(groups[len(groups)-2])
+ }
+ return primary, secondary
+}
+
+// foldSpaceRune makes every space one mark, and U+2019 the apostrophe,
+// as rastrillo's Clean and money parser treat them.
+func foldSpaceRune(r rune) rune {
+ if unicode.IsSpace(r) || unicode.In(r, unicode.Zs) {
+ return ' '
+ }
+ if r == '\u2019' {
+ return '\''
+ }
+ return r
+}
+
+// numberError is a refused number, with an example in the reader's own
+// format.
+type numberError struct{ example string }
+
+func (e numberError) Error() string { return "Enter a number, like " + e.example + "." }
+
+// readNumber reads s in format's own convention into the canonical
+// form. Blank is "", nil: whether blank is allowed is the field's call.
+func readNumber(format, s string) (string, error) {
+ m := marksFor(format)
+ refuse := numberError{example: seedNumber(format, "1200.5")}
+ s = cleanNumber(s)
+ if s == "" {
+ return "", nil
+ }
+ negative := false
+ if r, size := utf8.DecodeRuneInString(s); r == '-' || r == '−' || r == m.minus {
+ negative, s = true, s[size:]
+ }
+ whole, frac, ok := splitNumber(s, m)
+ if !ok || len(whole)+len(frac) > maxDigits || whole+frac == "" {
+ return "", refuse
+ }
+ return canonicalOf(negative, whole, frac), nil
+}
+
+// cleanNumber drops bidi marks and folds every space to U+0020, as
+// rastrillo's currency.Clean does, then trims.
+func cleanNumber(s string) string {
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r == '‎' || r == '‏' || r == '؜' || (r >= '‪' && r <= '‮') || (r >= '⁦' && r <= '⁩'):
+ default:
+ b.WriteRune(foldSpaceRune(r))
+ }
+ }
+ return strings.TrimSpace(b.String())
+}
+
+// splitNumber reads digits, the group mark at valid positions only and
+// the decimal mark once, into ASCII whole and fraction digits.
+func splitNumber(s string, m numberMarks) (whole, frac string, ok bool) {
+ var groups []string
+ var cur strings.Builder
+ sawDecimal, sawGroup := false, false
+ for _, r := range s {
+ d, isDigit := digitOf(r, m.digits)
+ switch {
+ case isDigit:
+ cur.WriteByte(d)
+ case r == m.decimal && !sawDecimal:
+ groups, sawDecimal = append(groups, cur.String()), true
+ cur.Reset()
+ case m.group != 0 && r == m.group && !sawDecimal && cur.Len() > 0:
+ groups, sawGroup = append(groups, cur.String()), true
+ cur.Reset()
+ default:
+ return "", "", false
+ }
+ }
+ if sawDecimal {
+ frac = cur.String()
+ if frac == "" && (len(groups) == 0 || groups[len(groups)-1] == "") {
+ return "", "", false
+ }
+ } else {
+ groups = append(groups, cur.String())
+ }
+ if sawGroup && !validGroups(groups, m.primary, m.secondary) {
+ return "", "", false
+ }
+ return strings.Join(groups, ""), frac, true
+}
+
+// validGroups: the last group has the primary size, earlier ones the
+// secondary size, and the first one to the secondary size.
+func validGroups(groups []string, primary, secondary int) bool {
+ n := len(groups)
+ if n < 2 || len(groups[n-1]) != primary {
+ return false
+ }
+ for i := 1; i < n-1; i++ {
+ if len(groups[i]) != secondary {
+ return false
+ }
+ }
+ return len(groups[0]) >= 1 && len(groups[0]) <= secondary
+}
+
+func digitOf(r rune, local []rune) (byte, bool) {
+ if r >= '0' && r <= '9' {
+ return byte(r), true
+ }
+ for i, l := range local {
+ if r == l && i < 10 {
+ return byte('0' + i), true
+ }
+ }
+ return 0, false
+}
+
+func canonicalOf(negative bool, whole, frac string) string {
+ whole = strings.TrimLeft(whole, "0")
+ if whole == "" {
+ whole = "0"
+ }
+ frac = strings.TrimRight(frac, "0")
+ out := whole
+ if frac != "" {
+ out += "." + frac
+ }
+ if negative && out != "0" {
+ out = "-" + out
+ }
+ return out
+}
+
+// seedNumber is a canonical number as an editor starts from it: the
+// reader's decimal mark and no group marks (§6.8), so it reads back as
+// itself under every reading. ASCII digits, which every reading takes.
+func seedNumber(format, canonical string) string {
+ if !canonicalNumber(canonical) {
+ return canonical
+ }
+ m := marksFor(format)
+ return strings.Replace(canonical, ".", string(m.decimal), 1)
+}
+
+// readNumberInput is what a posted number means: was itself when the
+// text is was's own seed (the unchanged-seed rule, §6.8), otherwise the
+// strict reading.
+func readNumberInput(format, posted, was string) (string, error) {
+ if was != "" && cleanNumber(posted) == seedNumber(format, was) {
+ return was, nil
+ }
+ return readNumber(format, posted)
+}
diff --git a/internal/fichas/render.go b/internal/fichas/render.go
index 14099b0..0bf964a 100644
--- a/internal/fichas/render.go
+++ b/internal/fichas/render.go
@@ -13,9 +13,10 @@ import (
"amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/ui"
- // The en pack: rastrillo refuses to start without the packs for the
- // locales it is configured with, and Fichas speaks English.
- _ "amadan.net/rastrillo/rastrillo/locales/en"
+ // Every pack: Fichas speaks English, but writes numbers and dates in
+ // each reader's own format (level-up §6.8), so any reader's locale
+ // must be linked. 420 KB on a 28 MB binary, measured at b791bdd.
+ _ "amadan.net/rastrillo/rastrillo/locales/modern"
"amadan.net/oficina/fichas/internal/fichas/icons"
)
@@ -56,7 +57,8 @@ func init() {
"stageTone": stageTone,
"isLong": isLong,
"lower": lower,
- "commas": commas,
+ "count": count,
+ "showNumber": showNumber,
"errFor": errFor,
"yesNo": yesNo,
"displayURL": displayURL,
diff --git a/internal/fichas/templates/index.html b/internal/fichas/templates/index.html
index 54aebed..2b7b752 100644
--- a/internal/fichas/templates/index.html
+++ b/internal/fichas/templates/index.html
@@ -1,7 +1,7 @@
{{define "title"}}{{.Result.Plural}} · Fichas{{end}}
{{define "content"}}
<header fichas-appbar>
- <h1 fichas-appbar-title>{{.Result.Plural}}{{if .Result.All}} <span>{{commas .Result.All}} {{if eq .Result.All 1}}record{{else}}records{{end}}</span>{{end}}</h1>
+ <h1 fichas-appbar-title>{{.Result.Plural}}{{if .Result.All}} <span>{{number $.L .Result.All}} {{if eq .Result.All 1}}record{{else}}records{{end}}</span>{{end}}</h1>
<div fichas-appbar-actions><a rst-btn="primary" href="/cards/new?type={{.TypeKey}}">{{icon "plus"}} Add a {{lower .Result.Label}}</a></div>
</header>