Skip to main content

moss_core/
resolved.rs

1//! A value paired with its origin. Lets downstream consumers decide
2//! whether to honor the value as author intent (explicit) or override
3//! it with an inferred default (auto-detected).
4//!
5//! Generic over `T` so any wrapped value participates: in v4 used for
6//! `children_group` and `children_style` on `ParsedDocument`; future
7//! fields with the same shape (e.g. cascaded layout fields) can adopt
8//! it.
9
10use serde::{Deserialize, Serialize};
11
12/// Origin of a resolved value — used to gate whether a downstream
13/// override should fire (auto-detected values lose to inference;
14/// explicit author intent wins).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[cfg_attr(feature = "specta", derive(specta::Type))]
17pub enum ResolvedOrigin {
18    /// Declared in the document's own frontmatter.
19    Frontmatter,
20    /// Inherited from an ancestor folder's `cascade:` block.
21    Cascade,
22    /// Auto-detected by a default-derivation rule.
23    Auto,
24}
25
26/// A value plus the rule that produced it.
27///
28/// Use [`Resolved::is_explicit`] to branch: explicit author intent
29/// (frontmatter or cascade) survives downstream overrides; auto-detected
30/// defaults can be replaced.
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32#[cfg_attr(feature = "specta", derive(specta::Type))]
33pub struct Resolved<T> where T: Clone {
34    pub value: T,
35    pub origin: ResolvedOrigin,
36}
37
38impl<T: Clone> Resolved<T> {
39    pub fn frontmatter(value: T) -> Self {
40        Self { value, origin: ResolvedOrigin::Frontmatter }
41    }
42    pub fn cascade(value: T) -> Self {
43        Self { value, origin: ResolvedOrigin::Cascade }
44    }
45    pub fn auto(value: T) -> Self {
46        Self { value, origin: ResolvedOrigin::Auto }
47    }
48    /// True iff origin is [`ResolvedOrigin::Frontmatter`] or
49    /// [`ResolvedOrigin::Cascade`] — i.e. some author (current doc or
50    /// ancestor) explicitly set this value, as opposed to the build
51    /// pipeline auto-deriving it.
52    pub fn is_explicit(&self) -> bool {
53        matches!(self.origin, ResolvedOrigin::Frontmatter | ResolvedOrigin::Cascade)
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn is_explicit_classifies_origins() {
63        assert!(Resolved::frontmatter("x".to_string()).is_explicit());
64        assert!(Resolved::cascade("x".to_string()).is_explicit());
65        assert!(!Resolved::auto("x".to_string()).is_explicit());
66    }
67
68    #[test]
69    fn roundtrips_through_serde() {
70        let r = Resolved::frontmatter("year".to_string());
71        let json = serde_json::to_string(&r).unwrap();
72        let back: Resolved<String> = serde_json::from_str(&json).unwrap();
73        assert_eq!(r, back);
74    }
75}