1use std::cell::RefCell;
33use std::collections::HashMap;
34use std::sync::Arc;
35
36use rustango::core::Column as _;
37use rustango::sql::FetcherPool as _;
38use tera::{Filter, Function, Tera, Value};
39
40use crate::page::Page;
41
42pub const MAX_PREFETCH_IDS: usize = 16;
45
46thread_local! {
47 static CURRENT_PAGES_BY_ID: RefCell<Option<Arc<HashMap<i64, String>>>>
51 = const { RefCell::new(None) };
52
53 static CURRENT_URL_PREFIX: RefCell<String> = const { RefCell::new(String::new()) };
58 static CURRENT_SITE_PREFIX: RefCell<String> = const { RefCell::new(String::new()) };
60}
61
62#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
66pub struct PageUrlGuard {
67 _priv: (),
69}
70
71impl Drop for PageUrlGuard {
72 fn drop(&mut self) {
73 CURRENT_PAGES_BY_ID.with(|cell| {
74 *cell.borrow_mut() = None;
75 });
76 }
77}
78
79pub fn install(pages_by_id: HashMap<i64, String>) -> PageUrlGuard {
83 CURRENT_PAGES_BY_ID.with(|cell| {
84 *cell.borrow_mut() = Some(Arc::new(pages_by_id));
85 });
86 PageUrlGuard { _priv: () }
87}
88
89#[must_use]
95pub fn lookup(id: i64) -> Option<String> {
96 if id <= 0 {
97 return None;
98 }
99 CURRENT_PAGES_BY_ID.with(|cell| cell.borrow().as_ref().and_then(|m| m.get(&id).cloned()))
100}
101
102#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
105pub struct UrlPrefixGuard {
106 _priv: (),
107}
108
109impl Drop for UrlPrefixGuard {
110 fn drop(&mut self) {
111 CURRENT_URL_PREFIX.with(|cell| cell.borrow_mut().clear());
112 }
113}
114
115#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
117pub struct SitePrefixGuard {
118 _priv: (),
119}
120impl Drop for SitePrefixGuard {
121 fn drop(&mut self) {
122 CURRENT_SITE_PREFIX.with(|cell| cell.borrow_mut().clear());
123 }
124}
125
126pub fn install_site_prefix(prefix: &str) -> SitePrefixGuard {
134 CURRENT_SITE_PREFIX.with(|cell| {
135 *cell.borrow_mut() = prefix.to_owned();
136 });
137 SitePrefixGuard { _priv: () }
138}
139
140fn current_site_prefix() -> String {
141 CURRENT_SITE_PREFIX.with(|cell| cell.borrow().clone())
142}
143
144pub fn install_url_prefix(prefix: &str) -> UrlPrefixGuard {
148 CURRENT_URL_PREFIX.with(|cell| {
149 *cell.borrow_mut() = prefix.to_owned();
150 });
151 UrlPrefixGuard { _priv: () }
152}
153
154fn current_url_prefix() -> String {
155 CURRENT_URL_PREFIX.with(|cell| cell.borrow().clone())
156}
157
158pub fn register_tera_function(tera: &mut Tera) {
168 tera.register_function("pageurl", PageurlFn);
169 tera.register_filter("pageurl", PageurlFilter);
170 tera.register_function("page_href", PageHrefFn);
177 tera.register_filter("page_href", PageHrefFilter);
178 tera.register_function("page_link", PageLinkFn);
184 tera.register_filter("page_link", PageLinkFilter);
185}
186
187struct PageLinkFn;
188
189impl Function for PageLinkFn {
190 fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
191 let (href, title) = match args.get("page") {
192 Some(page) => (href_from_value(page), title_from_value(page)),
193 None => {
194 let id = args.get("id").and_then(read_id);
195 (href_from_id(id), None)
196 }
197 };
198 let class = args.get("class").and_then(Value::as_str);
199 Ok(Value::String(anchor(&href, title.as_deref(), class)))
200 }
201 fn is_safe(&self) -> bool {
202 true
203 }
204}
205
206struct PageLinkFilter;
207
208impl Filter for PageLinkFilter {
209 fn filter(&self, value: &Value, args: &HashMap<String, Value>) -> tera::Result<Value> {
210 let class = args.get("class").and_then(Value::as_str);
211 Ok(Value::String(anchor(
212 &href_from_value(value),
213 title_from_value(value).as_deref(),
214 class,
215 )))
216 }
217 fn is_safe(&self) -> bool {
218 true
219 }
220}
221
222fn title_from_value(value: &Value) -> Option<String> {
225 value
226 .get("title")
227 .and_then(Value::as_str)
228 .filter(|s| !s.is_empty())
229 .map(str::to_owned)
230}
231
232fn anchor(href: &str, title: Option<&str>, class: Option<&str>) -> String {
235 let label = escape_html(title.unwrap_or(href));
236 match class {
237 Some(c) if !c.is_empty() => {
238 format!(r#"<a class="{}" href="{href}">{label}</a>"#, escape_html(c))
239 }
240 _ => format!(r#"<a href="{href}">{label}</a>"#),
241 }
242}
243
244fn escape_html(s: &str) -> String {
249 let mut out = String::with_capacity(s.len());
250 for c in s.chars() {
251 match c {
252 '&' => out.push_str("&"),
253 '<' => out.push_str("<"),
254 '>' => out.push_str(">"),
255 '"' => out.push_str("""),
256 '\'' => out.push_str("'"),
257 _ => out.push(c),
258 }
259 }
260 out
261}
262
263struct PageHrefFn;
264
265impl Function for PageHrefFn {
266 fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
267 let href = match args.get("page") {
269 Some(page) => href_from_value(page),
270 None => href_from_id(args.get("id").and_then(read_id)),
271 };
272 Ok(Value::String(href))
273 }
274 fn is_safe(&self) -> bool {
275 true
276 }
277}
278
279struct PageHrefFilter;
280
281impl Filter for PageHrefFilter {
282 fn filter(&self, value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
283 Ok(Value::String(href_from_value(value)))
284 }
285 fn is_safe(&self) -> bool {
286 true
287 }
288}
289
290fn href_from_value(value: &Value) -> String {
293 if let Some(url_path) = value.get("url_path").and_then(Value::as_str) {
294 return with_prefix(url_path);
295 }
296 href_from_id(read_id(value))
298}
299
300fn href_from_id(id: Option<i64>) -> String {
303 match id.and_then(lookup) {
304 Some(url_path) => with_prefix(&url_path),
305 None => "#".to_owned(),
306 }
307}
308
309fn with_prefix(url_path: &str) -> String {
312 let prefix = current_url_prefix();
313 let site = current_site_prefix();
318 let url_path = crate::site::to_public_path(&site, url_path);
319 if url_path.is_empty() {
320 format!("{prefix}/")
321 } else {
322 format!("{prefix}{url_path}")
323 }
324}
325
326struct PageurlFn;
327
328impl Function for PageurlFn {
329 fn call(&self, args: &HashMap<String, Value>) -> tera::Result<Value> {
330 let id = args.get("id").and_then(read_id);
331 Ok(Value::String(href_from_id(id)))
333 }
334 fn is_safe(&self) -> bool {
335 true
336 }
337}
338
339struct PageurlFilter;
340
341impl Filter for PageurlFilter {
342 fn filter(&self, value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
343 Ok(Value::String(href_from_id(read_id(value))))
344 }
345 fn is_safe(&self) -> bool {
346 true
347 }
348}
349
350fn read_id(v: &Value) -> Option<i64> {
354 if v.is_null() {
355 return None;
356 }
357 if let Some(n) = v.as_i64() {
358 return Some(n);
359 }
360 v.as_str()
361 .map(str::trim)
362 .filter(|s| !s.is_empty())
363 .and_then(|s| s.parse::<i64>().ok())
364}
365
366pub async fn prefetch_for_extension(
378 extension: &serde_json::Value,
379 pool: &rustango::sql::Pool,
380) -> HashMap<i64, String> {
381 let mut ids: Vec<i64> = candidate_ids(extension);
382 if ids.is_empty() {
383 return HashMap::new();
384 }
385 ids.sort_unstable();
388 ids.dedup();
389 if ids.len() > MAX_PREFETCH_IDS {
390 tracing::debug!(
391 target: "rustango_cms::page_url",
392 count = ids.len(),
393 cap = MAX_PREFETCH_IDS,
394 "extension referenced more *_id fields than the prefetch cap; tail truncated",
395 );
396 ids.truncate(MAX_PREFETCH_IDS);
397 }
398 match Page::objects()
399 .where_(Page::id.is_in(ids))
400 .fetch(pool)
401 .await
402 {
403 Ok(rows) => rows
404 .into_iter()
405 .filter_map(|p| p.id.get().copied().map(|id| (id, p.url_path)))
406 .collect(),
407 Err(e) => {
408 tracing::warn!(
409 target: "rustango_cms::page_url",
410 error = %e,
411 "pageurl prefetch failed; templates will see '#'",
412 );
413 HashMap::new()
414 }
415 }
416}
417
418fn candidate_ids(extension: &serde_json::Value) -> Vec<i64> {
429 let Some(obj) = extension.as_object() else {
430 return Vec::new();
431 };
432 obj.iter()
433 .filter(|(k, _)| k.ends_with("_id"))
434 .filter_map(|(_, v)| read_id(v))
435 .filter(|n| *n > 0)
436 .collect()
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442 use serde_json::json;
443 use tera::{Context, Tera};
444
445 fn fresh_tera() -> Tera {
446 let mut tera = Tera::default();
447 register_tera_function(&mut tera);
448 tera
449 }
450
451 #[test]
452 fn function_resolves_known_id() {
453 let mut map = HashMap::new();
454 map.insert(42i64, "/about".to_owned());
455 let _guard = install(map);
456
457 let tera = fresh_tera();
458 let mut t = tera.clone();
459 t.add_raw_template("t.html", "{{ pageurl(id=42) }}")
460 .unwrap();
461 let out = t.render("t.html", &Context::new()).unwrap();
462 assert_eq!(out, "/about");
463 }
464
465 #[test]
466 fn function_returns_hash_for_unknown_id() {
467 let _guard = install(HashMap::new());
468 let tera = fresh_tera();
469 let mut t = tera.clone();
470 t.add_raw_template("t.html", "{{ pageurl(id=999) }}")
471 .unwrap();
472 let out = t.render("t.html", &Context::new()).unwrap();
473 assert_eq!(out, "#");
474 }
475
476 #[test]
477 fn function_returns_hash_for_zero_and_negative() {
478 let mut map = HashMap::new();
479 map.insert(0i64, "/should-not-leak".to_owned());
480 let _guard = install(map);
481 let tera = fresh_tera();
482 let mut t = tera.clone();
483 t.add_raw_template("z.html", "{{ pageurl(id=0) }}").unwrap();
484 t.add_raw_template("n.html", "{{ pageurl(id=-3) }}")
485 .unwrap();
486 assert_eq!(t.render("z.html", &Context::new()).unwrap(), "#");
487 assert_eq!(t.render("n.html", &Context::new()).unwrap(), "#");
488 }
489
490 #[test]
491 fn function_accepts_stringified_id() {
492 let mut map = HashMap::new();
494 map.insert(7i64, "/team".to_owned());
495 let _guard = install(map);
496 let tera = fresh_tera();
497 let mut t = tera.clone();
498 t.add_raw_template("t.html", r#"{{ pageurl(id="7") }}"#)
499 .unwrap();
500 assert_eq!(t.render("t.html", &Context::new()).unwrap(), "/team");
501 }
502
503 #[test]
504 fn filter_resolves_known_id() {
505 let mut map = HashMap::new();
506 map.insert(3i64, "/blog".to_owned());
507 let _guard = install(map);
508 let tera = fresh_tera();
509 let mut t = tera.clone();
510 let mut ctx = Context::new();
511 ctx.insert("hero_cta_page_id", &3i64);
512 t.add_raw_template("t.html", "{{ hero_cta_page_id | pageurl }}")
513 .unwrap();
514 assert_eq!(t.render("t.html", &ctx).unwrap(), "/blog");
515 }
516
517 #[test]
518 fn filter_returns_hash_for_null() {
519 let _guard = install(HashMap::new());
520 let tera = fresh_tera();
521 let mut t = tera.clone();
522 let mut ctx = Context::new();
523 ctx.insert("maybe_id", &serde_json::Value::Null);
524 t.add_raw_template("t.html", "{{ maybe_id | pageurl }}")
525 .unwrap();
526 assert_eq!(t.render("t.html", &ctx).unwrap(), "#");
527 }
528
529 #[test]
530 fn guard_clears_thread_local() {
531 {
532 let mut map = HashMap::new();
533 map.insert(1i64, "/x".to_owned());
534 let _g = install(map);
535 assert_eq!(href_from_id(Some(1)), "/x");
536 }
537 assert_eq!(href_from_id(Some(1)), "#");
538 }
539
540 #[test]
541 fn candidate_ids_picks_up_underscore_id_fields() {
542 let ext = json!({
543 "title": "Home",
544 "hero_cta_page_id": 4,
545 "related_page_id": "9",
546 "irrelevant": 1,
547 "body_stream": [{"type": "page_chooser", "value": {"page_id": 99}}],
548 "expire_at_id": null,
549 });
550 let mut ids = candidate_ids(&ext);
551 ids.sort_unstable();
552 assert_eq!(ids, vec![4, 9]);
553 }
554
555 #[test]
556 fn candidate_ids_ignores_non_object_extension() {
557 assert!(candidate_ids(&serde_json::Value::Null).is_empty());
558 assert!(candidate_ids(&json!([1, 2, 3])).is_empty());
559 assert!(candidate_ids(&json!("string")).is_empty());
560 }
561
562 #[test]
563 fn candidate_ids_skips_non_positive() {
564 let ext = json!({"foo_id": 0, "bar_id": -1, "baz_id": 5});
565 let ids = candidate_ids(&ext);
566 assert_eq!(ids, vec![5]);
567 }
568
569 fn render_expr(expr: &str, ctx: &Context) -> String {
572 let mut t = fresh_tera();
573 t.add_raw_template("t.html", expr).unwrap();
574 t.render("t.html", ctx).unwrap()
575 }
576
577 #[test]
578 fn page_href_filter_uses_full_url_path_not_leaf_slug() {
579 let _prefix = install_url_prefix("");
581 let mut ctx = Context::new();
582 ctx.insert(
583 "child",
584 &json!({ "slug": "team", "url_path": "/about/team", "title": "Team" }),
585 );
586 assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/about/team");
587 }
588
589 #[test]
590 fn page_href_prepends_mount_prefix() {
591 let _prefix = install_url_prefix("/p");
592 let mut ctx = Context::new();
593 ctx.insert("child", &json!({ "url_path": "/about" }));
594 assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/p/about");
595 }
596
597 #[test]
598 fn page_href_function_form_and_id_resolution() {
599 let mut map = HashMap::new();
600 map.insert(42i64, "/about".to_owned());
601 let _guard = install(map);
602 let _prefix = install_url_prefix("/p");
603 let mut ctx = Context::new();
605 ctx.insert("anc", &json!({ "url_path": "/about/team" }));
606 assert_eq!(
607 render_expr("{{ page_href(page=anc) }}", &ctx),
608 "/p/about/team"
609 );
610 assert_eq!(
612 render_expr("{{ page_href(id=42) }}", &Context::new()),
613 "/p/about"
614 );
615 }
616
617 #[test]
618 fn page_href_missing_and_empty() {
619 let _guard = install(HashMap::new());
620 let _prefix = install_url_prefix("");
621 assert_eq!(render_expr("{{ page_href(id=999) }}", &Context::new()), "#");
623 let mut ctx = Context::new();
625 ctx.insert("root", &json!({ "url_path": "" }));
626 assert_eq!(render_expr("{{ root | page_href }}", &ctx), "/");
627 }
628
629 #[test]
630 fn page_href_prefix_guard_clears() {
631 {
632 let _p = install_url_prefix("/p");
633 assert_eq!(current_url_prefix(), "/p");
634 }
635 assert_eq!(current_url_prefix(), "");
636 }
637
638
639 #[test]
642 fn site_prefix_is_stripped_before_the_mount_prefix_is_added() {
643 let _mount = install_url_prefix("/p");
644 let _site = install_site_prefix("/site-b");
645 let mut ctx = Context::new();
646 ctx.insert("child", &json!({ "url_path": "/site-b/about" }));
647 assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/p/about");
648 }
649
650 #[test]
651 fn the_site_root_itself_links_to_the_mount_root() {
652 let _mount = install_url_prefix("");
653 let _site = install_site_prefix("/site-b");
654 let mut ctx = Context::new();
655 ctx.insert("child", &json!({ "url_path": "/site-b" }));
656 assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/");
657 }
658
659 #[test]
662 fn a_page_outside_the_site_keeps_its_absolute_path() {
663 let _mount = install_url_prefix("");
664 let _site = install_site_prefix("/site-b");
665 let mut ctx = Context::new();
666 ctx.insert("child", &json!({ "url_path": "/other/page" }));
667 assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/other/page");
668 }
669
670 #[test]
673 fn no_site_prefix_means_unchanged_behaviour() {
674 let _mount = install_url_prefix("/p");
675 let mut ctx = Context::new();
676 ctx.insert("child", &json!({ "url_path": "/about" }));
677 assert_eq!(render_expr("{{ child | page_href }}", &ctx), "/p/about");
678 }
679
680 #[test]
682 fn pageurl_strips_the_site_and_adds_the_mount_prefix() {
683 let _mount = install_url_prefix("/p");
684 let _site = install_site_prefix("/site-b");
685 let _pages = install(HashMap::from([(4i64, "/site-b/about".to_owned())]));
686 let ctx = Context::new();
687 assert_eq!(render_expr("{{ pageurl(id=4) }}", &ctx), "/p/about");
688 assert_eq!(render_expr("{{ 4 | pageurl }}", &ctx), "/p/about");
689 }
690}