1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
|
// Package web renders lectio's daily readings as an HTML fragment and
// serves a set of "colour only" theme stylesheets (see docs/THEMES.md) that
// restyle a fixed set of role classes/variables; it never lays out or types
// anything itself -- that lives in the embedded base.css. It consumes
// liturgy.Section and render.GatherVersion, never the reverse.
package web
import (
"bytes"
"embed"
"fmt"
"html/template"
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/lukaszkasprzak/lectio/internal/bible"
"github.com/lukaszkasprzak/lectio/internal/i18n"
"github.com/lukaszkasprzak/lectio/internal/liturgy"
"github.com/lukaszkasprzak/lectio/internal/render"
)
//go:embed templates
var templatesFS embed.FS
//go:embed static
var staticFS embed.FS
// tmpl holds every parsed templates/*.html, keyed by base file name (so
// "readings.html" is looked up as "readings.html").
var tmpl = template.Must(template.ParseFS(templatesFS, "templates/*.html"))
// verseNumRe matches a bible verse block's "chapter:verse " prefix, as
// produced by render.GatherVersion (e.g. "3:16 Tak bowiem..."). Mirrors
// internal/tui's verseNumRe.
var verseNumRe = regexp.MustCompile(`^(\d+:\d+) (.*)$`)
// sectionView, columnView and blockView are the data readings.html ranges
// over: one sectionView per liturgy.Section, one columnView per requested
// version, one blockView per render.GatherVersion block.
type sectionView struct {
Heading, Subtitle, PartID string
Columns []columnView
}
type columnView struct {
Label string
Blocks []blockView
}
// blockView is one paragraph or verse line. VNum is set (and Text holds
// only the verse text) when the block was a bible verse line; otherwise
// VNum is empty and Text holds the whole block, with Refrain set for a
// responsorial psalm's deduped first ("bt") block.
type blockView struct {
VNum, Text string
Refrain bool
}
// ilSectionView, ilVerseView and ilLineView are what
// templates/readings-interlinear.html ranges over: one ilSectionView per
// liturgy.Section, one ilVerseView per chapter:verse key (in ordered-union
// order, see buildInterlinearViews), one ilLineView per version that carries
// that verse. Note holds a short escaped message in place of Verses when no
// requested version could be interleaved for the section.
type ilSectionView struct {
Heading, Subtitle, PartID string
Verses []ilVerseView
Note string
}
type ilVerseView struct {
VNum string
Lines []ilLineView
}
type ilLineView struct {
Label, Text string
}
// RenderReadings builds the reading pane fragment for one of three layouts:
//
// - "horizontal" (or anything unrecognized): the original stacked layout,
// one column per version rendered under a shared heading, unchanged.
// - "vertical": the same per-version columns side by side in a
// ".display-vertical" grid, like the CLI `compare` view.
// - "interlinear": versions interleaved verse-by-verse by chapter:verse
// (see buildInterlinearViews); "bt" cannot participate (no verse
// numbers) and is substituted/dropped via render.OfflineVersions'
// bt->wuj transform before gathering.
//
// In every mode, heading, citation (subtitle), verse-number and refrain
// text are wrapped in class="heading|citation|vnum|refrain|version-label"
// spans so theme CSS can restyle them; verse/paragraph text is escaped by
// html/template. lang localises the version-column labels and each section
// heading's part-label word (render.LocalizeHeading, brief §3b); the
// citation/verse text is never touched. dayInfo is rendered once, ahead of
// every layout's own sections, as the day's celebration header (see
// renderDayInfo) -- never translated (source-language, like the readings/
// citations), and simply omitted when the source carried none.
func RenderReadings(secs []liturgy.Section, versions []string, lectionary, display, lang string, dayInfo liturgy.DayInfo) template.HTML {
var body template.HTML
switch display {
case "vertical":
body = renderTemplate("readings-vertical.html", buildColumnViews(secs, versions, lectionary, lang))
case "interlinear":
body = renderTemplate("readings-interlinear.html", buildInterlinearViews(secs, versions, lectionary, lang))
default:
body = renderTemplate("readings.html", buildColumnViews(secs, versions, lectionary, lang))
}
return renderDayInfo(dayInfo) + body
}
// renderDayInfo builds the "<p class="dayinfo">" header RenderReadings
// prepends to the reading pane: the celebration Name as its heading-role
// span, the temporal Season (if any) as its citation-role span. Reusing
// those two role classes (rather than inventing new ones) means every
// existing theme restyles it identically without a new CSS rule -- see
// base.css/docs/THEMES.md. Returns "" (the header is simply omitted, never
// an error) when the source yielded no DayInfo (info.Name == "").
func renderDayInfo(info liturgy.DayInfo) template.HTML {
if info.Name == "" {
return ""
}
var b strings.Builder
b.WriteString(`<p class="dayinfo"><span class="heading">`)
b.WriteString(template.HTMLEscapeString(info.Name))
b.WriteString(`</span>`)
if info.Season != "" {
b.WriteString(` <span class="citation">`)
b.WriteString(template.HTMLEscapeString(info.Season))
b.WriteString(`</span>`)
}
b.WriteString(`</p>`)
return template.HTML(b.String())
}
// renderTemplate executes the named embedded template with data, degrading
// to a visible, escaped error paragraph on failure (should be unreachable:
// the templates are embedded and fixed at build time) rather than panicking
// a request handler in the caller.
func renderTemplate(name string, data any) template.HTML {
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
return template.HTML("<p class=\"error\">" + template.HTMLEscapeString(err.Error()) + "</p>")
}
return template.HTML(buf.String())
}
// buildColumnViews gathers each section's per-version columns via
// render.GatherVersion -- the shared data both the "horizontal"
// (readings.html) and "vertical" (readings-vertical.html) templates range
// over; only the surrounding markup differs between the two layouts. lang
// localises the column labels and the heading's part-label word (see
// RenderReadings).
func buildColumnViews(secs []liturgy.Section, versions []string, lectionary, lang string) []sectionView {
views := make([]sectionView, 0, len(secs))
for _, sec := range secs {
isPsalm := sec.PartID == "psalm"
cols := make([]columnView, 0, len(versions))
for _, v := range versions {
label, blocks := render.GatherVersion(v, sec, lectionary, lang)
bviews := make([]blockView, 0, len(blocks))
for bi, b := range blocks {
// A bible verse line always carries its "chapter:verse "
// prefix; only text without one (i.e. the "bt" version's
// paragraphs) can be the deduped psalm refrain -- matches
// internal/tui's styleBlock precedence.
if m := verseNumRe.FindStringSubmatch(b); m != nil {
bviews = append(bviews, blockView{VNum: m[1], Text: m[2]})
continue
}
bviews = append(bviews, blockView{Text: b, Refrain: isPsalm && bi == 0})
}
cols = append(cols, columnView{Label: label, Blocks: bviews})
}
views = append(views, sectionView{
Heading: render.LocalizeHeading(sec.Heading, sec.PartID, lang),
Subtitle: sec.Subtitle,
PartID: sec.PartID,
Columns: cols,
})
}
return views
}
// interlinearVersions maps versions through the same bt->wuj substitution
// render.OfflineVersions performs for offline mode: "bt" (niedziela.pl
// paragraph text) carries no verse numbers and cannot interleave, so it is
// dropped, substituting "wuj" (the Polish-language bible version) in its
// place unless "wuj" was already selected. Reuses render.OfflineVersions
// rather than duplicating its two-line transform.
func interlinearVersions(versions []string) []string {
return render.OfflineVersions(versions)
}
// verseSet is one version's verses plus its column label, the unit both the
// interlinear readings view and the reader passage view interleave over.
type verseSet struct {
label string
verses []bible.Verse
}
// interleaveVerses interleaves several versions' verses by chapter:verse: the
// ordered union of keys follows the first set's verse order, then any key only
// a later set has is appended in that set's order (stable, no duplicates).
func interleaveVerses(sets []verseSet) []ilVerseView {
type vkey struct{ chapter, verse int }
order := make([]vkey, 0)
seen := map[vkey]bool{}
bySet := make([]map[vkey]bible.Verse, len(sets))
for i, s := range sets {
m := make(map[vkey]bible.Verse, len(s.verses))
for _, v := range s.verses {
k := vkey{v.Chapter, v.Verse}
m[k] = v
if !seen[k] {
seen[k] = true
order = append(order, k)
}
}
bySet[i] = m
}
vviews := make([]ilVerseView, 0, len(order))
for _, k := range order {
var lines []ilLineView
for i, s := range sets {
if v, ok := bySet[i][k]; ok {
lines = append(lines, ilLineView{Label: s.label, Text: v.Text})
}
}
vviews = append(vviews, ilVerseView{VNum: fmt.Sprintf("%d:%d", k.chapter, k.verse), Lines: lines})
}
return vviews
}
// buildInterlinearViews gathers each requested version's verses via
// render.GatherVerses (after the bt->wuj substitution, see
// interlinearVersions) and interleaves them by chapter:verse: the ordered
// union of keys is taken from the first versified version's own verse
// order, then any keys that only appear in a later version are appended in
// that version's order (stable, no duplicates). A version that comes back
// unversified (a bible lookup miss) is simply skipped -- the remaining
// versions still render. A section where nothing could be interleaved gets
// a short escaped Note instead of an empty Verses list. lang localises the
// per-version labels and the heading's part-label word (see RenderReadings).
func buildInterlinearViews(secs []liturgy.Section, versions []string, lectionary, lang string) []ilSectionView {
mapped := interlinearVersions(versions)
views := make([]ilSectionView, 0, len(secs))
for _, sec := range secs {
view := ilSectionView{Heading: render.LocalizeHeading(sec.Heading, sec.PartID, lang), Subtitle: sec.Subtitle, PartID: sec.PartID}
var sets []verseSet
for _, v := range mapped {
label, verses, versified := render.GatherVerses(v, sec, lectionary, lang)
if !versified {
continue
}
sets = append(sets, verseSet{label: label, verses: verses})
}
if len(sets) == 0 {
view.Note = i18n.Get(lang).NoInterlinearVerses
views = append(views, view)
continue
}
view.Verses = interleaveVerses(sets)
views = append(views, view)
}
return views
}
// webVersionLabel is the localized column label for a version, falling back to
// the bare code (mirrors render's unexported versionLabel, which web can't reach).
func webVersionLabel(v, lang string) string {
if l, ok := i18n.Get(lang).Version[v]; ok {
return l
}
return v
}
// readerCorpusVersions are the versions the /reader offers: the four with an
// embedded full-text corpus. "bt" (the niedziela.pl scrape) has no corpus and
// cannot be read chapter-by-chapter.
var readerCorpusVersions = []string{"wuj", "vul", "grb", "drb"}
// UnionChapters returns the sorted union of chapter numbers a book has across
// all corpus versions, so the reader's chapter navigation is stable regardless
// of which versions are currently selected (a version lacking the book just
// shows a note).
func UnionChapters(canonical string) []int {
seen := map[int]bool{}
for _, v := range readerCorpusVersions {
for _, c := range bible.Chapters(v, canonical) {
seen[c] = true
}
}
chaps := make([]int, 0, len(seen))
for c := range seen {
chaps = append(chaps, c)
}
sort.Ints(chaps)
return chaps
}
// RenderPassage builds the reader pane for one book+chapter across versions, in
// the same three layouts as RenderReadings (columns / vertical / interlinear),
// reusing the very same templates and role classes. name is the book's display
// name in the sigla dialect (the section heading is "<name> <chap>"). versions
// are corpus versions; one lacking the chapter shows a localized "(not in X)"
// note (columns) or is skipped (interlinear). lang localizes the version labels.
func RenderPassage(canonical, name string, chap int, versions []string, display, lang string) template.HTML {
heading := fmt.Sprintf("%s %d", name, chap)
switch display {
case "interlinear":
return renderTemplate("readings-interlinear.html", passageInterlinear(canonical, heading, chap, versions, lang))
case "vertical":
return renderTemplate("readings-vertical.html", passageColumns(canonical, heading, chap, versions, lang))
default:
return renderTemplate("readings.html", passageColumns(canonical, heading, chap, versions, lang))
}
}
func passageColumns(canonical, heading string, chap int, versions []string, lang string) []sectionView {
cols := make([]columnView, 0, len(versions))
for _, v := range versions {
verses := bible.Verses(v, canonical, chap)
var blocks []blockView
if len(verses) == 0 {
blocks = append(blocks, blockView{Text: fmt.Sprintf(i18n.Get(lang).NoVersion, v)})
}
for _, ve := range verses {
blocks = append(blocks, blockView{VNum: fmt.Sprintf("%d:%d", ve.Chapter, ve.Verse), Text: ve.Text})
}
cols = append(cols, columnView{Label: webVersionLabel(v, lang), Blocks: blocks})
}
return []sectionView{{Heading: heading, PartID: "reader", Columns: cols}}
}
func passageInterlinear(canonical, heading string, chap int, versions []string, lang string) []ilSectionView {
var sets []verseSet
for _, v := range versions {
verses := bible.Verses(v, canonical, chap)
if len(verses) == 0 {
continue
}
sets = append(sets, verseSet{label: webVersionLabel(v, lang), verses: verses})
}
view := ilSectionView{Heading: heading, PartID: "reader"}
if len(sets) == 0 {
view.Note = i18n.Get(lang).NoInterlinearVerses
return []ilSectionView{view}
}
view.Verses = interleaveVerses(sets)
return []ilSectionView{view}
}
// Themes returns the sorted, deduplicated union of the embedded theme
// stems (static/themes/*.css) and the *.css stems found in the user theme
// directory (${XDG_CONFIG_HOME:-~/.config}/lectio/themes/); a user theme
// overrides a built-in of the same name but does not add a second entry.
func Themes() []string {
set := map[string]bool{}
for _, name := range themeStems(staticFS, "static/themes") {
set[name] = true
}
if dir, err := userThemesDir(); err == nil {
for _, name := range themeStems(os.DirFS(dir), ".") {
set[name] = true
}
}
names := make([]string, 0, len(set))
for name := range set {
names = append(names, name)
}
sort.Strings(names)
return names
}
// themeNameRe is the allowlist a theme name must match: letters, digits,
// underscore, hyphen only. Legitimate theme stems (built-in or user) already
// fit this shape; it is deliberately stricter than "no path separators" so
// it rejects "." / ".." / any other filesystem metacharacter outright
// instead of trying to enumerate what's unsafe.
var themeNameRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
// themeCSS returns one theme's CSS: the user file
// ${XDG_CONFIG_HOME:-~/.config}/lectio/themes/<name>.css if it exists,
// otherwise the embedded static/themes/<name>.css, otherwise an error.
// name must match themeNameRe -- callers (B2's /theme.css?name= handler)
// pass this straight through from an HTTP query parameter, so this rejects
// path traversal rather than trusting it.
func themeCSS(name string) ([]byte, error) {
if !themeNameRe.MatchString(name) {
return nil, fmt.Errorf("web: invalid theme name %q", name)
}
if dir, err := userThemesDir(); err == nil {
if b, err := os.ReadFile(filepath.Join(dir, name+".css")); err == nil {
return b, nil
}
}
b, err := staticFS.ReadFile(path.Join("static", "themes", name+".css"))
if err != nil {
return nil, fmt.Errorf("web: unknown theme %q", name)
}
return b, nil
}
// userThemesDir resolves ${XDG_CONFIG_HOME:-~/.config}/lectio/themes via
// os.UserConfigDir(), which already honors XDG_CONFIG_HOME on Linux.
func userThemesDir() (string, error) {
dir, err := os.UserConfigDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "lectio", "themes"), nil
}
// themeStems lists the *.css stems (base name, no extension) directly in
// dir of fsys, silently returning none if dir doesn't exist or isn't
// readable -- a missing user theme directory is normal, not an error.
func themeStems(fsys fs.FS, dir string) []string {
entries, err := fs.ReadDir(fsys, dir)
if err != nil {
return nil
}
var names []string
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".css") {
continue
}
names = append(names, strings.TrimSuffix(e.Name(), ".css"))
}
return names
}
|