From 2453b598def94649cc7ce9af7155bfaad40cce12 Mon Sep 17 00:00:00 2001 From: Lukasz Kasprzak Date: Fri, 24 Jul 2026 15:01:03 +0200 Subject: web: /settings page to edit config + books.toml, persisted and applied live; v0.14.0 --- internal/bible/booktable.go | 4 + internal/config/config.go | 74 +++++++++++++- internal/config/config_test.go | 25 +++++ internal/web/server.go | 193 +++++++++++++++++++++++++++++++++-- internal/web/server_test.go | 68 ++++++++++++ internal/web/static/base.css | 7 ++ internal/web/templates/index.html | 1 + internal/web/templates/reader.html | 1 + internal/web/templates/settings.html | 115 +++++++++++++++++++++ 9 files changed, 481 insertions(+), 7 deletions(-) create mode 100644 internal/web/templates/settings.html (limited to 'internal') diff --git a/internal/bible/booktable.go b/internal/bible/booktable.go index 007e75e..9ec95be 100644 --- a/internal/bible/booktable.go +++ b/internal/bible/booktable.go @@ -88,6 +88,10 @@ func mustReadEmbedded() []byte { return b } +// DefaultBooksTOML returns the embedded default books.toml (the seed the +// /settings editor shows when the user has no override yet). +func DefaultBooksTOML() []byte { return mustReadEmbedded() } + func parseBooks(data []byte) (map[string]map[string][]string, error) { var raw map[string]map[string][]string if err := toml.Unmarshal(data, &raw); err != nil { diff --git a/internal/config/config.go b/internal/config/config.go index 3428ae8..a4d2c3e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,6 +11,7 @@ import ( "fmt" "os" "path/filepath" + "sort" "strings" "github.com/pelletier/go-toml/v2" @@ -24,7 +25,7 @@ var seedTOML []byte // Version is lectio's release version, shared by every binary's // -v/--version output (lectio, lectio-ui, lectio-web). -const Version = "0.13.1" +const Version = "0.14.0" // validVersions are the five scripture versions lectio understands. var validVersions = map[string]bool{ @@ -300,3 +301,74 @@ func validate(cfg Config) error { } return nil } + +// Validate exposes the semantic checks Load applies, so callers that build a +// Config (the web /settings form) can reject an invalid one before saving. +func Validate(cfg Config) error { return validate(cfg) } + +// Save writes cfg to the config file (configPath, honoring LECTIO_CONFIG), +// creating the directory if needed, as commented TOML (regenerated -- the +// explanatory comments are kept, the values are cfg's). +func Save(cfg Config) error { + path, _, err := configPath() + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return os.WriteFile(path, renderConfigTOML(cfg), 0o644) +} + +func tomlStr(s string) string { return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` } + +func tomlStrSlice(ss []string) string { + q := make([]string, len(ss)) + for i, s := range ss { + q[i] = tomlStr(s) + } + return "[" + strings.Join(q, ", ") + "]" +} + +// renderConfigTOML regenerates config.toml from cfg, preserving the seed's +// field comments. Parts (the per-lectionary hide map) is written back verbatim +// so a config that had [parts.*] sections keeps them across a Save. +func renderConfigTOML(cfg Config) []byte { + var b strings.Builder + fmt.Fprintf(&b, "schema_version = %d\n", cfg.SchemaVersion) + fmt.Fprintf(&b, "lectionary = %s # \"new\" (niedziela.pl) or \"traditional\" (missalemeum, 1962)\n", tomlStr(cfg.Lectionary)) + fmt.Fprintf(&b, "traditional_lang = %s # vernacular for traditional propers: \"pl\" or \"en\"\n", tomlStr(cfg.TraditionalLang)) + fmt.Fprintf(&b, "versions = %s # compare set + TUI cycle order (bt = Biblia Tysiąclecia)\n", tomlStrSlice(cfg.Versions)) + fmt.Fprintf(&b, "default_version = %s # TUI start / `lectio -b` default\n", tomlStr(cfg.DefaultVersion)) + fmt.Fprintf(&b, "width = %d # CLI wrap width; 0 = detect terminal\n", cfg.Width) + fmt.Fprintf(&b, "all = %t # all parts (true) or just the gospel (false)\n", cfg.All) + fmt.Fprintf(&b, "offline = %t # true = never fetch; read only cache + harvested sigla\n", cfg.Offline) + fmt.Fprintf(&b, "ui_language = %s # interface language: \"en\" or \"pl\" (readings stay source-language)\n", tomlStr(cfg.UILanguage)) + fmt.Fprintf(&b, "sigla_style = %s # citation dialect for --ref/--list/--citation: \"auto\", \"polish\", \"english\"\n", tomlStr(cfg.SiglaStyle)) + fmt.Fprintf(&b, "web_theme = %s # default lectio-web theme\n", tomlStr(cfg.WebTheme)) + fmt.Fprintf(&b, "web_port = %d # lectio-web port; 0 = try 1099, then any free port\n", cfg.WebPort) + fmt.Fprintf(&b, "web_display = %s # lectio-web layout: \"horizontal\", \"vertical\", \"interlinear\"\n", tomlStr(cfg.WebDisplay)) + fmt.Fprintf(&b, "web_mono = %t # lectio-web: monospace reading face\n", cfg.WebMono) + fmt.Fprintf(&b, "web_versions = %s # which versions start toggled on; empty = just default_version\n", tomlStrSlice(cfg.WebVersions)) + fmt.Fprintf(&b, "pager = %s # pager for `lectio` output; \"\" = off\n", tomlStr(cfg.Pager)) + + // Preserve the parts map (not edited by the form) so [parts.*] survives Save. + lects := make([]string, 0, len(cfg.Parts)) + for l := range cfg.Parts { + lects = append(lects, l) + } + sort.Strings(lects) + for _, l := range lects { + parts := cfg.Parts[l] + keys := make([]string, 0, len(parts)) + for k := range parts { + keys = append(keys, k) + } + sort.Strings(keys) + fmt.Fprintf(&b, "\n[parts.%s]\n", l) + for _, k := range keys { + fmt.Fprintf(&b, "%s = %t\n", k, parts[k]) + } + } + return []byte(b.String()) +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go index cc0c941..53a3980 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -199,6 +199,31 @@ func TestSiglaStyleDefaultsAndDialect(t *testing.T) { } } +func TestSaveRoundTrip(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + t.Setenv("LECTIO_CONFIG", path) + + cfg := Default() + cfg.UILanguage = "pl" + cfg.SiglaStyle = "english" + cfg.WebMono = true + cfg.WebVersions = []string{"wuj", "vul"} + cfg.Pager = "less -R" + cfg.Parts = map[string]map[string]bool{"new": {"psalm": false}} + if err := Save(cfg); err != nil { + t.Fatal(err) + } + got, err := Load() + if err != nil { + t.Fatalf("reload: %v", err) + } + if got.UILanguage != "pl" || got.SiglaStyle != "english" || !got.WebMono || + len(got.WebVersions) != 2 || got.Pager != "less -R" || got.PartShown("new", "psalm") { + t.Errorf("round-trip mismatch: %+v", got) + } +} + func TestPartShown(t *testing.T) { var empty Config if !empty.PartShown("new", "psalm") { diff --git a/internal/web/server.go b/internal/web/server.go index 7c90e9e..34371b7 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -12,11 +12,13 @@ import ( "io/fs" "net" "net/http" + "os" "os/exec" "regexp" "runtime" "strconv" "strings" + "sync" "time" "github.com/lukaszkasprzak/lectio/internal/bible" @@ -32,18 +34,40 @@ import ( // every visitor sees the same five choices regardless of their config file. var bibleVersions = []string{"bt", "wuj", "vul", "grb", "drb"} +// server holds the live, mutable config + book table so /settings can apply +// changes to the running process. All handlers read a snapshot via get()/table(). +type server struct { + mu sync.RWMutex + cfg config.Config + tbl *bible.BookTable +} + +func (s *server) get() config.Config { s.mu.RLock(); defer s.mu.RUnlock(); return s.cfg } +func (s *server) table() *bible.BookTable { s.mu.RLock(); defer s.mu.RUnlock(); return s.tbl } +func (s *server) apply(cfg config.Config, tbl *bible.BookTable) { + s.mu.Lock() + defer s.mu.Unlock() + s.cfg = cfg + if tbl != nil { + s.tbl = tbl + } +} + // NewServer builds lectio-web's route tree. cfg supplies the defaults // (lectionary, versions, theme, offline) that requests can override via -// query parameters; it is never mutated. +// query parameters; it is never mutated -- /settings applies changes to a +// live, mutable copy held by server, which every handler reads per request. func NewServer(cfg config.Config) http.Handler { tbl, _ := bible.LoadBookTable(config.UserBooksTOML()) + s := &server{cfg: cfg, tbl: tbl} mux := http.NewServeMux() - - mux.HandleFunc("GET /{$}", indexHandler(cfg)) - mux.HandleFunc("GET /readings", readingsHandler(cfg)) - mux.HandleFunc("GET /reader", readerHandler(cfg, tbl)) - mux.HandleFunc("GET /theme.css", themeCSSHandler(cfg)) + mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { indexHandler(s.get())(w, r) }) + mux.HandleFunc("GET /readings", func(w http.ResponseWriter, r *http.Request) { readingsHandler(s.get())(w, r) }) + mux.HandleFunc("GET /reader", func(w http.ResponseWriter, r *http.Request) { readerHandler(s.get(), s.table())(w, r) }) + mux.HandleFunc("GET /theme.css", func(w http.ResponseWriter, r *http.Request) { themeCSSHandler(s.get())(w, r) }) + mux.HandleFunc("GET /settings", settingsGet(s)) + mux.HandleFunc("POST /settings", settingsPost(s)) staticSub, err := fs.Sub(staticFS, "static") if err != nil { @@ -508,6 +532,163 @@ func themeCSSHandler(cfg config.Config) http.HandlerFunc { } } +// settingsData drives templates/settings.html. +type settingsData struct { + Cfg config.Config + Books string // current books.toml text (user override, else the embedded default) + ThemeOpts []themeOpt // for the web_theme diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html new file mode 100644 index 0000000..bea6fb9 --- /dev/null +++ b/internal/web/templates/settings.html @@ -0,0 +1,115 @@ +{{/* settings.html — lectio-web /settings page: a form for every config + setting plus a raw books.toml editor. A plain POST form (no htmx) -- + saving redirects (PRG) back here with ?saved=1. On a validation error + the form re-renders with the submitted values and an inline message + instead of redirecting. Self-contained and theme-aware, like index.html. */}} + + + + + +lectio — settings + + + + + +
+ +

← {{.L.BannerReadings}}

+ + {{if .Saved}}

Saved.

{{end}} + {{if .Error}}

{{.Error}}

{{end}} + +
+ + + + + + + + + + + + + + + +
+ versions + {{range .VersionOpts}}{{end}} +
+ +
+ web versions + {{range .WebVersionOpts}}{{end}} +
+ +
+ + + +
+ + + + + + + + + +
+ +
+ +
+ +
+ + -- cgit v1.3