use crate::widget::{Widget, WidgetKind};
pub const SCOPE: &str = "preview";
pub const FIELD: &str = "base_url";
crate::register_site_setting!(SCOPE, "Headless preview", || vec![Widget::new(
WidgetKind::Text,
FIELD,
"Frontend preview URL",
)
.with_help(
"Where the page editor's “Preview on site” link sends an editor, for \
sites rendered by a separate frontend. Use {token}, {path} and {id} \
as placeholders — e.g. https://app.example.com/api/preview?token={token}&path={path}. \
A plain URL with no placeholders gets them appended as query \
parameters. Leave empty when the CMS renders the site itself.",
)]);
#[must_use]
pub fn build(base: &str, token: &str, page_id: i64, url_path: &str) -> Option<String> {
let base = base.trim();
if base.is_empty() {
return None;
}
let path = if url_path.is_empty() { "/" } else { url_path };
let id = page_id.to_string();
let has_placeholder =
base.contains("{token}") || base.contains("{path}") || base.contains("{id}");
if has_placeholder {
return Some(
base.replace("{token}", &encode(token))
.replace("{path}", &encode_path(path))
.replace("{id}", &encode(&id)),
);
}
let sep = if base.contains('?') { '&' } else { '?' };
Some(format!(
"{base}{sep}token={}&path={}&id={}",
encode(token),
encode_path(path),
encode(&id),
))
}
#[must_use]
pub fn for_page(
site_base: Option<&str>,
page_override: &str,
token: &str,
page_id: i64,
url_path: &str,
) -> Option<String> {
let over = page_override.trim();
if is_absolute(over) {
return build(over, token, page_id, url_path);
}
let base = site_base?;
let path = if over.is_empty() { url_path } else { over };
build(base, token, page_id, path)
}
fn is_absolute(raw: &str) -> bool {
let lower = raw.trim().to_ascii_lowercase();
lower.starts_with("http://") || lower.starts_with("https://")
}
fn encode_path(raw: &str) -> String {
raw.split('/').map(encode).collect::<Vec<_>>().join("/")
}
fn encode(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for b in raw.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(char::from(b));
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
pub async fn configured_base(
pool: &rustango::sql::Pool,
) -> Result<Option<String>, rustango::sql::ExecError> {
Ok(crate::site_setting::get(pool, SCOPE)
.await?
.and_then(|row| {
row.value_json
.get(FIELD)
.and_then(|v| v.as_str())
.map(str::to_owned)
})
.filter(|s| !s.trim().is_empty()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_unconfigured_tenant_gets_no_link() {
assert_eq!(build("", "tok", 7, "/docs"), None);
assert_eq!(build(" ", "tok", 7, "/docs"), None);
}
#[test]
fn a_template_substitutes_every_placeholder() {
let got = build(
"https://app.example.com/api/preview?token={token}&path={path}&id={id}",
"abc123",
7,
"/docs/intro",
);
assert_eq!(
got.unwrap(),
"https://app.example.com/api/preview?token=abc123&path=/docs/intro&id=7",
);
}
#[test]
fn a_placeholder_may_appear_in_the_path_not_just_the_query() {
let got = build("https://app.example.com/preview/{id}?t={token}", "abc", 42, "/x");
assert_eq!(got.unwrap(), "https://app.example.com/preview/42?t=abc");
}
#[test]
fn path_in_the_path_position_keeps_its_separators() {
let got = build(
"http://localhost:5173{path}?token={token}",
"9.123.abc",
9,
"/features/ai-engine",
);
assert_eq!(
got.unwrap(),
"http://localhost:5173/features/ai-engine?token=9.123.abc",
);
}
#[test]
fn a_path_segment_that_would_break_the_url_is_still_escaped() {
let got = build("https://x.test{path}", "t", 1, "/a b/c?d#e").unwrap();
assert_eq!(got, "https://x.test/a%20b/c%3Fd%23e");
}
#[test]
fn a_plain_base_url_gets_the_parameters_appended() {
let got = build("https://app.example.com/preview", "abc", 7, "/docs");
assert_eq!(
got.unwrap(),
"https://app.example.com/preview?token=abc&path=/docs&id=7",
);
}
#[test]
fn an_existing_query_string_is_preserved() {
let got = build("https://app.example.com/preview?mode=draft", "abc", 7, "/x");
assert_eq!(
got.unwrap(),
"https://app.example.com/preview?mode=draft&token=abc&path=/x&id=7",
);
}
#[test]
fn the_root_page_previews_as_slash() {
let got = build("https://app.example.com/p", "abc", 1, "");
assert!(got.unwrap().contains("path=/&"), "root must still send a path");
}
#[test]
fn a_token_with_url_specials_survives_the_round_trip() {
let got = build("https://x.test/p?t={token}", "a.b-c_d~e", 1, "/x").unwrap();
assert!(got.ends_with("t=a.b-c_d~e"), "got {got}");
}
#[test]
fn a_page_without_an_override_follows_its_url_path() {
let got = for_page(Some("https://app.test{path}?t={token}"), "", "tok", 9, "/features/ai");
assert_eq!(got.unwrap(), "https://app.test/features/ai?t=tok");
}
#[test]
fn a_page_path_override_replaces_only_the_path() {
let got = for_page(
Some("https://app.test{path}?t={token}"),
"/product/ai-engine",
"tok",
9,
"/features/ai",
);
assert_eq!(got.unwrap(), "https://app.test/product/ai-engine?t=tok");
}
#[test]
fn an_absolute_override_wins_outright() {
let got = for_page(
Some("https://app.test{path}?t={token}"),
"https://other.test/x?t={token}",
"tok",
9,
"/features/ai",
);
assert_eq!(got.unwrap(), "https://other.test/x?t=tok");
}
#[test]
fn an_absolute_override_works_with_no_site_template_at_all() {
let got = for_page(None, "https://other.test/x?t={token}", "tok", 9, "/a");
assert_eq!(got.unwrap(), "https://other.test/x?t=tok");
}
#[test]
fn no_template_and_no_override_is_no_link() {
assert_eq!(for_page(None, "", "tok", 9, "/a"), None);
assert_eq!(for_page(None, " ", "tok", 9, "/a"), None);
assert_eq!(for_page(None, "/product/x", "tok", 9, "/a"), None);
}
#[test]
fn an_override_is_trimmed_before_it_is_judged() {
let got = for_page(Some("https://app.test{path}"), " /p/9 ", "t", 9, "/a");
assert_eq!(got.unwrap(), "https://app.test/p/9");
}
#[test]
fn scheme_relative_is_treated_as_a_path_not_a_url() {
assert!(!is_absolute("//other.test/x"));
let got = for_page(Some("https://app.test{path}"), "//other.test/x", "t", 9, "/a");
assert_eq!(got.unwrap(), "https://app.test//other.test/x");
}
#[test]
fn an_absolute_override_is_recognised_case_insensitively() {
assert!(is_absolute("HTTPS://other.test/x"));
assert!(is_absolute("Http://other.test/x"));
assert!(!is_absolute("ftp://other.test/x"));
}
#[test]
fn encoding_escapes_what_would_break_a_query() {
assert_eq!(encode("/a b&c=d?e#f"), "%2Fa%20b%26c%3Dd%3Fe%23f");
assert_eq!(encode("plain-Text_1.0~"), "plain-Text_1.0~");
}
}