larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
use std::path::PathBuf;
use std::sync::LazyLock;

use laravel::time::{Dates, Timestamp};
use regex::Regex;
use serde_json::{Map, Value};

use crate::conditionals::Condition;
use crate::markdown::Heading;
use crate::support;
use crate::{Author, Blog, Category, LarablogConfig};

static VISIBLE_HEADING: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"(?i)<h[23]\b[^>]*\bid="([^"]+)""#).expect("a valid pattern"));

/// One post in one language.
///
/// `id` is the folder, shared by every translation and never part of a URL; `slug` is this
/// language's own. The body is rendered on first use and cached, so a listing of fifty posts never
/// renders fifty bodies.
#[derive(Debug, Clone, PartialEq)]
pub struct Post {
    /// The collection it belongs to.
    pub collection: String,
    /// The folder, shared by every translation.
    pub id: String,
    /// The language of this file.
    pub locale: String,
    /// The slug of this language.
    pub slug: String,
    /// The title.
    pub title: String,
    /// `description`, or `excerpt`.
    pub description: Option<String>,
    /// When it goes out. A date in the future schedules it.
    pub date: Timestamp,
    /// When it last changed, from `updated` or `updated_at`.
    pub updated: Option<Timestamp>,
    /// The category's key.
    pub category: Option<String>,
    /// Its tags, as written.
    pub tags: Vec<String>,
    /// The author's key.
    pub author: Option<String>,
    /// The picture, from `image` or `cover`.
    pub image: Option<String>,
    /// Its alternative text, from `image_alt` or `cover_alt`.
    pub image_alt: Option<String>,
    /// Whether the frontmatter marks it as featured.
    pub featured: bool,
    /// A draft is never published.
    pub draft: bool,
    /// Minutes to read, from `reading_time` or the word count.
    pub reading_time: u32,
    /// Every other frontmatter field, as written.
    pub meta: Map<String, Value>,
    /// The file it was read from.
    pub file: PathBuf,
}

impl Post {
    /// The collection it belongs to.
    ///
    /// # Panics
    ///
    /// Panics when the collection is no longer in the configuration.
    pub fn blog(&self) -> Blog {
        crate::collection(&self.collection).expect("a post belongs to a configured collection")
    }

    /// Whether the post can be shown: not a draft and not dated in the future, unless the
    /// configuration says to preview those.
    pub fn is_published(&self) -> bool {
        let config = laravel::config();
        let settings = config.section::<LarablogConfig>();

        if self.draft && !settings.show_drafts {
            return false;
        }

        !self.date.is_future() || settings.show_scheduled
    }

    /// The body as HTML, with `post:` links and conditions resolved for this visit.
    pub fn html(&self) -> String {
        let blog = self.blog();

        blog.resolve_links(&blog.rendered(self).html, &self.locale)
    }

    /// The `h2` and `h3` of the body, each with the id its anchor carries: an "On this page" index.
    /// A heading inside a condition that does not hold is left out.
    pub fn headings(&self) -> Vec<Heading> {
        let rendered = self.blog().rendered(self);

        if !rendered.html.contains("<!--larablog:if-published:") {
            return rendered.headings.clone();
        }

        let html = self.html();
        let visible: Vec<&str> = VISIBLE_HEADING
            .captures_iter(&html)
            .filter_map(|found| found.get(1).map(|id| id.as_str()))
            .collect();

        rendered
            .headings
            .iter()
            .filter(|heading| visible.contains(&heading.id.as_str()))
            .cloned()
            .collect()
    }

    /// The conditions the body declares, closed or not.
    pub fn conditions(&self) -> Vec<Condition> {
        crate::conditionals::references(&self.blog().rendered(self).html)
    }

    /// Its address, absolute.
    pub fn url(&self) -> String {
        self.url_with(true)
    }

    /// Its address, absolute or just the path.
    pub fn url_with(&self, absolute: bool) -> String {
        self.blog()
            .url("show", Some(&self.locale), &[("slug", &self.slug)], absolute)
    }

    /// The same post in every language it is written in, language => URL, this one included.
    pub fn alternates(&self) -> Vec<(String, String)> {
        self.translations(true)
            .into_iter()
            .map(|(locale, post)| (locale, post.url()))
            .collect()
    }

    /// The same post in the other languages, or in every language with `include_self`.
    pub fn translations(&self, include_self: bool) -> Vec<(String, Post)> {
        self.blog().translations_of(self, include_self)
    }

    /// Who wrote it, in this post's language.
    pub fn author(&self) -> Option<Author> {
        self.author
            .as_deref()
            .map(|key| self.blog().author(key, Some(&self.locale)))
    }

    /// Its category, in this post's language.
    pub fn category(&self) -> Option<Category> {
        self.category
            .as_deref()
            .and_then(|key| self.blog().category(key, Some(&self.locale)))
    }

    /// Posts in the same language that share the category or tags, the closest first.
    pub fn related(&self, limit: usize) -> Vec<Post> {
        self.blog().related(self, limit)
    }

    /// The picture for the post and its social preview: the one the frontmatter names, or the card
    /// Laracards drew for it, or `None`.
    pub fn image_url(&self) -> Option<String> {
        if let Some(image) = &self.image {
            return Some(if image.starts_with("http") {
                image.clone()
            } else {
                laravel::url::to(&format!("/{}", image.trim_start_matches('/')))
            });
        }

        let card = self.card_path()?;
        let config = laravel::config();

        config
            .app
            .public_path(&card)
            .is_file()
            .then(|| laravel::url::to(&format!("/{card}")))
    }

    /// Where this post's card lives, relative to `public/`, or `None` when cards are off.
    pub fn card_path(&self) -> Option<String> {
        let settings = self.blog().settings();

        settings.cards.enabled.then(|| {
            format!(
                "{}/{}/{}.png",
                settings.cards.path.trim_matches('/'),
                self.locale,
                self.slug
            )
        })
    }

    /// A frontmatter field that has no property of its own, with dots for depth.
    pub fn meta(&self, key: &str) -> Option<Value> {
        support::data_get(&Value::Object(self.meta.clone()), key).cloned()
    }
}