forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

preferences.rs227 lines, 8.1 KiBHistoryRawDownload
1//! Per-user UI preference newtypes: color theme, interface language, and accent
2//! color. All are optional on the account — `None` means the user never chose,
3//! and the frontend falls back to the device preference (`prefers-color-scheme`,
4//! browser language) or its own default accent.
5
6use sqlx::Type;
7
8use crate::constant::PALETTE_COLOR_LEN;
9use crate::error::ValidationError;
10
11/// The frontend color scheme.
12///
13/// Each variant stores as a bare lowercase TEXT value (`"light"` /
14/// `"dark"`) — same encoding contract as [`crate::domain::role::Role`].
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
16#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
17pub enum Theme {
18 Light,
19 Dark,
20}
21
22impl Theme {
23 /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`.
24 pub fn as_str(self) -> &'static str {
25 match self {
26 Theme::Light => "light",
27 Theme::Dark => "dark",
28 }
29 }
30
31 /// Parse a wire string into a theme — the inverse of [`Theme::as_str`].
32 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
33 THEMES
34 .into_iter()
35 .find(|theme| theme.as_str() == value)
36 .ok_or(ValidationError::Invalid {
37 field: "theme",
38 reason: "must be one of: light, dark",
39 })
40 }
41}
42
43pub const THEMES: [Theme; 2] = [Theme::Light, Theme::Dark];
44
45/// The frontend interface language, as an ISO 639-1 code — the same values the
46/// frontend's locale switch uses (`"tr"` Turkish, `"en"` English).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Type)]
48#[sqlx(type_name = "TEXT", rename_all = "lowercase")]
49pub enum Language {
50 Tr,
51 En,
52}
53
54impl Language {
55 /// The wire/storage form. Must stay in lockstep with `rename_all = "lowercase"`.
56 pub fn as_str(self) -> &'static str {
57 match self {
58 Language::Tr => "tr",
59 Language::En => "en",
60 }
61 }
62
63 /// Parse a wire string into a language — the inverse of [`Language::as_str`].
64 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
65 LANGUAGES
66 .into_iter()
67 .find(|language| language.as_str() == value)
68 .ok_or(ValidationError::Invalid {
69 field: "language",
70 reason: "must be one of: tr, en",
71 })
72 }
73}
74
75pub const LANGUAGES: [Language; 2] = [Language::Tr, Language::En];
76
77/// The frontend accent color, a 6-digit hex with a leading `#`, stored
78/// lowercase (`"#fefae0"`).
79///
80/// Unlike [`Theme`] and [`Language`] this is an **open** value set: any valid
81/// hex passes, so the frontend can grow its palette without a backend change.
82/// A plain newtype over `String`, which stores as a bare string — the same
83/// `TEXT NULL` column contract the two enums encode into.
84#[derive(Debug, Clone, PartialEq, Eq, Type)]
85#[sqlx(transparent)]
86pub struct PaletteColor(String);
87
88impl PaletteColor {
89 /// The wire/storage form: always lowercase.
90 pub fn as_str(&self) -> &str {
91 &self.0
92 }
93
94 /// Parse a wire string into an accent color. Mixed case is accepted (the
95 /// frontend's own validator is case-insensitive) and normalized down; no
96 /// trimming, so a stray space is a rejection rather than a silent fix.
97 pub fn try_from_str(value: &str) -> Result<Self, ValidationError> {
98 let invalid = ValidationError::Invalid {
99 field: "palette_color",
100 reason: "must be a hex color: # followed by exactly 6 hex digits, e.g. #fefae0",
101 };
102 if value.len() != PALETTE_COLOR_LEN
103 || !value.starts_with('#')
104 || !value[1..].chars().all(|c| c.is_ascii_hexdigit())
105 {
106 return Err(invalid);
107 }
108 Ok(Self(value.to_ascii_lowercase()))
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115 use crate::constant::PALETTE_COLOR_PATTERN;
116
117 #[tokio::test]
118 async fn theme_str_round_trips() {
119 for theme in THEMES {
120 assert_eq!(Theme::try_from_str(theme.as_str()).unwrap(), theme);
121 }
122 assert!(Theme::try_from_str("solarized").is_err());
123 assert!(Theme::try_from_str("Light").is_err());
124 assert!(Theme::try_from_str("").is_err());
125 }
126
127 #[tokio::test]
128 async fn language_str_round_trips() {
129 for language in LANGUAGES {
130 assert_eq!(Language::try_from_str(language.as_str()).unwrap(), language);
131 }
132 assert!(Language::try_from_str("turkish").is_err());
133 assert!(Language::try_from_str("de").is_err());
134 assert!(Language::try_from_str("").is_err());
135 }
136
137 #[tokio::test]
138 async fn palette_color_normalizes_and_rejects_non_hex() {
139 assert_eq!(
140 PaletteColor::try_from_str("#fefae0").unwrap().as_str(),
141 "#fefae0"
142 );
143 // Mixed case is accepted (the frontend validator is case-insensitive)
144 // and stored lowercase.
145 assert_eq!(
146 PaletteColor::try_from_str("#FEFAE0").unwrap().as_str(),
147 "#fefae0"
148 );
149 assert!(PaletteColor::try_from_str("fefae0").is_err()); // no #
150 assert!(PaletteColor::try_from_str("#fff").is_err()); // short form
151 assert!(PaletteColor::try_from_str("#gggggg").is_err()); // not hex
152 assert!(PaletteColor::try_from_str("#fefae0 ").is_err()); // untrimmed
153 assert!(PaletteColor::try_from_str("").is_err());
154
155 // The pattern `GET /limits` publishes must describe the rule above.
156 assert_eq!(
157 PALETTE_COLOR_PATTERN,
158 format!("^#[0-9a-fA-F]{{{}}}$", PALETTE_COLOR_LEN - 1)
159 );
160 }
161
162 /// The published pattern is a promise a client validates its own input
163 /// against, so it must describe the **accept** set exactly — not the
164 /// storage set. A lowercase-only pattern would have a client refuse
165 /// `#FEFAE0`, which this server takes and normalizes. Length agreement
166 /// (above) cannot catch that; only running both sides over the same
167 /// examples can.
168 #[tokio::test]
169 async fn published_pattern_agrees_with_the_accept_set() {
170 let pattern = regex::Regex::new(PALETTE_COLOR_PATTERN).expect("pattern compiles");
171 for accepted in [
172 "#fefae0", "#FEFAE0", "#FeFaE0", "#000000", "#ffffff", "#283618",
173 ] {
174 assert!(
175 PaletteColor::try_from_str(accepted).is_ok(),
176 "validator rejects {accepted}"
177 );
178 assert!(
179 pattern.is_match(accepted),
180 "published pattern rejects accepted input {accepted}"
181 );
182 }
183 for rejected in [
184 "",
185 "fefae0",
186 "#fff",
187 "#gggggg",
188 "#fefae0 ",
189 " #fefae0",
190 "#fefae01",
191 "#fefae",
192 "#fefae0\n",
193 "rebeccapurple",
194 ] {
195 assert!(
196 PaletteColor::try_from_str(rejected).is_err(),
197 "validator accepts {rejected:?}"
198 );
199 assert!(
200 !pattern.is_match(rejected),
201 "published pattern accepts rejected input {rejected:?}"
202 );
203 }
204 }
205
206 #[test]
207 fn sqlx_encodes_the_storage_form() {
208 // `rename_all` keeps the stored value the bare lowercase string the
209 // TEXT columns carry; the palette color stores as the string it
210 // validated to. Guard that the sqlx encoding never drifts.
211 let mut buf = sqlx::postgres::PgArgumentBuffer::default();
212 for theme in THEMES {
213 buf.clear();
214 let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&theme, &mut buf).unwrap();
215 assert_eq!(std::str::from_utf8(&buf).unwrap(), theme.as_str());
216 }
217 for language in LANGUAGES {
218 buf.clear();
219 let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&language, &mut buf).unwrap();
220 assert_eq!(std::str::from_utf8(&buf).unwrap(), language.as_str());
221 }
222 let color = PaletteColor::try_from_str("#fefae0").unwrap();
223 buf.clear();
224 let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&color, &mut buf).unwrap();
225 assert_eq!(std::str::from_utf8(&buf).unwrap(), "#fefae0");
226 }
227}