summaryrefslogtreecommitdiff
path: root/pages/page.go
blob: f60620588f2fe0f25d663accb2174e64ec7219ce (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
package pages

import (
	"context"
	"gosten/model"
	"net/http"

	"github.com/a-h/templ"
	"github.com/go-chi/chi/v5"
)

var Q *model.Queries

func Connect(tx model.DBTX) {
	Q = model.New(tx)
}

type Page interface {
	http.Handler
}

type dataFunc[T any] func(ctx context.Context) T
type tplFunc[T any] func(T) templ.Component

func simple(c templ.Component) Page {
	r := chi.NewRouter()
	r.Get("/", render(c))
	return r
}

func simpleWithData[T any](tpl tplFunc[T], dataFn dataFunc[T]) Page {
	r := chi.NewRouter()
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		input := dataFn(r.Context())
		c := tpl(input)
		render(c)(w, r)
	})
	return r
}

func simpleByQuery[T any](tpl tplFunc[T], query func(context.Context, int32) (T, error)) Page {
	dataFn := func(ctx context.Context) T {
		d, err := query(ctx, getUser(ctx).ID)
		if err != nil {
			panic(err.Error())
		}
		return d
	}
	return simpleWithData(tpl, dataFn)
}

type ctxPath struct{}

func render(c templ.Component) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := context.WithValue(r.Context(), ctxPath{}, r.URL.Path)
		if err := c.Render(ctx, w); err != nil {
			panic(err.Error())
		}
	}
}

func getCurrPath(ctx context.Context) string {
	return ctx.Value(ctxPath{}).(string)
}

func isCurrPath(ctx context.Context, path string) bool {
	currPath := getCurrPath(ctx)
	if path[0] != '/' {
		path = "/" + path
	}

	if currPath == "/" {
		return path == "/"
	}

	if currPath[len(currPath)-1] == '/' {
		currPath = currPath[:len(currPath)-1]
	}

	if path[len(path)-1] == '/' {
		path = path[:len(path)-1]
	}

	return currPath == path
}