Hero becomes a content-owned module; site asset proxy; gesture growth fix
Test / test (push) Successful in 24s

site.yaml's hero is now plain | module, where module names a
JavaScript file the content repo ships (mount(container) -> handle
with stop()). Portal serves content assets same-origin at
/site/<path> (Gitea raw sends no CORS headers), starts the module at
HTML parse time, adopts it on hydration, mounts fresh via the inline
script's __mountHero on client-side navigation, and stops it on
leave. The YES canvas (yes.js) and the gesture hero mode leave the
engine - uhhm/questions ships YES as its hero.js, redoal/questions
ships a sine-swings band. Gesture form canvas no longer balloons after
a stroke: the wrap's aspect-ratio reservation is scoped to :empty
(pre-mount) so it can't turn echo-strip height into width inside the
flex field.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Bendik Aagaard Lynghaug
2026-08-25 17:26:29 +02:00
co-authored by Claude Fable 5
parent 307fd7e753
commit 1afd34c22e
8 changed files with 230 additions and 884 deletions
+71 -131
View File
@@ -407,32 +407,6 @@ fn ResponsibleNote(responsible: Responsible) -> impl IntoView {
}
}
// Binds the actual "YES - Rasterized Lines" piece live at uhhm.no
// (ported to `public/yes.js`, an ES module now instead of a page-owning
// script) as a typed JS class - the idiomatic wasm-bindgen way to drive
// an existing JS module from Rust, rather than re-implementing canvas
// animation logic here.
#[cfg(feature = "hydrate")]
mod yes {
use wasm_bindgen::prelude::*;
// raw_module (a runtime URL, not a bundled snippet) on purpose:
// the file lives in public/ so it's served at the stable /yes.js
// - the same URL the hero's inline early-mount script imports.
// A bundled snippet would sit under a per-build hashed
// /pkg/snippets/ path the inline script couldn't know.
#[wasm_bindgen(raw_module = "/yes.js")]
extern "C" {
#[wasm_bindgen(js_name = RasterizedYES)]
pub type RasterizedYes;
#[wasm_bindgen(constructor, js_class = "RasterizedYES")]
pub fn new() -> RasterizedYes;
#[wasm_bindgen(method)]
pub fn stop(this: &RasterizedYes);
}
}
// Same idiomatic-typed-module approach as `yes` above, for the
// prosekit-backed rich-text requirement kind (`prosekit-editor.js`,
@@ -478,12 +452,6 @@ mod gesture {
relay_url: &str,
) -> GestureWidget;
#[wasm_bindgen(js_name = mountGestureHero)]
pub fn mount_gesture_hero(
container: &web_sys::HtmlDivElement,
relay_url: &str,
) -> GestureWidget;
#[wasm_bindgen(method)]
pub fn stop(this: &GestureWidget);
}
@@ -491,131 +459,103 @@ mod gesture {
#[component]
fn Hero(title: String, description: String, landing: bool, site: SiteConfig) -> impl IntoView {
// Only the landing page gets a full interactive piece - it's the
// one page a hero is actually "the" hero for; other pages
// (thank-you pages, /review) get the plain dark header below.
// WHICH piece is the content repo's call (`site.yaml`'s
// hero.kind): the YES canvas (default - uhhm's look), a redoal
// gesture canvas, or nothing.
let hero_kind = if landing { site.hero.kind.clone() } else { "plain".to_string() };
let show_yes = hero_kind == "yes";
let show_gesture = hero_kind == "gesture";
// Only the landing page gets a piece - it's the one page a hero is
// actually "the" hero for; every other page gets the plain header.
// WHAT the piece is belongs to the content repo: site.yaml's
// `hero: {kind: module, module: hero.js}` names a JavaScript module
// (served same-origin at /site/<path>) exporting
// `mount(container) -> handle` with `handle.stop()`. Portal knows
// nothing about what it draws.
let module = if landing && site.hero.kind == "module" {
site.hero.module.clone()
} else {
None
};
let has_module = module.is_some();
let wordmark = site.wordmark.clone().unwrap_or_else(|| "/wordmark.svg".to_string());
let site_title = site.title.clone().unwrap_or_else(|| SITE_NAME.to_string());
// Starts the YES animation once the canvas elements exist, and
// explicitly stops the requestAnimationFrame loop on unmount - the
// original page-owning script never needed this since navigating
// away meant a full document unload, which doesn't happen in an
// SPA.
let raster_ref: NodeRef<leptos::html::Canvas> = NodeRef::new();
let gesture_ref: NodeRef<leptos::html::Div> = NodeRef::new();
let piece_ref: NodeRef<leptos::html::Div> = NodeRef::new();
#[cfg(feature = "hydrate")]
if show_yes {
// `on_cleanup` requires Send + Sync (even single-threaded, wasm),
// which a JS-backed value never is - `StoredValue`'s `LocalStorage`
// variant is the established way around this (same pattern
// cnats' WebRTC call state uses for its own non-Send peer map).
let instance: StoredValue<Option<yes::RasterizedYes>, LocalStorage> =
if has_module {
use wasm_bindgen::JsCast;
// Handle = whatever the module's mount() returned; kept as a
// raw JsValue so the contract stays "has a stop()", nothing
// typed on the Rust side.
let handle: StoredValue<Option<wasm_bindgen::JsValue>, LocalStorage> =
StoredValue::new_local(None);
// Gated on the canvas NodeRef resolving, not just "the Effect
// ran" - on a fresh page load the DOM is already there by the
// time this fires, but navigating back to `/` client-side hit a
// real race: the Effect ran before the new view's <canvas> was
// actually inserted, RasterizedYES::new() (yes.js) did an
// unchecked `document.getElementById(...).getContext(...)` on
// null and threw mid-reactive-update - which then corrupted
// wasm_bindgen_futures' single-threaded executor state badly
// enough to panic ("RefCell already borrowed") on the next
// tick. Waiting for the NodeRef itself guarantees DOM presence
// the same way the prosekit editor's own mount Effect does.
Effect::new(move |_| {
if raster_ref.get().is_none() {
let Some(container) = piece_ref.get() else {
return;
};
if handle.with_value(|h| h.is_some()) {
return;
}
if instance.with_value(|i| i.is_some()) {
return;
}
// Adopt the hero's inline early-mount instance (started at
// HTML parse time, long before this wasm was even fetched)
// instead of starting a second animation. The flag covers
// the opposite ordering too: an inline script that runs
// after this sees it and stays inert.
use wasm_bindgen::JsCast;
// Adopt the inline early-mount's instance (started at HTML
// parse time) if it's there; otherwise (client-side
// navigation back to /) mount fresh through the helper the
// inline script left on window. Either order is safe.
let global = js_sys::global();
let _ = js_sys::Reflect::set(&global, &"__yesAdopted".into(), &true.into());
let early = js_sys::Reflect::get(&global, &"__yesEarly".into())
let _ = js_sys::Reflect::set(&global, &"__heroAdopted".into(), &true.into());
let early = js_sys::Reflect::get(&global, &"__heroEarly".into())
.ok()
.filter(|v| !v.is_undefined() && !v.is_null());
let inst = match early {
match early {
Some(v) => {
let _ = js_sys::Reflect::delete_property(&global, &"__yesEarly".into());
v.unchecked_into::<yes::RasterizedYes>()
let _ = js_sys::Reflect::delete_property(&global, &"__heroEarly".into());
handle.set_value(Some(v));
}
None => yes::RasterizedYes::new(),
};
instance.set_value(Some(inst));
None => {
if let Ok(mounter) = js_sys::Reflect::get(&global, &"__mountHero".into()) {
if let Some(f) = mounter.dyn_ref::<js_sys::Function>() {
if let Ok(promise) = f.call1(&global, &container) {
let promise: js_sys::Promise = promise.unchecked_into();
leptos::task::spawn_local(async move {
if let Ok(h) =
wasm_bindgen_futures::JsFuture::from(promise).await
{
handle.set_value(Some(h));
}
});
}
}
}
}
}
});
on_cleanup(move || {
instance.update_value(|opt| {
if let Some(inst) = opt.take() {
inst.stop();
handle.update_value(|opt| {
if let Some(h) = opt.take() {
if let Ok(stop) = js_sys::Reflect::get(&h, &"stop".into()) {
if let Some(f) = stop.dyn_ref::<js_sys::Function>() {
let _ = f.call0(&h);
}
}
}
});
});
}
// The gesture hero mounts the same widget the `type: gesture`
// requirement uses, in hero mode (no form field; echoes render as
// ambient strokes on the canvas itself). Same StoredValue +
// on_cleanup shape as the YES piece - it may own a live WebSocket.
#[cfg(feature = "hydrate")]
if show_gesture {
let relay = site.hero.relay.clone().unwrap_or_default();
let widget: StoredValue<Option<gesture::GestureWidget>, LocalStorage> =
StoredValue::new_local(None);
Effect::new(move |_| {
let Some(container) = gesture_ref.get() else {
return;
};
if widget.with_value(|w| w.is_some()) {
return;
}
widget.set_value(Some(gesture::mount_gesture_hero(&container, &relay)));
});
on_cleanup(move || {
widget.update_value(|opt| {
if let Some(w) = opt.take() {
w.stop();
}
});
});
}
// The inline script starts the piece at HTML parse time instead of
// waiting out the wasm bundle; it also leaves __mountHero for the
// hydrate side's client-side-navigation case. Module path is
// validated to plain segments by SiteConfig::validate, so it can't
// break out of the string here.
let early_script = module.as_ref().map(|m| {
format!(
"const url = '/site/{m}'; window.__mountHero = (el) => import(url).then((mod) => mod.mount(el)); if (!window.__heroAdopted && !window.__heroEarly) window.__mountHero(document.querySelector('.hero-piece')).then((h) => {{ if (!window.__heroAdopted) window.__heroEarly = h; else if (h && h.stop) h.stop(); }});"
)
});
view! {
<header class="hero" class:hero-yes=show_yes class:hero-gesture=show_gesture>
{show_yes
<header class="hero" class:hero-module=has_module>
{has_module
.then(|| {
view! {
<div class="hero-canvas" aria-hidden="true">
<canvas id="lineCanvas"></canvas>
<canvas id="rasterCanvas" node_ref=raster_ref></canvas>
</div>
// Starts the animation at HTML parse time
// instead of waiting out the wasm bundle's
// fetch + hydration; the hydrate Effect above
// adopts (never duplicates) the instance, and
// the guards make either execution order safe.
<script
type="module"
inner_html="import('/yes.js').then((m) => { if (!window.__yesAdopted && !window.__yesEarly) window.__yesEarly = new m.RasterizedYES(); });"
></script>
<div class="hero-piece" aria-hidden="true" node_ref=piece_ref></div>
<script type="module" inner_html=early_script.unwrap_or_default()></script>
}
})}
{show_gesture
.then(|| {
view! { <div class="hero-draw" node_ref=gesture_ref></div> }
})}
<div class="hero-copy">
<a class="wordmark" href="/">
<img src=wordmark alt=site_title/>
+118 -29
View File
@@ -347,51 +347,76 @@ pub struct SiteConfig {
pub hero: HeroConfig,
}
/// What the landing page's hero is: the YES canvas piece (`yes`, the
/// default), a redoal gesture-drawing canvas (`gesture`), or copy
/// only (`plain`).
/// What the landing page's hero is. `plain` is just the copy; `module`
/// hands the hero to a JavaScript module the content repo itself
/// ships (`module: hero.js`, a repo-relative path portal serves
/// same-origin at `/site/<path>`, since Gitea's raw endpoint sends no
/// CORS headers). The module exports `mount(container) -> handle` and
/// the handle has `stop()`; portal starts it at HTML parse time and
/// adopts it on hydration. The piece's look - canvases, SVG, CSS - is
/// entirely the module's: portal only reserves the box.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct HeroConfig {
#[serde(default = "default_hero_kind")]
pub kind: String,
/// `kind: gesture` only - ws(s):// URL of a redoal-relay for
/// ambient echoes. Absent means the hero draws offline.
#[serde(default)]
pub relay: Option<String>,
pub module: Option<String>,
}
impl Default for HeroConfig {
fn default() -> Self {
Self { kind: default_hero_kind(), relay: None }
Self { kind: default_hero_kind(), module: None }
}
}
fn default_hero_kind() -> String {
"yes".to_string()
"plain".to_string()
}
#[cfg(feature = "ssr")]
impl SiteConfig {
/// Shared by `load_site_from_gitea` and the `question-lint` binary
/// so a typo'd hero kind is a caught rejection, not a silently
/// plain hero.
/// Same policy as `validate_questions`: content declares, the
/// runtime refuses what it doesn't understand at load time, so a
/// typo'd hero kind is a caught rejection, not a silently plain
/// hero.
pub fn validate(&self) -> anyhow::Result<()> {
if !matches!(self.hero.kind.as_str(), "yes" | "gesture" | "plain") {
anyhow::bail!(
"site.yaml: hero.kind {:?} is not one of yes | gesture | plain",
self.hero.kind
);
}
if let Some(relay) = &self.hero.relay {
if self.hero.kind != "gesture" {
anyhow::bail!("site.yaml: hero.relay only makes sense with hero.kind: gesture");
match self.hero.kind.as_str() {
"plain" => {
if self.hero.module.is_some() {
anyhow::bail!("site.yaml: hero.module only makes sense with hero.kind: module");
}
}
validate_relay_url(relay).map_err(|e| anyhow::anyhow!("site.yaml: {e}"))?;
"module" => {
let Some(module) = &self.hero.module else {
anyhow::bail!("site.yaml: hero.kind: module needs hero.module (a repo-relative path like hero.js)");
};
if !is_safe_site_path(module) {
anyhow::bail!(
"site.yaml: hero.module {module:?} must be a plain repo-relative path (no scheme, no .., no leading /)"
);
}
}
other => anyhow::bail!("site.yaml: hero.kind {other:?} is not one of plain | module"),
}
Ok(())
}
}
/// A repo-relative asset path portal is willing to proxy from the
/// content repo: plain segments only - no traversal, no leading slash,
/// no scheme - so `/site/<path>` can only ever reach the content repo.
pub fn is_safe_site_path(path: &str) -> bool {
!path.is_empty()
&& !path.starts_with('/')
&& path.split('/').all(|seg| {
!seg.is_empty()
&& seg != ".."
&& seg
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
})
}
/// A relay must be a ws:// or wss:// URL - shared between site.yaml's
/// hero and `Requirement.relay` validation.
#[cfg(feature = "ssr")]
@@ -428,6 +453,15 @@ pub async fn load_site_from_gitea(repo_url: &str, branch: &str) -> anyhow::Resul
/// Extracts `scheme://host` from a repo's normal browser URL - the
/// Gitea API base every helper in this module builds requests against.
#[cfg(feature = "ssr")]
/// `{gitea}/api/v1/repos/{owner}/{repo}/raw` - the base
/// `site_asset_handler` proxies content-shipped files from.
#[cfg(feature = "ssr")]
pub fn gitea_raw_base(repo_url: &str) -> anyhow::Result<String> {
let (owner, repo) = parse_owner_repo(repo_url)?;
Ok(format!("{}/api/v1/repos/{owner}/{repo}/raw", gitea_api_base(repo_url)?))
}
#[cfg(feature = "ssr")]
pub fn gitea_api_base(repo_url: &str) -> anyhow::Result<String> {
let parsed = url::Url::parse(repo_url)
@@ -1091,6 +1125,54 @@ pub struct GiteaRepoQuery {
pub repo: String,
}
/// `GET /site/{*path}` - serves a file from the content repo's default
/// branch same-origin, so content-shipped assets (the hero module,
/// its stylesheet) are importable by the page: Gitea's raw endpoint
/// sends no CORS headers, and an ES module import across origins is
/// refused without them. Path is validated to plain segments
/// (`is_safe_site_path`), the response revalidates like /pkg
/// (Cache-Control: no-cache) so a content push shows up on reload.
#[cfg(feature = "ssr")]
pub async fn site_asset_handler(
axum::extract::State(state): axum::extract::State<crate::server::AppState>,
axum::extract::Path(path): axum::extract::Path<String>,
) -> axum::response::Response {
use axum::http::{header, StatusCode};
use axum::response::IntoResponse;
if !is_safe_site_path(&path) {
return (StatusCode::BAD_REQUEST, "invalid asset path").into_response();
}
let url = format!("{}/{path}?ref={}", state.content_raw_base, state.content_branch);
let client = openidconnect::reqwest::Client::new();
let resp = match client.get(&url).send().await.and_then(|r| r.error_for_status()) {
Ok(r) => r,
Err(e) => {
tracing::warn!("site asset {path}: {e}");
return (StatusCode::NOT_FOUND, "no such site asset").into_response();
}
};
let bytes = match resp.bytes().await {
Ok(b) => b,
Err(e) => return (StatusCode::BAD_GATEWAY, e.to_string()).into_response(),
};
let mime = match path.rsplit('.').next() {
Some("js") | Some("mjs") => "text/javascript; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("svg") => "image/svg+xml",
Some("json") => "application/json",
Some("png") => "image/png",
Some("webp") => "image/webp",
Some("woff2") => "font/woff2",
_ => "application/octet-stream",
};
(
[(header::CONTENT_TYPE, mime), (header::CACHE_CONTROL, "no-cache")],
bytes,
)
.into_response()
}
/// Looks up `owner/repo` on the same Gitea instance content is loaded
/// from (`AppState.gitea_base`) - a raw Axum handler (mounted at
/// `/gitea-repo` in `main.rs`), not a Leptos server fn, since the
@@ -1386,9 +1468,9 @@ alternatives:
}
#[test]
fn site_config_defaults_to_the_yes_hero() {
fn site_config_defaults_to_the_plain_hero() {
let site = SiteConfig::default();
assert_eq!(site.hero.kind, "yes");
assert_eq!(site.hero.kind, "plain");
assert!(site.validate().is_ok());
// And an empty file parses to the same thing.
let parsed: SiteConfig = serde_yaml::from_str("{}").unwrap();
@@ -1403,21 +1485,28 @@ alternatives:
}
#[test]
fn site_config_rejects_relay_without_gesture_hero() {
let site: SiteConfig =
serde_yaml::from_str("hero: { kind: yes, relay: \"wss://relay.redoal.com\" }").unwrap();
assert!(site.validate().is_err());
fn site_config_module_hero_needs_a_safe_path() {
let missing: SiteConfig = serde_yaml::from_str("hero: { kind: module }").unwrap();
assert!(missing.validate().is_err());
let traversal: SiteConfig =
serde_yaml::from_str("hero: { kind: module, module: ../etc/passwd }").unwrap();
assert!(traversal.validate().is_err());
let absolute: SiteConfig =
serde_yaml::from_str("hero: { kind: module, module: https://x/y.js }").unwrap();
assert!(absolute.validate().is_err());
let ok: SiteConfig = serde_yaml::from_str("hero: { kind: module, module: hero.js }").unwrap();
assert!(ok.validate().is_ok());
}
#[test]
fn redoal_site_yaml_shape_parses() {
let site: SiteConfig = serde_yaml::from_str(
"title: redoal\nwordmark: https://project.uhhm.no/redoal/questions/raw/branch/main/wordmark.svg\nhero:\n kind: gesture\n relay: wss://relay.redoal.com\n",
"title: redoal\nwordmark: https://project.uhhm.no/redoal/questions/raw/branch/main/wordmark.svg\nhero:\n kind: module\n module: hero.js\n",
)
.unwrap();
assert!(site.validate().is_ok());
assert_eq!(site.title.as_deref(), Some("redoal"));
assert_eq!(site.hero.kind, "gesture");
assert_eq!(site.hero.module.as_deref(), Some("hero.js"));
}
#[test]
+6 -16
View File
@@ -29,6 +29,7 @@ async fn main() -> anyhow::Result<()> {
.unwrap_or_else(|_| "https://project.uhhm.no/uhhm/questions".to_string());
let content_branch = std::env::var("CONTENT_BRANCH").unwrap_or_else(|_| "main".to_string());
let gitea_base = content::gitea_api_base(&content_repo)?;
let content_raw_base = content::gitea_raw_base(&content_repo)?;
let aggregates = content::load_aggregates_from_gitea(&content_repo, &content_branch).await?;
let questions = content::load_questions_from_gitea(&content_repo, &content_branch, "questions").await?;
content::validate_questions(&questions, &aggregates)?;
@@ -67,7 +68,7 @@ async fn main() -> anyhow::Result<()> {
tokio::spawn(content::watch_for_reload(
nats.clone(),
content_repo,
content_branch,
content_branch.clone(),
"questions".to_string(),
questions.clone(),
aggregates.clone(),
@@ -82,6 +83,8 @@ async fn main() -> anyhow::Result<()> {
aggregates,
site,
gitea_base,
content_raw_base,
content_branch: content_branch.clone(),
oidc: oidc_state,
garage,
};
@@ -129,10 +132,6 @@ async fn main() -> anyhow::Result<()> {
let favicon_dark_path = format!("{}/favicon-dark.svg", leptos_options.site_root);
let wordmark_path = format!("{}/wordmark.svg", leptos_options.site_root);
let swiper_path = format!("{}/swiper-element-bundle.min.js", leptos_options.site_root);
// yes.js sits in public/ (not a wasm-bindgen snippet) so the
// hero's inline early-mount script and the wasm binding can share
// one stable URL - see `mod yes` in app.rs.
let yes_path = format!("{}/yes.js", leptos_options.site_root);
let fonts_dir = format!("{}/fonts", leptos_options.site_root);
let app = Router::new()
@@ -142,6 +141,8 @@ async fn main() -> anyhow::Result<()> {
.route("/api/{*fn_name}", any(server_fn_handler))
.route("/upload", post(upload::upload))
.route("/gitea-repo", get(content::gitea_repo_handler))
// Content-shipped assets (hero module etc.), same-origin.
.route("/site/{*path}", get(content::site_asset_handler))
.route("/automation/kv/{bucket}", get(content::automation_kv_handler))
// no-cache = "revalidate before reuse", not "don't cache":
// pkg files keep the same names across releases (portal.js,
@@ -167,17 +168,6 @@ async fn main() -> anyhow::Result<()> {
"/swiper-element-bundle.min.js",
ServeFile::new(swiper_path),
)
// Same skew concern as /pkg: the wasm's raw_module import and
// the hero's inline script both load this by fixed name.
.route_service(
"/yes.js",
tower::ServiceBuilder::new()
.layer(tower_http::set_header::SetResponseHeaderLayer::overriding(
axum::http::header::CACHE_CONTROL,
axum::http::HeaderValue::from_static("no-cache"),
))
.service(ServeFile::new(yes_path)),
)
.leptos_routes_with_context(
&state,
routes,
+4
View File
@@ -38,6 +38,10 @@ pub struct AppState {
/// rather than re-derived per call, since `resolve_gitea_repo` needs
/// it too and has no other reason to see `CONTENT_REPO` itself.
pub gitea_base: String,
/// `{gitea}/api/v1/repos/{owner}/{repo}/raw` and the branch - what
/// `content::site_asset_handler` proxies content-shipped assets from.
pub content_raw_base: String,
pub content_branch: String,
pub oidc: Arc<oidc::Oidc>,
/// `None` when `GARAGE_*` env vars aren't set - uploads are the one
/// optional feature, everything else works without Garage.