maudit 0.11.0

Library for generating static websites.
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Core functions and structs to define the content sources of your website.
//!
//! Content sources represent the content of your website, such as articles, blog posts, etc. Then, content sources can be passed to [`coronate()`](crate::coronate), through the [`content_sources!`](crate::content_sources) macro, to be loaded.
use std::{any::Any, path::PathBuf, sync::Arc};

use rustc_hash::FxHashMap;

mod highlight;
pub mod markdown;
mod slugger;
pub mod tracked;

use crate::{
    assets::RouteAssets,
    route::{DynamicRouteContext, PageContext, PageParams},
};
pub use markdown::{
    components::{
        BlockQuoteKind, BlockquoteComponent, CodeComponent, EmphasisComponent, HardBreakComponent,
        HeadingComponent, HorizontalRuleComponent, ImageComponent, LinkComponent, LinkType,
        ListComponent, ListItemComponent, ListType, MarkdownComponents, ParagraphComponent,
        StrikethroughComponent, StrongComponent, TableAlignment, TableCellComponent,
        TableComponent, TableHeadComponent, TableRowComponent, TaskListMarkerComponent,
    },
    *,
};

pub use highlight::{HighlightOptions, highlight_code};
pub use tracked::TrackedContentSource;

/// Helps implement a struct as a Markdown content entry.
///
/// ## Example
/// ```rust
/// use maudit::{coronate, content_sources, routes, BuildOptions, BuildOutput};
/// use maudit::content::{markdown_entry, glob_markdown};
///
/// #[markdown_entry]
/// pub struct ArticleContent {
///   pub title: String,
///   pub description: String,
/// }
///
/// fn main() -> Result<BuildOutput, Box<dyn std::error::Error>> {
///   coronate(
///     routes![],
///     content_sources![
///       "articles" => glob_markdown::<ArticleContent>("content/articles/*.md")
///     ],
///     BuildOptions::default(),
///   )
/// }
/// ```
///
/// ## Expand
/// ```rust
/// use maudit::content::{markdown_entry};
///
/// #[markdown_entry]
/// pub struct Article {
///   pub title: String,
///   pub content: String,
/// }
/// ```
/// expands to
/// ```rust
/// #[derive(serde::Deserialize)]
/// pub struct Article {
///   pub title: String,
///   pub content: String,
///   #[serde(skip)]
///   __internal_headings: Vec<maudit::content::MarkdownHeading>
/// }
///
/// impl maudit::content::MarkdownContent for Article {
///   fn get_headings(&self) -> &Vec<maudit::content::MarkdownHeading> {
///     &self.__internal_headings
///   }
/// }
///
/// impl maudit::content::InternalMarkdownContent for Article {
///   fn set_headings(&mut self, headings: Vec<maudit::content::MarkdownHeading>) {
///     self.__internal_headings = headings;
///   }
/// }
/// ```
pub use maudit_macros::markdown_entry;

/// A single entry of a [`ContentSource`].
///
/// ## Example
/// ```rust
/// use maudit::route::prelude::*;
/// # use maudit::content::markdown_entry;
/// #
/// # #[markdown_entry]
/// # pub struct ArticleContent {
/// #    pub title: String,
/// #    pub description: String,
/// # }
///
/// #[route("/articles/my-article")]
/// pub struct Article;
///
/// #[derive(Params)]
/// pub struct ArticleParams {
///     pub article: String,
/// }
///
/// impl Route for Article {
///    fn render(&self, ctx: &mut PageContext) -> impl Into<RenderResult> {
///      let articles = ctx.content::<ArticleContent>("articles");
///      let article = articles.get_entry("my-article"); // returns a Entry<ArticleContent>
///
///      article.render(ctx)
///   }
/// }
/// ```
/// A dependency of a content entry, used for incremental build change detection.
#[derive(Debug, Clone)]
pub enum Dependency {
    /// A file on disk. Changes to this file will trigger a rebuild of pages that depend on this entry.
    File(PathBuf),
    // TODO: Add other types of dependencies
}

pub struct EntryInner<T> {
    pub id: String,
    render: OptionalContentRenderFn,
    pub raw_content: Option<String>,
    data_loader: Option<DataLoadingFn<T>>,
    cached_data: std::sync::OnceLock<T>,
    pub dependencies: Vec<Dependency>,
}

/// Helper type for easier usage of `EntryInner`. Content sources always return Arc-wrapped entries, but the user ergonomics of writing `Arc<EntryInner<T>>` is not great.
pub type Entry<T> = Arc<EntryInner<T>>;

pub trait ContentEntry<T> {
    fn create(
        id: String,
        render: OptionalContentRenderFn,
        raw_content: Option<String>,
        data: T,
        dependencies: Vec<Dependency>,
    ) -> Entry<T> {
        Arc::new(EntryInner {
            id,
            render,
            raw_content,
            data_loader: None,
            cached_data: std::sync::OnceLock::from(data),
            dependencies,
        })
    }

    fn create_lazy(
        id: String,
        render: OptionalContentRenderFn,
        raw_content: Option<String>,
        data_loader: DataLoadingFn<T>,
        dependencies: Vec<Dependency>,
    ) -> Entry<T> {
        Arc::new(EntryInner {
            id,
            render,
            raw_content,
            data_loader: Some(data_loader),
            cached_data: std::sync::OnceLock::new(),
            dependencies,
        })
    }
}

impl<T> ContentEntry<T> for Entry<T> {}

/// Trait for contexts that can provide access to content
pub trait ContentContext {
    fn content(&self) -> &ContentSources;
    fn assets(&mut self) -> &mut RouteAssets;
}

impl ContentContext for PageContext<'_> {
    fn content(&self) -> &ContentSources {
        self.content
    }

    fn assets(&mut self) -> &mut RouteAssets {
        self.assets
    }
}

impl ContentContext for DynamicRouteContext<'_> {
    fn content(&self) -> &ContentSources {
        self.content
    }

    fn assets(&mut self) -> &mut RouteAssets {
        self.assets
    }
}

type DataLoadingFn<T> = Box<dyn Fn(&mut dyn ContentContext) -> T + Send + Sync>;

type OptionalContentRenderFn =
    Option<Box<dyn Fn(&str, &mut crate::route::PageContext) -> String + Send + Sync>>;

impl<T> EntryInner<T> {
    pub fn data<C: ContentContext>(&self, ctx: &mut C) -> &T {
        self.cached_data.get_or_init(|| {
            if let Some(ref loader) = self.data_loader {
                loader(ctx)
            } else {
                panic!("No data loader available and no cached data")
            }
        })
    }

    pub fn render(&self, ctx: &mut PageContext) -> String {
        (self.render.as_ref().unwrap())(self.raw_content.as_ref().unwrap(), ctx)
    }
}

/// Represents an untyped content source.
pub type Untyped = FxHashMap<String, String>;

/// Main struct to access all content sources.
///
/// # Example
/// In `main.rs`:
/// ```rust
/// use maudit::{coronate, content_sources, routes, BuildOptions, BuildOutput};
/// use maudit::content::{markdown_entry, glob_markdown};
///
/// #[markdown_entry]
/// pub struct ArticleContent {
///   pub title: String,
///   pub description: String,
/// }
///
/// fn main() -> Result<BuildOutput, Box<dyn std::error::Error>> {
///   coronate(
///     routes![],
///     content_sources![
///       "articles" => glob_markdown::<ArticleContent>("content/articles/*.md")
///     ],
///     BuildOptions::default(),
///   )
/// }
/// ```
///
/// In a page:
/// ```rust
/// use maudit::route::prelude::*;
/// # use maudit::content::markdown_entry;
/// #
/// # #[markdown_entry]
/// # pub struct ArticleContent {
/// #    pub title: String,
/// #    pub description: String,
/// # }
///
/// #[route("/articles/[article]")]
/// pub struct Article;
///
/// #[derive(Params, Clone)]
/// pub struct ArticleParams {
///     pub article: String,
/// }
///
/// impl Route<ArticleParams> for Article {
///    fn render(&self, ctx: &mut PageContext) -> impl Into<RenderResult> {
///      let params = ctx.params::<ArticleParams>();
///      let articles = ctx.content::<ArticleContent>("articles");
///      let article = articles.get_entry(&params.article);
///      article.render(ctx)
///   }
///
///   fn pages(&self, ctx: &mut DynamicRouteContext) -> Pages<ArticleParams> {
///     let articles = ctx.content::<ArticleContent>("articles");
///
///     articles.into_pages(|entry| Page::from_params(ArticleParams {
///        article: entry.id.clone(),
///     }))
///   }
/// }
/// ```
pub struct ContentSources(pub Vec<Box<dyn ContentSourceInternal>>);

impl From<Vec<Box<dyn ContentSourceInternal>>> for ContentSources {
    fn from(content_sources: Vec<Box<dyn ContentSourceInternal>>) -> Self {
        Self(content_sources)
    }
}

impl ContentSources {
    pub fn new(content_sources: Vec<Box<dyn ContentSourceInternal>>) -> Self {
        Self(content_sources)
    }

    pub fn sources(&self) -> &Vec<Box<dyn ContentSourceInternal>> {
        &self.0
    }

    pub fn sources_mut(&mut self) -> &mut Vec<Box<dyn ContentSourceInternal>> {
        &mut self.0
    }

    pub fn init_all(&mut self) {
        for source in &mut self.0 {
            source.init();
        }
    }

    pub fn get_untyped_source(&self, name: &str) -> &ContentSource<Untyped> {
        self.get_source::<Untyped>(name)
    }

    pub fn get_untyped_source_safe(&self, name: &str) -> Option<&ContentSource<Untyped>> {
        self.get_source_safe::<Untyped>(name)
    }

    pub fn get_source<T: 'static>(&self, name: &str) -> &ContentSource<T> {
        self.0
            .iter()
            .find_map(
                |source| match source.as_any().downcast_ref::<ContentSource<T>>() {
                    Some(source) if source.name == name => Some(source),
                    _ => None,
                },
            )
            .unwrap_or_else(|| panic!("Content source with name '{}' not found", name))
    }

    pub fn get_source_safe<T: 'static>(&self, name: &str) -> Option<&ContentSource<T>> {
        self.0.iter().find_map(
            |source| match source.as_any().downcast_ref::<ContentSource<T>>() {
                Some(source) if source.name == name => Some(source),
                _ => None,
            },
        )
    }
}

type ContentSourceInitMethod<T> = Box<dyn Fn() -> Vec<Arc<EntryInner<T>>> + Send + Sync>;

/// A source of content such as articles, blog posts, etc.
pub struct ContentSource<T = Untyped> {
    pub name: String,
    pub entries: FxHashMap<String, Arc<EntryInner<T>>>,
    pub(crate) init_method: ContentSourceInitMethod<T>,
}

impl<T> ContentSource<T> {
    pub fn new<P>(name: P, entries: ContentSourceInitMethod<T>) -> Self
    where
        P: Into<String>,
    {
        Self {
            name: name.into(),
            entries: FxHashMap::default(),
            init_method: entries,
        }
    }

    pub fn get_entry(&self, id: &str) -> &Entry<T> {
        self.entries
            .get(id)
            .unwrap_or_else(|| panic!("Entry with id '{}' not found", id))
    }

    pub fn get_entry_safe(&self, id: &str) -> Option<&Entry<T>> {
        self.entries.get(id)
    }

    pub fn into_params<P>(&self, cb: impl FnMut(&Entry<T>) -> P) -> Vec<P>
    where
        P: Into<PageParams>,
    {
        self.entries.values().map(cb).collect()
    }

    pub fn into_pages<Params, Props>(
        &self,
        cb: impl FnMut(&Entry<T>) -> crate::route::Page<Params, Props>,
    ) -> crate::route::Pages<Params, Props>
    where
        Params: Into<PageParams>,
    {
        self.entries.values().map(cb).collect()
    }
}

#[doc(hidden)]
/// Used internally by Maudit and should not be implemented by the user.
/// We expose it because it's implemented for [`ContentSource`], which is public.
pub trait ContentSourceInternal: Send + Sync {
    fn init(&mut self);
    fn get_name(&self) -> &str;
    fn as_any(&self) -> &dyn Any; // Used for type checking at runtime

    /// Return (entry_id, file_paths) for each entry.
    /// Used by the incremental build system to track file hashes.
    fn entry_file_info(&self) -> Vec<(String, Vec<PathBuf>)>;

    /// Return (entry_id, raw_content) for entries that have raw content loaded.
    /// Used to hash content without re-reading files from disk.
    fn entry_raw_content(&self) -> FxHashMap<String, &str> {
        FxHashMap::default()
    }

    /// Return sorted entry IDs for structural change detection.
    fn entry_ids(&self) -> Vec<String>;
}

impl<T: 'static + Sync + Send> ContentSourceInternal for ContentSource<T> {
    fn init(&mut self) {
        self.entries = (self.init_method)()
            .into_iter()
            .map(|e| (e.id.clone(), e))
            .collect();
    }
    fn get_name(&self) -> &str {
        &self.name
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn entry_file_info(&self) -> Vec<(String, Vec<PathBuf>)> {
        self.entries
            .values()
            .map(|e| {
                let files = e
                    .dependencies
                    .iter()
                    .map(|d| match d {
                        Dependency::File(p) => p.clone(),
                    })
                    .collect();
                (e.id.clone(), files)
            })
            .collect()
    }
    fn entry_raw_content(&self) -> FxHashMap<String, &str> {
        self.entries
            .values()
            .filter_map(|e| e.raw_content.as_deref().map(|rc| (e.id.clone(), rc)))
            .collect()
    }
    fn entry_ids(&self) -> Vec<String> {
        let mut ids: Vec<String> = self.entries.keys().cloned().collect();
        ids.sort();
        ids
    }
}