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

import (
	"encoding/json"
	"fmt"

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

type SitePreferences struct {
	SidebarWidth     string `json:"sidebar_width"`
	MainContentWidth string `json:"main_content_width"`
	H1FontSize       string `json:"h1_font_size"`
	BodyFontSize     string `json:"body_font_size"`
	SmallFontSize    string `json:"small_font_size"`
	PostsPerPage     int    `json:"posts_per_page"`
}

func PreferencesContextProcessor(context *fiber.Ctx) error {
	defaultPreferences := SitePreferences{
		SidebarWidth:     "180px",
		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 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,
	)
}