larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
Documentation
//! One social card per post and language, for every collection with cards on.
//!
//! Registered with Laracards on its own, so `cards:generate` draws them with the rest. The card is
//! keyed by collection, language and post, and named after the slug of its language, because that
//! is the address a preview is fetched for. Scheduled posts get theirs too, so the card exists the
//! morning the post goes out.

use async_trait::async_trait;
use laracards::{Card, CardSource};
use serde_json::json;

use crate::{CardSettings, Post, support};

/// The cards of every collection.
#[derive(Debug, Clone, Copy, Default)]
pub struct PostCards;

#[async_trait]
impl CardSource for PostCards {
    async fn cards(&self) -> laravel::Result<Vec<Card>> {
        let mut cards = Vec::new();

        for (_, blog) in crate::collections() {
            let settings = blog.settings().cards;

            if !settings.enabled {
                continue;
            }

            for post in blog.all() {
                if post.draft || post.card_path().is_none() {
                    continue;
                }

                cards.push(Self::card(&post, &settings));
            }
        }

        Ok(cards)
    }
}

impl PostCards {
    /// The card of one post.
    pub fn card(post: &Post, settings: &CardSettings) -> Card {
        let category = post.category();
        let app = &laravel::config().app;
        let brand = settings.brand.clone().unwrap_or_else(|| {
            app.url
                .split("://")
                .nth(1)
                .unwrap_or(&app.url)
                .split(['/', ':'])
                .next()
                .unwrap_or_default()
                .to_owned()
        });
        let accent = category
            .as_ref()
            .and_then(|category| category.meta("accent").and_then(|value| support::scalar_text(&value)))
            .or_else(|| category.as_ref().and_then(|category| category.color.clone()))
            .unwrap_or_default();

        Card::make(format!("larablog:{}:{}:{}", post.collection, post.locale, post.id))
            .template(settings.template.clone())
            .data(json!({
                "title": post.title,
                "description": post.description.clone().unwrap_or_default(),
                "category_label": category.as_ref().map_or_else(String::new, |category| category.name.to_uppercase()),
                "accent": accent,
                "author_name": post.author().map(|author| author.name).unwrap_or_default(),
                "date_formatted": support::long_date(post.date, &post.locale),
                "reading_time": post.reading_time.to_string(),
                "brand_label": brand,
                "locale": post.locale,
            }))
            .output(app.public_path(post.card_path().unwrap_or_default()))
    }
}