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
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()
}
}