statica 0.50.3

A blazingly fast static site generator that builds on just HTML
Documentation
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Build-time context composition for pages and fragments.
//!
//! The build process owns canonical page data, but canonical roots are not
//! ambient globals. Pages opt in with `<html data-bind="...">`; fragments only
//! see their bound value and linked data sources.

use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;

use serde_json::Value;

use crate::content::{DataKind, DataSet};
use crate::discover::PageSource;
use crate::funnel::{self, DataSource};
use crate::i18n;

/// Canonical page context roots produced by statica.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CanonicalRoot {
    /// All linked page data, keyed by data source id.
    Data,
    /// The current collection item for dynamic routes.
    Item,
    /// Route, params, and pagination metadata.
    Page,
    /// Active locale metadata and any bound translation catalog.
    I18n,
}

impl CanonicalRoot {
    /// Canonical roots in stable declaration order.
    pub const ALL: [Self; 4] = [Self::Data, Self::Item, Self::Page, Self::I18n];

    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Data => "data",
            Self::Item => "item",
            Self::Page => "page",
            Self::I18n => "i18n",
        }
    }

    #[must_use]
    pub fn from_str(value: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|root| root.as_str() == value)
    }
}

/// Fields under the canonical `page` root.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CanonicalPageField {
    /// Source route for the current page, e.g. `blog/[page]`.
    Route,
    /// Resolved dynamic route params keyed by param name.
    Params,
    /// Pagination chunk and navigation metadata for `[page]` routes.
    Pagination,
}

impl CanonicalPageField {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Route => "route",
            Self::Params => "params",
            Self::Pagination => "pagination",
        }
    }
}

/// Where a context is being used.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextScope {
    /// Page templates may use bound page data and declared data link ids.
    Page,
    /// Fragments may use bound fragment data and linked data ids; no canonical fallback.
    Fragment,
}

/// A named layer in the context tree, ordered from highest to lowest precedence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextLayer {
    /// Values produced by `data-bind`.
    Bound,
    /// Values from valid `<link rel="statica/data" id="...">` sources.
    Linked,
}

impl ContextScope {
    #[must_use]
    pub const fn layers(self) -> &'static [ContextLayer] {
        match self {
            Self::Page | Self::Fragment => &[ContextLayer::Bound, ContextLayer::Linked],
        }
    }
}

/// Canonical page context built by statica before page binding.
#[derive(Debug, Clone)]
pub struct CanonicalContext {
    value: Value,
}

impl CanonicalContext {
    #[must_use]
    pub fn new(
        source: &PageSource,
        current: Option<&Value>,
        page_data: &HashMap<String, DataSource>,
        locale: Option<&str>,
        bound_roots: &HashSet<&str>,
    ) -> Self {
        let mut data = serde_json::Map::new();
        if bound_roots.contains(CanonicalRoot::Data.as_str()) {
            data.extend(
                page_data
                    .iter()
                    .map(|(id, source)| (id.clone(), source.value())),
            );
        }

        let current = current.cloned().unwrap_or(Value::Null);
        let nested_item = current
            .get(CanonicalRoot::Item.as_str())
            .filter(|_| {
                current
                    .get(CanonicalPageField::Pagination.as_str())
                    .is_some()
            })
            .cloned();
        let pagination = current
            .get(CanonicalPageField::Pagination.as_str())
            .cloned();
        let render_item = nested_item.clone().unwrap_or_else(|| current.clone());
        let is_pagination = pagination.is_some()
            || current
                .as_object()
                .is_some_and(crate::paginate::is_pagination_chunk);

        let mut params = serde_json::Map::new();
        if bound_roots.contains(CanonicalRoot::Page.as_str()) {
            for param in &source.params {
                let param_name = param.as_str();
                let value = if param_name == i18n::LOCALE_PARAM {
                    locale.map_or(Value::Null, |loc| Value::String(loc.to_string()))
                } else {
                    funnel::read_field(&current, param_name)
                        .or_else(|| {
                            nested_item
                                .as_ref()
                                .and_then(|item| funnel::read_field(item, param_name))
                        })
                        .cloned()
                        .unwrap_or(Value::Null)
                };
                params.insert(param_name.to_string(), value);
            }
        }

        let mut page = serde_json::Map::new();
        page.insert(
            CanonicalPageField::Route.as_str().into(),
            Value::String(source.route.as_str().to_string()),
        );
        page.insert(
            CanonicalPageField::Params.as_str().into(),
            Value::Object(params),
        );
        if is_pagination {
            page.insert(
                CanonicalPageField::Pagination.as_str().into(),
                pagination.unwrap_or_else(|| current.clone()),
            );
        }

        let mut value = serde_json::Map::new();
        if bound_roots.contains(CanonicalRoot::Data.as_str()) {
            value.insert(CanonicalRoot::Data.as_str().into(), Value::Object(data));
        }
        if bound_roots.contains(CanonicalRoot::Item.as_str()) {
            value.insert(
                CanonicalRoot::Item.as_str().into(),
                if is_pagination && nested_item.is_none() {
                    Value::Null
                } else {
                    render_item
                },
            );
        }
        if bound_roots.contains(CanonicalRoot::Page.as_str()) {
            value.insert(CanonicalRoot::Page.as_str().into(), Value::Object(page));
        }
        if bound_roots.contains(CanonicalRoot::I18n.as_str()) {
            value.insert(
                CanonicalRoot::I18n.as_str().into(),
                serde_json::json!({ "locale": locale.unwrap_or("") }),
            );
        }

        Self {
            value: Value::Object(value),
        }
    }

    #[must_use]
    pub const fn value(&self) -> &Value {
        &self.value
    }

    #[must_use]
    pub fn as_data_sources(&self, page_data: &HashMap<String, DataSource>) -> ContextData {
        let canonical_sources = CanonicalRoot::ALL.into_iter().map(|root| {
            let id = root.as_str();
            let value = funnel::read_field(&self.value, id)
                .cloned()
                .unwrap_or(Value::Null);
            (
                id.to_string(),
                DataSource {
                    id: id.to_string(),
                    kind: DataKind::Json,
                    path: PathBuf::from(format!("statica:{id}")),
                    data: Arc::new(DataSet::Json(value)),
                },
            )
        });
        ContextData(
            page_data
                .clone()
                .into_iter()
                .chain(canonical_sources)
                .collect(),
        )
    }
}

/// Data sources available to mount expressions and nested fragment expansion.
#[derive(Debug, Clone)]
pub struct ContextData(HashMap<String, DataSource>);

impl ContextData {
    #[must_use]
    pub const fn new(data: HashMap<String, DataSource>) -> Self {
        Self(data)
    }

    #[must_use]
    pub const fn as_map(&self) -> &HashMap<String, DataSource> {
        &self.0
    }

    #[must_use]
    pub fn with_links(&self, links: &HashMap<String, DataSource>) -> Self {
        Self(
            self.0
                .clone()
                .into_iter()
                .chain(
                    links
                        .iter()
                        .map(|(id, source)| (id.clone(), source.clone())),
                )
                .collect(),
        )
    }
}

/// Ordered tree of context layers for one render scope.
#[derive(Debug, Clone)]
pub struct ContextTree {
    scope: ContextScope,
    bound: Value,
    data: ContextData,
}

impl ContextTree {
    #[must_use]
    pub const fn new(scope: ContextScope, bound: Value, data: ContextData) -> Self {
        Self { scope, bound, data }
    }

    #[must_use]
    pub fn render_context(&self) -> Value {
        self.render_context_with_linked_roots(None)
    }

    #[must_use]
    pub fn render_context_with_linked_roots(
        &self,
        linked_roots: Option<&HashSet<String>>,
    ) -> Value {
        let mut roots = serde_json::Map::new();
        for layer in self.scope.layers() {
            for (key, value) in self.roots(*layer, linked_roots) {
                roots.entry(key).or_insert(value);
            }
        }
        Value::Object(roots)
    }

    #[must_use]
    pub fn translated_context(&self, catalog: Option<&Value>) -> Value {
        self.translated_context_with_linked_roots(catalog, None)
    }

    #[must_use]
    pub fn translated_context_with_linked_roots(
        &self,
        catalog: Option<&Value>,
        linked_roots: Option<&HashSet<String>>,
    ) -> Value {
        let mut ctx = match self.render_context_with_linked_roots(linked_roots) {
            Value::Object(map) => map,
            _ => serde_json::Map::new(),
        };
        let i18n_root = CanonicalRoot::I18n.as_str();
        if let (Some(base), Some(catalog)) = (ctx.get(i18n_root), catalog) {
            ctx.insert(i18n_root.into(), deep_merge(base, catalog));
        }
        Value::Object(ctx)
    }

    fn roots(
        &self,
        layer: ContextLayer,
        linked_roots_filter: Option<&HashSet<String>>,
    ) -> serde_json::Map<String, Value> {
        match layer {
            ContextLayer::Bound => value_roots(&self.bound),
            ContextLayer::Linked => linked_roots(self.data.as_map(), linked_roots_filter),
        }
    }
}

fn value_roots(value: &Value) -> serde_json::Map<String, Value> {
    match value {
        Value::Object(map) => map.clone(),
        _ => serde_json::Map::new(),
    }
}

fn linked_roots(
    data: &HashMap<String, DataSource>,
    filter: Option<&HashSet<String>>,
) -> serde_json::Map<String, Value> {
    let mut roots = serde_json::Map::new();
    for (id, source) in data {
        if CanonicalRoot::from_str(id).is_none() {
            if filter.is_some_and(|roots| !roots.contains(id)) {
                continue;
            }
            roots.insert(id.clone(), source.value());
        }
    }
    roots
}

fn deep_merge(base: &Value, overlay: &Value) -> Value {
    match (base, overlay) {
        (Value::Object(base_map), Value::Object(overlay_map)) => {
            let mut out = base_map.clone();
            for (key, value) in overlay_map {
                out.insert(
                    key.clone(),
                    match out.get(key) {
                        Some(existing) if existing.is_object() && value.is_object() => {
                            deep_merge(existing, value)
                        }
                        _ => value.clone(),
                    },
                );
            }
            Value::Object(out)
        }
        (_, overlay) => overlay.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn source(id: &str, value: Value) -> DataSource {
        DataSource {
            id: id.to_string(),
            kind: DataKind::Json,
            path: PathBuf::from(format!("{id}.json")),
            data: Arc::new(DataSet::Json(value)),
        }
    }

    #[test]
    fn page_bound_roots_precede_linked_roots() {
        let data = ContextData::new(HashMap::from([(
            "title".into(),
            source("title", json!("linked")),
        )]));
        let tree = ContextTree::new(ContextScope::Page, json!({"title": "bound"}), data);

        assert_eq!(tree.render_context(), json!({"title": "bound"}));
    }

    #[test]
    fn fragment_bound_roots_precede_linked_roots_without_canonical_fallback() {
        let data = ContextData::new(HashMap::from([
            ("label".into(), source("label", json!("linked"))),
            (
                "item".into(),
                source("item", json!({"headline": "canonical"})),
            ),
        ]));
        let tree = ContextTree::new(ContextScope::Fragment, json!({"label": "bound"}), data);

        assert_eq!(tree.render_context(), json!({"label": "bound"}));
    }

    #[test]
    fn i18n_catalog_merges_only_when_i18n_is_bound() {
        let data = ContextData::new(HashMap::new());
        let unbound = ContextTree::new(ContextScope::Page, json!({}), data.clone());
        assert_eq!(
            unbound.translated_context(Some(&json!({"title": "Home"}))),
            json!({})
        );

        let bound = ContextTree::new(ContextScope::Page, json!({"i18n": {"locale": "en"}}), data);
        assert_eq!(
            bound.translated_context(Some(&json!({"title": "Home"}))),
            json!({"i18n": {"locale": "en", "title": "Home"}})
        );
    }
}