feat(api): streamline generated app authoring

Move the canonical examples toward generated component-root helpers, typed form decoding, async/state handler registration, and derive-driven app/component registry wiring. Tighten requirements and diagnostics for the server-first, selectorless authoring path.

Verified with cargo run -p slhx-xtask -- test, cargo check --workspace, redgate list, redgate refs, redgate health --strict, and git diff --check.

req: canonical/001

req: canonical/003

req: canonical/004

req: dx/002

req: derive_app/001

req: component/003

req: form/004

req: axum_integration/003
This commit is contained in:
slhx agent
2026-06-05 06:33:41 +02:00
parent eb6086616c
commit d4e865ef92
34 changed files with 4573 additions and 1156 deletions
+12 -9
View File
@@ -4,7 +4,7 @@ A board with drag-and-drop cards, 60fps pointer-follow, optimistic updates,
offline queue, conflict reconciliation, live presence, and SSR-first rendering —
all without React/Vue/VDOM, in a single typed Rust codebase.
This is the north-star integration test for slhx + hemplate + slhx-sync.
This is an explicitly advanced/low-level north-star boundary sketch for slhx + hemplate + slhx-sync, not the beginner-facing authoring path. Raw sync/effect/wire vocabulary below is excluded from beginner-facing examples by design.
---
@@ -270,24 +270,27 @@ The runtime does not know "presence". It executes generated DOM updates.
---
## 9. What the browser receives
## 9. What app authors write; what the browser receives
Initial SSR:
Initial SSR stays an ordinary rendered template with symbolic slhx attributes at
the authoring boundary:
```html
<section data-slhx-root data-sid="0" data-aid="0">
<section data-slhx-root="board" data-slhx-slot="board" data-slhx-atom="board">
...
<article data-sid="3" data-key="42" data-hid="1">
Fix login bug
<article data-slhx-slot="card" data-slhx-handle="select_card" +data-card-id="card.id">
{+ card.title +}
</article>
...
</section>
<!-- the app shell loads /slhx.js and any bootstrap state -->
```
Runtime attachment: `/slhx.js` installs delegated root listeners for forms,
clicks, and pointer/drag events. App authors keep composing generated resources;
they do not attach per-node listeners or write selector glue.
The compiler lowers those symbols to compact runtime metadata, but that metadata
is not an app-authoring contract. Runtime attachment: `/slhx.js` installs
delegated root listeners for forms, clicks, and pointer/drag events. App authors
keep composing generated resources; they do not attach per-node listeners, copy
numeric ids, or write selector glue.
No framework download. No VDOM. No hydration. No game loop.
+13 -10
View File
@@ -6,7 +6,7 @@ mod tests {
use super::ui::{board, board_card};
use hemplate::Hemplate;
use scraper::{Html, Selector};
use slhx::{Effect, IntoEffect, Payload};
use slhx::IntoEffect;
use slhx_test::inspect;
#[derive(Hemplate)]
@@ -27,12 +27,11 @@ mod tests {
#[test]
fn kanban_board_updates_generated_slot() {
fn render_board() -> impl IntoEffect {
board::targets::board.put(&empty_board())
board::board.put(&empty_board())
}
let effect = inspect(render_board());
assert!(effect.has_slot(board::slots::board));
assert!(matches!(effect.ops(), [Effect::Put { payload: Payload::Html(_), .. }]));
assert!(effect.updates_html(board::board));
}
// req: html_safety/002 req: view/001 req: test/005
@@ -45,7 +44,9 @@ mod tests {
fn empty_board() -> BoardColumns {
// req: html_safety/002 req: view/001
BoardColumns { columns: Vec::new() }
BoardColumns {
columns: Vec::new(),
}
}
fn selector(value: &str) -> Selector {
@@ -57,19 +58,21 @@ mod tests {
fn kanban_form_handler_is_checked_against_hemplate_form() {
#[slhx::handler]
fn create_card(_form: slhx::Form<CreateCard>) -> impl IntoEffect {
board::slots::notice.text("queued")
board::notice.text("queued")
}
let effect = inspect(create_card(CreateCard::FORM));
assert!(effect.has_slot(board::slots::notice));
assert!(matches!(effect.ops(), [Effect::Put { payload: Payload::Text(_), .. }]));
assert!(effect.updates_text(board::notice));
}
// req: examples/001 req: form/002 req: codegen/003
#[test]
fn kanban_template_exports_form_and_card_handles() {
assert_ne!(board::handles::create_card.id(), board_card::handles::move_right.id());
assert_eq!(board::forms::create_card.field("title").resource, board::forms::create_card.id());
assert_ne!(board::create_card.id(), board_card::move_right.id());
assert_eq!(
board::create_card_form.field("title").resource,
board::create_card_form.id()
);
}
}
+119 -38
View File
@@ -4,14 +4,14 @@ use axum::routing::get;
use axum::Router;
use futures_util::{stream, StreamExt};
use hemplate::Hemplate;
use slhx::{IntoEffect, SafeHtml};
use slhx::{Html, IntoEffect};
use slhx_axum::{
interactions, runtime_js, sse, DispatchRegistry, DispatchRejection, EffectResponse,
InteractionRequest, PageRequest,
};
use slhx_kanban_example::ui::board::{self as board};
use slhx_kanban_example::ui::board_card as card_board;
use slhx_kanban_example::ui::{self, board as board_ui};
use slhx_kanban_example::ui::board::{forms, handles, slots, targets};
use slhx_kanban_example::ui::board_card::handles as card_handles;
use std::collections::BTreeMap;
use std::convert::Infallible;
use std::net::SocketAddr;
@@ -40,7 +40,7 @@ struct Card {
#[derive(Hemplate)]
struct AppShell {
body: SafeHtml,
body: Html,
}
#[derive(Hemplate)]
@@ -67,8 +67,8 @@ struct BoardCard {
#[derive(Hemplate)]
struct Board {
options: SafeHtml,
board: SafeHtml,
options: Html,
board: Html,
}
#[derive(Hemplate)]
@@ -96,9 +96,21 @@ async fn main() {
board: Mutex::new(BoardState {
next_id: 4,
cards: vec![
Card { id: 1, title: "Write requirements".into(), column: 0 },
Card { id: 2, title: "Build browser example".into(), column: 1 },
Card { id: 3, title: "Verify with HTTP".into(), column: 2 },
Card {
id: 1,
title: "Write requirements".into(),
column: 0,
},
Card {
id: 2,
title: "Build browser example".into(),
column: 1,
},
Card {
id: 3,
title: "Verify with HTTP".into(),
column: 2,
},
],
}),
});
@@ -138,14 +150,20 @@ async fn interact(
// 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 = targets::presence.put(&Presence { count: 1 });
return sse(stream::iter([Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT))]).boxed());
let effect = board::presence.put(&Presence { count: 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(4)).await;
let effect = targets::presence.put(&Presence { count });
Some((Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)), count + 1))
let effect = board::presence.put(&Presence { count });
Some((
Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)),
count + 1,
))
})
.boxed();
sse(batches)
@@ -153,7 +171,7 @@ async fn events(Query(params): Query<BTreeMap<String, String>>) -> impl IntoResp
fn registry(state: Arc<AppState>) -> impl DispatchRegistry {
interactions(ui::BUILD_FINGERPRINT)
.on(handles::create_card, {
.on(board::create_card, {
let state = state.clone();
move |form| {
// req: examples/001 req: form/002
@@ -163,12 +181,16 @@ fn registry(state: Arc<AppState>) -> impl DispatchRegistry {
if !title.is_empty() {
let id = board.next_id;
board.next_id += 1;
board.cards.push(Card { id, title: title.into(), column });
board.cards.push(Card {
id,
title: title.into(),
column,
});
}
board_effects(&board, "Card added")
}
})
.on(card_handles::move_left, {
.on(card_board::move_left, {
let state = state.clone();
move |form| {
// req: examples/001 req: list/003
@@ -176,10 +198,17 @@ fn registry(state: Arc<AppState>) -> impl DispatchRegistry {
let moved = update_card(&mut board, form.parse("card_id"), |card| {
card.column = card.column.saturating_sub(1);
});
board_effects(&board, if moved { "Card moved left" } else { "Card not found" })
board_effects(
&board,
if moved {
"Card moved left"
} else {
"Card not found"
},
)
}
})
.on(card_handles::move_right, {
.on(card_board::move_right, {
let state = state.clone();
move |form| {
// req: examples/001 req: list/003
@@ -187,10 +216,17 @@ fn registry(state: Arc<AppState>) -> impl DispatchRegistry {
let moved = update_card(&mut board, form.parse("card_id"), |card| {
card.column = (card.column + 1).min(COLUMNS.len() - 1);
});
board_effects(&board, if moved { "Card moved right" } else { "Card not found" })
board_effects(
&board,
if moved {
"Card moved right"
} else {
"Card not found"
},
)
}
})
.on(card_handles::delete_card, {
.on(card_board::delete_card, {
let state = state.clone();
move |form| {
// req: examples/001 req: list/003
@@ -199,16 +235,23 @@ fn registry(state: Arc<AppState>) -> impl DispatchRegistry {
if let Some(id) = form.parse::<u64>("card_id") {
board.cards.retain(|card| card.id != id);
}
board_effects(&board, if board.cards.len() < before { "Card deleted" } else { "Card not found" })
board_effects(
&board,
if board.cards.len() < before {
"Card deleted"
} else {
"Card not found"
},
)
}
})
}
fn board_effects(board: &BoardState, notice: &'static str) -> impl IntoEffect {
(
targets::board.put(&board_view(board)),
slots::notice.text(notice),
forms::create_card.clear("title"),
board::board.put(&board_view(board)),
board::notice.text(notice),
board::create_card_form.clear(),
)
}
@@ -235,7 +278,7 @@ fn parse_column(value: Option<&str>) -> usize {
.unwrap_or(0)
}
fn page_html(board: &BoardState) -> SafeHtml {
fn page_html(board: &BoardState) -> Html {
// req: html_safety/002 req: view/001
board_ui::render(&Board {
options: render_options(),
@@ -243,12 +286,12 @@ fn page_html(board: &BoardState) -> SafeHtml {
})
}
fn shell(body: SafeHtml) -> SafeHtml {
fn shell(body: Html) -> Html {
// req: html_safety/001 req: html_safety/002 req: axum_integration/001
slhx::render(&AppShell { body })
}
fn render_options() -> SafeHtml {
fn render_options() -> Html {
// req: html_safety/002 req: view/001
ui::render(&ColumnOptions {
options: COLUMNS
@@ -290,6 +333,11 @@ fn render_card(card: &Card) -> BoardCard {
mod tests {
use super::*;
use scraper::{Html, Selector};
use slhx_test::{
class_child_selector, disabled_button_selector, element_class_selector,
escaped_markup_selector, form_selector, keyed_selector, root_element_selector,
select_options_selector, small_text_selector, strong_text_selector,
};
fn selector(value: &str) -> Selector {
Selector::parse(value).expect("test selector parses")
@@ -303,10 +351,22 @@ mod tests {
assert!(!html.as_str().contains("__BOARD__"));
let document = Html::parse_fragment(html.as_str());
assert_eq!(document.select(&selector("section[data-slhx-root=\"kanban\"]")).count(), 1);
assert_eq!(document.select(&selector("select[name=\"column\"] > option")).count(), 3);
assert_eq!(document.select(&selector("[data-sid]")).count(), 3);
assert_eq!(document.select(&selector("[data-hid]")).count(), 1);
assert_eq!(
document
.select(&selector(&root_element_selector("section", "kanban")))
.count(),
1
);
assert_eq!(
document
.select(&selector(&select_options_selector("column")))
.count(),
3
);
assert_eq!(
document.select(&selector(&form_selector("header"))).count(),
1
);
}
// req: html_safety/002 req: view/001 req: test/005
@@ -323,15 +383,31 @@ mod tests {
let html = ui::render(&board_view(&board));
let document = Html::parse_fragment(html.as_str());
assert_eq!(document.select(&selector(".columns > section.column")).count(), 3);
assert_eq!(
document
.select(&selector(&class_child_selector(
"columns", "section", "column"
)))
.count(),
3
);
let card = document
.select(&selector("article.card[data-key=\"1\"]"))
.select(&selector(&keyed_selector("article.card", 1)))
.next()
.expect("card renders");
let title = card.select(&selector("strong")).next().expect("card title renders");
let title = card
.select(&selector(strong_text_selector()))
.next()
.expect("card title renders");
assert_eq!(title.text().collect::<String>(), "<b>Compile checked</b>");
assert!(card.select(&selector("b")).next().is_none());
assert_eq!(card.select(&selector("button[disabled]")).count(), 1);
assert!(card
.select(&selector(&escaped_markup_selector("b")))
.next()
.is_none());
assert_eq!(
card.select(&selector(disabled_button_selector())).count(),
1
);
}
// req: html_safety/002 req: view/001 req: test/005
@@ -339,10 +415,15 @@ mod tests {
fn presence_payload_is_rendered_by_a_hemplate_view() {
let html = ui::render(&Presence { count: 7 });
let document = Html::parse_fragment(html.as_str());
assert_eq!(document.select(&selector("span.presence")).count(), 2);
assert_eq!(
document
.select(&selector("small"))
.select(&selector(&element_class_selector("span", "presence")))
.count(),
2
);
assert_eq!(
document
.select(&selector(small_text_selector()))
.next()
.map(|small| small.text().collect::<String>()),
Some("tick #7".to_owned())
+1 -1
View File
@@ -18,7 +18,7 @@ This is a polished Linear-style product demo for planning typed work across lane
- page-enhancer navigation with native link fallback
- SSE server push into a generated slot
- drag-and-drop lane moves persisted by typed server handlers through the slhx runtime
- an opaque canvas island fed by `Effect::event`/`CustomEvent`, without teaching slhx core about the widget
- an explicit advanced opaque canvas island fed by a generated event helper, without teaching slhx core about the widget
- no user-authored browser JavaScript in slhx-managed UI; the island JavaScript is a leaf-widget escape hatch
Verification:
+14 -17
View File
@@ -3,11 +3,11 @@ pub mod ui {}
#[cfg(test)]
mod tests {
use super::ui::control_center::{forms, handles, slots, targets};
use super::ui::issue_card::handles as card_handles;
use super::ui::control_center::{hero_metrics, launch_work, launch_work_form, notice};
use super::ui::issue_card::advance_work;
use super::ui::issue_lane::events as lane_events;
use hemplate::Hemplate;
use slhx::{Effect, IntoEffect, Payload};
use slhx::IntoEffect;
use slhx_test::inspect;
#[derive(Hemplate)]
@@ -30,14 +30,14 @@ mod tests {
fn techdemo_uses_generated_slots_for_multi_target_updates() {
fn update() -> impl IntoEffect {
(
targets::hero_metrics.put(&FastMetric { label: "fast" }),
slots::notice.text("typed"),
hero_metrics.put(&FastMetric { label: "fast" }),
notice.text("typed"),
)
}
let batch = inspect(update());
assert!(batch.has_slot(slots::hero_metrics));
assert!(batch.has_slot(slots::notice));
assert!(batch.has_target(hero_metrics));
assert!(batch.has_target(notice));
}
// req: examples/001 req: form/001 req: form/004 req: form/006 req: derive_handler/003
@@ -45,22 +45,21 @@ mod tests {
fn techdemo_form_handler_is_checked_against_hemplate_form() {
#[slhx::handler]
fn launch_work(_form: slhx::Form<LaunchWork>) -> impl IntoEffect {
slots::notice.text("queued")
notice.text("queued")
}
let batch = inspect(launch_work(LaunchWork::FORM));
assert!(batch.has_slot(slots::notice));
assert!(matches!(batch.ops(), [Effect::Put { payload: Payload::Text(_), .. }]));
assert!(batch.updates_text(notice));
}
// req: examples/001 req: form/002 req: codegen/003
#[test]
fn techdemo_exports_form_and_interaction_handles() {
assert_ne!(handles::launch_work.id(), card_handles::advance_work.id());
assert_ne!(launch_work.id(), advance_work.id());
assert_eq!(
forms::launch_work.field("title").resource,
forms::launch_work.id()
launch_work_form.field("title").resource,
launch_work_form.id()
);
}
@@ -68,9 +67,7 @@ mod tests {
#[test]
fn techdemo_exports_generated_event_constants() {
assert_eq!(lane_events::drop.as_str(), "drop");
assert!(matches!(
slhx::event(lane_events::drop, "card-1"),
Effect::Emit { name, payload } if name == "drop" && payload == "card-1"
));
let event = inspect(lane_events::drop.emit("card-1"));
assert!(event.emits("drop", "card-1"));
}
}
+197 -79
View File
@@ -1,18 +1,18 @@
use axum::extract::{Query, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use futures_util::{stream, StreamExt};
use hemplate::Hemplate;
use slhx::{CssClass, CssClasses, IntoEffect, SafeHtml};
use slhx::{CssClass, CssClasses, EventName, Html, IntoEffect};
use slhx_axum::{
interactions, runtime_js, sse, DispatchRegistry, DispatchRejection, EffectResponse,
InteractionRequest, PageRequest,
};
use slhx_techdemo::ui;
use slhx_techdemo::ui::control_center::{classes, forms, handles, slots, targets};
use slhx_techdemo::ui::issue_card::handles as card_handles;
use slhx_techdemo::ui::issue_lane::handles as lane_handles;
use slhx_techdemo::ui::control_center::{self as control, classes};
use slhx_techdemo::ui::{issue_card as card_control, issue_lane as lane_control};
use std::collections::{BTreeMap, VecDeque};
use std::convert::Infallible;
use std::net::SocketAddr;
@@ -24,6 +24,7 @@ const LANES: [(&str, &str, &str); 3] = [
("runtime", "Runtime", "typed updates → DOM"),
("product", "Product", "Native UX, zero app JS"),
];
const ISLAND_ORBIT: EventName = EventName::new("slhx:island-orbit");
#[derive(Clone)]
struct WorkItem {
@@ -73,9 +74,27 @@ impl Default for DemoState {
let mut state = Self {
next_id: 4,
work: vec![
WorkItem { id: 1, title: "Compile checked handles".into(), lane: 0, impact: 9, stage: Stage::Shipped },
WorkItem { id: 2, title: "Stream typed presence".into(), lane: 1, impact: 7, stage: Stage::Active },
WorkItem { id: 3, title: "Replace dashboard widgets".into(), lane: 2, impact: 8, stage: Stage::Draft },
WorkItem {
id: 1,
title: "Compile checked handles".into(),
lane: 0,
impact: 9,
stage: Stage::Shipped,
},
WorkItem {
id: 2,
title: "Stream typed presence".into(),
lane: 1,
impact: 7,
stage: Stage::Active,
},
WorkItem {
id: 3,
title: "Replace dashboard widgets".into(),
lane: 2,
impact: 8,
stage: Stage::Draft,
},
],
activity: VecDeque::new(),
spotlight: "No selectors. Generated resources address every target.".into(),
@@ -128,22 +147,22 @@ struct BoardLanes {
#[derive(Hemplate)]
struct ControlCenter {
hero: SafeHtml,
board: SafeHtml,
inspector: SafeHtml,
activity: SafeHtml,
hero: Html,
board: Html,
inspector: Html,
activity: Html,
island_snapshot: String,
}
#[derive(Hemplate)]
struct AppShell {
body: SafeHtml,
body: Html,
}
#[derive(Hemplate)]
#[hemplate = "partials"]
struct InspectorPanel {
selected: SafeHtml,
selected: Html,
spotlight: String,
}
@@ -199,11 +218,14 @@ struct HeroMetrics {
#[tokio::main]
async fn main() {
let state = Arc::new(Shared { demo: Mutex::new(DemoState::default()) });
let state = Arc::new(Shared {
demo: Mutex::new(DemoState::default()),
});
let app = Router::new()
.route("/", get(home).post(interact))
.route("/architecture", get(architecture))
.route("/events", get(events))
.route("/favicon.ico", get(favicon))
.route("/slhx.js", get(runtime))
.route("/app.css", get(app_css))
.route("/control_center.css", get(control_center_css))
@@ -247,16 +269,29 @@ async fn runtime() -> impl IntoResponse {
runtime_js()
}
async fn favicon() -> StatusCode {
StatusCode::NO_CONTENT
}
async fn app_css() -> impl IntoResponse {
([("content-type", "text/css; charset=utf-8")], include_str!("../templates/app_shell.css"))
(
[("content-type", "text/css; charset=utf-8")],
include_str!("../templates/app_shell.css"),
)
}
async fn control_center_css() -> impl IntoResponse {
([("content-type", "text/css; charset=utf-8")], include_str!("../templates/control_center.css"))
(
[("content-type", "text/css; charset=utf-8")],
include_str!("../templates/control_center.css"),
)
}
async fn island_js() -> impl IntoResponse {
([("content-type", "text/javascript; charset=utf-8")], include_str!("../templates/island.js"))
(
[("content-type", "text/javascript; charset=utf-8")],
include_str!("../templates/island.js"),
)
}
async fn interact(
@@ -269,14 +304,20 @@ async fn interact(
// 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 = targets::live_feed.put(&LiveFeed { tick: 1 });
return sse(stream::iter([Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT))]).boxed());
let effect = control::live_feed.put(&LiveFeed { tick: 1 });
return sse(stream::iter([Ok::<_, Infallible>(
effect.into_batch(ui::BUILD_FINGERPRINT),
)])
.boxed());
}
let batches = stream::unfold(1_u64, |tick| async move {
tokio::time::sleep(Duration::from_secs(4)).await;
let effect = targets::live_feed.put(&LiveFeed { tick });
Some((Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)), tick + 1))
let effect = control::live_feed.put(&LiveFeed { tick });
Some((
Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)),
tick + 1,
))
})
.boxed();
sse(batches)
@@ -284,7 +325,7 @@ async fn events(Query(params): Query<BTreeMap<String, String>>) -> impl IntoResp
fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
interactions(ui::BUILD_FINGERPRINT)
.on(handles::launch_work, {
.on(control::launch_work, {
let shared = shared.clone();
move |form| {
// req: form/002 req: examples/001
@@ -303,7 +344,7 @@ fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
demo_effects(&demo, "Launch accepted · 4 targets updated")
}
})
.on(card_handles::advance_work, {
.on(card_control::advance_work, {
let shared = shared.clone();
move |form| {
// req: list/003 req: examples/001
@@ -321,7 +362,7 @@ fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
demo_effects(&demo, "Pipeline advanced")
}
})
.on(lane_handles::move_to_lane, {
.on(lane_control::move_to_lane, {
let shared = shared.clone();
move |form| {
// req: list/003 req: examples/001
@@ -343,7 +384,7 @@ fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
demo_effects(&demo, "Drag-and-drop move persisted")
}
})
.on(card_handles::delete_work, {
.on(card_control::delete_work, {
let shared = shared.clone();
move |form| {
// req: list/003 req: examples/001
@@ -362,7 +403,7 @@ fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
demo_effects(&demo, "Card removed")
}
})
.on(card_handles::spotlight_work, {
.on(card_control::spotlight_work, {
let shared = shared.clone();
move |form| {
// req: examples/001
@@ -377,23 +418,23 @@ fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
demo_effects(&demo, "Inspector focused")
}
})
.on(handles::simulate_push, {
.on(control::simulate_push, {
let shared = shared.clone();
move |_| {
// req: push/003 req: examples/001
let mut demo = shared.demo.lock().unwrap();
demo.log("Simulated push event produced the same generated update shape");
(
targets::live_feed.put(&LiveFeed {
control::live_feed.put(&LiveFeed {
tick: demo.activity.len() as u64,
}),
targets::activity.put(&activity_view(&demo)),
slots::notice.text("Push simulated · no client app code"),
slhx::event("slhx:island-orbit", island_snapshot(&demo)),
control::activity.put(&activity_view(&demo)),
control::notice.text("Push simulated · no client app code"),
ISLAND_ORBIT.emit(island_snapshot(&demo)),
)
}
})
.on(handles::reset_demo, {
.on(control::reset_demo, {
let shared = shared.clone();
move |_| {
// req: examples/001
@@ -404,7 +445,11 @@ fn registry(shared: Arc<Shared>) -> impl DispatchRegistry {
})
}
fn update_work(demo: &mut DemoState, id: Option<u64>, update: impl FnOnce(&mut WorkItem)) -> Option<String> {
fn update_work(
demo: &mut DemoState,
id: Option<u64>,
update: impl FnOnce(&mut WorkItem),
) -> Option<String> {
let id = id?;
let item = demo.work.iter_mut().find(|item| item.id == id)?;
let title = item.title.clone();
@@ -414,26 +459,37 @@ fn update_work(demo: &mut DemoState, id: Option<u64>, update: impl FnOnce(&mut W
fn demo_effects(demo: &DemoState, notice: &'static str) -> impl IntoEffect {
(
targets::hero_metrics.put(&hero_view(demo)),
targets::board.put(&board_view(demo)),
targets::activity.put(&activity_view(demo)),
targets::inspector.put(&inspector_view(demo)),
slots::notice.text(notice),
forms::launch_work.clear("title"),
slhx::event("slhx:island-orbit", island_snapshot(demo)),
control::hero_metrics.put(&hero_view(demo)),
control::board.put(&board_view(demo)),
control::activity.put(&activity_view(demo)),
control::inspector.put(&inspector_view(demo)),
control::notice.text(notice),
control::launch_work_form.clear(),
ISLAND_ORBIT.emit(island_snapshot(demo)),
)
}
fn parse_lane(value: Option<&str>) -> usize {
let value = value.unwrap_or(LANES[0].0);
LANES.iter().position(|(id, _, _)| *id == value).unwrap_or(0)
LANES
.iter()
.position(|(id, _, _)| *id == value)
.unwrap_or(0)
}
fn island_snapshot(demo: &DemoState) -> String {
// Opaque leaf-widget bridge: compact server snapshot in, native CustomEvent out.
// req: interop/001 req: examples/001
let active = demo.work.iter().filter(|item| item.stage == Stage::Active).count();
let shipped = demo.work.iter().filter(|item| item.stage == Stage::Shipped).count();
let active = demo
.work
.iter()
.filter(|item| item.stage == Stage::Active)
.count();
let shipped = demo
.work
.iter()
.filter(|item| item.stage == Stage::Shipped)
.count();
let impact: u64 = demo.work.iter().map(|item| item.impact as u64).sum();
format!(
"{}|{}|{}|{} active · {} shipped · {} activity rows",
@@ -446,7 +502,7 @@ fn island_snapshot(demo: &DemoState) -> String {
)
}
fn page_html(demo: &DemoState) -> SafeHtml {
fn page_html(demo: &DemoState) -> Html {
// req: html_safety/002 req: view/001
render_control_center(ControlCenter {
hero: render_hero(demo),
@@ -457,15 +513,23 @@ fn page_html(demo: &DemoState) -> SafeHtml {
})
}
fn shell(body: SafeHtml) -> SafeHtml {
fn shell(body: Html) -> Html {
// req: html_safety/001 req: html_safety/002 req: axum_integration/001 req: component/003
ui::app_shell::render(&AppShell { body })
}
fn hero_view(demo: &DemoState) -> HeroMetrics {
// req: html_safety/002 req: view/001
let shipped = demo.work.iter().filter(|item| item.stage == Stage::Shipped).count();
let active = demo.work.iter().filter(|item| item.stage == Stage::Active).count();
let shipped = demo
.work
.iter()
.filter(|item| item.stage == Stage::Shipped)
.count();
let active = demo
.work
.iter()
.filter(|item| item.stage == Stage::Active)
.count();
let impact: u64 = demo.work.iter().map(|item| item.impact as u64).sum();
HeroMetrics {
resource_count: 13,
@@ -475,7 +539,7 @@ fn hero_view(demo: &DemoState) -> HeroMetrics {
}
}
fn render_hero(demo: &DemoState) -> SafeHtml {
fn render_hero(demo: &DemoState) -> Html {
// req: html_safety/002 req: view/001 req: component/003
ui::render(&hero_view(demo))
}
@@ -519,7 +583,7 @@ fn activity_view(demo: &DemoState) -> ActivityFeed {
}
}
fn render_activity(demo: &DemoState) -> SafeHtml {
fn render_activity(demo: &DemoState) -> Html {
// req: html_safety/002 req: view/001 req: component/003
ui::render(&activity_view(demo))
}
@@ -546,32 +610,32 @@ fn inspector_view(demo: &DemoState) -> InspectorPanel {
}
}
fn render_inspector(demo: &DemoState) -> SafeHtml {
fn render_inspector(demo: &DemoState) -> Html {
// req: html_safety/002 req: view/001 req: component/003
ui::render(&inspector_view(demo))
}
fn architecture_hero() -> SafeHtml {
fn architecture_hero() -> Html {
// req: html_safety/002 req: view/001
ui::render(&ArchitectureHero)
}
fn architecture_board() -> SafeHtml {
fn architecture_board() -> Html {
// req: html_safety/002 req: view/001
ui::render(&ArchitectureBoard)
}
fn architecture_inspector() -> SafeHtml {
fn architecture_inspector() -> Html {
// req: html_safety/002 req: view/001
ui::render(&ArchitectureInspector)
}
fn architecture_activity() -> SafeHtml {
fn architecture_activity() -> Html {
// req: html_safety/002 req: view/001
ui::render(&ArchitectureActivity)
}
fn render_control_center(page: ControlCenter) -> SafeHtml {
fn render_control_center(page: ControlCenter) -> Html {
// req: html_safety/002 req: view/001 req: component/003
ui::render(&page)
}
@@ -597,11 +661,36 @@ mod tests {
.map(|title| title.text().collect::<String>()),
Some("slhx Techdemo".to_owned())
);
assert_eq!(document.select(&selector("script[src=\"/slhx.js\"]")).count(), 1);
assert_eq!(document.select(&selector("link[rel=\"stylesheet\"]")).count(), 2);
assert_eq!(document.select(&selector("link[href=\"/app.css\"]")).count(), 1);
assert_eq!(document.select(&selector("link[href=\"/control_center.css\"]")).count(), 1);
assert_eq!(document.select(&selector("main[data-slhx-root=\"techdemo\"]")).count(), 1);
assert_eq!(
document
.select(&selector("script[src=\"/slhx.js\"]"))
.count(),
1
);
assert_eq!(
document
.select(&selector("link[rel=\"stylesheet\"]"))
.count(),
2
);
assert_eq!(
document
.select(&selector("link[href=\"/app.css\"]"))
.count(),
1
);
assert_eq!(
document
.select(&selector("link[href=\"/control_center.css\"]"))
.count(),
1
);
assert_eq!(
document
.select(&selector("main[data-slhx-root=\"techdemo\"]"))
.count(),
1
);
assert!(!html.contains("{+="));
}
@@ -615,13 +704,29 @@ mod tests {
assert!(!html.contains("__ACTIVITY__"));
let document = Html::parse_fragment(html.as_str());
assert_eq!(document.select(&selector("[data-slhx-root=\"techdemo\"]")).count(), 1);
assert!(document.select(&selector("[data-sid]")).count() >= 7);
assert!(document.select(&selector("[data-hid]")).count() >= 7);
assert_eq!(document.select(&selector(".hero-panel .metrics")).count(), 1);
assert_eq!(
document
.select(&selector("[data-slhx-root=\"techdemo\"]"))
.count(),
1
);
assert_eq!(
document.select(&selector(".hero-panel .metrics")).count(),
1
);
assert_eq!(document.select(&selector(".board-card .lanes")).count(), 1);
assert_eq!(document.select(&selector(".glass-card .inspector-hero")).count(), 1);
assert_eq!(document.select(&selector(".glass-card ol.activity")).count(), 1);
assert_eq!(
document
.select(&selector(".glass-card .inspector-hero"))
.count(),
1
);
assert_eq!(
document
.select(&selector(".glass-card ol.activity"))
.count(),
1
);
}
// req: html_safety/002 req: view/001 req: test/005
@@ -629,7 +734,9 @@ mod tests {
fn hero_metrics_are_rendered_by_a_hemplate_view() {
let html = render_hero(&DemoState::default());
let document = Html::parse_fragment(html.as_str());
let metrics = document.select(&selector(".metrics > .metric")).collect::<Vec<_>>();
let metrics = document
.select(&selector(".metrics > .metric"))
.collect::<Vec<_>>();
assert_eq!(metrics.len(), 4);
assert_eq!(
metrics[0]
@@ -638,9 +745,10 @@ mod tests {
.map(|span| span.text().collect::<String>()),
Some("generated resources on this page".to_owned())
);
assert!(metrics
.iter()
.any(|metric| metric.text().collect::<String>().contains("aggregate impact score")));
assert!(metrics.iter().any(|metric| metric
.text()
.collect::<String>()
.contains("aggregate impact score")));
}
// req: style/001 req: style/002 req: style/003 req: test/005
@@ -652,7 +760,10 @@ mod tests {
assert_eq!(classes::is_selected.as_str(), "is-selected");
let document = Html::parse_fragment(board.as_str());
assert_eq!(document.select(&selector(".lanes > section.lane")).count(), 3);
assert_eq!(
document.select(&selector(".lanes > section.lane")).count(),
3
);
let lane = document
.select(&selector(r#"section.lane[data-lane="compiler"]"#))
.next()
@@ -663,7 +774,10 @@ mod tests {
.select(&selector(r#"article.work-card.is-selected[data-key="2"]"#))
.next()
.expect("selected work card renders");
assert_eq!(selected_card.value().attr("class"), Some("work-card is-selected"));
assert_eq!(
selected_card.value().attr("class"),
Some("work-card is-selected")
);
}
// req: html_safety/002 req: view/001 req: test/005
@@ -684,7 +798,7 @@ mod tests {
assert_eq!(document.select(&selector(".inspector-row")).count(), 3);
assert!(document
.select(&selector("code"))
.any(|code| code.text().collect::<String>().contains("targets::*")));
.any(|code| code.text().collect::<String>().contains("control::*")));
}
// req: html_safety/002 req: view/001 req: test/005
@@ -698,16 +812,16 @@ mod tests {
.expect("live feed row renders");
let text = row.text().collect::<String>();
assert!(text.contains("SSE tick #7"));
assert!(row
.select(&selector("code"))
.any(|code| code.text().collect::<String>() == "slots::live_feed"));
assert!(text.contains("live feed target"));
assert_eq!(row.select(&selector("code")).count(), 0);
}
// req: html_safety/002 req: view/001 req: test/005
#[test]
fn activity_payload_is_rendered_by_a_hemplate_view() {
let mut demo = DemoState::default();
demo.activity.push_back("<b>escaped activity</b>".to_owned());
demo.activity
.push_back("<b>escaped activity</b>".to_owned());
let html = render_activity(&demo);
let document = Html::parse_fragment(html.as_str());
@@ -753,7 +867,9 @@ mod tests {
.next()
.expect("architecture inspector row renders");
assert_eq!(
row.select(&selector("b")).next().map(|b| b.text().collect::<String>()),
row.select(&selector("b"))
.next()
.map(|b| b.text().collect::<String>()),
Some("Page swap".to_owned())
);
assert!(row
@@ -786,7 +902,9 @@ mod tests {
fn architecture_board_is_rendered_by_a_hemplate_view() {
let html = architecture_board();
let document = Html::parse_fragment(html.as_str());
let lanes = document.select(&selector(".lanes > section.lane")).collect::<Vec<_>>();
let lanes = document
.select(&selector(".lanes > section.lane"))
.collect::<Vec<_>>();
assert_eq!(lanes.len(), 3);
assert_eq!(
lanes[0]
@@ -17,7 +17,7 @@
<aside class="command-card">
<h2>Create an issue</h2>
<form id="launch-work" method="post" data-slhx-handle="launch_work" data-slhx-form="launch_work" data-slhx-disable-while-pending>
<label>Title <input name="title" required="required" value="Ship typed effects"></label>
<label>Title <input name="title" required="required" value="Ship typed updates"></label>
<label>Lane
<select name="lane" required="required">
<option value="compiler">Compiler</option>
@@ -32,7 +32,7 @@
<button type="button" data-slhx-handle="simulate_push">Simulate server push</button>
<button type="button" data-slhx-handle="reset_demo">Reset demo</button>
</div>
<p data-slhx-slot="notice" class="notice">Every control posts a numeric handle id and receives typed effects.</p>
<p data-slhx-slot="notice" class="notice">Every control posts through a generated handle and receives typed updates.</p>
</aside>
<section class="board-card">
@@ -46,8 +46,8 @@
<section class="insight-grid">
<article class="glass-card">
<h2>Effect inspector</h2>
<div data-slhx-slot="inspector">{+= self.inspector =+}</div>
<h2>Update inspector</h2>
<div data-slhx-slot="inspector" class="inspector-slot">{+= self.inspector =+}</div>
</article>
<article class="glass-card island-card" data-slhx-island="orbit" +data-island-snapshot="self.island_snapshot">
<h2>Opaque island bridge</h2>
@@ -60,7 +60,7 @@
</article>
<article class="glass-card glow">
<h2>Server push</h2>
<div data-slhx-slot="live_feed">Waiting for SSE heartbeat…</div>
<div data-slhx-slot="live_feed" class="live-feed">Waiting for SSE heartbeat…</div>
</article>
</section>
@@ -1,4 +1,4 @@
{+= self.selected =+}
<div class="inspector-row"><b>What happened</b><br>{+ self.spotlight +}</div>
<div class="inspector-row"><b>Update path</b><br><code>targets::* → tuple effects → DOM</code></div>
<div class="inspector-row"><b>Runtime</b><br>Root-scoped delegated listeners; numeric targets only.</div>
<div class="inspector-row"><b>Update path</b><br><code>generated targets → tuple updates → DOM</code></div>
<div class="inspector-row"><b>Runtime</b><br>Root-scoped delegated listeners; generated targets only.</div>
@@ -2,8 +2,8 @@
<header><strong>{+ self.title +}</strong><span class="pill">{+ self.stage +}</span></header>
<div class="impact"><i +style="self.impact_style"></i></div>
<div class="card-actions">
<button type="button" data-slhx-handle="spotlight_work" +data-work-id="self.id">Inspect</button>
<button type="button" data-slhx-handle="advance_work" +data-work-id="self.id">Advance</button>
<button type="button" data-slhx-handle="delete_work" +data-work-id="self.id">Delete</button>
<button type="button" data-slhx-handle="spotlight_work" +data-work-id="self.id" name="work_id" +value="self.id">Inspect</button>
<button type="button" data-slhx-handle="advance_work" +data-work-id="self.id" name="work_id" +value="self.id">Advance</button>
<button type="button" data-slhx-handle="delete_work" +data-work-id="self.id" name="work_id" +value="self.id">Delete</button>
</div>
</article>
@@ -1 +1 @@
<div class="live-row"><strong>SSE tick #{+ self.tick +}</strong><br>Server streamed a generated update into <code>slots::live_feed</code>.</div>
<div class="live-row"><strong>SSE tick #{+ self.tick +}</strong><br>Server streamed a generated update into the live feed target.</div>
+59 -93
View File
@@ -1,5 +1,9 @@
use slhx_techdemo::ui::control_center::{handles, slots};
use slhx_techdemo::ui::issue_card::handles as card_handles;
use slhx_techdemo::ui::control_center::{self as control, launch_work, simulate_push};
use slhx_test::{
any_root_selector, document_body_selector, handle_button_selector, handle_selector,
island_probe_script, island_readout_selector, keyed_selector, nav_link_selector,
scoped_island_readout_selector, target_selector,
};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
use thirtyfour::prelude::*;
@@ -48,63 +52,70 @@ async fn browser_drives_typed_product_end_to_end() -> WebDriverResult<()> {
let result = async {
driver.goto(&format!("http://{APP_ADDR}/")).await?;
assert_text(&driver, "A Linear-class work system without a frontend framework").await?;
assert_text(
&driver,
"A Linear-class work system without a frontend framework",
)
.await?;
assert_text(&driver, "Compile checked handles").await?;
assert_text(&driver, "No selectors. Generated resources address every target.").await?;
assert_text(
&driver,
"No selectors. Generated resources address every target.",
)
.await?;
assert_text(&driver, "Opaque island bridge").await?;
wait_for_runtime(&driver).await?;
insert_probe_island(&driver).await?;
wait_for_text(&driver, "#probe-island [data-island-readout]", "probe live").await?;
wait_for_text(
&driver,
&scoped_island_readout_selector("#probe-island"),
"probe live",
)
.await?;
driver
.find(By::Css(&handle_selector(handles::simulate_push)))
.find(By::Css(&handle_selector(simulate_push)))
.await?
.click()
.await?;
wait_for_text(&driver, &slot_selector(slots::notice), "Push simulated").await?;
wait_for_text(&driver, "[data-island-readout]", "activity rows").await?;
driver.find(By::Css("button.primary-action")).await?.click().await?;
wait_for_text(&driver, ".work-card[data-key='4']", "Ship typed effects").await?;
assert_text(&driver, "width:77%").await?;
drag_card_to_lane(&driver, 2, "product").await?;
wait_for_text(&driver, ".lane[data-lane='product'] .work-card[data-key='2']", "Shipped").await?;
wait_for_text(&driver, &slot_selector(slots::notice), "Drag-and-drop move persisted").await?;
wait_for_text(&driver, &target_selector(control::notice), "Push simulated").await?;
wait_for_text(&driver, island_readout_selector(), "activity rows").await?;
driver
.find(By::Css(&card_button_selector(card_handles::spotlight_work, 2)))
.find(By::Css(&handle_button_selector(launch_work)))
.await?
.click()
.await?;
wait_for_text(
&driver,
&slot_selector(slots::inspector),
"Stream typed presence · lane=Product · stage=Shipped · impact=7",
&keyed_selector(".work-card", 4),
"Ship typed updates",
)
.await?;
assert_text(&driver, "width:77%").await?;
driver
.find(By::Css(&card_button_selector(card_handles::advance_work, 3)))
.find(By::Css(&handle_selector(simulate_push)))
.await?
.click()
.await?;
wait_for_text(&driver, ".lane[data-lane='product'] .work-card[data-key='3']", "Active").await?;
wait_for_text(&driver, &target_selector(control::live_feed), "SSE tick").await?;
driver
.find(By::Css(&handle_selector(handles::simulate_push)))
.find(By::Css(&nav_link_selector("/architecture")))
.await?
.click()
.await?;
wait_for_text(&driver, &slot_selector(slots::live_feed), "SSE tick").await?;
driver.find(By::Css("a[href='/architecture']")).await?.click().await?;
wait_for_text(&driver, &slot_selector(slots::inspector), "Page swap").await?;
wait_for_text(&driver, "[data-island-readout]", "activity rows").await?;
assert!(driver.current_url().await?.as_str().ends_with("/architecture"));
wait_for_text(&driver, &target_selector(control::inspector), "Page swap").await?;
wait_for_text(&driver, island_readout_selector(), "activity rows").await?;
assert!(driver
.current_url()
.await?
.as_str()
.ends_with("/architecture"));
driver.goto(&format!("http://{APP_ADDR}/")).await?;
wait_for_text(&driver, &slot_selector(slots::live_feed), "SSE tick").await?;
wait_for_text(&driver, &target_selector(control::live_feed), "SSE tick").await?;
Ok::<(), WebDriverError>(())
}
@@ -125,68 +136,15 @@ fn wait_for_tcp(addr: &str) {
panic!("timed out waiting for {addr}");
}
fn handle_selector(handle: impl std::fmt::Display) -> String {
format!(r#"[data-hid="{handle}"]"#)
}
fn slot_selector(slot: impl std::fmt::Display) -> String {
format!(r#"[data-sid="{slot}"]"#)
}
fn card_button_selector(handle_id: impl std::fmt::Display, work_id: u64) -> String {
format!(r#"[data-hid="{handle_id}"][data-work-id="{work_id}"]"#)
}
async fn insert_probe_island(driver: &WebDriver) -> WebDriverResult<()> {
let root = driver.find(By::Css("[data-slhx-root]")).await?;
driver
.execute(
r#"
const root = arguments[0];
const island = document.createElement('article');
island.id = 'probe-island';
island.setAttribute('data-slhx-island', 'orbit');
island.setAttribute('data-island-snapshot', '1|1|1|probe waiting');
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 16;
island.appendChild(canvas);
const readout = document.createElement('p');
readout.setAttribute('data-island-readout', '');
readout.textContent = 'waiting';
island.appendChild(readout);
root.appendChild(island);
setTimeout(() => {
root.dispatchEvent(new CustomEvent('slhx:island-orbit', { bubbles: true, detail: '7|2|8|probe live' }));
}, 25);
return true;
"#,
vec![root.to_json()?],
)
.await?;
Ok(())
}
async fn drag_card_to_lane(driver: &WebDriver, work_id: u64, lane: &str) -> WebDriverResult<()> {
let card = driver.find(By::Css(format!(".work-card[data-key='{work_id}']"))).await?;
let lane = driver.find(By::Css(format!(".lane[data-lane='{lane}']"))).await?;
driver
.execute(
r#"
const card = arguments[0];
const lane = arguments[1];
const data = new DataTransfer();
card.dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer: data }));
lane.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: data }));
lane.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: data }));
return true;
"#,
vec![card.to_json()?, lane.to_json()?],
)
.await?;
let root = driver.find(By::Css(any_root_selector())).await?;
let script = island_probe_script(
"probe-island",
"orbit",
"1|1|1|probe waiting",
"7|2|8|probe live",
);
driver.execute(&script, vec![root.to_json()?]).await?;
Ok(())
}
@@ -194,7 +152,10 @@ async fn wait_for_runtime(driver: &WebDriver) -> WebDriverResult<()> {
let deadline = Instant::now() + Duration::from_secs(8);
loop {
let loaded = driver
.execute("return !!window.slhx && window.slhx.roots().length > 0", Vec::new())
.execute(
"return !!window.slhx && window.slhx.roots().length > 0",
Vec::new(),
)
.await?
.json()
.as_bool()
@@ -210,7 +171,7 @@ async fn wait_for_runtime(driver: &WebDriver) -> WebDriverResult<()> {
}
async fn assert_text(driver: &WebDriver, text: &str) -> WebDriverResult<()> {
wait_for_text(driver, "body", text).await
wait_for_text(driver, document_body_selector(), text).await
}
async fn wait_for_text(driver: &WebDriver, selector: &str, text: &str) -> WebDriverResult<()> {
@@ -225,7 +186,12 @@ async fn wait_for_text(driver: &WebDriver, selector: &str, text: &str) -> WebDri
}
}
if Instant::now() >= deadline {
let body = driver.find(By::Css("body")).await?.text().await.unwrap_or_default();
let body = driver
.find(By::Css(document_body_selector()))
.await?
.text()
.await
.unwrap_or_default();
panic!("timed out waiting for {text:?} in {selector:?}; body={body:?}");
}
tokio::time::sleep(Duration::from_millis(50)).await;
+158 -149
View File
@@ -1,10 +1,14 @@
use scraper::{Html, Selector};
use slhx::{Effect, EffectBatch, Handle, Payload, EFFECT_BATCH_ABI_VERSION};
use slhx_axum::SLHX_HANDLE_FIELD;
use slhx_techdemo::ui::control_center::{self as control, launch_work, reset_demo, simulate_push};
use slhx_techdemo::ui::issue_card::{advance_work, delete_work, spotlight_work};
use slhx_techdemo::ui::issue_lane::move_to_lane as move_to_lane_handle;
use slhx_techdemo::ui::BUILD_FINGERPRINT;
use slhx_techdemo::ui::control_center::handles;
use slhx_techdemo::ui::issue_card::handles as card_handles;
use slhx_techdemo::ui::issue_lane::handles as lane_handles;
use slhx_test::{
class_descendant_selector, class_selector, handle_form_body, inspect_wire,
island_attribute_name, island_event_name, island_selector, island_snapshot_marker,
root_selector, sse_endpoint_marker, strong_text_selector, unknown_handle_form_body,
EffectInspector,
};
use std::io::{Read, Write};
use std::net::TcpStream;
use std::process::{Child, Command, Stdio};
@@ -12,17 +16,6 @@ use std::time::{Duration, Instant};
const ADDR: &str = "127.0.0.1:3002";
fn handle_body<I>(handle: Handle<I>, fields: &[(&str, &str)]) -> String {
let mut body = format!("{SLHX_HANDLE_FIELD}={handle}");
for (name, value) in fields {
body.push('&');
body.push_str(name);
body.push('=');
body.push_str(value);
}
body
}
struct Server {
child: Child,
}
@@ -63,29 +56,32 @@ fn product_is_e2e_working_over_http() {
assert_eq!(home.status, 200);
assert!(home.header("content-type").contains("text/html"));
let document = Html::parse_document(home.text());
assert_text(&document, "A Linear-class work system without a frontend framework");
assert_text(
&document,
"A Linear-class work system without a frontend framework",
);
assert_text(&document, "Compile checked handles");
assert_text(&document, "Stream typed presence");
assert_selector_count_at_least(&document, "[data-slhx-root=techdemo]", 1);
assert_selector_count_at_least(&document, "[data-hid]", 8);
assert_selector_count_at_least(&document, "[data-sid]", 7);
assert_selector_count_at_least(&document, ".work-card", 3);
assert_selector_count_at_least(&document, "[data-slhx-island=orbit]", 1);
assert_selector_count_at_least(&document, &root_selector("techdemo"), 1);
assert_work_card_count_at_least(&document, 3);
assert_selector_count_at_least(&document, &island_selector("orbit"), 1);
assert_text(&document, "Opaque island bridge");
assert!(home.text().contains("data-island-snapshot="));
assert!(home.text().contains("data-slhx-sse=\"/events\""));
assert!(home.text().contains(island_snapshot_marker()));
assert!(home.text().contains(&sse_endpoint_marker("/events")));
assert!(home.text().contains("/island.js"));
let favicon = get("/favicon.ico");
assert_eq!(favicon.status, 204);
let runtime = get("/slhx.js");
assert_eq!(runtime.status, 200);
assert!(runtime.header("content-type").contains("javascript"));
assert!(runtime.text().contains("const HID = \"data-hid\""));
let island = get("/island.js");
assert_eq!(island.status, 200);
assert!(island.header("content-type").contains("javascript"));
assert!(island.text().contains("slhx:island-orbit"));
assert!(island.text().contains("data-slhx-island"));
assert!(island.text().contains(&island_event_name("orbit")));
assert!(island.text().contains(island_attribute_name()));
assert!(island.text().contains("MutationObserver"));
assert!(island.text().contains("removeEventListener"));
@@ -98,156 +94,183 @@ fn product_is_e2e_working_over_http() {
let launch = post(
"/",
&handle_body(
handles::launch_work,
&handle_form_body(
launch_work,
&[
("title", "Design+hero+moment"),
("title", "Design hero moment"),
("lane", "product"),
("impact", "9"),
],
),
);
assert_effect_response(&launch);
let launch_batch = launch.batch();
let launch_batch = launch.effects();
assert_payload_contains(&launch_batch, "Design hero moment");
assert_card(&launch_batch, "Design hero moment", "Product", "Draft", "width:99%");
assert_card(
&launch_batch,
"Design hero moment",
"Product",
"Draft",
"width:99%",
);
assert_payload_contains(&launch_batch, "Launch accepted");
assert_payload_contains(&launch_batch, "Launched card #4");
assert_emit(&launch_batch, "slhx:island-orbit", "activity rows");
assert_emit(&launch_batch, &island_event_name("orbit"), "activity rows");
assert!(
launch_batch.ops.len() >= 6,
launch_batch.op_count() >= 6,
"launch should update generated targets and notify the island"
);
let default_impact = post(
"/",
&handle_body(
handles::launch_work,
&[("title", "Default+impact"), ("lane", "compiler")],
&handle_form_body(
launch_work,
&[("title", "Default impact"), ("lane", "compiler")],
),
);
assert_effect_response(&default_impact);
let default_impact_batch = default_impact.batch();
let default_impact_batch = default_impact.effects();
assert_payload_contains(&default_impact_batch, "Default impact");
assert_card(&default_impact_batch, "Default impact", "Compiler", "Draft", "width:55%");
assert_card(
&default_impact_batch,
"Default impact",
"Compiler",
"Draft",
"width:55%",
);
let low_impact = post(
"/",
&handle_body(
handles::launch_work,
&handle_form_body(
launch_work,
&[
("title", "Low+impact"),
("title", "Low impact"),
("lane", "runtime"),
("impact", "0"),
],
),
);
assert_effect_response(&low_impact);
let low_impact_batch = low_impact.batch();
assert_card(&low_impact_batch, "Low impact", "Runtime", "Draft", "width:11%");
let low_impact_batch = low_impact.effects();
assert_card(
&low_impact_batch,
"Low impact",
"Runtime",
"Draft",
"width:11%",
);
let high_impact = post(
"/",
&handle_body(
handles::launch_work,
&handle_form_body(
launch_work,
&[
("title", "High+impact"),
("title", "High impact"),
("lane", "runtime"),
("impact", "99"),
],
),
);
assert_effect_response(&high_impact);
let high_impact_batch = high_impact.batch();
assert_card(&high_impact_batch, "High impact", "Runtime", "Draft", "width:99%");
let high_impact_batch = high_impact.effects();
assert_card(
&high_impact_batch,
"High impact",
"Runtime",
"Draft",
"width:99%",
);
let missing_title = post(
"/",
&handle_body(handles::launch_work, &[("lane", "runtime"), ("impact", "8")]),
&handle_form_body(launch_work, &[("lane", "runtime"), ("impact", "8")]),
);
assert_effect_response(&missing_title);
let missing_title_batch = missing_title.batch();
let missing_title_batch = missing_title.effects();
assert_payload_contains(&missing_title_batch, "Launch accepted");
assert_payload_not_contains(&missing_title_batch, "data-key=\"8\"");
assert!(missing_title_batch.payload_excludes_key(8));
assert_payload_not_contains(&missing_title_batch, "MUTATED");
let move_to_lane = post(
"/",
&handle_body(
lane_handles::move_to_lane,
&handle_form_body(
move_to_lane_handle,
&[("work_id", "4"), ("lane", "runtime")],
),
);
assert_effect_response(&move_to_lane);
let move_to_lane_batch = move_to_lane.batch();
assert_card(&move_to_lane_batch, "Design hero moment", "Runtime", "Active", "width:99%");
let move_to_lane_batch = move_to_lane.effects();
assert_card(
&move_to_lane_batch,
"Design hero moment",
"Runtime",
"Active",
"width:99%",
);
assert_payload_contains(&move_to_lane_batch, "Drag-and-drop move persisted");
let inspect = post(
"/",
&handle_body(card_handles::spotlight_work, &[("work_id", "4")]),
);
let inspect = post("/", &handle_form_body(spotlight_work, &[("work_id", "4")]));
assert_effect_response(&inspect);
let inspect_batch = inspect.batch();
let inspect_batch = inspect.effects();
assert_payload_contains(&inspect_batch, "Design hero moment · lane=Runtime");
assert_payload_contains(&inspect_batch, "Inspector focused");
let advance = post(
"/",
&handle_body(card_handles::advance_work, &[("work_id", "4")]),
);
let advance = post("/", &handle_form_body(advance_work, &[("work_id", "4")]));
assert_effect_response(&advance);
let advance_batch = advance.batch();
let advance_batch = advance.effects();
assert_payload_contains(&advance_batch, "Pipeline advanced");
assert_payload_contains(&advance_batch, "<span class=\"pill\">Active</span>");
let advance_default = post(
"/",
&handle_body(card_handles::advance_work, &[("work_id", "5")]),
);
let advance_default = post("/", &handle_form_body(advance_work, &[("work_id", "5")]));
assert_effect_response(&advance_default);
let advance_default_batch = advance_default.batch();
let advance_default_batch = advance_default.effects();
assert_payload_contains(&advance_default_batch, "Default impact");
assert_card(&advance_default_batch, "Default impact", "Compiler", "Active", "width:55%");
let ship_default = post(
"/",
&handle_body(card_handles::advance_work, &[("work_id", "5")]),
assert_card(
&advance_default_batch,
"Default impact",
"Compiler",
"Active",
"width:55%",
);
assert_effect_response(&ship_default);
let ship_default_batch = ship_default.batch();
assert_card(&ship_default_batch, "Default impact", "Product", "Shipped", "width:55%");
let simulated_push = post("/", &handle_body(handles::simulate_push, &[]));
let ship_default = post("/", &handle_form_body(advance_work, &[("work_id", "5")]));
assert_effect_response(&ship_default);
let ship_default_batch = ship_default.effects();
assert_card(
&ship_default_batch,
"Default impact",
"Product",
"Shipped",
"width:55%",
);
let simulated_push = post("/", &handle_form_body(simulate_push, &[]));
assert_effect_response(&simulated_push);
let push_batch = simulated_push.batch();
let push_batch = simulated_push.effects();
assert_payload_contains(&push_batch, "SSE tick");
assert_payload_contains(&push_batch, "Push simulated · no client app code");
assert_payload_contains(&push_batch, "Simulated push event produced the same generated update shape");
assert_emit(&push_batch, "slhx:island-orbit", "activity rows");
let delete_missing = post(
"/",
&handle_body(card_handles::delete_work, &[("work_id", "999")]),
assert_payload_contains(
&push_batch,
"Simulated push event produced the same generated update shape",
);
assert_emit(&push_batch, &island_event_name("orbit"), "activity rows");
let delete_missing = post("/", &handle_form_body(delete_work, &[("work_id", "999")]));
assert_effect_response(&delete_missing);
let delete_missing_batch = delete_missing.batch();
let delete_missing_batch = delete_missing.effects();
assert_payload_not_contains(&delete_missing_batch, "Deleted card #999");
let delete = post(
"/",
&handle_body(card_handles::delete_work, &[("work_id", "4")]),
);
let delete = post("/", &handle_form_body(delete_work, &[("work_id", "4")]));
assert_effect_response(&delete);
let delete_batch = delete.batch();
let delete_batch = delete.effects();
assert_payload_contains(&delete_batch, "Card removed");
assert_payload_contains(&delete_batch, "Deleted card #4");
assert_payload_not_contains(&delete_batch, "data-key=\"4\"");
assert!(delete_batch.payload_excludes_key(4));
assert_payload_contains(&delete_batch, "Default impact");
let reset = post("/", &handle_body(handles::reset_demo, &[]));
let reset = post("/", &handle_form_body(reset_demo, &[]));
assert_effect_response(&reset);
let reset_batch = reset.batch();
let reset_batch = reset.effects();
assert_payload_contains(&reset_batch, "Demo reset from Rust state");
assert_payload_contains(&reset_batch, "Compile checked handles");
@@ -257,7 +280,7 @@ fn product_is_e2e_working_over_http() {
assert!(sse.text().contains("event: slhx"));
assert!(sse.text().contains("data: "));
let unknown = post("/", &format!("{SLHX_HANDLE_FIELD}=999999"));
let unknown = post("/", &unknown_handle_form_body(999999));
assert_eq!(unknown.status, 404);
assert!(unknown.text().contains("unknown slhx handle id 999999"));
}
@@ -265,42 +288,37 @@ fn product_is_e2e_working_over_http() {
fn assert_effect_response(response: &Response) {
assert_eq!(response.status, 200);
assert!(response.header("content-type").contains("application/slhx"));
assert_eq!(response.header("x-slhx-fingerprint"), BUILD_FINGERPRINT.0.to_string());
let batch = response.batch();
assert_eq!(batch.abi_version, EFFECT_BATCH_ABI_VERSION);
assert!(!batch.ops.is_empty());
assert_eq!(
response.header("x-slhx-fingerprint"),
BUILD_FINGERPRINT.0.to_string()
);
assert!(!response.effects().is_empty());
}
fn assert_payload_contains(batch: &EffectBatch, needle: &str) {
fn assert_payload_contains(batch: &EffectInspector, needle: &str) {
assert!(
batch.ops.iter().any(|op| match op {
Effect::Put { payload, .. } | Effect::Insert { payload, .. } | Effect::Prepend { payload, .. } => payload_value(payload).contains(needle),
Effect::Emit { payload, .. } => payload.contains(needle),
Effect::Navigate { url, .. } => url.contains(needle),
Effect::Remove { .. } | Effect::Move { .. } | Effect::Focus { .. } => false,
}),
batch.payload_contains(needle),
"missing payload {needle:?} in {batch:#?}"
);
}
fn assert_emit(batch: &EffectBatch, name: &str, needle: &str) {
fn assert_emit(batch: &EffectInspector, name: &str, needle: &str) {
assert!(
batch.ops.iter().any(|op| match op {
Effect::Emit { name: actual, payload } => actual == name && payload.contains(needle),
_ => false,
}),
batch.emits_containing(name, needle),
"missing emit {name:?} containing {needle:?} in {batch:#?}"
);
}
fn assert_card(batch: &EffectBatch, title: &str, lane: &str, stage: &str, impact_style: &str) {
let board = board_html(batch);
fn assert_card(batch: &EffectInspector, title: &str, lane: &str, stage: &str, impact_style: &str) {
let board = batch
.target_html_containing(control::board, "class=\"lanes\"")
.expect("board html payload");
let document = Html::parse_fragment(&board);
let lane_selector = Selector::parse(".lane").unwrap();
let card_selector = Selector::parse(".work-card").unwrap();
let strong_selector = Selector::parse("strong").unwrap();
let stage_selector = Selector::parse(".pill").unwrap();
let impact_selector = Selector::parse(".impact i").unwrap();
let lane_selector = Selector::parse(&class_selector("lane")).unwrap();
let card_selector = Selector::parse(&class_selector("work-card")).unwrap();
let strong_selector = Selector::parse(strong_text_selector()).unwrap();
let stage_selector = Selector::parse(&class_selector("pill")).unwrap();
let impact_selector = Selector::parse(&class_descendant_selector("impact", "i")).unwrap();
for lane_node in document.select(&lane_selector) {
let lane_text = lane_node.text().collect::<Vec<_>>().join(" ");
@@ -327,7 +345,10 @@ fn assert_card(batch: &EffectBatch, title: &str, lane: &str, stage: &str, impact
.and_then(|node| node.value().attr("style"))
.unwrap_or("");
assert_eq!(card_stage, stage);
assert!(style.contains(impact_style), "style {style:?} missing {impact_style:?}");
assert!(
style.contains(impact_style),
"style {style:?} missing {impact_style:?}"
);
return;
}
}
@@ -335,40 +356,22 @@ fn assert_card(batch: &EffectBatch, title: &str, lane: &str, stage: &str, impact
panic!("missing card title={title:?} lane={lane:?} in {board}");
}
fn board_html(batch: &EffectBatch) -> String {
batch
.ops
.iter()
.find_map(|op| match op {
Effect::Put { payload: Payload::Html(value), .. } if value.contains("class=\"lanes\"") => Some(value.clone()),
_ => None,
})
.expect("board html payload")
}
fn assert_payload_not_contains(batch: &EffectBatch, needle: &str) {
fn assert_payload_not_contains(batch: &EffectInspector, needle: &str) {
assert!(
batch.ops.iter().all(|op| match op {
Effect::Put { payload, .. } | Effect::Insert { payload, .. } | Effect::Prepend { payload, .. } => !payload_value(payload).contains(needle),
Effect::Emit { payload, .. } => !payload.contains(needle),
Effect::Navigate { url, .. } => !url.contains(needle),
Effect::Remove { .. } | Effect::Move { .. } | Effect::Focus { .. } => true,
}),
batch.payload_excludes(needle),
"unexpected payload {needle:?} in {batch:#?}"
);
}
fn payload_value(payload: &Payload) -> &str {
match payload {
Payload::Text(value) | Payload::Html(value) => value,
}
}
fn assert_text(document: &Html, text: &str) {
let body = document.root_element().text().collect::<Vec<_>>().join(" ");
assert!(body.contains(text), "missing text {text:?} in {body:?}");
}
fn assert_work_card_count_at_least(document: &Html, expected: usize) {
assert_selector_count_at_least(document, &class_selector("work-card"), expected);
}
fn assert_selector_count_at_least(document: &Html, selector: &str, expected: usize) {
let selector = Selector::parse(selector).unwrap();
let count = document.select(&selector).count();
@@ -390,7 +393,9 @@ fn post(path: &str, body: &str) -> Response {
fn request(method: &str, path: &str, headers: &[(&str, &str)], body: &str) -> Response {
let mut stream = TcpStream::connect(ADDR).expect("connect to server");
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
write!(
stream,
"{method} {path} HTTP/1.1\r\nHost: {ADDR}\r\nConnection: close\r\nContent-Length: {}\r\n",
@@ -431,7 +436,11 @@ impl Response {
.filter_map(|line| line.split_once(':'))
.map(|(name, value)| (name.trim().to_ascii_lowercase(), value.trim().to_string()))
.collect();
Self { status, headers, body }
Self {
status,
headers,
body,
}
}
fn header(&self, name: &str) -> &str {
@@ -446,7 +455,7 @@ impl Response {
std::str::from_utf8(&self.body).unwrap()
}
fn batch(&self) -> EffectBatch {
EffectBatch::from_wire(&self.body).unwrap()
fn effects(&self) -> EffectInspector {
inspect_wire(&self.body)
}
}
+43 -34
View File
@@ -5,7 +5,7 @@ pub mod ui {}
mod tests {
use super::ui::{auth, counter, notifications, page_swap, todos, wizard};
use hemplate::Hemplate;
use slhx::{push, Effect, IntoEffect, NavigateMode, Payload};
use slhx::{push, IntoEffect};
use slhx_test::inspect;
#[derive(Clone, Debug)]
@@ -36,9 +36,16 @@ mod tests {
#[derive(Hemplate)]
#[hemplate = "partials"]
struct TodoRow {
id: u64,
title: String,
}
impl slhx::KeyedPartial for TodoRow {
fn slhx_key(&self) -> String {
self.id.to_string()
}
}
#[derive(Hemplate)]
#[hemplate = "partials"]
struct DocsContent {
@@ -49,13 +56,12 @@ mod tests {
#[test]
fn counter_updates_a_generated_slot() {
fn increment(count: u64) -> impl IntoEffect {
counter::targets::counter_value.text(count + 1)
counter::counter_value.set(count + 1)
}
let effect = inspect(increment(1));
assert!(effect.has_slot(counter::slots::counter_value));
assert!(matches!(effect.ops(), [Effect::Put { .. }]));
assert!(effect.updates_text(counter::counter_value));
}
// req: examples/001 req: form/001 req: form/004 req: form/006 req: derive_handler/003
@@ -63,27 +69,33 @@ mod tests {
fn form_handler_is_checked_against_hemplate_form() {
#[slhx::handler]
fn add_todo(_form: slhx::Form<TodoInput>) -> impl IntoEffect {
todos::slots::todo_list.text("queued")
todos::todo_list.set("queued")
}
let effect = inspect(add_todo(TodoInput::FORM));
assert!(effect.has_slot(todos::slots::todo_list));
assert!(matches!(effect.ops(), [Effect::Put { payload: Payload::Text(_), .. }]));
assert!(effect.updates_text(todos::todo_list));
}
// req: examples/001 req: progressive_disclosure/001 req: build/001 req: build/005 req: codegen/002
#[test]
fn todos_append_keyed_rows_from_form_input() {
fn add_todo(input: TodoInput) -> impl IntoEffect {
let todo = Todo { id: 7, title: input.title };
todos::targets::todo_row.append(todo.id, &TodoRow { title: todo.title })
let todo = Todo {
id: 7,
title: input.title,
};
todos::todo_row.append(TodoRow {
id: todo.id,
title: todo.title,
})
}
let effect = inspect(add_todo(TodoInput { title: "Ship v0".into() }));
let effect = inspect(add_todo(TodoInput {
title: "Ship v0".into(),
}));
assert!(effect.has_resource(todos::slots::todo_row.id()));
assert!(matches!(effect.ops(), [Effect::Insert { key, payload, .. }] if key == "7" && matches!(payload, Payload::Html(_))));
assert!(effect.inserts_html_containing(todos::todo_row, 7, "Ship v0"));
}
// req: examples/001 req: form/001 req: form/004 req: form/006 req: derive_handler/003
@@ -91,26 +103,24 @@ mod tests {
fn wizard_form_handler_is_checked_against_hemplate_form() {
#[slhx::handler]
fn next_step(_form: slhx::Form<WizardInput>) -> impl IntoEffect {
wizard::slots::wizard_step.text("queued")
wizard::wizard_step.set("queued")
}
let effect = inspect(next_step(WizardInput::FORM));
assert!(effect.has_slot(wizard::slots::wizard_step));
assert!(matches!(effect.ops(), [Effect::Put { payload: Payload::Text(_), .. }]));
assert!(effect.updates_text(wizard::wizard_step));
}
// req: examples/001 req: progressive_disclosure/001 req: build/001 req: build/005 req: codegen/004
#[test]
fn wizard_form_swaps_the_current_step() {
fn next_step(input: WizardInput) -> impl IntoEffect {
wizard::slots::wizard_step.text(format!("Step {}", input.step + 1))
wizard::wizard_step.set(format!("Step {}", input.step + 1))
}
let effect = inspect(next_step(WizardInput { step: 1 }));
assert!(effect.has_slot(wizard::slots::wizard_step));
assert!(matches!(effect.ops(), [Effect::Put { .. }]));
assert!(effect.updates_text(wizard::wizard_step));
}
// req: examples/001 req: page_swap/002 req: page_swap/003 req: build/001 req: build/005 req: view/001
@@ -118,20 +128,19 @@ mod tests {
fn page_swap_updates_content_and_history() {
fn load_docs() -> impl IntoEffect {
(
page_swap::put(page_swap::slots::content, &DocsContent {
page_swap::content.put(&DocsContent {
message: "This page was swapped.",
}),
page_swap::slots::title.text("Docs"),
page_swap::title.set("Docs"),
push("/docs"),
)
}
let effect = inspect(load_docs());
assert!(effect.has_slot(page_swap::slots::content));
assert!(effect.has_slot(page_swap::slots::title));
assert!(matches!(effect.ops().first(), Some(Effect::Put { payload: Payload::Html(_), .. })));
assert!(matches!(effect.ops().last(), Some(Effect::Navigate { url, mode: NavigateMode::Push, .. }) if url == "/docs"));
assert!(effect.updates_html_containing(page_swap::content, "This page was swapped."));
assert!(effect.updates_text(page_swap::title));
assert!(effect.pushes_to("/docs"));
}
// req: examples/001 req: form/001 req: form/004 req: form/006 req: derive_handler/003
@@ -139,13 +148,12 @@ mod tests {
fn auth_form_handler_is_checked_against_hemplate_form() {
#[slhx::handler]
fn login(_form: slhx::Form<Credentials>) -> impl IntoEffect {
auth::slots::login_status.text("queued")
auth::login_status.set("queued")
}
let effect = inspect(login(Credentials::FORM));
assert!(effect.has_slot(auth::slots::login_status));
assert!(matches!(effect.ops(), [Effect::Put { payload: Payload::Text(_), .. }]));
assert!(effect.updates_text(auth::login_status));
}
// req: examples/001 req: progressive_disclosure/001 req: build/001 req: build/005 req: codegen/004
@@ -158,25 +166,26 @@ mod tests {
"Try again"
};
auth::slots::login_status.text(status)
auth::login_status.set(status)
}
let effect = inspect(login(Credentials { email: "demo@example.com".into(), password: "secret".into() }));
let effect = inspect(login(Credentials {
email: "demo@example.com".into(),
password: "secret".into(),
}));
assert!(effect.has_slot(auth::slots::login_status));
assert!(matches!(effect.ops(), [Effect::Put { .. }]));
assert!(effect.updates_text(auth::login_status));
}
// req: examples/001 req: push/001 req: push/003 req: build/001 req: build/005
#[test]
fn sse_notifications_update_a_generated_slot() {
fn notification(message: &str) -> impl IntoEffect {
notifications::slots::notifications.text(message)
notifications::notifications.set(message)
}
let effect = inspect(notification("Build finished"));
assert!(effect.has_slot(notifications::slots::notifications));
assert!(matches!(effect.ops(), [Effect::Put { .. }]));
assert!(effect.updates_text(notifications::notifications));
}
}
+412 -102
View File
@@ -4,18 +4,12 @@ use axum::routing::get;
use axum::Router;
use futures_util::{stream, StreamExt};
use hemplate::Hemplate;
use slhx::{push, IntoEffect, SafeHtml};
use slhx::{Html, IntoEffect};
use slhx_axum::{
interactions, runtime_js, sse, DispatchRegistry, EffectResponse, InteractionRequest, PageRequest,
interactions, runtime_js, sse, EffectResponse, Form, InteractionRequest, PageRequest, Registry,
};
use slhx_v0_examples::ui;
use slhx_v0_examples::ui::{auth, counter, notifications, page_swap, todos, wizard};
use slhx_v0_examples::ui::auth::{handles as auth_handles, targets as auth_targets};
use slhx_v0_examples::ui::counter::{handles as counter_handles, targets as counter_targets};
use slhx_v0_examples::ui::notifications::targets as notification_targets;
use slhx_v0_examples::ui::page_swap::{handles as page_handles, targets as page_targets};
use slhx_v0_examples::ui::todos::{forms as todo_forms, handles as todo_handles, targets as todo_targets};
use slhx_v0_examples::ui::wizard::{handles as wizard_handles, targets as wizard_targets};
use slhx_v0_examples::ui::{auth, counter, notifications, page_swap, todo_row, todos, wizard};
use std::collections::BTreeMap;
use std::convert::Infallible;
use std::net::SocketAddr;
@@ -25,36 +19,101 @@ use std::time::Duration;
#[derive(Default)]
struct ExampleState {
counter: Mutex<u64>,
todos: Mutex<Vec<Todo>>,
todos: Mutex<Vec<TodoRecord>>,
wizard_step: Mutex<u8>,
}
#[derive(Clone)]
struct Todo {
struct TodoRecord {
// Domain/SQL-shaped rows stay as boring Rust data; hemplate view structs are derived at render/update boundaries.
// req: examples/001 req: view/001
id: u64,
title: String,
}
#[slhx::form("new_todo")]
struct NewTodo {
title: String,
}
#[slhx::form("rename_todo")]
struct RenameTodo {
id: u64,
title: String,
}
#[slhx::form("delete_todo")]
struct DeleteTodo {
id: u64,
}
#[slhx::form("wizard_input")]
struct WizardInput {
step: String,
}
#[slhx::form("credentials")]
struct Credentials {
email: String,
password: String,
}
#[derive(Debug)]
struct TodoMutationError(String);
impl std::fmt::Display for TodoMutationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for TodoMutationError {}
#[derive(Hemplate)]
#[hemplate = "partials"]
struct TodoItems {
items: Vec<TodoItem>,
}
#[derive(Hemplate)]
#[hemplate = "partials"]
struct TodoRow {
id: u64,
title: String,
}
impl slhx::KeyedPartial for TodoRow {
fn slhx_key(&self) -> String {
self.id.to_string()
}
}
struct TodoItem {
id: u64,
title: String,
}
#[derive(Hemplate)]
struct Counter;
#[derive(Hemplate)]
struct Wizard;
#[derive(Hemplate)]
struct Auth;
#[derive(Hemplate)]
struct Notifications;
#[derive(Hemplate)]
struct PageSwap {
content: SafeHtml,
content: Html,
title: &'static str,
}
#[derive(Hemplate)]
struct AppShell {
body: SafeHtml,
body: Html,
}
#[derive(Hemplate)]
@@ -100,7 +159,7 @@ async fn interact(
State(state): State<Arc<ExampleState>>,
request: InteractionRequest,
) -> Result<EffectResponse, impl IntoResponse> {
request.dispatch(registry(state))
request.dispatch_async(registry(state)).await
}
async fn runtime() -> impl IntoResponse {
@@ -110,96 +169,201 @@ async fn runtime() -> impl IntoResponse {
// 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 = notification_targets::notifications.text("Server event #1");
return sse(stream::iter([Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT))]).boxed());
let effect = notifications::notifications.set("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 = notification_targets::notifications.text(format!("Server event #{count}"));
Some((Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)), count + 1))
let effect = notifications::notifications.set(format!("Server event #{count}"));
Some((
Ok::<_, Infallible>(effect.into_batch(ui::BUILD_FINGERPRINT)),
count + 1,
))
})
.boxed();
sse(batches)
}
fn registry(state: Arc<ExampleState>) -> impl DispatchRegistry {
#[slhx::app(
counter_handlers,
todo_handlers,
todo_row_handlers,
wizard_handlers,
auth_handlers
)]
fn registry(state: Arc<ExampleState>) -> Registry {
interactions(ui::BUILD_FINGERPRINT)
.on(counter_handles::increment, {
let state = state.clone();
move |_| {
// req: examples/001
let mut counter = state.counter.lock().unwrap();
*counter += 1;
counter_targets::counter_value.text(*counter)
}
})
.on(todo_handles::add_todo, {
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() });
}
(
todo_targets::todo_list.put(&todos_view(&todos)),
todo_forms::new_todo.clear("title"),
)
}
})
.on(wizard_handles::next_step, {
let state = state.clone();
move |_| {
// req: examples/001
let mut step = state.wizard_step.lock().unwrap();
*step += 1;
wizard_targets::wizard_step.text(format!("Step {}", *step + 1))
}
})
.on(auth_handles::login, |form| {
// req: examples/001
let ok = form.value("email") == Some("demo@example.com")
&& form.value("password").is_some_and(|password| !password.is_empty());
auth_targets::login_status.text(if ok {
"Signed in as demo@example.com"
} else {
"Try demo@example.com with any password"
})
})
.on(page_handles::load_docs, |_| {
// req: page_swap/002, req: examples/001
(
page_targets::content.put(&DocsContent {
message: "This content came from a generated update response.",
}),
page_targets::title.text("Docs"),
push("/docs"),
)
})
}
fn all_examples() -> SafeHtml {
// Static `.heml` fragments are lowered by generated code before they join rendered views.
fn all_examples() -> Html {
// req: html_safety/001 req: html_safety/002 req: component/003
SafeHtml::join([
counter::static_fragment(include_str!("../templates/counter.heml")),
todos::static_fragment(include_str!("../templates/todos.heml")),
wizard::static_fragment(include_str!("../templates/wizard.heml")),
auth::static_fragment(include_str!("../templates/auth.heml")),
Html::join([
counter::render(&Counter),
ui::render(&todos_view(&[])),
wizard::render(&Wizard),
auth::render(&Auth),
render_page_swap("Welcome", "Welcome"),
notifications::static_fragment(include_str!("../templates/notifications.heml")),
notifications::render(&Notifications),
])
}
fn shell(body: SafeHtml) -> SafeHtml {
fn shell(body: Html) -> Html {
// req: html_safety/001 req: html_safety/002 req: axum_integration/001 req: component/003
ui::render(&AppShell { body })
}
fn todos_view(todos: &[Todo]) -> TodoItems {
#[slhx::component("counter")]
mod counter_handlers {
use super::*;
#[slhx::handler]
async fn increment(State(state): State<Arc<ExampleState>>) -> impl IntoEffect {
// req: examples/001
let mut counter = state.counter.lock().unwrap();
*counter += 1;
counter::counter_value.set(*counter)
}
}
#[slhx::component("todos")]
mod todo_handlers {
use super::*;
#[slhx::handler]
async fn add_todo(
State(state): State<Arc<ExampleState>>,
Form(form): Form<NewTodo>,
) -> Result<impl IntoEffect, TodoMutationError> {
// req: examples/001 req: canonical_authoring/003
let mut todos = state.todos.lock().unwrap();
let id = todos.last().map_or(1, |todo| todo.id + 1);
let created = if form.title.is_empty() {
None
} else {
todos.push(TodoRecord {
id,
title: form.title.clone(),
});
Some(todos::todo_row.append(TodoRow {
id,
title: form.title,
}))
};
let summary = todo_summary(&todos);
Ok((
created,
todos::summary.set(summary),
todos::new_todo.clear(),
))
}
#[slhx::handler]
async fn rename_todo(
State(state): State<Arc<ExampleState>>,
Form(form): Form<RenameTodo>,
) -> impl IntoEffect {
rename_todo_effect(state, form)
}
#[slhx::handler]
async fn delete_todo(
State(state): State<Arc<ExampleState>>,
Form(form): Form<DeleteTodo>,
) -> impl IntoEffect {
delete_todo_effect(state, form)
}
}
#[slhx::component("todo_row")]
mod todo_row_handlers {
use super::*;
#[slhx::handler]
async fn rename_todo_row(
State(state): State<Arc<ExampleState>>,
Form(form): Form<RenameTodo>,
) -> impl IntoEffect {
rename_todo_effect(state, form)
}
#[slhx::handler]
async fn delete_todo_row(
State(state): State<Arc<ExampleState>>,
Form(form): Form<DeleteTodo>,
) -> impl IntoEffect {
delete_todo_effect(state, form)
}
}
#[slhx::component("wizard")]
mod wizard_handlers {
use super::*;
#[slhx::handler]
async fn next_step(
State(state): State<Arc<ExampleState>>,
Form(form): Form<WizardInput>,
) -> impl IntoEffect {
// req: examples/001
let _submitted_step = form.step;
let mut step = state.wizard_step.lock().unwrap();
*step += 1;
wizard::wizard_step.set(format!("Step {}", *step + 1))
}
}
#[slhx::component("auth")]
mod auth_handlers {
use super::*;
#[slhx::handler]
async fn login(
State(_state): State<Arc<ExampleState>>,
Form(credentials): Form<Credentials>,
) -> impl IntoEffect {
// req: examples/001
let ok = credentials.email == "demo@example.com" && !credentials.password.is_empty();
auth::login_status.set(if ok {
"Signed in as demo@example.com"
} else {
"Try demo@example.com with any password"
})
}
}
fn rename_todo_effect(state: Arc<ExampleState>, form: RenameTodo) -> impl IntoEffect {
// req: examples/001 req: canonical_authoring/003
let mut todos = state.todos.lock().unwrap();
todos
.iter_mut()
.find(|todo| todo.id == form.id)
.map(|todo| {
todo.title = form.title.clone();
todos::todo_row.replace(TodoRow {
id: form.id,
title: form.title,
})
})
}
fn delete_todo_effect(state: Arc<ExampleState>, form: DeleteTodo) -> impl IntoEffect {
// req: examples/001 req: canonical_authoring/003
let mut todos = state.todos.lock().unwrap();
let before = todos.len();
todos.retain(|todo| todo.id != form.id);
let deleted = todos.len() != before;
let summary = todo_summary(&todos);
(
deleted.then(|| todos::todo_row.remove(form.id)),
deleted.then(|| todos::summary.set(summary)),
)
}
fn todos_view(todos: &[TodoRecord]) -> TodoItems {
// req: html_safety/002 req: view/001
TodoItems {
items: todos
@@ -212,7 +376,15 @@ fn todos_view(todos: &[Todo]) -> TodoItems {
}
}
fn render_page_swap(title: &'static str, message: &'static str) -> SafeHtml {
fn todo_summary(todos: &[TodoRecord]) -> String {
match todos.len() {
0 => "No todos".to_owned(),
1 => "1 todo".to_owned(),
count => format!("{count} todos"),
}
}
fn render_page_swap(title: &'static str, message: &'static str) -> Html {
// req: html_safety/002 req: view/001 req: component/003
page_swap::render(&PageSwap {
content: render_docs_content(message),
@@ -220,7 +392,7 @@ fn render_page_swap(title: &'static str, message: &'static str) -> SafeHtml {
})
}
fn render_docs_content(message: &'static str) -> SafeHtml {
fn render_docs_content(message: &'static str) -> Html {
// req: html_safety/002 req: view/001 req: component/003
ui::render(&DocsContent { message })
}
@@ -229,11 +401,25 @@ fn render_docs_content(message: &'static str) -> SafeHtml {
mod tests {
use super::*;
use scraper::{Html, Selector};
use slhx_test::{
article_selector, document_title_selector, escaped_markup_selector, heading_selector,
inspect_batch, keyed_items_selector, keyed_selector, list_item_selector,
page_nav_link_selector, prose_selector, root_element_selector, runtime_script_selector,
};
fn selector(value: &str) -> Selector {
Selector::parse(value).expect("test selector parses")
}
fn form<I>(handle: slhx::Handle<I>, fields: &[(&str, &str)]) -> slhx_axum::InteractionForm {
slhx_axum::InteractionForm::for_handle(
handle,
fields
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned())),
)
}
// req: html_safety/002 req: view/001 req: test/005
#[test]
fn shell_is_rendered_by_a_hemplate_view() {
@@ -241,15 +427,28 @@ mod tests {
let document = Html::parse_document(html.as_str());
assert_eq!(
document
.select(&selector("title"))
.select(&selector(document_title_selector()))
.next()
.map(|title| title.text().collect::<String>()),
Some("slhx v0 examples".to_owned())
);
assert_eq!(document.select(&selector("script[src=\"/slhx.js\"]")).count(), 1);
assert_eq!(document.select(&selector("main[data-slhx-root=\"docs\"]")).count(), 1);
assert_eq!(
document
.select(&selector(runtime_script_selector()))
.count(),
1
);
assert_eq!(
document
.select(&selector(&root_element_selector("main", "docs")))
.count(),
1
);
assert!(
document.root_element().text().all(|text| !text.contains("{+=")),
document
.root_element()
.text()
.all(|text| !text.contains("{+=")),
"hemplate insertion markers must not leak into rendered text"
);
}
@@ -261,14 +460,14 @@ mod tests {
let document = Html::parse_fragment(html.as_str());
assert_eq!(
document
.select(&selector("h1"))
.select(&selector(&heading_selector("", 1)))
.next()
.map(|heading| heading.text().collect::<String>()),
Some("Docs".to_owned())
);
assert_eq!(
document
.select(&selector("p"))
.select(&selector(&prose_selector("")))
.next()
.map(|paragraph| paragraph.text().collect::<String>()),
Some("This content came from a generated update response.".to_owned())
@@ -280,11 +479,22 @@ mod tests {
fn docs_page_partial_is_rendered_by_a_hemplate_view() {
let html = render_page_swap("Docs", "This page was swapped without a full reload.");
let document = Html::parse_fragment(html.as_str());
assert_eq!(document.select(&selector("main[data-slhx-root=\"docs\"]")).count(), 1);
assert_eq!(document.select(&selector("article[data-sid]")).count(), 1);
assert_eq!(
document
.select(&selector("article h1"))
.select(&selector(&root_element_selector("main", "docs")))
.count(),
1
);
assert_eq!(document.select(&selector(article_selector())).count(), 1);
assert_eq!(
document
.select(&selector(&page_nav_link_selector("/docs")))
.count(),
1
);
assert_eq!(
document
.select(&selector(&heading_selector("article", 1)))
.next()
.map(|heading| heading.text().collect::<String>()),
Some("Docs".to_owned())
@@ -294,15 +504,26 @@ mod tests {
// req: html_safety/002 req: view/001 req: test/005
#[test]
fn todos_payload_is_rendered_by_a_hemplate_view() {
let todos = vec![Todo { id: 7, title: "<b>Ship v0</b>".to_owned() }];
let todos = vec![TodoRecord {
id: 7,
title: "<b>Ship v0</b>".to_owned(),
}];
let html = ui::render(&todos_view(&todos));
let document = Html::parse_fragment(html.as_str());
let rows = document.select(&selector("li[data-key]")).collect::<Vec<_>>();
let rows = document
.select(&selector(&keyed_items_selector("li")))
.collect::<Vec<_>>();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].value().attr("data-key"), Some("7"));
assert_eq!(rows[0].text().collect::<String>(), "<b>Ship v0</b>");
assert!(document.select(&selector("b")).next().is_none());
let row = document
.select(&selector(&keyed_selector("li", 7)))
.next()
.expect("generated keyed row");
assert_eq!(row.text().collect::<String>(), "<b>Ship v0</b>");
assert!(document
.select(&selector(&escaped_markup_selector("b")))
.next()
.is_none());
}
// req: html_safety/002 req: view/001 req: test/005
@@ -310,8 +531,97 @@ mod tests {
fn empty_todos_payload_is_rendered_by_a_hemplate_view() {
let html = ui::render(&todos_view(&[]));
let document = Html::parse_fragment(html.as_str());
let rows = document.select(&selector("li")).collect::<Vec<_>>();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].text().collect::<String>(), "No todos yet");
let rows = document
.select(&selector(&list_item_selector("")))
.collect::<Vec<_>>();
assert_eq!(rows.len(), 0);
}
// req: examples/001 req: page_swap/002 req: page_swap/003 req: component/005 req: public_api/003 req: test/005
#[tokio::test]
async fn registry_dispatches_generated_keyed_crud_effects() {
let state = Arc::new(ExampleState::default());
let counter = inspect_batch(
InteractionRequest::from(form(counter::increment, &[]))
.dispatch_async(registry(state.clone()))
.await
.unwrap()
.batch,
);
assert_eq!(*state.counter.lock().unwrap(), 1);
assert!(counter.updates_text(counter::counter_value));
assert!(counter.payload_contains("1"));
let add = inspect_batch(
InteractionRequest::from(form(todos::add_todo, &[("title", "Ship v0")]))
.dispatch_async(registry(state.clone()))
.await
.unwrap()
.batch,
);
assert_eq!(state.todos.lock().unwrap()[0].title, "Ship v0");
assert_eq!(add.op_count(), 3);
assert!(add.inserts_html_containing(todos::todo_row, "1", "Ship v0"));
assert!(add.updates_text(todos::summary));
assert!(add.resets_form(todos::new_todo));
let rename = inspect_batch(
InteractionRequest::from(form(
todo_row::rename_todo_row,
&[("id", "1"), ("title", "Ship 1.0")],
))
.dispatch_async(registry(state.clone()))
.await
.unwrap()
.batch,
);
assert_eq!(state.todos.lock().unwrap()[0].title, "Ship 1.0");
assert_eq!(rename.op_count(), 1);
assert!(rename.replaces_keyed_html_containing(todos::todo_row, "1", "Ship 1.0"));
let delete = inspect_batch(
InteractionRequest::from(form(todo_row::delete_todo_row, &[("id", "1")]))
.dispatch_async(registry(state.clone()))
.await
.unwrap()
.batch,
);
assert!(state.todos.lock().unwrap().is_empty());
assert_eq!(delete.op_count(), 2);
assert!(delete.removes_key(todos::todo_row, "1"));
assert!(delete.updates_text(todos::summary));
let missing_delete = inspect_batch(
InteractionRequest::from(form(todo_row::delete_todo_row, &[("id", "99")]))
.dispatch_async(registry(state.clone()))
.await
.unwrap()
.batch,
);
assert!(missing_delete.is_empty());
let wizard = inspect_batch(
InteractionRequest::from(form(wizard::next_step, &[("step", "1")]))
.dispatch_async(registry(state.clone()))
.await
.unwrap()
.batch,
);
assert!(wizard.updates_text(wizard::wizard_step));
assert!(wizard.payload_contains("Step 2"));
let auth = inspect_batch(
InteractionRequest::from(form(
auth::login,
&[("email", "demo@example.com"), ("password", "secret")],
))
.dispatch_async(registry(state))
.await
.unwrap()
.batch,
);
assert!(auth.updates_text(auth::login_status));
assert!(auth.payload_contains("Signed in as demo@example.com"));
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
<main data-slhx-root="docs">
<nav data-slhx-slot="nav">
<a href="/docs" data-slhx-nav="" data-slhx-handle="load_docs">Docs</a>
<a href="/docs" data-slhx-nav="">Docs</a>
</nav>
<article data-slhx-slot="content">{+= self.content =+}</article>
<title data-slhx-slot="title">{+ self.title +}</title>
@@ -1,6 +1,3 @@
<template h-if="self.items.is_empty()">
<li>No todos yet</li>
</template>
<template h-else>
<template h-if="!self.items.is_empty()">
<li h-for="todo in &self.items" +data-key="todo.id">{+ todo.title +}</li>
</template>
+10 -1
View File
@@ -1 +1,10 @@
<li>{+ self.title +}</li>
<li>
<span>{+ self.title +}</span>
<form data-slhx-handle="rename_todo_row">
<input type="hidden" name="id" +value="self.id">
<button type="submit" name="title" value="Renamed todo">Rename</button>
</form>
<form data-slhx-handle="delete_todo_row">
<button type="submit" name="id" +value="self.id">Delete</button>
</form>
</li>
+17 -5
View File
@@ -3,9 +3,21 @@
<input name="title" required="required">
<button type="submit">Add</button>
</form>
<ul data-slhx-slot="todo_list">
<template h-for="todo in &self.todos" h-key="todo.id">
<li data-slhx-slot="todo_row">{+ todo.title +}</li>
</template>
</ul>
<p data-slhx-slot="summary">{+ self.summary +}</p>
<div data-slhx-slot="todo_list">
<ul data-slhx-slot="todo_row">
<template h-for="todo in &self.items" h-key="todo.id">
<li data-slhx-slot="todo_row" +data-key="todo.id">
<span>{+ todo.title +}</span>
<form data-slhx-handle="rename_todo">
<input type="hidden" name="id" +value="todo.id">
<button type="submit" name="title" value="Renamed todo">Rename</button>
</form>
<form data-slhx-handle="delete_todo">
<button type="submit" name="id" +value="todo.id">Delete</button>
</form>
</li>
</template>
</ul>
</div>
</section>