aboutsummaryrefslogtreecommitdiff
path: root/processors/preferences.go
blob: 21b7c16fd7fd9cc98cd6acd6b4f71447223a0db0 (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
package processors

import (
	"encoding/json"
	"fmt"
	"imageboard/config"

	"github.com/gofiber/fiber/v2"
)

func PreferencesContextProcessor(context *fiber.Ctx) error {
	defaultPreferences := config.SitePreferences{
		SidebarWidth:     "220px",
		MainContentWidth: "1200px",
		H1FontSize:       "16px",
		BodyFontSize:     "13px",
		SmallFontSize:    "11px",
		PostsPerPage:     42,
	}

	preferences := defaultPreferences

	preferencesCookie := context.Cookies("preferences")
	if preferencesCookie != "" {
		_ = json.Unmarshal([]byte(preferencesCookie), &preferences)
	}

	bytes, err := json.Marshal(preferences)
	if err == nil {
		context.Cookie(&fiber.Cookie{
			Name:     "preferences",
			Value:    string(bytes),
			Path:     "/",
			SameSite: fiber.CookieSameSiteLaxMode,
		})
	}

	context.Locals("Preferences", preferences)
	context.Locals("PreferencesCSS", preferencesToCSS(preferences))
	return context.Next()
}

func preferencesToCSS(preferences config.SitePreferences) string {
	return fmt.Sprintf(`
	<style>
		main {
			width: %s;
		}
		body {
			font-size: %s;
		}
		h1 {
			font-size: %s;
		}
		small {
			font-size: %s;
		}
		.sidebar {
			width: %s;
		}
	</style>`,
		preferences.MainContentWidth,
		preferences.BodyFontSize,
		preferences.H1FontSize,
		preferences.SmallFontSize,
		preferences.SidebarWidth,
	)
}