feat(examples): serve v0 browser demo

req: examples/001

req: v0_scope/003

req: push/001

req: page_swap/002
This commit is contained in:
slhx agent
2026-05-10 23:47:52 +02:00
parent 61da7a7b24
commit 13f948cc7a
5 changed files with 346 additions and 1 deletions
+210
View File
@@ -0,0 +1,210 @@
use axum::extract::{Query, State};
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use futures_util::{stream, StreamExt};
use slhx::{push, IntoEffect, SafeHtml};
use slhx_axum::{runtime_js, sse, EffectResponse, HandlerRegistry, InteractionForm, PageRequest};
use slhx_v0_examples::ui;
use std::collections::BTreeMap;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Default)]
struct ExampleState {
counter: Mutex<u64>,
todos: Mutex<Vec<Todo>>,
wizard_step: Mutex<u8>,
}
#[derive(Clone)]
struct Todo {
id: u64,
title: String,
}
#[tokio::main]
async fn main() {
let state = Arc::new(ExampleState::default());
let app = Router::new()
.route("/", get(home).post(interact))
.route("/docs", get(docs).post(interact))
.route("/events", get(events))
.route("/slhx.js", get(runtime))
.with_state(state);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
println!("slhx v0 examples: http://{addr}");
axum::serve(listener, app).await.unwrap();
}
// req: examples/001
async fn home(request: PageRequest) -> impl IntoResponse {
request
.page(all_examples(), shell)
.title("slhx v0 examples")
.fingerprint(ui::BUILD_FINGERPRINT)
}
// req: page_swap/002, req: examples/001
async fn docs(request: PageRequest) -> impl IntoResponse {
let partial = ui::page_swap::lower_html(
r#"<main data-slhx-root="docs">
<nav data-slhx-slot="nav">
<a href="/" data-slhx-nav="">Examples</a>
<a href="/docs" data-slhx-nav="">Docs</a>
</nav>
<article data-slhx-slot="content"><h1>Docs</h1><p>This page was swapped without a full reload.</p></article>
<title data-slhx-slot="title">Docs</title>
</main>"#,
);
request
.page(partial, shell)
.title("Docs")
.fingerprint(ui::BUILD_FINGERPRINT)
}
async fn interact(
State(state): State<Arc<ExampleState>>,
form: InteractionForm,
) -> Result<EffectResponse, impl IntoResponse> {
registry(state).dispatch(form)
}
async fn runtime() -> impl IntoResponse {
runtime_js()
}
// req: push/001, req: push/003, req: examples/001
async fn events(Query(params): Query<BTreeMap<String, String>>) -> impl IntoResponse {
if params.contains_key("once") {
let effect = ui::notifications::slots::notifications.text("Server event #1");
return sse(stream::iter([Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT))]).boxed());
}
let batches = stream::unfold(1_u64, |count| async move {
tokio::time::sleep(Duration::from_secs(3)).await;
let effect = ui::notifications::slots::notifications.text(format!("Server event #{count}"));
Some((Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)), count + 1))
})
.boxed();
sse(batches)
}
fn registry(state: Arc<ExampleState>) -> HandlerRegistry {
HandlerRegistry::new(ui::BUILD_FINGERPRINT)
.register(ui::counter::handles::increment.id().id, {
let state = state.clone();
move |_| {
// req: examples/001
let mut counter = state.counter.lock().unwrap();
*counter += 1;
ui::counter::slots::counter_value.text(*counter)
}
})
.register(ui::todos::handles::add_todo.id().id, {
let state = state.clone();
move |form| {
// req: examples/001
let title = form.value("title").unwrap_or("").trim();
let mut todos = state.todos.lock().unwrap();
if !title.is_empty() {
let id = todos.last().map_or(1, |todo| todo.id + 1);
todos.push(Todo { id, title: title.into() });
}
(
ui::todos::slots::todo_list.html(SafeHtml::trusted(render_todos(&todos))),
ui::todos::forms::new_todo.clear("title"),
)
}
})
.register(ui::wizard::handles::next_step.id().id, {
let state = state.clone();
move |_| {
// req: examples/001
let mut step = state.wizard_step.lock().unwrap();
*step += 1;
ui::wizard::slots::wizard_step.text(format!("Step {}", *step + 1))
}
})
.register(ui::auth::handles::login.id().id, |form| {
// req: examples/001
let ok = form.value("email") == Some("demo@example.com")
&& form.value("password").is_some_and(|password| !password.is_empty());
ui::auth::slots::login_status.text(if ok {
"Signed in as demo@example.com"
} else {
"Try demo@example.com with any password"
})
})
.register(ui::page_swap::handles::load_docs.id().id, |_| {
// req: page_swap/002, req: examples/001
(
ui::page_swap::slots::content.html(SafeHtml::trusted(
"<h1>Docs</h1><p>This content came from an EffectBatch.</p>",
)),
ui::page_swap::slots::title.text("Docs"),
push("/docs"),
)
})
}
fn all_examples() -> String {
[
ui::counter::lower_html(include_str!("../templates/counter.heml")),
ui::todos::lower_html(include_str!("../templates/todos.heml")),
ui::wizard::lower_html(include_str!("../templates/wizard.heml")),
ui::auth::lower_html(include_str!("../templates/auth.heml")),
ui::page_swap::lower_html(include_str!("../templates/page_swap.heml")),
ui::notifications::lower_html(include_str!("../templates/notifications.heml")),
]
.join("\n")
}
fn shell(body: String) -> String {
format!(
r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>slhx v0 examples</title>
<script src="/slhx.js" defer></script>
<style>
body {{ font-family: system-ui, sans-serif; margin: 2rem; max-width: 54rem; }}
section, main {{ border: 1px solid #ddd; border-radius: .5rem; margin: 1rem 0; padding: 1rem; }}
input, button {{ font: inherit; margin: .25rem; }}
nav a {{ margin-right: .75rem; }}
</style>
</head>
<body>
<h1>slhx v0 browser examples</h1>
<p>Try the counter, todo form, wizard, login, page swap, and live SSE notifications.</p>
{body}
</body>
</html>"#
)
}
fn render_todos(todos: &[Todo]) -> String {
if todos.is_empty() {
return "<li>No todos yet</li>".into();
}
todos
.iter()
.map(|todo| format!(r#"<li data-key="{}">{}</li>"#, todo.id, escape_html(&todo.title)))
.collect::<Vec<_>>()
.join("")
}
fn escape_html(value: &str) -> String {
value
.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}