summaryrefslogtreecommitdiff
path: root/views.go
blob: 60c6d7ea15a8259902f82817175e2d7e9e498b18 (plain)
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package main

import (
	"bytes"
	"fmt"
	"html/template"
	"io"
	"math"
	"path"
	"sort"
	"strings"
	"time"

	"code.laria.me/laria.me/menu"
)

type ViewMenuItem struct {
	Active bool
	Url    string
	Title  string
}

type ViewMenu [][]ViewMenuItem

func buildViewMenuLevel(
	item *menu.MenuItem,
	current string,
	withNextLevel bool,
) (level []ViewMenuItem, nextLevel []ViewMenuItem) {
	level = make([]ViewMenuItem, 0, len(item.Children))

	for _, child := range item.Children {
		isCur := child.Ident == current

		level = append(level, ViewMenuItem{
			Active: isCur,
			Url:    child.Url,
			Title:  child.Title,
		})

		if isCur && withNextLevel {
			nextLevel, _ = buildViewMenuLevel(child, "", false)
		}
	}

	return
}

func buildViewMenuLevels(item *menu.MenuItem, current string, withNextLevel bool) ViewMenu {
	if item == nil {
		return nil
	}

	viewMenu := buildViewMenuLevels(item.Parent, item.Ident, false)

	level, nextLevel := buildViewMenuLevel(item, current, withNextLevel)

	if len(level) > 0 {
		viewMenu = append(viewMenu, level)
	}

	if len(nextLevel) > 0 {
		viewMenu = append(viewMenu, nextLevel)
	}

	return viewMenu
}

func BuildViewMenu(menu *menu.Menu, current string) ViewMenu {
	curMenu := menu.Root()

	curMenuItem := menu.ByIdent(current)
	if curMenuItem != nil {
		curMenu = curMenuItem.Parent
	}

	return buildViewMenuLevels(curMenu, current, true)
}

type RootData struct {
	Menu  ViewMenu
	Title string
	Main  interface{}
}

type ViewArticle struct {
	Published time.Time
	Slug      string
	Title     string
	Content   template.HTML
	ReadMore  bool
	Tags      []string
}

type Views struct {
	archiveDay   *template.Template
	archive      *template.Template
	archiveMonth *template.Template
	archiveYear  *template.Template
	article      *template.Template
	blog         *template.Template
	content      *template.Template
	search       *template.Template
	start        *template.Template
	tag          *template.Template
	tags         *template.Template
}

func monthText(m int) string {
	switch m {
	case 1:
		return "January"
	case 2:
		return "February"
	case 3:
		return "March"
	case 4:
		return "April"
	case 5:
		return "May"
	case 6:
		return "June"
	case 7:
		return "July"
	case 8:
		return "August"
	case 9:
		return "September"
	case 10:
		return "October"
	case 11:
		return "November"
	case 12:
		return "December"
	default:
		return fmt.Sprintf("<unknown month %d>", m)
	}
}

func nth(n int) string {
	switch n {
	case 1:
		return "1st"
	case 2:
		return "2nd"
	case 3:
		return "3rd"
	default:
		return fmt.Sprintf("%dth", n)
	}
}

type paginationArg struct {
	K, V string
}

type paginationTemplateData struct {
	Action string
	Args   []paginationArg
	Cur    int
	Pages  int
}

var paginationTemplate = template.Must(template.New("").Funcs(template.FuncMap{"seq": func(max int) <-chan int {
	ch := make(chan int)
	go func() {
		defer close(ch)
		for i := 1; i <= max; i++ {
			ch <- i
		}
	}()
	return ch
}}).Parse(`<form action="{{.Action}}" method="get" class="pagination">
	{{- range .Args -}}
		<input type="hidden" name="{{.K}}" value="{{.V}}">
	{{- end -}}
	{{- $cur := .Cur -}}
	<label for="pagination-select">Page:</label>
	<select name="page" id="pagination-select">{{- range (seq .Pages) -}}
		<option {{if eq . $cur}}selected{{end}} value="{{.}}">{{.}}</option>
	{{- end -}}</select>
	<button type="submit">Go to</button>
</form>`))

func normalizeDate(y, m, d int) (int, int, int) {
	t := time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.UTC)
	y, month, d := t.Date()

	return y, int(month), d
}

func dayText(y, m, d int) string {
	return fmt.Sprintf("%s %s %d", nth(d), monthText(m), y)
}

func LoadViews(templatesDir string) (Views, error) {
	views := Views{}

	root, err := template.New("root.html").ParseFiles(path.Join(templatesDir, "root.html"))

	if err != nil {
		return views, err
	}

	root.Funcs(template.FuncMap{
		"add": func(nums ...int) int {
			sum := 0
			for _, i := range nums {
				sum = sum + i
			}
			return sum
		},
		"concat": func(ss ...string) string {
			sb := new(strings.Builder)
			for _, s := range ss {
				sb.WriteString(s)
			}
			return sb.String()
		},
		"nth":        nth,
		"day_text":   dayText,
		"month_text": monthText,
		"pagination": func(pages, page int, path string, queryArgs ...string) (template.HTML, error) {
			if len(queryArgs)%2 != 0 {
				return "", fmt.Errorf("pagination: need even number of query args")
			}

			args := make([]paginationArg, 0, len(queryArgs)/2)
			for i := 0; i < len(queryArgs); i += 2 {
				args = append(args, paginationArg{K: queryArgs[i], V: queryArgs[i+1]})
			}

			buf := new(bytes.Buffer)

			err := paginationTemplate.Execute(buf, paginationTemplateData{
				Action: path,
				Args:   args,
				Cur:    page,
				Pages:  pages,
			})

			if err != nil {
				return "", err
			}

			return template.HTML(buf.String()), nil
		},
		"archive_link": func(components ...int) (string, error) {
			switch len(components) {
			case 0:
				return "/blog/archive", nil
			case 1:
				y := components[0]
				return fmt.Sprintf("/blog/%d", y), nil
			case 2:
				y := components[0]
				m := components[1]

				y, m, _ = normalizeDate(y, m, 1)

				return fmt.Sprintf("/blog/%d/%d", y, m), nil
			case 3:
				y := components[0]
				m := components[1]
				d := components[2]

				y, m, d = normalizeDate(y, m, d)

				return fmt.Sprintf("/blog/%d/%d/%d", y, m, d), nil
			default:
				return "", fmt.Errorf("archive_link accepts at most 3 arguments")
			}
		},
	})

	for name, t := range map[string]**template.Template{
		"archive-day":   &(views.archiveDay),
		"archive":       &(views.archive),
		"archive-month": &(views.archiveMonth),
		"archive-year":  &(views.archiveYear),
		"article":       &(views.article),
		"blog":          &(views.blog),
		"content":       &(views.content),
		"search":        &(views.search),
		"start":         &(views.start),
		"tag":           &(views.tag),
		"tags":          &(views.tags),
	} {
		templateFile := path.Join(templatesDir, name+".html")

		if *t, err = template.Must(root.Clone()).ParseFiles(templateFile); err != nil {
			return views, fmt.Errorf("Failed loading template %s: %w", name, err)
		}
	}

	return views, nil
}

func (v Views) RenderArchiveDay(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	y, m, d int,
	articles []ViewArticle,
) error {
	return v.archiveDay.Execute(w, RootData{BuildViewMenu(menu, curMenu), dayText(y, m, d), struct {
		Year, Month, Day int
		MonthText        string
		Articles         []ViewArticle
	}{
		Year:      y,
		Month:     m,
		Day:       d,
		MonthText: monthText(m),
		Articles:  articles,
	}})
}

type archiveEntryWithCount struct {
	Num   int
	Count int
}

type archiveEntriesWithCount []archiveEntryWithCount

func (a archiveEntriesWithCount) Len() int           { return len(a) }
func (a archiveEntriesWithCount) Less(i, j int) bool { return a[i].Num < a[j].Num }
func (a archiveEntriesWithCount) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func buildArchiveEntries(keyedCounts map[int]int) archiveEntriesWithCount {
	entries := make(archiveEntriesWithCount, 0, len(keyedCounts))
	for k, v := range keyedCounts {
		entries = append(entries, archiveEntryWithCount{
			Num:   k,
			Count: v,
		})
	}

	sort.Sort(entries)

	return entries
}

func (v Views) RenderArchive(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	countByYear map[int]int,
) error {
	return v.archive.Execute(w, RootData{BuildViewMenu(menu, curMenu), "Archive", struct {
		Years archiveEntriesWithCount
	}{Years: buildArchiveEntries(countByYear)}})
}

func (v Views) RenderArchiveMonth(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	year, month int,
	countByDay map[int]int,
) error {
	title := fmt.Sprintf("%s %d", monthText(month), year)

	return v.archiveMonth.Execute(w, RootData{BuildViewMenu(menu, curMenu), title, struct {
		Year, Month int
		Days        archiveEntriesWithCount
	}{
		Year:  year,
		Month: month,
		Days:  buildArchiveEntries(countByDay),
	}})
}

func (v Views) RenderArchiveYear(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	year int,
	countByMonth map[int]int,
) error {
	return v.archiveYear.Execute(w, RootData{BuildViewMenu(menu, curMenu), string(year), struct {
		Year   int
		Months archiveEntriesWithCount
	}{
		Year:   year,
		Months: buildArchiveEntries(countByMonth),
	}})
}

func (v Views) RenderArticle(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	article ViewArticle,
) error {
	return v.article.Execute(w, RootData{BuildViewMenu(menu, curMenu), article.Title, article})
}

func (v Views) RenderContent(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	html template.HTML,
) error {
	return v.content.Execute(w, RootData{BuildViewMenu(menu, curMenu), "", html})
}

func (v Views) RenderSearch(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	query string,
	total int,
	results []ViewArticle,
	pages int,
	page int,
) error {
	return v.search.Execute(w, RootData{BuildViewMenu(menu, curMenu), "Search", struct {
		Q           string
		Total       int
		Results     []ViewArticle
		Pages, Page int
	}{
		Q:       query,
		Total:   total,
		Results: results,
		Pages:   pages,
		Page:    page,
	}})
}

func (v Views) RenderStart(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	content template.HTML,
	blogArticles []ViewArticle,
) error {
	return v.start.Execute(w, RootData{BuildViewMenu(menu, curMenu), "", struct {
		Content template.HTML
		Blog    []ViewArticle
	}{
		Content: content,
		Blog:    blogArticles,
	}})
}

func (v Views) RenderTag(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	tag string,
	articles []ViewArticle,
	pages, page int,
) error {
	return v.tag.Execute(w, RootData{BuildViewMenu(menu, curMenu), "Tag " + tag, struct {
		Tag         string
		Articles    []ViewArticle
		Pages, Page int
	}{
		Tag:      tag,
		Articles: articles,
		Pages:    pages,
		Page:     page,
	}})
}

func (v Views) RenderBlog(
	w io.Writer,
	menu *menu.Menu,
	curMenu string,
	articles []ViewArticle,
	pages, page int,
) error {
	return v.blog.Execute(w, RootData{BuildViewMenu(menu, curMenu), "Blog", struct {
		Articles    []ViewArticle
		Pages, Page int
	}{
		Articles: articles,
		Pages:    pages,
		Page:     page,
	}})
}

type tagcloudTag struct {
	Tag       string
	SizeClass int
}

type tagcloudTags []tagcloudTag

func (t tagcloudTags) Len() int { return len(t) }
func (t tagcloudTags) Less(i, j int) bool {
	return strings.ToLower(t[i].Tag) < strings.ToLower(t[j].Tag)
}
func (t tagcloudTags) Swap(i, j int) { t[i], t[j] = t[j], t[i] }

const tagcloudCategories = 5

func (v Views) RenderTags(w io.Writer, menu *menu.Menu, curMenu string, tagCounts map[string]int) error {
	tags := make(tagcloudTags, 0, len(tagCounts))

	maxCount := 0
	for tag, count := range tagCounts {
		tags = append(tags, tagcloudTag{
			Tag:       tag,
			SizeClass: count,
		})

		if count > maxCount {
			maxCount = count
		}
	}

	for i, tag := range tags {
		tags[i].SizeClass = int(math.Ceil((float64(tag.SizeClass) / float64(maxCount)) * tagcloudCategories))
	}

	sort.Sort(tags)

	return v.tags.Execute(w, RootData{BuildViewMenu(menu, curMenu), "Tags", struct {
		Tags tagcloudTags
	}{
		Tags: tags,
	}})
}