larablog 0.1.0

Markdown blogs for Laravel Rust in several languages, where every language has its own URL.
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};

use laravel::time::Timestamp;
use regex::{Captures, Regex};
use serde::Serialize;
use serde_json::Value;

use crate::conditionals;
use crate::config::{CollectionConfig, LarablogConfig};
use crate::index::{IndexData, IndexError, Source};
use crate::markdown::{Markdown, Rendered};
use crate::routes::{self, Kind};
use crate::{Author, Category, Error, Post, support};

static POST_LINK: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?s)<a\b([^>]*?)\shref="post:([A-Za-z0-9_.-]+)([#?][^"]*)?"([^>]*)>(.*?)</a>"#)
        .expect("a valid pattern")
});
static LINKED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"\]\(post:([A-Za-z0-9_.-]+)|href="post:([A-Za-z0-9_.-]+)"#).expect("a valid pattern")
});

/// What the cache of the process holds for each collection.
pub(crate) struct Shared {
    pub(crate) markdown: Markdown,
    indexes: Mutex<HashMap<String, Entry>>,
}

struct Entry {
    signature: String,
    checked_at: i64,
    index: Arc<IndexData>,
}

impl Shared {
    pub(crate) fn new() -> Self {
        Self {
            markdown: Markdown::new(),
            indexes: Mutex::new(HashMap::new()),
        }
    }
}

tokio::task_local! {
    static SCOPE: Scope;
}

/// What one request, command or test has already read, so one page sees one snapshot: the scoped
/// instance of the PHP package.
#[derive(Default)]
struct Scope {
    indexes: Mutex<HashMap<String, Arc<IndexData>>>,
    url: Option<String>,
}

/// Run a future with one snapshot of the collections, and the address of the page being served.
/// [`UseLocale`](crate::UseLocale) does it for every request of the blog; wrap a command or a test
/// in it to read each collection once.
pub async fn scoped<F: std::future::Future>(url: Option<String>, future: F) -> F::Output {
    SCOPE
        .scope(
            Scope {
                indexes: Mutex::new(HashMap::new()),
                url,
            },
            future,
        )
        .await
}

/// Forget what the current [`scoped`] snapshot has read, so the next call reads the collections
/// again. PHP does it with `forgetScopedInstances()`.
pub fn flush() {
    let _ = SCOPE.try_with(|scope| scope.indexes.lock().unwrap_or_else(PoisonError::into_inner).clear());
}

/// A tag of the published posts of a language, with how many use it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Tag {
    /// Its slug.
    pub slug: String,
    /// Its name, as written the first time.
    pub name: String,
    /// How many published posts carry it.
    pub count: usize,
}

/// A page of a listing.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Pagination<T> {
    /// The posts of this page.
    pub items: Vec<T>,
    /// The page shown, from 1.
    pub current_page: usize,
    /// The last page.
    pub last_page: usize,
    /// Posts per page.
    pub per_page: usize,
    /// Posts in the whole listing.
    pub total: usize,
    /// The address of the previous page.
    pub prev_page_url: Option<String>,
    /// The address of the next page.
    pub next_page_url: Option<String>,
}

impl<T> Pagination<T> {
    /// Whether there is more than one page.
    pub fn has_pages(&self) -> bool {
        self.last_page > 1
    }
}

/// One address of the collection for a sitemap, with its alternates.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SitemapEntry {
    /// The address.
    pub loc: String,
    /// When it last changed, as an Atom date, or `None` for a listing.
    pub lastmod: Option<String>,
    /// Language => address of the same page, this one included.
    pub alternates: Vec<(String, String)>,
}

/// One collection: its posts in every language, and every question a site asks of them.
#[derive(Clone)]
pub struct Blog {
    name: String,
    shared: Arc<Shared>,
}

impl std::fmt::Debug for Blog {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.debug_struct("Blog").field("name", &self.name).finish()
    }
}

impl Blog {
    pub(crate) fn new(name: &str, shared: Arc<Shared>) -> Self {
        Self {
            name: name.to_owned(),
            shared,
        }
    }

    /// The collection's name, as `config.collections` has it.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The collection's settings, read live from the configuration. PHP's `config($key)`.
    pub fn settings(&self) -> CollectionConfig {
        laravel::config()
            .section::<LarablogConfig>()
            .collections
            .get(&self.name)
            .cloned()
            .unwrap_or_default()
    }

    /// The languages the collection is written in, the default first.
    pub fn locales(&self) -> Vec<String> {
        let supported = laravel::config()
            .get::<laralocale::LocaleConfig>()
            .map(|config| config.supported.clone())
            .unwrap_or_default();

        support::resolve_locales(self.settings().locales.as_deref(), &supported, &app_locale())
    }

    /// Published posts in one language, newest first.
    pub fn posts(&self, locale: Option<&str>) -> Vec<Post> {
        let locale = locale_or_current(locale);

        self.index()
            .posts
            .iter()
            .filter(|post| post.locale == locale && post.is_published())
            .cloned()
            .collect()
    }

    /// Every post in every language, drafts and scheduled ones included.
    pub fn all(&self) -> Vec<Post> {
        self.index().posts.clone()
    }

    /// A published post by its slug in a language.
    pub fn find(&self, slug: &str, locale: Option<&str>) -> Option<Post> {
        let locale = locale_or_current(locale);
        let index = self.index();
        let position = index.lookup.get(&locale)?.get(slug)?;

        Self::published_at(&index, *position)
    }

    /// A published post whose slug this is in ANY language, for a link that arrived with the
    /// wrong language's slug.
    pub fn find_in_any_locale(&self, slug: &str) -> Option<Post> {
        let index = self.index();
        let mut positions: Vec<usize> = index
            .lookup
            .values()
            .filter_map(|slugs| slugs.get(slug).copied())
            .collect();

        positions.sort_unstable();

        positions
            .into_iter()
            .find_map(|position| Self::published_at(&index, position))
    }

    /// The same post in the collection's languages, in its order. Only published translations.
    pub fn translations_of(&self, post: &Post, include_self: bool) -> Vec<(String, Post)> {
        let index = self.index();
        let mut found: Vec<(String, Post)> = Vec::new();

        for locale in self.locales() {
            if !include_self && locale == post.locale {
                continue;
            }

            for candidate in &index.posts {
                if candidate.id == post.id && candidate.locale == locale && candidate.is_published() {
                    found.retain(|(existing, _)| *existing != locale);
                    found.push((locale.clone(), candidate.clone()));
                }
            }
        }

        found
    }

    /// The URL a `post:{id}` link should take from a page in this language: the post in this
    /// language, or, when it is not translated, in the first language it is published in.
    ///
    /// A link written by folder rather than by slug follows the reader's language and survives a
    /// slug being changed, which a hand-written `/es/blog/...` does not.
    pub fn link_to(&self, id: &str, locale: &str) -> Option<String> {
        let index = self.index();
        let positions = index.positions.get(id)?;

        std::iter::once(locale.to_owned())
            .chain(self.locales())
            .find_map(|wanted| {
                positions
                    .get(&wanted)
                    .and_then(|position| Self::published_at(&index, *position))
            })
            .map(|post| post.url())
    }

    /// Rewrite every link to `post:{id}` (optionally with `#anchor` or `?query`) to the URL of
    /// that post in the given language, and resolve the conditions.
    ///
    /// A post that exists but is not out yet (dated ahead, or a draft) is linked as its words
    /// alone, with no anchor: the link appears by itself the day the post goes live. A post that
    /// does not exist at all points at `#`, and `larablog:check` reports it.
    ///
    /// Done on the rendered HTML, after the cache, because the target can change without this
    /// file changing: a translation added, a slug renamed, a date reached.
    pub fn resolve_links(&self, html: &str, locale: &str) -> String {
        let html = conditionals::resolve(html, |id| self.link_to(id, locale).is_some());

        if !html.contains("href=\"post:") {
            return html;
        }

        POST_LINK
            .replace_all(&html, |found: &Captures<'_>| {
                let attributes = &found[1];
                let id = &found[2];
                let rest = found.get(3).map_or("", |m| m.as_str());
                let after = &found[4];
                let text = &found[5];

                if let Some(url) = self.link_to(id, locale) {
                    return format!("<a{attributes} href=\"{}{rest}\"{after}>{text}</a>", escape(&url));
                }

                if self.exists(id) {
                    text.to_owned()
                } else {
                    format!("<a{attributes} href=\"#\"{after}>{text}</a>")
                }
            })
            .into_owned()
    }

    /// Every `post:{id}` link in a post's body that leads to no post at all. A post that exists
    /// and is not published yet is not broken: its link is plain text until it is.
    pub fn broken_links(&self, post: &Post) -> Vec<String> {
        self.linked_ids(post)
            .into_iter()
            .filter(|id| self.link_to(id, &post.locale).is_none() && !self.exists(id))
            .collect()
    }

    /// Every `post:{id}` link in a post's body to a post that exists and is not out yet, with the
    /// day it goes live (`None` for a draft, which has none).
    pub fn pending_links(&self, post: &Post) -> Vec<(String, Option<Timestamp>)> {
        let index = self.index();
        let mut pending = Vec::new();

        for id in self.linked_ids(post) {
            if self.link_to(&id, &post.locale).is_some() || !self.exists(&id) {
                continue;
            }

            let date = index
                .posts
                .iter()
                .filter(|candidate| candidate.id == id && !candidate.draft)
                .map(|candidate| candidate.date)
                .min();

            pending.push((id, date));
        }

        pending
    }

    fn exists(&self, id: &str) -> bool {
        self.index().positions.contains_key(id)
    }

    fn linked_ids(&self, post: &Post) -> Vec<String> {
        let content = std::fs::read_to_string(&post.file).unwrap_or_default();
        let mut ids: Vec<String> = Vec::new();

        for found in LINKED.captures_iter(&content) {
            if let Some(id) = found.get(1).or_else(|| found.get(2)) {
                ids.push(id.as_str().to_owned());
            }
        }

        ids.extend(post.conditions().into_iter().map(|condition| condition.post));

        let mut unique: Vec<String> = Vec::new();

        for id in ids {
            if !id.is_empty() && !unique.contains(&id) {
                unique.push(id);
            }
        }

        unique
    }

    /// A category in a language.
    pub fn category(&self, key: &str, locale: Option<&str>) -> Option<Category> {
        let locale = locale_or_current(locale);
        let fallback = fallback_locale();
        let index = self.index();
        let definition = index.category(key)?;

        let name = match definition {
            Value::Object(map) => support::localized(Some(map.get("name").unwrap_or(definition)), &locale, &fallback)
                .unwrap_or_else(|| support::headline(key)),
            other => support::scalar_text(other).unwrap_or_default(),
        };

        let explicit_slug = match definition {
            Value::Object(map) => map
                .get("slug")
                .map(|slug| support::localized(Some(slug), &locale, &fallback).unwrap_or_default()),
            _ => None,
        };

        let slug = explicit_slug.unwrap_or_else(|| support::slug(&name));
        let slug = if slug.is_empty() { support::slug(key) } else { slug };

        let (description, color, meta) = match definition {
            Value::Object(map) => (
                support::localized(map.get("description"), &locale, &fallback),
                map.get("color").and_then(support::scalar_text),
                map.iter()
                    .filter(|(field, _)| !["name", "slug", "description", "color"].contains(&field.as_str()))
                    .map(|(field, value)| (field.clone(), value.clone()))
                    .collect(),
            ),
            _ => (None, None, serde_json::Map::new()),
        };

        Some(Category {
            collection: self.name.clone(),
            key: key.to_owned(),
            locale,
            name,
            slug,
            description,
            color,
            meta,
        })
    }

    /// Every category with at least one published post in the language, in the order of
    /// `_categories.yml`.
    pub fn categories(&self, locale: Option<&str>) -> Vec<Category> {
        let locale = locale_or_current(locale);
        let used: Vec<String> = self
            .posts(Some(&locale))
            .into_iter()
            .filter_map(|post| post.category)
            .collect();

        self.index()
            .categories
            .iter()
            .filter(|(key, _)| used.contains(key))
            .filter_map(|(key, _)| self.category(key, Some(&locale)))
            .collect()
    }

    /// A category by its slug in a language.
    pub fn category_by_slug(&self, slug: &str, locale: Option<&str>) -> Option<Category> {
        let locale = locale_or_current(locale);

        self.index()
            .categories
            .iter()
            .filter_map(|(key, _)| self.category(key, Some(&locale)))
            .find(|category| category.slug == slug)
    }

    /// The published posts of a category.
    pub fn in_category(&self, category: &Category) -> Vec<Post> {
        self.posts(Some(&category.locale))
            .into_iter()
            .filter(|post| post.category.as_deref() == Some(category.key.as_str()))
            .collect()
    }

    /// The tags of the language's published posts, the most used first.
    pub fn tags(&self, locale: Option<&str>) -> Vec<Tag> {
        let mut tags: Vec<Tag> = Vec::new();

        for post in self.posts(locale) {
            for tag in &post.tags {
                let slug = support::slug(tag);

                match tags.iter_mut().find(|existing| existing.slug == slug) {
                    Some(existing) => existing.count += 1,
                    None => tags.push(Tag {
                        slug,
                        name: tag.clone(),
                        count: 1,
                    }),
                }
            }
        }

        tags.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));

        tags
    }

    /// The published posts that carry a tag.
    pub fn with_tag(&self, slug: &str, locale: Option<&str>) -> Vec<Post> {
        self.posts(locale)
            .into_iter()
            .filter(|post| post.tags.iter().any(|tag| support::slug(tag) == slug))
            .collect()
    }

    /// An author, in a language. An author `_authors.yml` does not know is named by its key.
    pub fn author(&self, key: &str, locale: Option<&str>) -> Author {
        let locale = locale_or_current(locale);
        let fallback = fallback_locale();
        let index = self.index();

        match index.author(key) {
            None => Author::named(key, key),
            Some(Value::Object(map)) => Author {
                key: key.to_owned(),
                name: map
                    .get("name")
                    .and_then(support::scalar_text)
                    .unwrap_or_else(|| key.to_owned()),
                role: support::localized(map.get("role"), &locale, &fallback),
                bio: support::localized(map.get("bio"), &locale, &fallback),
                avatar: map.get("avatar").and_then(support::scalar_text),
                links: match map.get("links") {
                    Some(Value::Object(links)) => links
                        .iter()
                        .filter_map(|(name, url)| Some((name.clone(), support::scalar_text(url)?)))
                        .collect::<BTreeMap<_, _>>(),
                    _ => BTreeMap::new(),
                },
            },
            Some(other) => Author::named(key, support::scalar_text(other).unwrap_or_default()),
        }
    }

    /// Posts in the same language that share the category or tags, the closest first.
    pub fn related(&self, post: &Post, limit: usize) -> Vec<Post> {
        let mut scored: Vec<(usize, Post)> = Vec::new();

        for candidate in self.posts(Some(&post.locale)) {
            if candidate.id == post.id {
                continue;
            }

            let score = if post.category.is_some() && candidate.category == post.category {
                3
            } else {
                0
            } + post.tags.iter().filter(|tag| candidate.tags.contains(tag)).count();

            if score > 0 {
                scored.push((score, candidate));
            }
        }

        scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.date.cmp(&a.1.date)));

        scored.into_iter().map(|(_, post)| post).take(limit).collect()
    }

    /// One page of a listing. `page` is the `page` of the query string when `None`.
    pub fn paginate(&self, posts: Vec<Post>, page: Option<usize>) -> Pagination<Post> {
        let per_page = self.settings().per_page.max(1);
        let page = page
            .unwrap_or_else(|| usize::try_from(laravel::pagination::current_page()).unwrap_or(1))
            .max(1);
        let total = posts.len();
        let last_page = total.div_ceil(per_page).max(1);
        let base = current_url();
        let link = |page: usize| format!("{base}?page={page}");

        Pagination {
            items: posts.into_iter().skip((page - 1) * per_page).take(per_page).collect(),
            current_page: page,
            last_page,
            per_page,
            total,
            prev_page_url: (page > 1).then(|| link(page - 1)),
            next_page_url: (page < last_page).then(|| link(page + 1)),
        }
    }

    /// The address of a page of the collection.
    ///
    /// `kind` is `index`, `show`, `category`, `tag` or `feed`, and the parameters fill the
    /// `{slug}`, `{category}` or `{tag}` of its address. PHP asks Laravel's router; here the
    /// address comes from the collection's configuration, which is also what registers the routes.
    pub fn url(&self, kind: &str, locale: Option<&str>, parameters: &[(&str, &str)], absolute: bool) -> String {
        let Some(kind) = Kind::parse(kind) else {
            return "#".to_owned();
        };
        let locale = locale_or_current(locale);
        let uri = routes::uri(
            &self.name,
            kind,
            &locale,
            &self.settings(),
            &self.locales(),
            &app_locale(),
        );
        let path = routes::fill(&uri, parameters);

        if !absolute {
            return path;
        }

        let base = laravel::url::to("/");

        format!("{}{}", base.trim_end_matches('/'), if path == "/" { "" } else { &path })
    }

    /// The listing in every language: for the switcher and hreflang on the index.
    pub fn index_alternates(&self) -> Vec<(String, String)> {
        self.locales()
            .into_iter()
            .map(|locale| {
                let url = self.url("index", Some(&locale), &[], true);

                (locale, url)
            })
            .collect()
    }

    /// A category in every language it has posts in.
    pub fn category_alternates(&self, category: &Category) -> Vec<(String, String)> {
        self.locales()
            .into_iter()
            .filter_map(|locale| {
                let translated = self.category(&category.key, Some(&locale))?;

                (!self.in_category(&translated).is_empty()).then(|| (locale, translated.url()))
            })
            .collect()
    }

    /// Every address of the collection for a sitemap, each with its alternates.
    pub fn sitemap(&self) -> Vec<SitemapEntry> {
        let index = self.index_alternates();
        let mut entries: Vec<SitemapEntry> = index
            .iter()
            .map(|(_, url)| SitemapEntry {
                loc: url.clone(),
                lastmod: None,
                alternates: index.clone(),
            })
            .collect();

        for locale in self.locales() {
            for post in self.posts(Some(&locale)) {
                entries.push(SitemapEntry {
                    loc: post.url(),
                    lastmod: Some(support::atom(post.updated.unwrap_or(post.date))),
                    alternates: post.alternates(),
                });
            }
        }

        entries
    }

    /// Problems found reading the files.
    pub fn errors(&self) -> Vec<IndexError> {
        self.index().errors.clone()
    }

    /// Rebuild the shared index now; ordinary requests also build it when it is missing.
    ///
    /// # Errors
    ///
    /// Fails when the collection is not in the configuration.
    pub fn rebuild_index(&self) -> Result<usize, Error> {
        let index = self.load(true);

        Ok(index.posts.len())
    }

    /// The name of a route: `en.blog.show`.
    pub fn route_name(collection: &str, kind: &str, locale: &str) -> String {
        routes::route_name(collection, kind, locale)
    }

    pub(crate) fn rendered(&self, post: &Post) -> Arc<Rendered> {
        let caching = laravel::config().section::<LarablogConfig>().cache.enabled;

        self.shared
            .markdown
            .render(&post.file, caching)
            .unwrap_or_else(|error| {
                tracing::warn!(file = %post.file.display(), %error, "A post could not be rendered");

                Arc::new(Rendered {
                    html: String::new(),
                    headings: Vec::new(),
                })
            })
    }

    fn published_at(index: &IndexData, position: usize) -> Option<Post> {
        let post = index.posts.get(position)?;

        (post.is_published() && post.file.is_file()).then(|| post.clone())
    }

    fn source(&self) -> Source {
        let settings = laravel::config();
        let app = &settings.app;
        let path = std::path::Path::new(
            settings
                .section::<LarablogConfig>()
                .collections
                .get(&self.name)
                .map_or("", |c| c.path.as_str()),
        );
        let path = if path.is_absolute() {
            path.to_path_buf()
        } else {
            app.base_path.join(path)
        };

        Source {
            name: self.name.clone(),
            path,
            locales: self.locales(),
            words_per_minute: settings.section::<LarablogConfig>().words_per_minute,
        }
    }

    fn index(&self) -> Arc<IndexData> {
        let source = self.source();
        let key = source.key();

        if let Ok(Some(index)) = SCOPE.try_with(|scope| {
            scope
                .indexes
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .get(&key)
                .cloned()
        }) {
            return index;
        }

        let index = self.load_from(&source, false);

        remember(&key, &index);

        index
    }

    fn load(&self, force: bool) -> Arc<IndexData> {
        let source = self.source();
        let index = self.load_from(&source, force);

        remember(&source.key(), &index);

        index
    }

    fn load_from(&self, source: &Source, force: bool) -> Arc<IndexData> {
        let config = laravel::config();
        let settings = config.section::<LarablogConfig>();

        if !settings.cache.enabled {
            return Arc::new(source.build());
        }

        let interval = settings
            .cache
            .check_interval
            .unwrap_or(if config.app.env.is_production() { 60 } else { 0 });
        let now = laravel::now().timestamp().as_second();
        let key = source.key();
        let mut indexes = self.shared.indexes.lock().unwrap_or_else(PoisonError::into_inner);
        let entry = indexes.get(&key);

        if !force
            && let Some(entry) = entry
            && u64::try_from(now - entry.checked_at).is_ok_and(|elapsed| elapsed < interval)
        {
            return Arc::clone(&entry.index);
        }

        let signature = source.signature();
        let index = match entry {
            Some(entry) if !force && entry.signature == signature => Arc::clone(&entry.index),
            _ => Arc::new(source.build()),
        };

        indexes.insert(
            key,
            Entry {
                signature,
                checked_at: now,
                index: Arc::clone(&index),
            },
        );

        index
    }
}

fn escape(text: &str) -> String {
    text.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#039;")
}

fn app_locale() -> String {
    laravel::config()
        .get::<laralocale::LocaleConfig>()
        .map_or_else(|| "en".to_owned(), |config| config.locale.clone())
}

fn fallback_locale() -> String {
    laralocale::fallback_locale()
}

fn locale_or_current(locale: Option<&str>) -> String {
    locale.map_or_else(laralocale::locale, str::to_owned)
}

/// The address of the page being served, without its query string; outside a request, the
/// application's.
fn current_url() -> String {
    SCOPE
        .try_with(|scope| scope.url.clone())
        .ok()
        .flatten()
        .unwrap_or_else(|| laravel::url::to("/").trim_end_matches('/').to_owned())
}

fn remember(key: &str, index: &Arc<IndexData>) {
    let _ = SCOPE.try_with(|scope| {
        scope
            .indexes
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key.to_owned(), Arc::clone(index));
    });
}