1use std::cell::RefCell;
44use std::cmp::Ordering;
45use std::sync::Arc;
46
47use tera::{Function, Tera, Value};
48
49use crate::page::Page;
50
51thread_local! {
52 static CURRENT_CHILDREN: RefCell<Option<Arc<ChildrenSnapshot>>>
57 = const { RefCell::new(None) };
58}
59
60struct ChildrenSnapshot {
61 rendered_page_id: i64,
65 children: Vec<Page>,
66}
67
68#[must_use = "the guard clears the thread-local on drop; bind it to a local"]
73pub struct ChildrenGuard {
74 _priv: (),
75}
76
77impl Drop for ChildrenGuard {
78 fn drop(&mut self) {
79 CURRENT_CHILDREN.with(|cell| {
80 *cell.borrow_mut() = None;
81 });
82 }
83}
84
85pub fn install(rendered_page_id: i64, children: Vec<Page>) -> ChildrenGuard {
89 CURRENT_CHILDREN.with(|cell| {
90 *cell.borrow_mut() = Some(Arc::new(ChildrenSnapshot {
91 rendered_page_id,
92 children,
93 }));
94 });
95 ChildrenGuard { _priv: () }
96}
97
98pub fn register_tera_function(tera: &mut Tera) {
101 tera.register_function("children_filtered", ChildrenFilteredFn);
102}
103
104struct ChildrenFilteredFn;
105
106impl Function for ChildrenFilteredFn {
107 fn call(&self, args: &std::collections::HashMap<String, Value>) -> tera::Result<Value> {
108 let snap = CURRENT_CHILDREN.with(|cell| cell.borrow().clone());
109 let Some(snap) = snap else {
110 return Ok(Value::Array(Vec::new()));
115 };
116
117 if let Some(pid) = args.get("parent_id").and_then(Value::as_i64) {
121 if pid != snap.rendered_page_id {
122 return Ok(Value::Array(Vec::new()));
123 }
124 }
125
126 let mut out: Vec<Page> = snap.children.clone();
127
128 if let Some(want) = args.get("status").and_then(Value::as_str) {
130 out.retain(|p| p.status == want);
131 }
132
133 if let Some(spec) = args.get("order_by").and_then(Value::as_str) {
137 let (desc, field) = match spec.strip_prefix('-') {
138 Some(f) => (true, f),
139 None => (false, spec),
140 };
141 if !sort_by_field(&mut out, field, desc) {
142 tracing::debug!(
143 target: "rustango_cms::children_filtered",
144 field,
145 "children_filtered: unrecognized order_by field; leaving order unchanged",
146 );
147 }
148 }
149
150 if let Some(n) = args.get("limit").and_then(Value::as_i64) {
152 if n > 0 {
153 out.truncate(n as usize);
154 }
155 }
156
157 serde_json::to_value(&out).map_err(|e| {
158 tera::Error::msg(format!(
159 "children_filtered: serializing filtered pages failed: {e}"
160 ))
161 })
162 }
163}
164
165fn sort_by_field(rows: &mut [Page], field: &str, desc: bool) -> bool {
170 let cmp: fn(&Page, &Page) -> Ordering = match field {
171 "sort_order" => |a, b| a.sort_order.cmp(&b.sort_order).then(cmp_id(a, b)),
172 "id" => cmp_id,
173 "title" => |a, b| a.title.cmp(&b.title).then(cmp_id(a, b)),
174 "slug" => |a, b| a.slug.cmp(&b.slug).then(cmp_id(a, b)),
175 "depth" => |a, b| a.depth.cmp(&b.depth).then(cmp_id(a, b)),
176 "published_at" => |a, b| a.published_at.cmp(&b.published_at).then(cmp_id(a, b)),
177 "last_published_at" => |a, b| {
178 a.last_published_at
179 .cmp(&b.last_published_at)
180 .then(cmp_id(a, b))
181 },
182 "created_at" => |a, b| {
183 a.created_at
184 .get()
185 .copied()
186 .cmp(&b.created_at.get().copied())
187 .then(cmp_id(a, b))
188 },
189 "updated_at" => |a, b| {
190 a.updated_at
191 .get()
192 .copied()
193 .cmp(&b.updated_at.get().copied())
194 .then(cmp_id(a, b))
195 },
196 _ => return false,
197 };
198 if desc {
199 rows.sort_by(|a, b| cmp(b, a));
200 } else {
201 rows.sort_by(cmp);
202 }
203 true
204}
205
206fn cmp_id(a: &Page, b: &Page) -> Ordering {
207 a.id.get().copied().cmp(&b.id.get().copied())
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use chrono::{TimeZone, Utc};
214 use rustango::sql::Auto;
215 use serde_json::json;
216 use tera::{Context, Tera};
217
218 fn page(id: i64, slug: &str, status: &str, published_at: Option<i64>) -> Page {
219 Page {
220 id: Auto::Set(id),
221 page_type_id: 1,
222 title: format!("Title {id}"),
223 slug: slug.to_owned(),
224 path: format!("{id:04}/"),
225 url_path: format!("/{slug}"),
226 preview_path: String::new(),
227 template_override: String::new(),
228 depth: 1,
229 parent_id: Some(99),
230 locale_variant_of: None,
231 alias_of: None,
232 theme_id: None,
233 sort_order: id as i32,
234 status: status.to_owned(),
235 published_at: published_at.map(|t| Utc.timestamp_opt(t, 0).single().unwrap()),
236 last_published_at: published_at.map(|t| Utc.timestamp_opt(t, 0).single().unwrap()),
237 go_live_at: None,
238 expire_at: None,
239 seo_title: String::new(),
240 seo_description: String::new(),
241 robots_index: true,
242 sitemap_priority: 0.5,
243 show_in_menus: false,
244 og_title: String::new(),
245 og_description: String::new(),
246 og_image_media_id: None,
247 twitter_card: String::from("summary_large_image"),
248 notification_pre_published_sent: false,
249 created_at: Auto::Set(Utc.timestamp_opt(0, 0).single().unwrap()),
250 updated_at: Auto::Set(Utc.timestamp_opt(0, 0).single().unwrap()),
251 }
252 }
253
254 fn fresh_tera() -> Tera {
255 let mut tera = Tera::default();
256 register_tera_function(&mut tera);
257 tera
258 }
259
260 fn render(tera: &Tera, src: &str) -> String {
261 let mut t = tera.clone();
262 t.add_raw_template("t.html", src).unwrap();
263 t.render("t.html", &Context::new()).unwrap()
264 }
265
266 #[test]
267 fn returns_empty_when_nothing_installed() {
268 let tera = fresh_tera();
269 let out = render(&tera, r#"{{ children_filtered() | length }}"#);
270 assert_eq!(out, "0");
271 }
272
273 #[test]
274 fn returns_full_list_when_no_filters_applied() {
275 let _g = install(
276 99,
277 vec![page(1, "a", "published", None), page(2, "b", "draft", None)],
278 );
279 let tera = fresh_tera();
280 let out = render(&tera, r#"{{ children_filtered() | length }}"#);
281 assert_eq!(out, "2");
282 }
283
284 #[test]
285 fn filters_by_status() {
286 let _g = install(
287 99,
288 vec![
289 page(1, "a", "published", None),
290 page(2, "b", "draft", None),
291 page(3, "c", "published", None),
292 ],
293 );
294 let tera = fresh_tera();
295 let out = render(
296 &tera,
297 r#"{% set p = children_filtered(status="published") %}{{ p | length }}|{{ p[0].slug }}"#,
298 );
299 assert_eq!(out, "2|a");
300 }
301
302 #[test]
303 fn orders_by_published_at_desc() {
304 let _g = install(
305 99,
306 vec![
307 page(1, "a", "published", Some(100)),
308 page(2, "b", "published", Some(300)),
309 page(3, "c", "published", Some(200)),
310 ],
311 );
312 let tera = fresh_tera();
313 let out = render(
314 &tera,
315 r#"{% for p in children_filtered(order_by="-published_at") %}{{ p.slug }} {% endfor %}"#,
316 );
317 assert_eq!(out, "b c a ");
318 }
319
320 #[test]
321 fn orders_by_title_asc() {
322 let _g = install(
323 99,
324 vec![
325 page(3, "c", "published", None),
326 page(1, "a", "published", None),
327 page(2, "b", "published", None),
328 ],
329 );
330 let tera = fresh_tera();
331 let out = render(
332 &tera,
333 r#"{% for p in children_filtered(order_by="title") %}{{ p.slug }} {% endfor %}"#,
334 );
335 assert_eq!(out, "a b c ");
337 }
338
339 #[test]
340 fn limit_truncates_after_sort() {
341 let _g = install(
342 99,
343 vec![
344 page(1, "a", "published", Some(100)),
345 page(2, "b", "published", Some(300)),
346 page(3, "c", "published", Some(200)),
347 ],
348 );
349 let tera = fresh_tera();
350 let out = render(
351 &tera,
352 r#"{% for p in children_filtered(order_by="-published_at", limit=2) %}{{ p.slug }} {% endfor %}"#,
353 );
354 assert_eq!(out, "b c ");
355 }
356
357 #[test]
358 fn parent_id_mismatch_returns_empty() {
359 let _g = install(99, vec![page(1, "a", "published", None)]);
360 let tera = fresh_tera();
361 let out = render(&tera, r#"{{ children_filtered(parent_id=42) | length }}"#);
362 assert_eq!(out, "0");
363 }
364
365 #[test]
366 fn parent_id_match_passes() {
367 let _g = install(99, vec![page(1, "a", "published", None)]);
368 let tera = fresh_tera();
369 let out = render(&tera, r#"{{ children_filtered(parent_id=99) | length }}"#);
370 assert_eq!(out, "1");
371 }
372
373 #[test]
374 fn unknown_order_by_leaves_input_order() {
375 let _g = install(
376 99,
377 vec![
378 page(3, "c", "published", None),
379 page(1, "a", "published", None),
380 ],
381 );
382 let tera = fresh_tera();
383 let out = render(
384 &tera,
385 r#"{% for p in children_filtered(order_by="bogus_field") %}{{ p.slug }} {% endfor %}"#,
386 );
387 assert_eq!(out, "c a ");
389 }
390
391 #[test]
392 fn guard_clears_thread_local() {
393 {
394 let _g = install(99, vec![page(1, "a", "published", None)]);
395 let tera = fresh_tera();
396 assert_eq!(render(&tera, r#"{{ children_filtered() | length }}"#), "1");
397 }
398 let tera = fresh_tera();
399 assert_eq!(render(&tera, r#"{{ children_filtered() | length }}"#), "0");
400 }
401
402 #[test]
403 fn serializes_full_page_shape() {
404 let _g = install(99, vec![page(7, "post", "published", Some(123))]);
408 let tera = fresh_tera();
409 let out = render(
410 &tera,
411 r#"{% set p = children_filtered() %}{{ p[0].id }}-{{ p[0].slug }}-{{ p[0].status }}"#,
412 );
413 assert_eq!(out, "7-post-published");
414 let json = serde_json::to_value(&page(7, "post", "published", Some(123))).unwrap();
416 assert_eq!(json["id"], json!(7));
417 assert_eq!(json["status"], json!("published"));
418 }
419}