Skip to main content

webserver_base/templates/
base.rs

1//! Per-server template data: what is true of every page on the site.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use super::site_entity::SiteEntity;
7use super::theme::{Fallback, ThemeColor, ThemeScript};
8
9/// Everything [`BaseTemplateData::new`] requires.
10///
11/// A named-field struct rather than sixteen positional arguments: every field
12/// is mandatory either way, but this one cannot be built with two of them
13/// transposed.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct BaseTemplateDataParams {
16    /// The site's name, e.g. `Boggledygook`.
17    pub project: String,
18    /// The default `<meta name="description">`.
19    pub description: String,
20    /// Who wrote it.
21    pub author: String,
22    /// The site's origin, without a trailing slash — `https://www.example.com`.
23    pub base_url: String,
24    /// The Twitter/X handle, without the leading `@`.
25    pub twitter_username: String,
26    /// The default Open Graph / Twitter card image.
27    pub social_image: String,
28    /// The default alt text for that image.
29    pub social_image_alt: String,
30    /// The browser-chrome colour, and the schemes this site supports.
31    pub theme_color: ThemeColor,
32    /// Which theme to stamp when neither the reader nor their OS states a
33    /// preference. Design data, so it lives beside the colours it chooses
34    /// between.
35    pub theme_fallback: Fallback,
36    /// Who or what the site represents, for schema.org.
37    pub site_entity: SiteEntity,
38    /// The `<html lang>` language subtag, e.g. `en`.
39    pub language_code: String,
40    /// The region subtag, e.g. `US`.
41    pub country_code: String,
42    /// Other places this author exists, emitted as `og:see_also`.
43    pub see_also: Vec<String>,
44    /// The first year of the copyright range. The last is computed per render.
45    pub copyright_start: String,
46    /// Stylesheets every page loads.
47    pub style_sheets: Vec<String>,
48    /// Scripts every page loads.
49    pub scripts: Vec<String>,
50}
51
52/// Per-server template data.
53///
54/// Built once at boot and held in the server's state. Everything on it can be
55/// overridden for a single page by [`PageTemplateData`](super::PageTemplateData),
56/// except the fields that identify the site itself.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct BaseTemplateData {
59    project: String,
60    description: String,
61    author: String,
62    base_url: String,
63    twitter_username: String,
64    social_image: String,
65    social_image_alt: String,
66    theme_color: ThemeColor,
67    theme_fallback: Fallback,
68    site_entity: SiteEntity,
69    language_code: String,
70    country_code: String,
71    see_also: Vec<String>,
72    copyright_start: String,
73    style_sheets: Vec<String>,
74    scripts: Vec<String>,
75    #[serde(default)]
76    site: Value,
77}
78
79impl BaseTemplateData {
80    /// Builds base data with every field supplied.
81    ///
82    /// Two paths are normalised on the way in. A trailing slash on `base_url`
83    /// is stripped, so joining it with a page URL cannot produce
84    /// `https://example.com//blog`. A *leading* slash on `social_image` is
85    /// stripped, so it keys into the cache-buster map exactly like the
86    /// stylesheet and script paths beside it — without that, the social card is
87    /// the one asset on the site that can never be content-hashed.
88    #[must_use]
89    pub fn new(params: BaseTemplateDataParams) -> Self {
90        Self {
91            project: params.project,
92            description: params.description,
93            author: params.author,
94            base_url: normalize_base_url(&params.base_url),
95            twitter_username: params.twitter_username,
96            social_image: normalize_asset_path(&params.social_image),
97            social_image_alt: params.social_image_alt,
98            theme_color: params.theme_color,
99            theme_fallback: params.theme_fallback,
100            site_entity: params.site_entity,
101            language_code: params.language_code,
102            country_code: params.country_code,
103            see_also: params.see_also,
104            copyright_start: params.copyright_start,
105            style_sheets: params.style_sheets,
106            scripts: params.scripts,
107            site: Value::Null,
108        }
109    }
110
111    /// The project's own site-wide data, reachable on every page — the 404
112    /// included — as `{{site.…}}`.
113    ///
114    /// For what every page shares but the library has no field for: a nav
115    /// tree, a phone number, opening hours. Supplying it once here is what
116    /// lets a partial read it on a page whose `{{app}}` knows nothing about it.
117    ///
118    /// # Panics
119    ///
120    /// If `site` cannot be serialized — at boot, never per request.
121    #[must_use]
122    pub fn with_site<A>(mut self, site: A) -> Self
123    where
124        A: Serialize,
125    {
126        self.site = serde_json::to_value(site)
127            .unwrap_or_else(|error| panic!("the site data is unserializable: {error}"));
128        self
129    }
130
131    /// Overrides the author.
132    #[must_use]
133    pub fn with_author(mut self, author: impl Into<String>) -> Self {
134        self.author = author.into();
135        self
136    }
137
138    /// Overrides the Twitter/X handle.
139    #[must_use]
140    pub fn with_twitter_username(mut self, twitter_username: impl Into<String>) -> Self {
141        self.twitter_username = twitter_username.into();
142        self
143    }
144
145    /// Overrides who or what the site represents.
146    #[must_use]
147    pub fn with_site_entity(mut self, site_entity: SiteEntity) -> Self {
148        self.site_entity = site_entity;
149        self
150    }
151
152    /// Overrides the language subtag.
153    #[must_use]
154    pub fn with_language_code(mut self, language_code: impl Into<String>) -> Self {
155        self.language_code = language_code.into();
156        self
157    }
158
159    /// Overrides the region subtag.
160    #[must_use]
161    pub fn with_country_code(mut self, country_code: impl Into<String>) -> Self {
162        self.country_code = country_code.into();
163        self
164    }
165
166    /// Replaces the `og:see_also` list wholesale.
167    ///
168    /// For a project that should not carry the author's personal links at all.
169    #[must_use]
170    pub fn replace_see_also<I, S>(mut self, see_also: I) -> Self
171    where
172        I: IntoIterator<Item = S>,
173        S: Into<String>,
174    {
175        self.see_also = see_also.into_iter().map(Into::into).collect();
176        self
177    }
178
179    /// Appends to the `og:see_also` list.
180    ///
181    /// For a project with its own presence alongside the author's — a band's
182    /// `YouTube` channel next to a personal one.
183    #[must_use]
184    pub fn extend_see_also<I, S>(mut self, see_also: I) -> Self
185    where
186        I: IntoIterator<Item = S>,
187        S: Into<String>,
188    {
189        self.see_also.extend(see_also.into_iter().map(Into::into));
190        self
191    }
192
193    /// Appends to the site-wide stylesheet list.
194    #[must_use]
195    pub fn extend_style_sheets<I, S>(mut self, style_sheets: I) -> Self
196    where
197        I: IntoIterator<Item = S>,
198        S: Into<String>,
199    {
200        self.style_sheets
201            .extend(style_sheets.into_iter().map(Into::into));
202        self
203    }
204
205    /// Appends to the site-wide script list.
206    #[must_use]
207    pub fn extend_scripts<I, S>(mut self, scripts: I) -> Self
208    where
209        I: IntoIterator<Item = S>,
210        S: Into<String>,
211    {
212        self.scripts.extend(scripts.into_iter().map(Into::into));
213        self
214    }
215
216    /// The project's site-wide data; `null` unless
217    /// [`with_site`](Self::with_site) was called.
218    #[must_use]
219    pub const fn site(&self) -> &Value {
220        &self.site
221    }
222
223    /// The site's name.
224    #[must_use]
225    pub fn project(&self) -> &str {
226        &self.project
227    }
228    /// The default description.
229    #[must_use]
230    pub fn description(&self) -> &str {
231        &self.description
232    }
233    /// The author.
234    #[must_use]
235    pub fn author(&self) -> &str {
236        &self.author
237    }
238    /// The site origin, with no trailing slash.
239    #[must_use]
240    pub fn base_url(&self) -> &str {
241        &self.base_url
242    }
243    /// The Twitter/X handle.
244    #[must_use]
245    pub fn twitter_username(&self) -> &str {
246        &self.twitter_username
247    }
248    /// The default social image.
249    #[must_use]
250    pub fn social_image(&self) -> &str {
251        &self.social_image
252    }
253    /// The default social image alt text.
254    #[must_use]
255    pub fn social_image_alt(&self) -> &str {
256        &self.social_image_alt
257    }
258    /// The browser-chrome colour and supported schemes.
259    #[must_use]
260    pub const fn theme_color(&self) -> &ThemeColor {
261        &self.theme_color
262    }
263    /// Who or what the site represents.
264    #[must_use]
265    pub const fn site_entity(&self) -> &SiteEntity {
266        &self.site_entity
267    }
268    /// The pre-paint theme script this site's design implies.
269    #[must_use]
270    pub const fn theme_script(&self) -> ThemeScript {
271        ThemeScript::new(self.theme_fallback)
272    }
273    /// The language subtag.
274    #[must_use]
275    pub fn language_code(&self) -> &str {
276        &self.language_code
277    }
278    /// The region subtag.
279    #[must_use]
280    pub fn country_code(&self) -> &str {
281        &self.country_code
282    }
283    /// The `og:see_also` list.
284    #[must_use]
285    pub fn see_also(&self) -> &[String] {
286        &self.see_also
287    }
288    /// The first year of the copyright range.
289    #[must_use]
290    pub fn copyright_start(&self) -> &str {
291        &self.copyright_start
292    }
293    /// The site-wide stylesheets.
294    #[must_use]
295    pub fn style_sheets(&self) -> &[String] {
296        &self.style_sheets
297    }
298    /// The site-wide scripts.
299    #[must_use]
300    pub fn scripts(&self) -> &[String] {
301        &self.scripts
302    }
303}
304
305/// Strips any trailing slashes from a site origin.
306fn normalize_base_url(base_url: &str) -> String {
307    base_url.trim().trim_end_matches('/').to_string()
308}
309
310/// Strips a leading slash, so an asset path matches its cache-buster key.
311fn normalize_asset_path(path: &str) -> String {
312    path.trim().trim_start_matches('/').to_string()
313}
314
315// ─────────────────────────────────────────────────────────────────────────────
316// preset
317// ─────────────────────────────────────────────────────────────────────────────
318
319/// Todd Everett Griffin's other web presences, emitted as `og:see_also`.
320#[cfg(feature = "preset")]
321pub const GODDTRIFFIN_SEE_ALSO: [&str; 8] = [
322    "https://www.toddgriffin.me/",
323    "https://x.com/goddtriffin",
324    "https://github.com/goddtriffin",
325    "https://www.instagram.com/goddtriffin/",
326    "https://www.youtube.com/@goddtriffin",
327    "https://www.facebook.com/goddtriffin/",
328    "https://stackoverflow.com/users/11767294/goddtriffin",
329    "https://www.reddit.com/user/goddtriffin",
330];
331
332/// Everything [`BaseTemplateData::goddtriffin`] cannot know for you.
333///
334/// Absent on purpose: the fields the preset fills in — author, language,
335/// region, handle, `site_entity` and `see_also` — and `social_image_alt`, which
336/// is derived as `"{project}: {description}"`. Every one of them can still be
337/// changed on the returned value with a `with_*`, `replace_*` or `extend_*`
338/// method.
339#[cfg(feature = "preset")]
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct GoddtriffinParams {
342    /// The site's name.
343    pub project: String,
344    /// The default description.
345    pub description: String,
346    /// The site's origin, without a trailing slash.
347    pub base_url: String,
348    /// The default social card image.
349    pub social_image: String,
350    /// The browser-chrome colour, and the schemes this site supports.
351    pub theme_color: ThemeColor,
352    /// Which theme to stamp when nothing states a preference.
353    pub theme_fallback: Fallback,
354    /// The first year of the copyright range.
355    pub copyright_start: String,
356    /// Stylesheets every page loads.
357    pub style_sheets: Vec<String>,
358    /// Scripts every page loads.
359    pub scripts: Vec<String>,
360}
361
362#[cfg(feature = "preset")]
363impl BaseTemplateData {
364    /// Base data pre-filled with Todd Everett Griffin's defaults.
365    ///
366    /// Fills in author, language, region, Twitter/X handle,
367    /// [`GODDTRIFFIN_SEE_ALSO`] and a `Person` site entity, and derives
368    /// `social_image_alt` as `"{project}: {description}"`. Everything else is
369    /// required, because it differs per project.
370    ///
371    /// A project that is not *him* — a band, a business — should call
372    /// [`with_site_entity`](Self::with_site_entity) with an
373    /// [`Organization`](SiteEntity::organization), because the entity node is a
374    /// factual claim search engines reconcile against.
375    ///
376    /// To change what the preset filled in, call
377    /// [`replace_see_also`](Self::replace_see_also),
378    /// [`extend_see_also`](Self::extend_see_also), or one of the `with_*`
379    /// methods on the returned value.
380    #[must_use]
381    pub fn goddtriffin(params: GoddtriffinParams) -> Self {
382        let social_image_alt: String = format!("{}: {}", params.project, params.description);
383
384        Self::new(BaseTemplateDataParams {
385            project: params.project,
386            description: params.description,
387            author: String::from("Todd Everett Griffin"),
388            base_url: params.base_url,
389            twitter_username: String::from("goddtriffin"),
390            social_image: params.social_image,
391            social_image_alt,
392            theme_color: params.theme_color,
393            theme_fallback: params.theme_fallback,
394            site_entity: SiteEntity::person("Todd Everett Griffin"),
395            language_code: String::from("en"),
396            country_code: String::from("US"),
397            see_also: GODDTRIFFIN_SEE_ALSO
398                .iter()
399                .map(|url| (*url).to_string())
400                .collect(),
401            copyright_start: params.copyright_start,
402            style_sheets: params.style_sheets,
403            scripts: params.scripts,
404        })
405    }
406}
407
408#[cfg(test)]
409mod tests {
410    use super::{BaseTemplateData, BaseTemplateDataParams, Fallback, SiteEntity, ThemeColor};
411
412    fn params() -> BaseTemplateDataParams {
413        BaseTemplateDataParams {
414            project: String::from("Test Project"),
415            description: String::from("A test."),
416            author: String::from("Someone"),
417            base_url: String::from("https://www.example.com"),
418            twitter_username: String::from("someone"),
419            social_image: String::from("static/social.webp"),
420            social_image_alt: String::from("A test image."),
421            theme_color: ThemeColor::light_dark("#fafafa", "#121212"),
422            theme_fallback: Fallback::Dark,
423            site_entity: SiteEntity::person("Someone"),
424            language_code: String::from("en"),
425            country_code: String::from("US"),
426            see_also: vec![String::from("https://www.example.com/")],
427            copyright_start: String::from("1998"),
428            style_sheets: vec![String::from("static/stylesheet/main.css")],
429            scripts: vec![String::from("static/script/main.js")],
430        }
431    }
432
433    #[test]
434    fn a_trailing_slash_is_stripped_so_urls_never_double_up() {
435        let mut with_slash: BaseTemplateDataParams = params();
436        with_slash.base_url = String::from("https://www.example.com/");
437
438        let expected: String = String::from("https://www.example.com");
439        let actual: String = BaseTemplateData::new(with_slash).base_url().to_string();
440        assert_eq!(expected, actual);
441    }
442
443    #[test]
444    fn a_leading_slash_on_the_social_image_is_stripped_so_it_can_be_cache_busted() {
445        let mut with_slash: BaseTemplateDataParams = params();
446        with_slash.social_image = String::from("/static/image/social/card.webp");
447
448        // The cache-buster map is keyed without a leading slash, exactly like
449        // `style_sheets` and `scripts`; a mismatch here is why the social card
450        // was historically the one asset that never got hashed.
451        let expected: String = String::from("static/image/social/card.webp");
452        let actual: String = BaseTemplateData::new(with_slash).social_image().to_string();
453        assert_eq!(expected, actual);
454    }
455
456    #[test]
457    fn every_field_survives_construction() {
458        let expected: BaseTemplateDataParams = params();
459        let actual: BaseTemplateData = BaseTemplateData::new(params());
460
461        assert_eq!(expected.project, actual.project());
462        assert_eq!(expected.description, actual.description());
463        assert_eq!(expected.author, actual.author());
464        assert_eq!(expected.base_url, actual.base_url());
465        assert_eq!(expected.twitter_username, actual.twitter_username());
466        assert_eq!(expected.social_image, actual.social_image());
467        assert_eq!(expected.social_image_alt, actual.social_image_alt());
468        assert_eq!(&expected.theme_color, actual.theme_color());
469        assert_eq!(expected.theme_fallback, actual.theme_fallback);
470        assert_eq!(&expected.site_entity, actual.site_entity());
471        assert_eq!(expected.language_code, actual.language_code());
472        assert_eq!(expected.country_code, actual.country_code());
473        assert_eq!(expected.see_also, actual.see_also());
474        assert_eq!(expected.copyright_start, actual.copyright_start());
475        assert_eq!(expected.style_sheets, actual.style_sheets());
476        assert_eq!(expected.scripts, actual.scripts());
477    }
478
479    #[test]
480    fn extend_appends_without_discarding() {
481        let base: BaseTemplateData = BaseTemplateData::new(params())
482            .extend_see_also(["https://www.youtube.com/@tripleentendreband"])
483            .extend_scripts(["static/script/home.js"]);
484
485        let expected_see_also: Vec<String> = vec![
486            String::from("https://www.example.com/"),
487            String::from("https://www.youtube.com/@tripleentendreband"),
488        ];
489        let actual_see_also: Vec<String> = base.see_also().to_vec();
490        assert_eq!(expected_see_also, actual_see_also);
491
492        let expected_scripts: Vec<String> = vec![
493            String::from("static/script/main.js"),
494            String::from("static/script/home.js"),
495        ];
496        let actual_scripts: Vec<String> = base.scripts().to_vec();
497        assert_eq!(expected_scripts, actual_scripts);
498    }
499
500    #[cfg(feature = "preset")]
501    #[test]
502    fn the_preset_fills_identity_and_leaves_the_rest_required() {
503        use super::{GODDTRIFFIN_SEE_ALSO, GoddtriffinParams};
504
505        let base: BaseTemplateData = BaseTemplateData::goddtriffin(GoddtriffinParams {
506            project: String::from("Boggledygook"),
507            description: String::from("Boggle, exhaustively."),
508            base_url: String::from("https://www.boggledygook.com"),
509            social_image: String::from("/og-image.png"),
510            theme_color: ThemeColor::light_dark("#fafafa", "#121212"),
511            theme_fallback: Fallback::Dark,
512            copyright_start: String::from("2025"),
513            style_sheets: vec![],
514            scripts: vec![],
515        });
516
517        let expected_author: String = String::from("Todd Everett Griffin");
518        let actual_author: String = base.author().to_string();
519        assert_eq!(expected_author, actual_author);
520
521        let expected_handle: String = String::from("goddtriffin");
522        let actual_handle: String = base.twitter_username().to_string();
523        assert_eq!(expected_handle, actual_handle);
524
525        let expected_entity: SiteEntity = SiteEntity::person("Todd Everett Griffin");
526        assert_eq!(&expected_entity, base.site_entity());
527
528        let expected_see_also: Vec<String> = GODDTRIFFIN_SEE_ALSO
529            .iter()
530            .map(|url| (*url).to_string())
531            .collect();
532        let actual_see_also: Vec<String> = base.see_also().to_vec();
533        assert_eq!(expected_see_also, actual_see_also);
534    }
535
536    #[cfg(feature = "preset")]
537    #[test]
538    fn the_preset_see_also_leads_with_the_personal_site_then_x_then_github() {
539        use super::GODDTRIFFIN_SEE_ALSO;
540
541        let expected: [&str; 3] = [
542            "https://www.toddgriffin.me/",
543            "https://x.com/goddtriffin",
544            "https://github.com/goddtriffin",
545        ];
546        let actual: [&str; 3] = [
547            GODDTRIFFIN_SEE_ALSO[0],
548            GODDTRIFFIN_SEE_ALSO[1],
549            GODDTRIFFIN_SEE_ALSO[2],
550        ];
551        assert_eq!(expected, actual);
552
553        assert!(
554            !GODDTRIFFIN_SEE_ALSO
555                .iter()
556                .any(|url| url.contains("twitter.com")),
557            "twitter.com was replaced by x.com"
558        );
559    }
560
561    #[cfg(feature = "preset")]
562    #[test]
563    fn a_preset_field_can_still_be_overridden() {
564        use super::GoddtriffinParams;
565
566        let base: BaseTemplateData = BaseTemplateData::goddtriffin(GoddtriffinParams {
567            project: String::from("Triple Entendre"),
568            description: String::from("A band."),
569            base_url: String::from("https://www.tripleentendreband.com"),
570            social_image: String::from("/static/social.webp"),
571            theme_color: ThemeColor::dark("#000000"),
572            theme_fallback: Fallback::Dark,
573            copyright_start: String::from("2019"),
574            style_sheets: vec![],
575            scripts: vec![],
576        })
577        .with_twitter_username("tripleentendre")
578        .extend_see_also(["https://www.youtube.com/@tripleentendreband"]);
579
580        let expected_handle: String = String::from("tripleentendre");
581        let actual_handle: String = base.twitter_username().to_string();
582        assert_eq!(expected_handle, actual_handle);
583
584        let expected_len: usize = 9;
585        let actual_len: usize = base.see_also().len();
586        assert_eq!(expected_len, actual_len);
587    }
588
589    #[cfg(feature = "preset")]
590    #[test]
591    fn the_preset_derives_social_image_alt_from_project_and_description() {
592        use super::GoddtriffinParams;
593
594        let base: BaseTemplateData = BaseTemplateData::goddtriffin(GoddtriffinParams {
595            project: String::from("Scannable Codes"),
596            description: String::from("Every scannable code, explained."),
597            base_url: String::from("https://www.scannablecodes.com"),
598            social_image: String::from("/static/social.webp"),
599            theme_color: ThemeColor::light_dark("#fafafa", "#121212"),
600            theme_fallback: Fallback::Dark,
601            copyright_start: String::from("1998"),
602            style_sheets: vec![],
603            scripts: vec![],
604        });
605
606        let expected: String = String::from("Scannable Codes: Every scannable code, explained.");
607        let actual: String = base.social_image_alt().to_string();
608        assert_eq!(expected, actual);
609    }
610
611    #[test]
612    fn replace_see_also_discards_whatever_was_there() {
613        let base: BaseTemplateData = BaseTemplateData::new(params())
614            .replace_see_also(["https://www.youtube.com/@tripleentendreband"]);
615
616        let expected: Vec<String> =
617            vec![String::from("https://www.youtube.com/@tripleentendreband")];
618        let actual: Vec<String> = base.see_also().to_vec();
619        assert_eq!(expected, actual);
620    }
621
622    #[test]
623    fn replace_then_extend_composes_in_that_order() {
624        let base: BaseTemplateData = BaseTemplateData::new(params())
625            .replace_see_also(["https://a.example.com"])
626            .extend_see_also(["https://b.example.com"]);
627
628        let expected: Vec<String> = vec![
629            String::from("https://a.example.com"),
630            String::from("https://b.example.com"),
631        ];
632        let actual: Vec<String> = base.see_also().to_vec();
633        assert_eq!(expected, actual);
634    }
635}