Skip to main content

rustango_cms/api/
menus.rs

1//! `GET /api/v2/menus/` + `GET /api/v2/menus/{slug}/`.
2//!
3//! Exposes the navigation the admin builds so headless frontends can
4//! render the navbar. Reuses [`crate::navigation::resolve_menus_with`] —
5//! the same resolved tree the server-side Tera path produces (page links
6//! resolve to `url_path`, external items pass through, nesting
7//! preserved). Menu items target `cms_page` rows, so code-defined and
8//! UI-created pages appear alike.
9//!
10//! Both endpoints are viewer-aware (#members) and both take `?locale=`.
11//! `detail` additionally takes `?current=<page id>` and marks the active
12//! item and its trail, so a client renders highlighting without
13//! re-deriving ancestry from URLs.
14
15// Our extractors, not axum's: they refuse a malformed value in the same
16// JSON envelope as everything else. See `query::Query`.
17use crate::api::query::{Path, Query};
18use axum::response::{IntoResponse, Response};
19use axum::Json;
20use rustango::core::Column as _;
21use rustango::extractors::{SessionUser, Tenant};
22use rustango::sql::FetcherPool as _;
23use rustango::tenancy::member_auth::CurrentMember;
24use serde::Deserialize;
25
26use crate::navigation::{Menu, MenuOptions};
27
28/// Query string shared by both endpoints.
29#[derive(Debug, Default, Deserialize)]
30pub struct MenuQuery {
31    /// `?locale=fr` — localized labels on the **detail** endpoint. Items
32    /// with no override for this locale keep their canonical label, so a
33    /// partly-translated menu degrades per item rather than blanking. An
34    /// unknown or inactive code falls back to the tenant default.
35    ///
36    /// Accepted but ignored by the list endpoint, which returns only
37    /// slugs and names — neither of which is translatable.
38    #[serde(default, deserialize_with = "crate::api::query::empty_string_as_none")]
39    pub locale: Option<String>,
40    /// `?current=<page id>` — mark the item targeting this page
41    /// `is_active`, and everything above it `in_active_trail`.
42    /// Ignored on the list endpoint, which returns no items.
43    #[serde(default, deserialize_with = "crate::api::query::empty_as_none")]
44    pub current: Option<i64>,
45    /// Paging, so the list honours the same `ListEnvelope` contract as
46    /// every other v2 list. It used to return every menu unpaginated and
47    /// omit `limit`/`offset` from `meta`, so a client typed against the
48    /// shared envelope broke on this one endpoint alone.
49    #[serde(default, deserialize_with = "crate::api::query::empty_as_none")]
50    pub limit: Option<usize>,
51    #[serde(default, deserialize_with = "crate::api::query::empty_as_none")]
52    pub offset: Option<usize>,
53}
54
55/// `GET /api/v2/menus/` — list configured menus (slug + name).
56///
57/// One query. It used to call `resolve_all_menus` and throw away every
58/// resolved tree, which made listing N menus cost `1 + 3N` queries to
59/// return `2N` strings.
60pub async fn list(tenant: Tenant, Query(q): Query<MenuQuery>) -> Response {
61    match list_inner(tenant.pool(), &q).await {
62        Ok(resp) => resp,
63        Err(e) => {
64            tracing::error!(target: "rustango_cms::api", error = %e, "menus list failed");
65            crate::api::error::ApiError::internal().into_response()
66        }
67    }
68}
69
70pub async fn list_inner(
71    pool: &rustango::sql::Pool,
72    q: &MenuQuery,
73) -> Result<Response, rustango::sql::ExecError> {
74    let mut menus: Vec<Menu> = Menu::objects().fetch(pool).await?;
75    menus.sort_by(|a, b| a.slug.cmp(&b.slug));
76
77    let total_count = menus.len();
78    let limit = crate::api::query::clamp_limit(q.limit);
79    let offset = q.offset.unwrap_or(0);
80
81    let items: Vec<serde_json::Value> = menus
82        .iter()
83        .skip(offset)
84        .take(limit)
85        .map(|m| {
86            serde_json::json!({
87                "slug": m.slug,
88                "name": m.name,
89                // Percent-encoded: a slug is only lowercased on save, so
90                // one containing `/` would otherwise render a path the
91                // single-segment route can never match.
92                "detail_url": format!("/api/v2/menus/{}/", encode_slug(&m.slug)),
93            })
94        })
95        .collect();
96
97    // No `locale` echo here: a menu's `slug` and `name` have no
98    // translations (only `cms_menu_item_translation` exists), so echoing
99    // one told a client its code had been honoured when nothing in the
100    // payload was localized. `?locale=` is still accepted and ignored,
101    // for clients that pass it uniformly. The detail endpoint, where
102    // labels *are* localized, does echo it.
103    let meta = crate::api::query::ListMeta::paged(total_count, limit, offset);
104    Ok(Json(crate::api::query::ListEnvelope { meta, items }).into_response())
105}
106
107/// `GET /api/v2/menus/{slug}/` — the resolved nested tree for one menu.
108/// Viewer-aware (#members): items the caller can't access are hidden.
109pub async fn detail(
110    tenant: Tenant,
111    SessionUser(session_user): SessionUser,
112    CurrentMember(member): CurrentMember,
113    crate::api::auth::BearerMember(bearer): crate::api::auth::BearerMember,
114    Path(slug): Path<String>,
115    Query(q): Query<MenuQuery>,
116) -> Response {
117    let viewer = member.as_ref().or(bearer.as_ref()).or(session_user.as_ref());
118    match detail_inner(tenant.pool(), viewer, &slug, &q).await {
119        Ok(resp) => resp,
120        Err(e) => {
121            tracing::error!(target: "rustango_cms::api", error = %e, slug = %slug, "menu detail failed");
122            crate::api::error::ApiError::internal().into_response()
123        }
124    }
125}
126
127/// Takes a `&Pool` for the same reason [`crate::api::tree::tree_inner`]
128/// does — so the resolved tree is testable without a PostgreSQL tenant.
129pub async fn detail_inner(
130    pool: &rustango::sql::Pool,
131    viewer: Option<&rustango::tenancy::auth::User>,
132    slug: &str,
133    q: &MenuQuery,
134) -> Result<Response, rustango::sql::ExecError> {
135    let locale = crate::translation::resolve_locale(pool, q.locale.as_deref()).await?;
136
137    // `?current=` is a hint for highlighting, not a lookup: an id that
138    // doesn't resolve simply means nothing is marked active. Failing the
139    // whole menu over it would take the navbar down for a bad link.
140    // `?current=` is a highlighting hint. It must not become an oracle:
141    // echoing `meta.current` back only for rows that exist told an
142    // anonymous caller whether a given id is a real (draft, or
143    // member-only) page, and `in_active_trail` then leaked which
144    // published subtree an unreleased draft lives under. Only a page this
145    // caller could actually be looking at counts.
146    let current = match q.current {
147        Some(id) => {
148            let found = crate::page::Page::objects()
149                .where_(crate::page::Page::id.eq(id))
150                .where_(crate::page::Page::status.is_in([
151                    crate::page::PageStatus::Published.as_str().to_owned(),
152                    crate::page::PageStatus::Archived.as_str().to_owned(),
153                ]))
154                .first(pool)
155                .await?;
156            match found {
157                Some(p) => {
158                    let pid = p.id.get().copied().unwrap_or_default();
159                    let denied = crate::view_restriction::denied_page_ids(
160                        pool,
161                        viewer,
162                        &[(pid, p.path.clone(), p.page_type_id)],
163                    )
164                    .await;
165                    (!denied.contains(&pid)).then_some(p)
166                }
167                None => None,
168            }
169        }
170        None => None,
171    };
172
173    let opts = MenuOptions {
174        viewer,
175        locale: locale.as_ref(),
176        current: current.as_ref(),
177    };
178    let Some(menu) = crate::navigation::resolve_menu_with(pool, slug, opts).await? else {
179        return Ok(crate::api::error::ApiError::not_found("menu").into_response());
180    };
181
182    // The `meta` + `items` envelope every other v2 endpoint uses. `detail`
183    // used to return a bare object, so a client had to special-case it.
184    Ok(Json(serde_json::json!({
185        "meta": {
186            "slug": menu.slug,
187            "name": menu.name,
188            "locale": locale.as_ref().map(|l| l.code.clone()),
189            "current": current.as_ref().and_then(|p| p.id.get().copied()),
190            "total_count": count_items(&menu.items),
191        },
192        "items": menu.items,
193    }))
194    .into_response())
195}
196
197/// Percent-encode a menu slug for use as one path segment.
198///
199/// Slugs are only `trim().to_lowercase()`d on save, so `a/b` is storable
200/// and would produce a `detail_url` of `/api/v2/menus/a/b/` — a path the
201/// single-segment route cannot match, i.e. a dead link the API itself
202/// handed out.
203fn encode_slug(slug: &str) -> String {
204    let mut out = String::with_capacity(slug.len());
205    for b in slug.bytes() {
206        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
207            out.push(char::from(b));
208        } else {
209            out.push_str(&format!("%{b:02X}"));
210        }
211    }
212    out
213}
214
215/// Total nodes in the resolved tree, not just top-level ones — the count
216/// a client uses to sanity-check what it received.
217fn count_items(items: &[crate::navigation::ResolvedMenuItem]) -> usize {
218    items.len() + items.iter().map(|i| count_items(&i.children)).sum::<usize>()
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use crate::navigation::ResolvedMenuItem;
225
226    fn item(children: Vec<ResolvedMenuItem>) -> ResolvedMenuItem {
227        ResolvedMenuItem {
228            id: None,
229            label: String::new(),
230            url: Some("/".to_owned()),
231            is_page: false,
232            page_id: None,
233            open_in_new_tab: false,
234            is_active: false,
235            in_active_trail: false,
236            children,
237        }
238    }
239
240    #[test]
241    fn a_slug_with_a_slash_is_encoded_into_one_segment() {
242        // Otherwise the advertised detail_url is unroutable.
243        assert_eq!(encode_slug("a/b"), "a%2Fb");
244        assert_eq!(encode_slug("my menu"), "my%20menu");
245    }
246
247    #[test]
248    fn an_ordinary_slug_is_left_alone() {
249        assert_eq!(encode_slug("main-nav_2.0~x"), "main-nav_2.0~x");
250    }
251
252    #[test]
253    fn count_items_counts_the_whole_tree() {
254        // A top-level-only count would report 2 for a menu of 4 nodes.
255        let tree = vec![item(vec![item(vec![]), item(vec![])]), item(vec![])];
256        assert_eq!(count_items(&tree), 4);
257    }
258
259    #[test]
260    fn count_items_on_an_empty_menu_is_zero() {
261        assert_eq!(count_items(&[]), 0);
262    }
263}