repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/main.rs
examples/hackernews_axum/src/main.rs
#[cfg(feature = "ssr")] #[tokio::main] async fn main() { use axum::{routing::get, Router}; use hackernews_axum::{shell, App}; use leptos::config::get_configuration; use leptos_axum::{generate_route_list, LeptosRoutes}; let conf = get_configuration(Some("Cargo.toml")).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(App); // build our application with a route let app = Router::new() .route( "/favicon.ico", get(|| async { ( [("content-type", "image/x-icon")], include_bytes!("../public/favicon.ico"), ) }), ) .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` println!("listening on {}", addr); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve(listener, app.into_make_service()) .await .unwrap(); } // client-only stuff for Trunk #[cfg(not(feature = "ssr"))] pub fn main() { use hackernews_axum::*; _ = console_log::init_with_level(log::Level::Debug); console_error_panic_hook::set_once(); mount_to_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/routes.rs
examples/hackernews_axum/src/routes.rs
pub mod nav; pub mod stories; pub mod story; pub mod users;
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/routes/users.rs
examples/hackernews_axum/src/routes/users.rs
use crate::api::{self, User}; use leptos::{either::Either, prelude::*, server::Resource}; use leptos_router::{hooks::use_params_map, lazy_route, LazyRoute}; #[derive(Debug)] pub struct UserRoute { user: Resource<Option<User>>, } #[lazy_route] impl LazyRoute for UserRoute { fn data() -> Self { let params = use_params_map(); let user = Resource::new( move || params.read().get("id").unwrap_or_default(), move |id| async move { if id.is_empty() { None } else { api::fetch_api::<User>(&api::user(&id)).await } }, ); UserRoute { user } } fn view(this: Self) -> AnyView { let UserRoute { user } = this; view! { <div class="user-view"> <Suspense fallback=|| view! { "Loading..." }> {move || Suspend::new(async move { match user.await.clone() { None => Either::Left(view! { <h1>"User not found."</h1> }), Some(user) => Either::Right(view! { <div> <h1>"User: " {user.id.clone()}</h1> <ul class="meta"> <li> <span class="label">"Created: "</span> {user.created} </li> <li> <span class="label">"Karma: "</span> {user.karma} </li> <li inner_html={user.about} class="about"></li> </ul> <p class="links"> <a href=format!("https://news.ycombinator.com/submitted?id={}", user.id)>"submissions"</a> " | " <a href=format!("https://news.ycombinator.com/threads?id={}", user.id)>"comments"</a> </p> </div> }) }})} </Suspense> </div> }.into_any() } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/routes/story.rs
examples/hackernews_axum/src/routes/story.rs
use crate::api::{self, Story}; use leptos::{either::Either, prelude::*}; use leptos_meta::Meta; use leptos_router::{ components::A, hooks::use_params_map, lazy_route, LazyRoute, }; #[derive(Debug)] pub struct StoryRoute { story: Resource<Option<Story>>, } #[lazy_route] impl LazyRoute for StoryRoute { fn data() -> Self { let params = use_params_map(); let story = Resource::new_blocking( move || params.read().get("id").unwrap_or_default(), move |id| async move { if id.is_empty() { None } else { api::fetch_api::<api::Story>(&api::story(&format!( "item/{id}" ))) .await } }, ); Self { story } } fn view(this: Self) -> AnyView { let StoryRoute { story } = this; Suspense(SuspenseProps::builder().fallback(|| "Loading...").children(ToChildren::to_children(move || Suspend::new(async move { match story.await.clone() { None => Either::Left("Story not found."), Some(story) => { Either::Right(view! { <Meta name="description" content=story.title.clone()/> <div class="item-view"> <div class="item-view-header"> <a href=story.url target="_blank"> <h1>{story.title}</h1> </a> <span class="host"> "("{story.domain}")" </span> <ShowLet some=story.user let:user> <p class="meta"> {story.points} " points | by " <A href=format!("/users/{user}")>{user.clone()}</A> {format!(" {}", story.time_ago)} </p> </ShowLet> </div> <div class="item-view-comments"> <p class="item-view-comments-header"> {if story.comments_count.unwrap_or_default() > 0 { format!("{} comments", story.comments_count.unwrap_or_default()) } else { "No comments yet.".into() }} </p> <ul class="comment-children"> <For each=move || story.comments.clone().unwrap_or_default() key=|comment| comment.id let:comment > <Comment comment /> </For> </ul> </div> </div> }) } } }))).build()).into_any() } } #[component] pub fn Comment(comment: api::Comment) -> impl IntoView { let (open, set_open) = signal(true); view! { <li class="comment"> <div class="by"> <A href=format!("/users/{}", comment.user.clone().unwrap_or_default())>{comment.user.clone()}</A> {format!(" {}", comment.time_ago)} </div> <div class="text" inner_html=comment.content></div> {(!comment.comments.is_empty()).then(|| { view! { <div> <div class="toggle" class:open=open> <a on:click=move |_| set_open.update(|n| *n = !*n)> { let comments_len = comment.comments.len(); move || if open.get() { "[-]".into() } else { format!("[+] {}{} collapsed", comments_len, pluralize(comments_len)) } } </a> </div> {move || open.get().then({ let comments = comment.comments.clone(); move || view! { <ul class="comment-children"> <For each=move || comments.clone() key=|comment| comment.id let:comment > <Comment comment /> </For> </ul> } })} </div> } })} </li> }.into_any() } fn pluralize(n: usize) -> &'static str { if n == 1 { " reply" } else { " replies" } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/routes/nav.rs
examples/hackernews_axum/src/routes/nav.rs
use leptos::prelude::*; use leptos_router::components::A; #[component] pub fn Nav() -> impl IntoView { view! { <header class="header"> <nav class="inner"> <A href="/home"> <strong>"HN"</strong> </A> <A href="/new"> <strong>"New"</strong> </A> <A href="/show"> <strong>"Show"</strong> </A> <A href="/ask"> <strong>"Ask"</strong> </A> <A href="/job"> <strong>"Jobs"</strong> </A> <a class="github" href="http://github.com/leptos-rs/leptos" target="_blank" rel="noreferrer"> "Built with Leptos" </a> </nav> </header> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/routes/stories.rs
examples/hackernews_axum/src/routes/stories.rs
use crate::api; use leptos::{either::Either, prelude::*}; use leptos_router::{ components::A, hooks::{use_params_map, use_query_map}, }; fn category(from: &str) -> &'static str { match from { "new" => "newest", "show" => "show", "ask" => "ask", "job" => "jobs", _ => "news", } } #[component] pub fn Stories() -> impl IntoView { let query = use_query_map(); let params = use_params_map(); let page = move || { query .read() .get("page") .and_then(|page| page.parse::<usize>().ok()) .unwrap_or(1) }; let story_type = move || { params .read() .get("stories") .unwrap_or_else(|| "top".to_string()) }; let stories = Resource::new( move || (page(), story_type()), move |(page, story_type)| async move { let path = format!("{}?page={}", category(&story_type), page); api::fetch_api::<Vec<api::Story>>(&api::story(&path)).await }, ); let (pending, set_pending) = signal(false); let hide_more_link = move || match &*stories.read() { Some(Some(stories)) => stories.len() < 28, _ => true } || pending.get(); view! { <div class="news-view"> <div class="news-list-nav"> <span> {move || if page() > 1 { Either::Left(view! { <a class="page-link" href=move || format!("/{}?page={}", story_type(), page() - 1) aria-label="Previous Page" > "< prev" </a> }) } else { Either::Right(view! { <span class="page-link disabled" aria-hidden="true"> "< prev" </span> }) }} </span> <span>"page " {page}</span> <Suspense> <span class="page-link" class:disabled=hide_more_link aria-hidden=hide_more_link > <a href=move || format!("/{}?page={}", story_type(), page() + 1) aria-label="Next Page" > "more >" </a> </span> </Suspense> </div> <main class="news-list"> <div> <Transition fallback=move || view! { <p>"Loading..."</p> } set_pending > <Show when=move || stories.read().as_ref().map(Option::is_none).unwrap_or(false)> > <p>"Error loading stories."</p> </Show> <ul> <For each=move || stories.get().unwrap_or_default().unwrap_or_default() key=|story| story.id let:story > <Story story/> </For> </ul> </Transition> </div> </main> </div> } } #[component] fn Story(story: api::Story) -> impl IntoView { view! { <li class="news-item"> <span class="score">{story.points}</span> <span class="title"> {if !story.url.starts_with("item?id=") { Either::Left(view! { <span> <a href=story.url target="_blank" rel="noreferrer"> {story.title.clone()} </a> <span class="host">"("{story.domain}")"</span> </span> }) } else { let title = story.title.clone(); Either::Right(view! { <A href=format!("/stories/{}", story.id)>{title}</A> }) }} </span> <br /> <span class="meta"> {if story.story_type != "job" { Either::Left(view! { <span> {"by "} <ShowLet some=story.user let:user> <A href=format!("/users/{user}")>{user.clone()}</A> </ShowLet> {format!(" {} | ", story.time_ago)} <A href=format!("/stories/{}", story.id)> {if story.comments_count.unwrap_or_default() > 0 { format!("{} comments", story.comments_count.unwrap_or_default()) } else { "discuss".into() }} </A> </span> }) } else { let title = story.title.clone(); Either::Right(view! { <A href=format!("/item/{}", story.id)>{title}</A> }) }} </span> {(story.story_type != "link").then(|| view! { " " <span class="label">{story.story_type}</span> })} </li> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todomvc/src/lib.rs
examples/todomvc/src/lib.rs
use leptos::{ev, html::Input, prelude::*}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use web_sys::KeyboardEvent; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Todos(pub Vec<Todo>); const STORAGE_KEY: &str = "todos-leptos"; impl Default for Todos { fn default() -> Self { let starting_todos = window() .local_storage() .ok() .flatten() .and_then(|storage| { storage.get_item(STORAGE_KEY).ok().flatten().and_then( |value| serde_json::from_str::<Vec<Todo>>(&value).ok(), ) }) .unwrap_or_default(); Self(starting_todos) } } // Basic operations to manipulate the todo list: nothing really interesting here impl Todos { pub fn is_empty(&self) -> bool { self.0.is_empty() } pub fn add(&mut self, todo: Todo) { self.0.push(todo); } pub fn remove(&mut self, id: Uuid) { self.retain(|todo| todo.id != id); } pub fn remaining(&self) -> usize { // `todo.completed` is a signal, so we call .get() to access its value self.0.iter().filter(|todo| !todo.completed.get()).count() } pub fn completed(&self) -> usize { // `todo.completed` is a signal, so we call .get() to access its value self.0.iter().filter(|todo| todo.completed.get()).count() } pub fn toggle_all(&self) { // if all are complete, mark them all active if self.remaining() == 0 { for todo in &self.0 { todo.completed.update(|completed| { if *completed { *completed = false } }); } } // otherwise, mark them all complete else { for todo in &self.0 { todo.completed.set(true); } } } fn clear_completed(&mut self) { self.retain(|todo| !todo.completed.get()); } fn retain(&mut self, mut f: impl FnMut(&Todo) -> bool) { self.0.retain(|todo| { let retain = f(todo); // because these signals are created at the top level, // they are owned by the <TodoMVC/> component and not // by the individual <Todo/> components. This means // that if they are not manually disposed when removed, they // will be held onto until the <TodoMVC/> is unmounted. if !retain { todo.title.dispose(); todo.completed.dispose(); } retain }) } } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct Todo { pub id: Uuid, pub title: RwSignal<String>, pub completed: RwSignal<bool>, } impl Todo { pub fn new(id: Uuid, title: String) -> Self { Self::new_with_completed(id, title, false) } pub fn new_with_completed( id: Uuid, title: String, completed: bool, ) -> Self { // RwSignal combines the getter and setter in one struct, rather than separating // the getter from the setter. This makes it more convenient in some cases, such // as when we're putting the signals into a struct and passing it around. let title = RwSignal::new(title); let completed = RwSignal::new(completed); Self { id, title, completed, } } pub fn toggle(&self) { // A signal's `update()` function gives you a mutable reference to the current value // You can use that to modify the value in place, which will notify any subscribers. self.completed.update(|completed| *completed = !*completed); } } const ESCAPE_KEY: u32 = 27; const ENTER_KEY: u32 = 13; #[component] pub fn TodoMVC() -> impl IntoView { // The `todos` are a signal, since we need to reactively update the list let (todos, set_todos) = signal(Todos::default()); // We provide a context that each <Todo/> component can use to update the list // Here, I'm just passing the `WriteSignal`; a <Todo/> doesn't need to read the whole list // (and shouldn't try to, as that would cause each individual <Todo/> to re-render when // a new todo is added! This kind of hygiene is why `signal` defaults to read-write // segregation.) provide_context(set_todos); // Handle the three filter modes: All, Active, and Completed let (mode, set_mode) = signal(Mode::All); window_event_listener(ev::hashchange, move |_| { let new_mode = location_hash().map(|hash| route(&hash)).unwrap_or_default(); set_mode.set(new_mode); }); // Callback to add a todo on pressing the `Enter` key, if the field isn't empty let input_ref = NodeRef::<Input>::new(); let add_todo = move |ev: KeyboardEvent| { let input = input_ref.get().unwrap(); ev.stop_propagation(); let key_code = ev.key_code(); if key_code == ENTER_KEY { let title = input.value(); let title = title.trim(); if !title.is_empty() { let new = Todo::new(Uuid::new_v4(), title.to_string()); set_todos.update(|t| t.add(new)); input.set_value(""); } } }; // A derived signal that filters the list of the todos depending on the filter mode // This doesn't need to be a `Memo`, because we're only reading it in one place let filtered_todos = move || { todos.with(|todos| match mode.get() { Mode::All => todos.0.to_vec(), Mode::Active => todos .0 .iter() .filter(|todo| !todo.completed.get()) .cloned() .collect(), Mode::Completed => todos .0 .iter() .filter(|todo| todo.completed.get()) .cloned() .collect(), }) }; // Serialization // // the effect reads the `todos` signal, and each `Todo`'s title and completed // status, so it will automatically re-run on any change to the list of tasks // // this is the main point of effects: to synchronize reactive state // with something outside the reactive system (like localStorage) Effect::new(move |_| { if let Ok(Some(storage)) = window().local_storage() { let json = serde_json::to_string(&todos) .expect("couldn't serialize Todos"); if storage.set_item(STORAGE_KEY, &json).is_err() { leptos::logging::error!( "error while trying to set item in localStorage" ); } } }); // focus the main input on load Effect::new(move |_| { if let Some(input) = input_ref.get() { let _ = input.focus(); } }); view! { <main> <section class="todoapp"> <header class="header"> <h1>"todos"</h1> <input class="new-todo" placeholder="What needs to be done?" autofocus on:keydown=add_todo node_ref=input_ref /> </header> <section class="main" class:hidden=move || todos.with(|t| t.is_empty())> <input id="toggle-all" class="toggle-all" type="checkbox" prop:checked=move || todos.with(|t| t.remaining() > 0) on:input=move |_| todos.with(|t| t.toggle_all()) /> <label for="toggle-all">"Mark all as complete"</label> <ul class="todo-list"> <For each=filtered_todos key=|todo| todo.id let:todo> <Todo todo/> </For> </ul> </section> <footer class="footer" class:hidden=move || todos.with(|t| t.is_empty())> <span class="todo-count"> <strong>{move || todos.with(|t| t.remaining().to_string())}</strong> {move || { if todos.with(|t| t.remaining()) == 1 { " item" } else { " items" } }} " left" </span> <ul class="filters"> <li> <a href="#/" class="selected" class:selected=move || mode.get() == Mode::All > "All" </a> </li> <li> <a href="#/active" class:selected=move || mode.get() == Mode::Active> "Active" </a> </li> <li> <a href="#/completed" class:selected=move || mode.get() == Mode::Completed > "Completed" </a> </li> </ul> <button class="clear-completed hidden" class:hidden=move || todos.with(|t| t.completed() == 0) on:click=move |_| set_todos.update(|t| t.clear_completed()) > "Clear completed" </button> </footer> </section> <footer class="info"> <p>"Double-click to edit a todo"</p> <p>"Created by " <a href="http://todomvc.com">"Greg Johnston"</a></p> <p>"Part of " <a href="http://todomvc.com">"TodoMVC"</a></p> </footer> </main> } } #[component] pub fn Todo(todo: Todo) -> impl IntoView { let (editing, set_editing) = signal(false); let set_todos = use_context::<WriteSignal<Todos>>().unwrap(); // this will be filled by node_ref=input below let todo_input = NodeRef::<Input>::new(); let save = move |value: &str| { let value = value.trim(); if value.is_empty() { set_todos.update(|t| t.remove(todo.id)); } else { todo.title.set(value.to_string()); } set_editing.set(false); }; view! { <li class="todo" class:editing=editing class:completed=move || todo.completed.get()> <div class="view"> <input node_ref=todo_input class="toggle" type="checkbox" bind:checked=todo.completed /> <label on:dblclick=move |_| { set_editing.set(true); if let Some(input) = todo_input.get() { _ = input.focus(); } }>{move || todo.title.get()}</label> <button class="destroy" on:click=move |_| set_todos.update(|t| t.remove(todo.id)) ></button> </div> {move || { editing .get() .then(|| { view! { <input class="edit" class:hidden=move || !editing.get() prop:value=move || todo.title.get() on:focusout:target=move |ev| save(&ev.target().value()) on:keyup:target=move |ev| { let key_code = ev.key_code(); if key_code == ENTER_KEY { save(&ev.target().value()); } else if key_code == ESCAPE_KEY { set_editing.set(false); } } /> } }) }} </li> } } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub enum Mode { Active, Completed, #[default] All, } pub fn route(hash: &str) -> Mode { match hash { "/active" => Mode::Active, "/completed" => Mode::Completed, _ => Mode::All, } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todomvc/src/main.rs
examples/todomvc/src/main.rs
pub use todomvc::*; fn main() { console_error_panic_hook::set_once(); leptos::mount::mount_to_body(TodoMVC) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/js-framework-benchmark/src/lib.rs
examples/js-framework-benchmark/src/lib.rs
use leptos::prelude::*; use rand::prelude::*; use std::sync::atomic::{AtomicUsize, Ordering}; static ADJECTIVES: &[&str] = &[ "pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy", ]; static COLOURS: &[&str] = &[ "red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange", ]; static NOUNS: &[&str] = &[ "table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard", ]; #[derive(Debug, Clone, PartialEq, Eq, Hash)] struct RowData { id: usize, label: ArcRwSignal<String>, } static ID_COUNTER: AtomicUsize = AtomicUsize::new(1); fn build_data(count: usize) -> Vec<RowData> { let mut thread_rng = thread_rng(); let mut data = Vec::new(); data.reserve_exact(count); for _i in 0..count { let adjective = ADJECTIVES.choose(&mut thread_rng).unwrap(); let colour = COLOURS.choose(&mut thread_rng).unwrap(); let noun = NOUNS.choose(&mut thread_rng).unwrap(); let capacity = adjective.len() + colour.len() + noun.len() + 2; let mut label = String::with_capacity(capacity); label.push_str(adjective); label.push(' '); label.push_str(colour); label.push(' '); label.push_str(noun); data.push(RowData { id: ID_COUNTER.load(Ordering::Relaxed), label: ArcRwSignal::new(label), }); ID_COUNTER .store(ID_COUNTER.load(Ordering::Relaxed) + 1, Ordering::Relaxed); } data } /// Button component. #[component] fn Button( /// ID for the button element id: &'static str, /// Text that should be included text: &'static str, ) -> impl IntoView { view! { <div class="col-sm-6 smallpad"> <button id=id class="btn btn-primary btn-block" type="button"> {text} </button> </div> } } #[component] pub fn App() -> impl IntoView { let (data, set_data) = signal(Vec::<RowData>::new()); let (selected, set_selected) = signal(None::<usize>); let remove = move |id: usize| { set_data.update(move |data| data.retain(|row| row.id != id)); }; let run = move |_| { set_data.set(build_data(1000)); set_selected.set(None); }; let run_lots = move |_| { set_data.set(build_data(10000)); set_selected.set(None); }; let add = move |_| { set_data.update(move |data| data.append(&mut build_data(1000))); }; let update = move |_| { data.with(|data| { for row in data.iter().step_by(10) { row.label.update(|n| n.push_str(" !!!")); } }); }; let clear = move |_| { set_data.set(Vec::new()); set_selected.set(None); }; let swap_rows = move |_| { set_data.update(|data| { if data.len() > 998 { data.swap(1, 998); } }); }; let is_selected = Selector::new(move || selected.get()); view! { <div class="container"> <div class="jumbotron"> <div class="row"> <div class="col-md-6"> <h1>"Leptos"</h1> </div> <div class="col-md-6"> <div class="row"> <Button id="run" text="Create 1,000 rows" on:click=run /> <Button id="runlots" text="Create 10,000 rows" on:click=run_lots /> <Button id="add" text="Append 1,000 rows" on:click=add /> <Button id="update" text="Update every 10th row" on:click=update /> <Button id="clear" text="Clear" on:click=clear /> <Button id="swaprows" text="Swap Rows" on:click=swap_rows /> </div> </div> </div> </div> <table class="table table-hover table-striped test-data"> <tbody> <For each=move || data.get() key=|row| row.id children=move |row: RowData| { let row_id = row.id; let label = row.label; let is_selected = is_selected.clone(); template! { < tr class : danger = { move || is_selected.selected(&Some(row_id)) } > < td class = "col-md-1" > { row_id.to_string() } </ td > < td class = "col-md-4" >< a on : click = move | _ | set_selected .set(Some(row_id)) > { move || label.get() } </ a ></ td > < td class = "col-md-1" >< a on : click = move | _ | remove(row_id) >< span class = "glyphicon glyphicon-remove" aria - hidden = "true" ></ span ></ a ></ td > < td class = "col-md-6" /> </ tr > } } /> </tbody> </table> <span class="preloadicon glyphicon glyphicon-remove" aria-hidden="true"></span> </div> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/js-framework-benchmark/src/main.rs
examples/js-framework-benchmark/src/main.rs
use js_framework_benchmark_leptos::App; use leptos::{ leptos_dom::helpers::document, mount::mount_to, wasm_bindgen::JsCast, }; pub fn main() { console_error_panic_hook::set_once(); let root = document().query_selector("#main").unwrap().unwrap(); let handle = mount_to(root.unchecked_into(), App); handle.forget(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/js-framework-benchmark/tests/web.rs
examples/js-framework-benchmark/tests/web.rs
use js_framework_benchmark_leptos::*; use leptos::{prelude::*, task::tick}; use wasm_bindgen::JsCast; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] async fn add_item() { let document = document(); let test_wrapper = document.create_element("section").unwrap(); let _ = document.body().unwrap().append_child(&test_wrapper); // start by rendering our counter and mounting it to the DOM let _handle = mount_to(test_wrapper.clone().unchecked_into(), App); let table = test_wrapper .query_selector("table") .unwrap() .unwrap() .unchecked_into::<web_sys::HtmlTableElement>(); let create = test_wrapper .query_selector("button#runlots") .unwrap() .unwrap() .unchecked_into::<web_sys::HtmlButtonElement>(); let add = test_wrapper .query_selector("button#add") .unwrap() .unwrap() .unchecked_into::<web_sys::HtmlButtonElement>(); let clear = test_wrapper .query_selector("button#clear") .unwrap() .unwrap() .unchecked_into::<web_sys::HtmlButtonElement>(); _handle.forget(); // now let's click the `clear` button clear.click(); tick().await; // now check that table is empty assert_eq!(table.rows().length(), 0); create.click(); tick().await; assert_eq!(table.rows().length(), 10000); add.click(); tick().await; assert_eq!(table.rows().length(), 11000); clear.click(); tick().await; assert_eq!(table.rows().length(), 0) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/lib.rs
examples/hackernews/src/lib.rs
use leptos::prelude::*; mod api; mod routes; use leptos_meta::{provide_meta_context, Link, Meta, Stylesheet}; use leptos_router::{ components::{FlatRoutes, Route, Router, RoutingProgress}, OptionalParamSegment, ParamSegment, StaticSegment, }; use routes::{nav::*, stories::*, story::*, users::*}; use std::time::Duration; #[component] pub fn App() -> impl IntoView { provide_meta_context(); let (is_routing, set_is_routing) = signal(false); view! { <Stylesheet id="leptos" href="/pkg/hackernews.css"/> <Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/> <Meta name="description" content="Leptos implementation of a HackerNews demo."/> <Router set_is_routing> // shows a progress bar while async data are loading <div class="routing-progress"> <RoutingProgress is_routing max_time=Duration::from_millis(250)/> </div> <Nav /> <main> <FlatRoutes fallback=|| "Not found."> <Route path=(StaticSegment("users"), ParamSegment("id")) view=User/> <Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/> <Route path=OptionalParamSegment("stories") view=Stories/> </FlatRoutes> </main> </Router> } } #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/api.rs
examples/hackernews/src/api.rs
use serde::{de::DeserializeOwned, Deserialize, Serialize}; pub fn story(path: &str) -> String { format!("https://node-hnapi.herokuapp.com/{path}") } pub fn user(path: &str) -> String { format!("https://hacker-news.firebaseio.com/v0/user/{path}.json") } #[cfg(not(feature = "ssr"))] pub fn fetch_api<T>( path: &str, ) -> impl std::future::Future<Output = Option<T>> + Send + '_ where T: Serialize + DeserializeOwned, { use leptos::prelude::on_cleanup; use send_wrapper::SendWrapper; SendWrapper::new(async move { let abort_controller = SendWrapper::new(web_sys::AbortController::new().ok()); let abort_signal = abort_controller.as_ref().map(|a| a.signal()); // abort in-flight requests if, e.g., we've navigated away from this page on_cleanup(move || { if let Some(abort_controller) = abort_controller.take() { abort_controller.abort() } }); gloo_net::http::Request::get(path) .abort_signal(abort_signal.as_ref()) .send() .await .map_err(|e| log::error!("{e}")) .ok()? .json() .await .ok() }) } #[cfg(feature = "ssr")] pub async fn fetch_api<T>(path: &str) -> Option<T> where T: Serialize + DeserializeOwned, { reqwest::get(path) .await .map_err(|e| log::error!("{e}")) .ok()? .json() .await .ok() } #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] pub struct Story { pub id: usize, pub title: String, pub points: Option<i32>, pub user: Option<String>, pub time: usize, pub time_ago: String, #[serde(alias = "type")] pub story_type: String, pub url: String, #[serde(default)] pub domain: String, #[serde(default)] pub comments: Option<Vec<Comment>>, pub comments_count: Option<usize>, } #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] pub struct Comment { pub id: usize, pub level: usize, pub user: Option<String>, pub time: usize, pub time_ago: String, pub content: Option<String>, pub comments: Vec<Comment>, } #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] pub struct User { pub created: usize, pub id: String, pub karma: i32, pub about: Option<String>, }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/main.rs
examples/hackernews/src/main.rs
// server-only stuff #[cfg(feature = "ssr")] mod ssr_imports { pub use actix_files::Files; pub use actix_web::*; pub use hackernews::App; #[get("/style.css")] pub async fn css() -> impl Responder { actix_files::NamedFile::open_async("./style.css").await } #[get("/favicon.ico")] pub async fn favicon() -> impl Responder { actix_files::NamedFile::open_async("./target/site//favicon.ico").await } } #[cfg(feature = "ssr")] #[actix_web::main] async fn main() -> std::io::Result<()> { use leptos::prelude::*; use leptos_actix::{generate_route_list, LeptosRoutes}; use leptos_meta::MetaTags; use ssr_imports::*; let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; HttpServer::new(move || { // Generate the list of routes in your Leptos App let routes = generate_route_list(App); let leptos_options = &conf.leptos_options; let site_root = &leptos_options.site_root; App::new() .service(css) .service(favicon) .leptos_routes(routes, { let leptos_options = leptos_options.clone(); move || { use leptos::prelude::*; view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=leptos_options.clone() /> <HydrationScripts options=leptos_options.clone()/> <MetaTags/> </head> <body> <App/> </body> </html> } }}) .service(Files::new("/", site_root.as_ref())) //.wrap(middleware::Compress::default()) }) .bind(&addr)? .run() .await } // CSR-only setup #[cfg(not(feature = "ssr"))] fn main() { use hackernews::App; console_error_panic_hook::set_once(); leptos::mount::mount_to_body(App) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/routes.rs
examples/hackernews/src/routes.rs
pub mod nav; pub mod stories; pub mod story; pub mod users;
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/routes/users.rs
examples/hackernews/src/routes/users.rs
use crate::api::{self, User}; use leptos::{either::Either, prelude::*, server::Resource}; use leptos_router::hooks::use_params_map; #[component] pub fn User() -> impl IntoView { let params = use_params_map(); let user = Resource::new( move || params.read().get("id").unwrap_or_default(), move |id| async move { if id.is_empty() { None } else { api::fetch_api::<User>(&api::user(&id)).await } }, ); view! { <div class="user-view"> <Suspense fallback=|| { view! { "Loading..." } }> {move || Suspend::new(async move { match user.await.clone() { None => Either::Left(view! { <h1>"User not found."</h1> }), Some(user) => { Either::Right( view! { <div> <h1>"User: " {user.id.clone()}</h1> <ul class="meta"> <li> <span class="label">"Created: "</span> {user.created} </li> <li> <span class="label">"Karma: "</span> {user.karma} </li> <li inner_html=user.about class="about"></li> </ul> <p class="links"> <a href=format!( "https://news.ycombinator.com/submitted?id={}", user.id, )>"submissions"</a> " | " <a href=format!( "https://news.ycombinator.com/threads?id={}", user.id, )>"comments"</a> </p> </div> }, ) } } })} </Suspense> </div> } .into_any() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/routes/story.rs
examples/hackernews/src/routes/story.rs
use crate::api; use leptos::{either::Either, prelude::*}; use leptos_meta::Meta; use leptos_router::{components::A, hooks::use_params_map}; #[component] pub fn Story() -> impl IntoView { let params = use_params_map(); let story = Resource::new_blocking( move || params.read().get("id").unwrap_or_default(), move |id| async move { if id.is_empty() { None } else { api::fetch_api::<api::Story>(&api::story(&format!("item/{id}"))) .await } }, ); Suspense(SuspenseProps::builder().fallback(|| "Loading...").children(ToChildren::to_children(move || Suspend::new(async move { match story.await.clone() { None => Either::Left("Story not found."), Some(story) => { Either::Right(view! { <Meta name="description" content=story.title.clone()/> <div class="item-view"> <div class="item-view-header"> <a href=story.url target="_blank"> <h1>{story.title}</h1> </a> <span class="host">"(" {story.domain} ")"</span> <ShowLet some=story.user let:user> <p class="meta"> {story.points} " points | by " <A href=format!("/users/{user}")>{user.clone()}</A> {format!(" {}", story.time_ago)} </p> </ShowLet> </div> <div class="item-view-comments"> <p class="item-view-comments-header"> {if story.comments_count.unwrap_or_default() > 0 { format!("{} comments", story.comments_count.unwrap_or_default()) } else { "No comments yet.".into() }} </p> <ul class="comment-children"> <For each=move || story.comments.clone().unwrap_or_default() key=|comment| comment.id let:comment > <Comment comment/> </For> </ul> </div> </div> }) } } }))).build()) .into_any() } #[component] pub fn Comment(comment: api::Comment) -> impl IntoView { let (open, set_open) = signal(true); view! { <li class="comment"> <div class="by"> <A href=format!( "/users/{}", comment.user.clone().unwrap_or_default(), )>{comment.user.clone()}</A> {format!(" {}", comment.time_ago)} </div> <div class="text" inner_html=comment.content></div> {(!comment.comments.is_empty()) .then(|| { view! { <div> <div class="toggle" class:open=open> <a on:click=move |_| { set_open.update(|n| *n = !*n) }> { let comments_len = comment.comments.len(); move || { if open.get() { "[-]".into() } else { format!( "[+] {}{} collapsed", comments_len, pluralize(comments_len), ) } } } </a> </div> {move || { open .get() .then({ let comments = comment.comments.clone(); move || { view! { <ul class="comment-children"> <For each=move || comments.clone() key=|comment| comment.id let:comment > <Comment comment/> </For> </ul> } } }) }} </div> } })} </li> }.into_any() } fn pluralize(n: usize) -> &'static str { if n == 1 { " reply" } else { " replies" } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/routes/nav.rs
examples/hackernews/src/routes/nav.rs
use leptos::prelude::*; use leptos_router::components::A; #[component] pub fn Nav() -> impl IntoView { view! { <header class="header"> <nav class="inner"> <A href="/home"> <strong>"HN"</strong> </A> <A href="/new"> <strong>"New"</strong> </A> <A href="/show"> <strong>"Show"</strong> </A> <A href="/ask"> <strong>"Ask"</strong> </A> <A href="/job"> <strong>"Jobs"</strong> </A> <a class="github" href="http://github.com/leptos-rs/leptos" target="_blank" rel="noreferrer" > "Built with Leptos" </a> </nav> </header> } .into_any() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews/src/routes/stories.rs
examples/hackernews/src/routes/stories.rs
use crate::api; use leptos::{either::Either, prelude::*}; use leptos_router::{ components::A, hooks::{use_params_map, use_query_map}, }; fn category(from: &str) -> &'static str { match from { "new" => "newest", "show" => "show", "ask" => "ask", "job" => "jobs", _ => "news", } } #[component] pub fn Stories() -> impl IntoView { let query = use_query_map(); let params = use_params_map(); let page = move || { query .read() .get("page") .and_then(|page| page.parse::<usize>().ok()) .unwrap_or(1) }; let story_type = move || { params .read() .get("stories") .unwrap_or_else(|| "top".to_string()) }; let stories = Resource::new( move || (page(), story_type()), move |(page, story_type)| async move { let path = format!("{}?page={}", category(&story_type), page); api::fetch_api::<Vec<api::Story>>(&api::story(&path)).await }, ); let (pending, set_pending) = signal(false); let hide_more_link = move || match &*stories.read() { Some(Some(stories)) => stories.len() < 28, _ => true } || pending.get(); view! { <div class="news-view"> <div class="news-list-nav"> <span> {move || { if page() > 1 { Either::Left( view! { <a class="page-link" href=move || { format!("/{}?page={}", story_type(), page() - 1) } aria-label="Previous Page" > "< prev" </a> }, ) } else { Either::Right( view! { <span class="page-link disabled" aria-hidden="true"> "< prev" </span> }, ) } }} </span> <span>"page " {page}</span> <Suspense> <span class="page-link" class:disabled=hide_more_link aria-hidden=hide_more_link > <a href=move || format!("/{}?page={}", story_type(), page() + 1) aria-label="Next Page" > "more >" </a> </span> </Suspense> </div> <main class="news-list"> <div> <Transition fallback=move || view! { <p>"Loading..."</p> } set_pending> <Show when=move || { stories.read().as_ref().map(Option::is_none).unwrap_or(false) }>> <p>"Error loading stories."</p></Show> <ul> <For each=move || stories.get().unwrap_or_default().unwrap_or_default() key=|story| story.id let:story > <Story story/> </For> </ul> </Transition> </div> </main> </div> } .into_any() } #[component] fn Story(story: api::Story) -> impl IntoView { view! { <li class="news-item"> <span class="score">{story.points}</span> <span class="title"> {if !story.url.starts_with("item?id=") { Either::Left( view! { <span> <a href=story.url target="_blank" rel="noreferrer"> {story.title.clone()} </a> <span class="host">"(" {story.domain} ")"</span> </span> }, ) } else { let title = story.title.clone(); Either::Right(view! { <A href=format!("/stories/{}", story.id)>{title}</A> }) }} </span> <br/> <span class="meta"> {if story.story_type != "job" { Either::Left( view! { <span> "by " <ShowLet some=story.user let:user> <A href=format!("/users/{user}")>{user.clone()}</A> </ShowLet> {format!(" {} | ", story.time_ago)} <A href=format!( "/stories/{}", story.id, )> {if story.comments_count.unwrap_or_default() > 0 { format!( "{} comments", story.comments_count.unwrap_or_default(), ) } else { "discuss".into() }} </A> </span> }, ) } else { let title = story.title.clone(); Either::Right(view! { <A href=format!("/item/{}", story.id)>{title}</A> }) }} </span> {(story.story_type != "link") .then(|| { view! { " " <span class="label">{story.story_type}</span> } })} </li> } .into_any() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/stores/src/lib.rs
examples/stores/src/lib.rs
use chrono::{Local, NaiveDate}; use leptos::{logging::warn, prelude::*}; use reactive_stores::{Field, Patch, Store}; use serde::{Deserialize, Serialize}; use std::sync::atomic::{AtomicUsize, Ordering}; // ID starts higher than 0 because we have a few starting todos by default static NEXT_ID: AtomicUsize = AtomicUsize::new(3); #[derive(Debug, Store, Serialize, Deserialize)] struct Todos { user: User, #[store(key: usize = |todo| todo.id)] todos: Vec<Todo>, } #[derive(Debug, Store, Patch, Serialize, Deserialize)] struct User { name: String, email: String, } #[derive(Debug, Store, Serialize, Deserialize)] struct Todo { id: usize, label: String, status: Status, } #[derive(Debug, Default, Clone, Store, Serialize, Deserialize)] enum Status { #[default] Pending, Scheduled, ScheduledFor { date: NaiveDate, }, Done, } impl Status { pub fn next_step(&mut self) { *self = match self { Status::Pending => Status::ScheduledFor { date: Local::now().naive_local().into(), }, Status::Scheduled | Status::ScheduledFor { .. } => Status::Done, Status::Done => Status::Done, }; } } impl Todo { pub fn new(label: impl ToString) -> Self { Self { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), label: label.to_string(), status: Status::Pending, } } } fn data() -> Todos { Todos { user: User { name: "Bob".to_string(), email: "lawblog@bobloblaw.com".into(), }, todos: vec![ Todo { id: 0, label: "Create reactive store".to_string(), status: Status::Pending, }, Todo { id: 1, label: "???".to_string(), status: Status::Pending, }, Todo { id: 2, label: "Profit".to_string(), status: Status::Pending, }, ], } } #[component] pub fn App() -> impl IntoView { let store = Store::new(data()); let input_ref = NodeRef::new(); view! { <p>"Hello, " {move || store.user().name().get()}</p> <UserForm user=store.user()/> <hr/> <form on:submit=move |ev| { ev.prevent_default(); store.todos().write().push(Todo::new(input_ref.get().unwrap().value())); }> <label>"Add a Todo" <input type="text" node_ref=input_ref/></label> <input type="submit"/> </form> <ol> // because `todos` is a keyed field, `store.todos()` returns a struct that // directly implements IntoIterator, so we can use it in <For/> and // it will manage reactivity for the store fields correctly <For each=move || store.todos() key=|row| row.id().get() let:todo > <TodoRow store todo/> </For> </ol> <pre>{move || serde_json::to_string_pretty(&*store.read())}</pre> } } #[component] fn UserForm(#[prop(into)] user: Field<User>) -> impl IntoView { let error = RwSignal::new(None); view! { {move || error.get().map(|n| view! { <p>{n}</p> })} <form on:submit:target=move |ev| { ev.prevent_default(); match User::from_event(&ev) { Ok(new_user) => { error.set(None); user.patch(new_user); } Err(e) => error.set(Some(e.to_string())), } }> <label> "Name" <input type="text" name="name" prop:value=move || user.name().get()/> </label> <label> "Email" <input type="email" name="email" prop:value=move || user.email().get()/> </label> <input type="submit"/> </form> } } #[component] fn TodoRow( store: Store<Todos>, #[prop(into)] todo: Field<Todo>, ) -> impl IntoView { let status = todo.status(); let title = todo.label(); let editing = RwSignal::new(true); view! { <li style:text-decoration=move || { if status.done() { "line-through" } else { Default::default() } }> <p class:hidden=move || editing.get() on:click=move |_| { editing.update(|n| *n = !*n); } > {move || title.get()} </p> <input class:hidden=move || !(editing.get()) type="text" prop:value=move || title.get() on:change=move |ev| { title.set(event_target_value(&ev)); } /> <button on:click=move |_| { status.write().next_step() }> {move || { if todo.status().done() { "Done" } else if status.scheduled() || status.scheduled_for() { "Scheduled" } else { "Pending" } }} </button> <button on:click=move |_| { let id = todo.id().get(); store.todos().write().retain(|todo| todo.id != id); }>"X"</button> <input type="date" prop:value=move || { todo.status().scheduled_for_date().map(|n| n.get().to_string()) } class:hidden=move || !todo.status().scheduled_for() on:change:target=move |ev| { if let Some(date) = todo.status().scheduled_for_date() { let value = ev.target().value(); match NaiveDate::parse_from_str(&value, "%Y-%m-%d") { Ok(new_date) => { date.set(new_date); } Err(e) => warn!("{e}"), } } } /> </li> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/stores/src/main.rs
examples/stores/src/main.rs
use leptos::prelude::*; use stores::App; pub fn main() { console_error_panic_hook::set_once(); mount_to_body(App) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_csr/src/app.rs
examples/tailwind_csr/src/app.rs
use leptos::prelude::*; use leptos_meta::*; use leptos_router::{ components::{Route, Router, Routes}, StaticSegment, }; #[component] pub fn App() -> impl IntoView { provide_meta_context(); view! { <Stylesheet id="leptos" href="/style/output.css"/> <Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/> <Router> <Routes fallback=|| "Page not found."> <Route path=StaticSegment("") view=Home/> </Routes> </Router> } } #[component] fn Home() -> impl IntoView { let (value, set_value) = signal(0); // thanks to https://tailwindcomponents.com/component/blue-buttons-example for the showcase layout view! { <Title text="Leptos + Tailwindcss"/> <main> <div class="bg-gradient-to-tl from-blue-800 to-blue-500 text-white font-mono flex flex-col min-h-screen"> <div class="flex flex-row-reverse flex-wrap m-auto"> <button on:click=move |_| set_value.update(|value| *value += 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white"> "+" </button> <button class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-800 border-blue-900 text-white"> {value} </button> <button on:click=move |_| set_value.update(|value| *value -= 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white" class:invisible=move || {value.get() < 1} > "-" </button> </div> </div> </main> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_csr/src/main.rs
examples/tailwind_csr/src/main.rs
mod app; use app::*; use leptos::{logging, mount}; pub fn main() { console_error_panic_hook::set_once(); logging::log!("csr mode - mounting to body"); mount::mount_to_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/timer/src/lib.rs
examples/timer/src/lib.rs
use leptos::prelude::*; use std::time::Duration; /// Timer example, demonstrating the use of `use_interval`. #[component] pub fn TimerDemo() -> impl IntoView { // count_a updates with a fixed interval of 1000 ms, whereas count_b has a dynamic // update interval. let count_a = RwSignal::new(0_i32); let count_b = RwSignal::new(0_i32); let interval = RwSignal::new(1000); use_interval(1000, move || { count_a.update(|c| *c += 1); }); use_interval(interval, move || { count_b.update(|c| *c += 1); }); view! { <div> <div>"Count A (fixed interval of 1000 ms)"</div> <div>{count_a}</div> <div>"Count B (dynamic interval, currently " {interval} " ms)"</div> <div>{count_b}</div> <input prop:value=interval on:input:target=move |ev| { if let Ok(value) = ev.target().value().parse::<u64>() { interval.set(value); } }/> </div> } } /// Hook to wrap the underlying `setInterval` call and make it reactive w.r.t. /// possible changes of the timer interval. pub fn use_interval<T, F>(interval_millis: T, f: F) where F: Fn() + Clone + 'static, T: Into<Signal<u64>> + 'static, { let interval_millis = interval_millis.into(); Effect::new(move |prev_handle: Option<IntervalHandle>| { // effects get their previous return value as an argument // each time the effect runs, it will return the interval handle // so if we have a previous one, we cancel it if let Some(prev_handle) = prev_handle { prev_handle.clear(); }; // here, we return the handle set_interval_with_handle( f.clone(), // this is the only reactive access, so this effect will only // re-run when the interval changes Duration::from_millis(interval_millis.get()), ) .expect("could not create interval") }); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/timer/src/main.rs
examples/timer/src/main.rs
use leptos::prelude::*; use timer::TimerDemo; pub fn main() { console_error_panic_hook::set_once(); mount_to_body(TimerDemo) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/islands/src/app.rs
examples/islands/src/app.rs
use leptos::prelude::*; pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=options.clone()/> <HydrationScripts options=options islands=true/> <link rel="stylesheet" id="leptos" href="/pkg/islands.css"/> <link rel="shortcut icon" type="image/ico" href="/favicon.ico"/> </head> <body> <App/> </body> </html> } } #[component] pub fn App() -> impl IntoView { view! { <header> <h1>"My Application"</h1> </header> <main> <OuterIsland> <InnerIsland/> <InnerIsland/> <InnerIsland/> </OuterIsland> </main> } } #[island] pub fn OuterIsland(children: Children) -> impl IntoView { provide_context(42i32); view! { <div class="outer-island"> <h2>"Outer Island"</h2> <button on:click=|_| leptos::logging::log!("clicked button in island!")> "Click me" </button> {children()} </div> } } #[island] pub fn InnerIsland() -> impl IntoView { let val = use_context::<i32>(); view! { <h2>"Inner Island"</h2> <button on:click=move |_| leptos::logging::log!("value should be Some(42) -- it's {val:?}")> "Click me (inner)" </button> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/islands/src/lib.rs
examples/islands/src/lib.rs
pub mod app; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { console_error_panic_hook::set_once(); leptos::mount::hydrate_islands(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/islands/src/main.rs
examples/islands/src/main.rs
use axum::Router; use islands::app::{shell, App}; use leptos::prelude::*; use leptos_axum::{generate_route_list, LeptosRoutes}; #[tokio::main] async fn main() { // Setting this to None means we'll be using cargo-leptos and its env vars let conf = get_configuration(None).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(App); // build our application with a route let app = Router::new() .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); println!("listening on http://{}", &addr); axum::serve(listener, app.into_make_service()) .await .unwrap(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter/src/lib.rs
examples/counter/src/lib.rs
use leptos::prelude::*; /// A simple counter component. /// /// You can use doc comments like this to document your component. #[component] pub fn SimpleCounter( /// The starting value for the counter initial_value: i32, /// The change that should be applied each time the button is clicked. step: i32, ) -> impl IntoView { let (value, set_value) = signal(initial_value); view! { <div> <button on:click=move |_| set_value.set(0)>"Clear"</button> <button on:click=move |_| *set_value.write() -= step>"-1"</button> <span>"Value: " {value} "!"</span> <button on:click=move |_| set_value.update(|value| *value += step)>"+1"</button> </div> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter/src/main.rs
examples/counter/src/main.rs
use counter::SimpleCounter; use leptos::prelude::*; pub fn main() { _ = console_log::init_with_level(log::Level::Debug); console_error_panic_hook::set_once(); mount_to_body(|| { view! { <SimpleCounter initial_value=0 step=1/> } }) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter/tests/web.rs
examples/counter/tests/web.rs
#![allow(dead_code)] use counter::*; use leptos::{mount::mount_to, prelude::*, task::tick}; use wasm_bindgen::JsCast; use wasm_bindgen_test::*; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] async fn clear() { let document = document(); let test_wrapper = document.create_element("section").unwrap(); let _ = document.body().unwrap().append_child(&test_wrapper); // start by rendering our counter and mounting it to the DOM // note that we start at the initial value of 10 let _dispose = mount_to( test_wrapper.clone().unchecked_into(), || view! { <SimpleCounter initial_value=10 step=1/> }, ); // now we extract the buttons by iterating over the DOM // this would be easier if they had IDs let div = test_wrapper.query_selector("div").unwrap().unwrap(); let clear = test_wrapper .query_selector("button") .unwrap() .unwrap() .unchecked_into::<web_sys::HtmlElement>(); // now let's click the `clear` button clear.click(); // the reactive system is built on top of the async system, so changes are not reflected // synchronously in the DOM // in order to detect the changes here, we'll just yield for a brief time after each change, // allowing the effects that update the view to run tick().await; // now let's test the <div> against the expected value // we can do this by testing its `outerHTML` assert_eq!(div.outer_html(), { // it's as if we're creating it with a value of 0, right? let (value, _set_value) = signal(0); // we can remove the event listeners because they're not rendered to HTML view! { <div> <button>"Clear"</button> <button>"-1"</button> <span>"Value: " {value} "!"</span> <button>"+1"</button> </div> } // Leptos supports multiple backend renderers for HTML elements // .into_view() here is just a convenient way of specifying "use the regular DOM renderer" .into_view() // views are lazy -- they describe a DOM tree but don't create it yet // calling .build() will actually build the DOM elements .build() // .build() returned an ElementState, which is a smart pointer for // a DOM element. So we can still just call .outer_html(), which access the outerHTML on // the actual DOM element .outer_html() }); // There's actually an easier way to do this... // We can just test against a <SimpleCounter/> with the initial value 0 assert_eq!(test_wrapper.inner_html(), { let comparison_wrapper = document.create_element("section").unwrap(); let _dispose = mount_to( comparison_wrapper.clone().unchecked_into(), || view! { <SimpleCounter initial_value=0 step=1/>}, ); comparison_wrapper.inner_html() }); } #[wasm_bindgen_test] async fn inc() { let document = document(); let test_wrapper = document.create_element("section").unwrap(); let _ = document.body().unwrap().append_child(&test_wrapper); let _dispose = mount_to( test_wrapper.clone().unchecked_into(), || view! { <SimpleCounter initial_value=0 step=1/> }, ); // You can do testing with vanilla DOM operations let div = test_wrapper.query_selector("div").unwrap().unwrap(); let clear = div .first_child() .unwrap() .dyn_into::<web_sys::HtmlElement>() .unwrap(); let dec = clear .next_sibling() .unwrap() .dyn_into::<web_sys::HtmlElement>() .unwrap(); let text = dec .next_sibling() .unwrap() .dyn_into::<web_sys::HtmlElement>() .unwrap(); let inc = text .next_sibling() .unwrap() .dyn_into::<web_sys::HtmlElement>() .unwrap(); inc.click(); inc.click(); tick().await; assert_eq!(text.text_content(), Some("Value: 2!".to_string())); dec.click(); dec.click(); dec.click(); dec.click(); tick().await; assert_eq!(text.text_content(), Some("Value: -2!".to_string())); clear.click(); tick().await; assert_eq!(text.text_content(), Some("Value: 0!".to_string())); // Or you can test against a sample view! assert_eq!( div.outer_html(), { let (value, _) = signal(0); view! { <div> <button>"Clear"</button> <button>"-1"</button> <span>"Value: " {value} "!"</span> <button>"+1"</button> </div> } } .into_view() .build() .outer_html() ); inc.click(); tick().await; assert_eq!( div.outer_html(), { // because we've clicked, it's as if the signal is starting at 1 let (value, _) = signal(1); view! { <div> <button>"Clear"</button> <button>"-1"</button> <span>"Value: " {value} "!"</span> <button>"+1"</button> </div> } } .into_view() .build() .outer_html() ); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/action-form-error-handling/src/app.rs
examples/action-form-error-handling/src/app.rs
use leptos::{logging, prelude::*}; use leptos_router::{ components::{FlatRoutes, Route, Router}, StaticSegment, }; #[component] pub fn App() -> impl IntoView { view! { // content for this welcome page <Router> <main id="app"> <FlatRoutes fallback=NotFound> <Route path=StaticSegment("") view=HomePage/> </FlatRoutes> </main> </Router> } } #[server] async fn do_something( should_error: Option<String>, ) -> Result<String, ServerFnError> { if should_error.is_none() { Ok(String::from("Successful submit")) } else { Err(ServerFnError::ServerError(String::from( "You got an error!", ))) } } /// Renders the home page of your application. #[component] fn HomePage() -> impl IntoView { let do_something_action = ServerAction::<DoSomething>::new(); let value = Signal::derive(move || { do_something_action .value() .get() .unwrap_or_else(|| Ok(String::new())) }); Effect::new_isomorphic(move |_| { logging::log!("Got value = {:?}", value.get()); }); view! { <h1>"Test the action form!"</h1> <ErrorBoundary fallback=move |error| { move || format!("{:#?}", error.get()) }> <pre>{value}</pre> <ActionForm action=do_something_action attr:class="form"> <label>"Should error: "<input type="checkbox" name="should_error"/></label> <button type="submit">Submit</button> </ActionForm> </ErrorBoundary> } } /// 404 - Not Found #[component] fn NotFound() -> impl IntoView { // set an HTTP status code 404 // this is feature gated because it can only be done during // initial server-side rendering // if you navigate to the 404 page subsequently, the status // code will not be set because there is not a new HTTP request // to the server #[cfg(feature = "ssr")] { // this can be done inline because it's synchronous // if it were async, we'd use a server function let resp = expect_context::<leptos_actix::ResponseOptions>(); resp.set_status(actix_web::http::StatusCode::NOT_FOUND); } view! { <h1>"Not Found"</h1> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/action-form-error-handling/src/lib.rs
examples/action-form-error-handling/src/lib.rs
pub mod app; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use app::*; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/action-form-error-handling/src/main.rs
examples/action-form-error-handling/src/main.rs
#[cfg(feature = "ssr")] #[actix_web::main] async fn main() -> std::io::Result<()> { use action_form_error_handling::app::*; use actix_files::Files; use actix_web::*; use leptos::prelude::*; use leptos_actix::{generate_route_list, LeptosRoutes}; use leptos_meta::MetaTags; // Generate the list of routes in your Leptos App let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; println!("listening on http://{}", &addr); HttpServer::new(move || { // Generate the list of routes in your Leptos App let routes = generate_route_list(App); let leptos_options = &conf.leptos_options; let site_root = &leptos_options.site_root; App::new() .service(Files::new("/pkg", format!("{site_root}/pkg"))) .leptos_routes(routes, { let leptos_options = leptos_options.clone(); move || { use leptos::prelude::*; view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <AutoReload options=leptos_options.clone()/> <HydrationScripts options=leptos_options.clone()/> <MetaTags/> </head> <body> <App/> </body> </html> } }}) //.wrap(middleware::Compress::default()) }) .bind(&addr)? .run() .await } #[cfg(not(feature = "ssr"))] pub fn main() { // no client-side main function // unless we want this to work with e.g., Trunk for pure client-side testing // see lib.rs for hydration function instead // see optional feature `csr` instead }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/lib.rs
examples/hackernews_islands_axum/src/lib.rs
use leptos::prelude::*; mod api; mod routes; use leptos_meta::{provide_meta_context, Link, Meta, MetaTags, Stylesheet}; use leptos_router::{ components::{FlatRoutes, Route, Router}, OptionalParamSegment, ParamSegment, StaticSegment, }; use routes::{nav::*, stories::*, story::*, users::*}; #[cfg(feature = "ssr")] pub mod fallback; pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=options.clone() /> <HydrationScripts options islands=true/> <MetaTags/> </head> <body> <App/> </body> </html> } } #[component] pub fn App() -> impl IntoView { provide_meta_context(); view! { <Stylesheet id="leptos" href="/pkg/hackernews.css"/> <Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/> <Meta name="description" content="Leptos implementation of a HackerNews demo."/> <Router> <Nav /> <main> <FlatRoutes fallback=|| "Not found."> <Route path=(StaticSegment("users"), ParamSegment("id")) view=User/> <Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/> <Route path=OptionalParamSegment("stories") view=Stories/> </FlatRoutes> </main> </Router> } } #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { console_error_panic_hook::set_once(); leptos::mount::hydrate_islands(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/api.rs
examples/hackernews_islands_axum/src/api.rs
#[cfg(feature = "ssr")] use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; #[cfg(feature = "ssr")] pub fn story(path: &str) -> String { format!("https://node-hnapi.herokuapp.com/{path}") } #[cfg(feature = "ssr")] pub fn user(path: &str) -> String { format!("https://hacker-news.firebaseio.com/v0/user/{path}.json") } #[cfg(feature = "ssr")] pub async fn fetch_api<T>(path: &str) -> Option<T> where T: Serialize + DeserializeOwned, { use leptos::logging; reqwest::get(path) .await .map_err(|e| logging::error!("{e}")) .ok()? .json() .await .ok() } #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] pub struct Story { pub id: usize, pub title: String, pub points: Option<i32>, pub user: Option<String>, pub time: usize, pub time_ago: String, #[serde(alias = "type")] pub story_type: String, pub url: String, #[serde(default)] pub domain: String, #[serde(default)] pub comments: Option<Vec<Comment>>, pub comments_count: Option<usize>, } #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] pub struct Comment { pub id: usize, pub level: usize, pub user: Option<String>, pub time: usize, pub time_ago: String, pub content: Option<String>, pub comments: Vec<Comment>, } #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] pub struct User { pub created: usize, pub id: String, pub karma: i32, pub about: Option<String>, }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/main.rs
examples/hackernews_islands_axum/src/main.rs
#[cfg(feature = "ssr")] #[tokio::main] async fn main() { use axum::routing::get; pub use axum::Router; use hackernews_islands::*; pub use leptos::config::get_configuration; pub use leptos_axum::{generate_route_list, LeptosRoutes}; use tower_http::compression::{ predicate::{NotForContentType, SizeAbove}, CompressionLayer, CompressionLevel, Predicate, }; let conf = get_configuration(Some("Cargo.toml")).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(App); let predicate = SizeAbove::new(1500) // files smaller than 1501 bytes are not compressed, since the MTU (Maximum Transmission Unit) of a TCP packet is 1500 bytes .and(NotForContentType::GRPC) .and(NotForContentType::IMAGES) // prevent compressing assets that are already statically compressed .and(NotForContentType::const_new("application/javascript")) .and(NotForContentType::const_new("application/wasm")) .and(NotForContentType::const_new("text/css")); // build our application with a route let app = Router::new() .route("/favicon.ico", get(fallback::file_and_error_handler)) .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .layer( CompressionLayer::new() .quality(CompressionLevel::Fastest) .compress_when(predicate), ) .fallback(fallback::file_and_error_handler) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` println!("listening on {}", addr); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve(listener, app.into_make_service()) .await .unwrap(); } // client-only stuff for Trunk #[cfg(not(feature = "ssr"))] pub fn main() { use hackernews_islands::*; use leptos::prelude::*; console_error_panic_hook::set_once(); leptos::mount::mount_to_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/fallback.rs
examples/hackernews_islands_axum/src/fallback.rs
use axum::{ body::Body, http::{header, Request, Response, StatusCode, Uri}, response::{IntoResponse, Response as AxumResponse}, }; use rust_embed::Embed; use std::borrow::Cow; #[cfg(not(debug_assertions))] const DEV_MODE: bool = false; #[cfg(debug_assertions)] const DEV_MODE: bool = true; #[derive(Embed)] #[folder = "target/site/"] struct Assets; pub async fn file_and_error_handler( uri: Uri, req: Request<Body>, ) -> AxumResponse { let accept_encoding = req .headers() .get("accept-encoding") .map(|h| h.to_str().unwrap_or("none")) .unwrap_or("none") .to_string(); let static_result = get_static_file(uri.clone(), accept_encoding).await; match static_result { Ok(res) => { if res.status() == StatusCode::OK { res.into_response() } else { (StatusCode::NOT_FOUND, "Not found.").into_response() } } Err(e) => e.into_response(), } } async fn get_static_file( uri: Uri, accept_encoding: String, ) -> Result<Response<Body>, (StatusCode, String)> { let (_, path) = uri.path().split_at(1); // split off the first `/` let mime = mime_guess::from_path(path); let (path, encoding) = if DEV_MODE { // during DEV, don't care about the precompression -> faster workflow (Cow::from(path), "none") } else if accept_encoding.contains("br") { (Cow::from(format!("{}.br", path)), "br") } else if accept_encoding.contains("gzip") { (Cow::from(format!("{}.gz", path)), "gzip") } else { (Cow::from(path), "none") }; match Assets::get(path.as_ref()) { Some(content) => { let body = Body::from(content.data); let res = match DEV_MODE { true => Response::builder() .header( header::CONTENT_TYPE, mime.first_or_octet_stream().as_ref(), ) .header(header::CONTENT_ENCODING, encoding) .body(body) .unwrap(), false => Response::builder() .header(header::CACHE_CONTROL, "max-age=86400") .header( header::CONTENT_TYPE, mime.first_or_octet_stream().as_ref(), ) .header(header::CONTENT_ENCODING, encoding) .body(body) .unwrap(), }; Ok(res.into_response()) } None => { eprintln!(">> Asset {} not found", path); for a in Assets::iter() { eprintln!("Available asset: {}", a); } Err((StatusCode::NOT_FOUND, "Not found".to_string())) } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/routes.rs
examples/hackernews_islands_axum/src/routes.rs
pub mod nav; pub mod stories; pub mod story; pub mod users;
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/routes/users.rs
examples/hackernews_islands_axum/src/routes/users.rs
use crate::api; use leptos::{either::Either, prelude::*, server::Resource}; use leptos_router::hooks::use_params_map; #[server] pub async fn fetch_user( id: String, ) -> Result<Option<api::User>, ServerFnError> { Ok(api::fetch_api::<api::User>(&api::user(&id)).await) } #[component] pub fn User() -> impl IntoView { let params = use_params_map(); let user = Resource::new( move || params.read().get("id").unwrap_or_default(), move |id| async move { if id.is_empty() { Ok(None) } else { fetch_user(id).await } }, ); view! { <div class="user-view"> <Suspense fallback=|| view! { "Loading..." }> {move || Suspend::new(async move { match user.await.ok().flatten() { None => Either::Left(view! { <h1>"User not found."</h1> }), Some(user) => Either::Right(view! { <div> <h1>"User: " {user.id.clone()}</h1> <ul class="meta"> <li> <span class="label">"Created: "</span> {user.created} </li> <li> <span class="label">"Karma: "</span> {user.karma} </li> <li inner_html={user.about} class="about"></li> </ul> <p class="links"> <a href=format!("https://news.ycombinator.com/submitted?id={}", user.id)>"submissions"</a> " | " <a href=format!("https://news.ycombinator.com/threads?id={}", user.id)>"comments"</a> </p> </div> }) }})} </Suspense> </div> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/routes/story.rs
examples/hackernews_islands_axum/src/routes/story.rs
use crate::api; use leptos::{either::Either, prelude::*}; use leptos_meta::Meta; use leptos_router::{components::A, hooks::use_params_map}; #[server] pub async fn fetch_story( id: String, ) -> Result<Option<api::Story>, ServerFnError> { Ok(api::fetch_api::<api::Story>(&api::story(&format!("item/{id}"))).await) } #[component] pub fn Story() -> impl IntoView { let params = use_params_map(); let story = Resource::new_blocking( move || params.read().get("id").unwrap_or_default(), move |id| async move { if id.is_empty() { Ok(None) } else { fetch_story(id).await } }, ); Suspense(SuspenseProps::builder().fallback(|| "Loading...").children(ToChildren::to_children(move || Suspend::new(async move { match story.await.ok().flatten() { None => Either::Left("Story not found."), Some(story) => { Either::Right(view! { <Meta name="description" content=story.title.clone()/> <div class="item-view"> <div class="item-view-header"> <a href=story.url target="_blank"> <h1>{story.title}</h1> </a> <span class="host"> "("{story.domain}")" </span> <ShowLet some=story.user let:user> <p class="meta"> {story.points} " points | by " <A href=format!("/users/{user}")>{user.clone()}</A> {format!(" {}", story.time_ago)} </p> </ShowLet> </div> <div class="item-view-comments"> <p class="item-view-comments-header"> {if story.comments_count.unwrap_or_default() > 0 { format!("{} comments", story.comments_count.unwrap_or_default()) } else { "No comments yet.".into() }} </p> <ul class="comment-children"> <For each=move || story.comments.clone().unwrap_or_default() key=|comment| comment.id let:comment > <Comment comment /> </For> </ul> </div> </div> }) } } }))).build()) } #[component] pub fn Comment(comment: api::Comment) -> impl IntoView { view! { <li class="comment"> <div class="by"> <A href=format!("/users/{}", comment.user.clone().unwrap_or_default())>{comment.user.clone()}</A> {format!(" {}", comment.time_ago)} </div> <div class="text" inner_html=comment.content></div> {(!comment.comments.is_empty()).then(|| { view! { <Toggle> {comment.comments.into_iter() .map(|comment: api::Comment| view! { <Comment comment /> }) .collect_view()} </Toggle> } })} </li> } } #[island] pub fn Toggle(children: Children) -> impl IntoView { let (open, set_open) = signal(true); view! { <div class="toggle" class:open=open> <a on:click=move |_| set_open.update(|n| *n = !*n)> {move || if open.get() { "[-]" } else { "[+] comments collapsed" }} </a> </div> <ul class="comment-children" style:display=move || if open.get() { "block" } else { "none" } > {children()} </ul> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/routes/nav.rs
examples/hackernews_islands_axum/src/routes/nav.rs
use leptos::prelude::*; use leptos_router::components::A; #[component] pub fn Nav() -> impl IntoView { view! { <header class="header"> <nav class="inner"> <A href="/home"> <strong>"HN"</strong> </A> <A href="/new"> <strong>"New"</strong> </A> <A href="/show"> <strong>"Show"</strong> </A> <A href="/ask"> <strong>"Ask"</strong> </A> <A href="/job"> <strong>"Jobs"</strong> </A> <a class="github" href="http://github.com/leptos-rs/leptos" target="_blank" rel="noreferrer"> "Built with Leptos" </a> </nav> </header> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_islands_axum/src/routes/stories.rs
examples/hackernews_islands_axum/src/routes/stories.rs
use crate::api; use leptos::{either::Either, prelude::*}; use leptos_router::{ components::A, hooks::{use_params_map, use_query_map}, }; fn category(from: &str) -> String { match from { "new" => "newest", "show" => "show", "ask" => "ask", "job" => "jobs", _ => "news", } .to_string() } #[server] pub async fn fetch_stories( story_type: String, page: usize, ) -> Result<Vec<api::Story>, ServerFnError> { let path = format!("{}?page={}", category(&story_type), page); Ok(api::fetch_api::<Vec<api::Story>>(&api::story(&path)) .await .unwrap_or_default()) } #[component] pub fn Stories() -> impl IntoView { let query = use_query_map(); let params = use_params_map(); let page = move || { query .read() .get("page") .and_then(|page| page.parse::<usize>().ok()) .unwrap_or(1) }; let story_type = move || { params .read() .get("stories") .unwrap_or_else(|| "top".to_string()) }; let stories = Resource::new( move || (page(), story_type()), move |(page, story_type)| async move { fetch_stories(story_type, page).await.ok() }, ); let (pending, set_pending) = signal(false); let hide_more_link = move || match &*stories.read() { Some(Some(stories)) => stories.len() < 28, _ => true } || pending.get(); view! { <div class="news-view"> <div class="news-list-nav"> <span> {move || if page() > 1 { Either::Left(view! { <a class="page-link" href=move || format!("/{}?page={}", story_type(), page() - 1) aria-label="Previous Page" > "< prev" </a> }) } else { Either::Right(view! { <span class="page-link disabled" aria-hidden="true"> "< prev" </span> }) }} </span> <span>"page " {page}</span> <Suspense> <span class="page-link" class:disabled=hide_more_link aria-hidden=hide_more_link > <a href=move || format!("/{}?page={}", story_type(), page() + 1) aria-label="Next Page" > "more >" </a> </span> </Suspense> </div> <main class="news-list"> <div> <Transition fallback=move || view! { <p>"Loading..."</p> } set_pending > <Show when=move || stories.read().as_ref().map(Option::is_none).unwrap_or(false)> > <p>"Error loading stories."</p> </Show> <ul> <For each=move || stories.get().unwrap_or_default().unwrap_or_default() key=|story| story.id let:story > <Story story/> </For> </ul> </Transition> </div> </main> </div> } } #[component] fn Story(story: api::Story) -> impl IntoView { view! { <li class="news-item"> <span class="score">{story.points}</span> <span class="title"> {if !story.url.starts_with("item?id=") { Either::Left(view! { <span> <a href=story.url target="_blank" rel="noreferrer"> {story.title.clone()} </a> <span class="host">"("{story.domain}")"</span> </span> }) } else { let title = story.title.clone(); Either::Right(view! { <A href=format!("/stories/{}", story.id)>{title}</A> }) }} </span> <br /> <span class="meta"> {if story.story_type != "job" { Either::Left(view! { <span> "by " <ShowLet some=story.user let:user> <A href=format!("/users/{user}")>{user.clone()}</A> </ShowLet> {format!(" {} | ", story.time_ago)} <A href=format!("/stories/{}", story.id)> {if story.comments_count.unwrap_or_default() > 0 { format!("{} comments", story.comments_count.unwrap_or_default()) } else { "discuss".into() }} </A> </span> }) } else { let title = story.title.clone(); Either::Right(view! { <A href=format!("/item/{}", story.id)>{title}</A> }) }} </span> {(story.story_type != "link").then(|| view! { " " <span class="label">{story.story_type}</span> })} </li> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_without_macros/src/lib.rs
examples/counter_without_macros/src/lib.rs
use leptos::{ ev, html::{button, div, span}, prelude::*, }; /// A simple counter view. // A component is really just a function call: it runs once to create the DOM and reactive system pub fn counter(initial_value: i32, step: u32) -> impl IntoView { let count = RwSignal::new(Count::new(initial_value, step)); Effect::new(move |_| { leptos::logging::log!("count = {:?}", count.get()); }); // the function name is the same as the HTML tag name div() // children can be added with .child() // this takes any type that implements IntoView as its argument // for example, a string or an HtmlElement<_> // it can also take an array of types that impl IntoView // or a tuple of up to 26 objects that impl IntoView .child(( button() // typed events found in leptos::ev // 1) prevent typos in event names // 2) allow for correct type inference in callbacks .on(ev::click, move |_| count.update(Count::clear)) .child("Clear"), button() .on(ev::click, move |_| count.update(Count::decrease)) .child("-1"), span().child(("Value: ", move || count.get().value(), "!")), button() .on(ev::click, move |_| count.update(Count::increase)) .child("+1"), )) } #[derive(Debug, Clone)] pub struct Count { value: i32, step: i32, } impl Count { pub fn new(value: i32, step: u32) -> Self { Count { value, step: step as i32, } } pub fn value(&self) -> i32 { leptos::logging::log!("value = {}", self.value); self.value } pub fn increase(&mut self) { self.value += self.step; } pub fn decrease(&mut self) { self.value += -self.step; } pub fn clear(&mut self) { self.value = 0; } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_without_macros/src/main.rs
examples/counter_without_macros/src/main.rs
use counter_without_macros::counter; /// Show the counter pub fn main() { console_error_panic_hook::set_once(); leptos::mount::mount_to_body(|| counter(0, 1)) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_without_macros/tests/business.rs
examples/counter_without_macros/tests/business.rs
mod count { use counter_without_macros::Count; use pretty_assertions::assert_eq; use rstest::rstest; #[rstest] #[case(-2, 1)] #[case(-1, 1)] #[case(0, 1)] #[case(1, 1)] #[case(2, 1)] #[case(3, 2)] #[case(4, 3)] fn should_increase_count(#[case] initial_value: i32, #[case] step: u32) { let mut count = Count::new(initial_value, step); count.increase(); assert_eq!(count.value(), initial_value + step as i32); } #[rstest] #[case(-2, 1)] #[case(-1, 1)] #[case(0, 1)] #[case(1, 1)] #[case(2, 1)] #[case(3, 2)] #[case(4, 3)] #[trace] fn should_decrease_count(#[case] initial_value: i32, #[case] step: u32) { let mut count = Count::new(initial_value, step); count.decrease(); assert_eq!(count.value(), initial_value - step as i32); } #[rstest] #[case(-2, 1)] #[case(-1, 1)] #[case(0, 1)] #[case(1, 1)] #[case(2, 1)] #[case(3, 2)] #[case(4, 3)] #[trace] fn should_clear_count(#[case] initial_value: i32, #[case] step: u32) { let mut count = Count::new(initial_value, step); count.clear(); assert_eq!(count.value(), 0); } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_without_macros/tests/web.rs
examples/counter_without_macros/tests/web.rs
#![allow(dead_code)] use counter_without_macros::counter; use leptos::{prelude::*, task::tick}; use pretty_assertions::assert_eq; use wasm_bindgen::JsCast; use wasm_bindgen_test::*; use web_sys::HtmlElement; wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] async fn should_increment_counter() { open_counter(); click_increment(); click_increment(); // reactive changes run asynchronously, so yield briefly before observing the DOM tick().await; assert_eq!(see_text(), Some("Value: 2!".to_string())); } #[wasm_bindgen_test] async fn should_decrement_counter() { open_counter(); click_decrement(); click_decrement(); tick().await; assert_eq!(see_text(), Some("Value: -2!".to_string())); } #[wasm_bindgen_test] async fn should_clear_counter() { open_counter(); click_increment(); click_increment(); click_clear(); tick().await; assert_eq!(see_text(), Some("Value: 0!".to_string())); } fn open_counter() { remove_existing_counter(); leptos::mount::mount_to_body(move || counter(0, 1)); } fn remove_existing_counter() { if let Some(counter) = document().query_selector("body div").unwrap() { counter.remove(); } } fn click_clear() { click_text("Clear"); } fn click_decrement() { click_text("-1"); } fn click_increment() { click_text("+1"); } fn click_text(text: &str) { find_by_text(text).click(); } fn see_text() -> Option<String> { find_by_text("Value: ").text_content() } fn find_by_text(text: &str) -> HtmlElement { let xpath = format!("//*[text()='{}']", text); let document = document(); document .evaluate(&xpath, &document) .unwrap() .iterate_next() .unwrap() .unwrap() .dyn_into::<HtmlElement>() .unwrap() }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_actix/src/app.rs
examples/tailwind_actix/src/app.rs
use leptos::prelude::*; use leptos_meta::*; use leptos_router::{ components::{FlatRoutes, Route, Router}, StaticSegment, }; #[component] pub fn App() -> impl IntoView { provide_meta_context(); view! { <Stylesheet id="leptos" href="/pkg/tailwind_actix.css"/> <Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/> <Router> <FlatRoutes fallback=|| "Page not found."> <Route path=StaticSegment("") view=Home/> </FlatRoutes> </Router> } } #[component] fn Home() -> impl IntoView { let (value, set_value) = signal(0); // thanks to https://tailwindcomponents.com/component/blue-buttons-example for the showcase layout view! { <Title text="Leptos + Tailwindcss"/> <main> <div class="bg-gradient-to-tl from-blue-800 to-blue-500 text-white font-mono flex flex-col min-h-screen"> <div class="flex flex-row-reverse flex-wrap m-auto"> <button on:click=move |_| set_value.update(|value| *value += 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white"> "+" </button> <button class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-800 border-blue-900 text-white"> {value} </button> <button on:click=move |_| set_value.update(|value| *value -= 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white" class:invisible=move || {value.get() < 1} > "-" </button> </div> </div> </main> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_actix/src/lib.rs
examples/tailwind_actix/src/lib.rs
mod app; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use crate::app::App; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_actix/src/main.rs
examples/tailwind_actix/src/main.rs
mod app; use crate::app::*; use actix_files::Files; use actix_web::*; use leptos::prelude::*; use leptos_actix::{generate_route_list, LeptosRoutes}; use leptos_meta::MetaTags; #[actix_web::main] async fn main() -> std::io::Result<()> { let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; HttpServer::new(move || { // Generate the list of routes in your Leptos App let routes = generate_route_list(App); let leptos_options = &conf.leptos_options; let site_root = &leptos_options.site_root; App::new() .leptos_routes(routes, { let leptos_options = leptos_options.clone(); move || { use leptos::prelude::*; view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=leptos_options.clone() /> <HydrationScripts options=leptos_options.clone()/> <MetaTags/> </head> <body> <App/> </body> </html> } }}) .service(Files::new("/", site_root.as_ref())) .wrap(middleware::Compress::default()) }) .bind(&addr)? .run() .await }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/src/app.rs
examples/suspense_tests/src/app.rs
use crate::instrumented::InstrumentedRoutes; use leptos::prelude::*; use leptos_router::{ components::{Outlet, ParentRoute, Redirect, Route, Router, Routes, A}, SsrMode, StaticSegment, }; const WAIT_ONE_SECOND: u64 = 1; const WAIT_TWO_SECONDS: u64 = 2; #[server] async fn first_wait_fn(seconds: u64) -> Result<(), ServerFnError> { tokio::time::sleep(tokio::time::Duration::from_secs(seconds)).await; Ok(()) } #[server] async fn second_wait_fn(seconds: u64) -> Result<(), ServerFnError> { tokio::time::sleep(tokio::time::Duration::from_secs(seconds)).await; Ok(()) } #[component] pub fn App() -> impl IntoView { let style = r" nav { display: flex; width: 100%; justify-content: space-around; } [aria-current] { font-weight: bold; } "; view! { <style>{style}</style> <Router> <nav> <A href="/out-of-order">"Out-of-Order"</A> <A href="/in-order">"In-Order"</A> <A href="/async">"Async"</A> <A href="/instrumented/">"Instrumented"</A> </nav> <main> <Routes fallback=|| "Page not found."> <Route path=StaticSegment("") view=|| view! { <Redirect path="/out-of-order"/> } /> // out-of-order <ParentRoute path=StaticSegment("out-of-order") view=|| { view! { <SecondaryNav/> <h1>"Out-of-Order"</h1> <Outlet/> } } > <Route path=StaticSegment("") view=Nested/> <Route path=StaticSegment("inside") view=NestedResourceInside/> <Route path=StaticSegment("single") view=Single/> <Route path=StaticSegment("parallel") view=Parallel/> <Route path=StaticSegment("inside-component") view=InsideComponent/> <Route path=StaticSegment("local") view=LocalResource/> <Route path=StaticSegment("none") view=None/> </ParentRoute> // in-order <ParentRoute path=StaticSegment("in-order") ssr=SsrMode::InOrder view=|| { view! { <SecondaryNav/> <h1>"In-Order"</h1> <Outlet/> } } > <Route path=StaticSegment("") view=Nested/> <Route path=StaticSegment("inside") view=NestedResourceInside/> <Route path=StaticSegment("single") view=Single/> <Route path=StaticSegment("parallel") view=Parallel/> <Route path=StaticSegment("inside-component") view=InsideComponent/> <Route path=StaticSegment("local") view=LocalResource/> <Route path=StaticSegment("none") view=None/> </ParentRoute> // async <ParentRoute path=StaticSegment("async") ssr=SsrMode::Async view=|| { view! { <SecondaryNav/> <h1>"Async"</h1> <Outlet/> } } > <Route path=StaticSegment("") view=Nested/> <Route path=StaticSegment("inside") view=NestedResourceInside/> <Route path=StaticSegment("single") view=Single/> <Route path=StaticSegment("parallel") view=Parallel/> <Route path=StaticSegment("inside-component") view=InsideComponent/> <Route path=StaticSegment("local") view=LocalResource/> <Route path=StaticSegment("none") view=None/> </ParentRoute> <InstrumentedRoutes/> </Routes> </main> </Router> } } #[component] fn SecondaryNav() -> impl IntoView { view! { <nav> <A href="" exact=true> "Nested" </A> <A href="inside" exact=true> "Nested (resource created inside)" </A> <A href="single">"Single"</A> <A href="parallel">"Parallel"</A> <A href="inside-component">"Inside Component"</A> <A href="local">"Local Resource"</A> <A href="none">"No Resources"</A> </nav> } } #[component] fn Nested() -> impl IntoView { let one_second = Resource::new(|| WAIT_ONE_SECOND, first_wait_fn); let two_second = Resource::new(|| WAIT_TWO_SECONDS, second_wait_fn); let (count, set_count) = signal(0); view! { <div> <Suspense fallback=|| { "Loading 1..." }> {move || { one_second.map(|_| view! { <p id="loaded-1">"One Second: Loaded 1!"</p> }) }} <Suspense fallback=|| { "Loading 2..." }> {move || { two_second .map(|_| { view! { <p id="loaded-2">"Two Second: Loaded 2!"</p> <button on:click=move |_| { set_count.update(|n| *n += 1) }>{count}</button> } }) }} </Suspense> </Suspense> </div> } } #[component] fn NestedResourceInside() -> impl IntoView { let one_second = Resource::new(|| WAIT_ONE_SECOND, first_wait_fn); let (count, set_count) = signal(0); view! { <div> <Suspense fallback=|| { "Loading 1..." }> {Suspend::new(async move { _ = one_second.await; let two_second = Resource::new( || (), move |_| async move { second_wait_fn(WAIT_TWO_SECONDS).await }, ); view! { <p id="loaded-1">"One Second: Loaded 1!"</p> <Suspense fallback=|| "Loading 2..."> <span id="loaded-2"> "Loaded 2 (created inside first suspense)!: " {Suspend::new(async move { format!("{:?}", two_second.await) })} </span> <button on:click=move |_| set_count.update(|n| *n += 1)>{count}</button> </Suspense> } })} </Suspense> </div> } } #[component] fn Parallel() -> impl IntoView { let one_second = Resource::new(|| WAIT_ONE_SECOND, first_wait_fn); let two_second = Resource::new(|| WAIT_TWO_SECONDS, second_wait_fn); let (count, set_count) = signal(0); view! { <div> <Suspense fallback=|| { "Loading 1..." }> {move || { one_second .map(move |_| { view! { <p id="loaded-1">"One Second: Loaded 1!"</p> <button on:click=move |_| { set_count.update(|n| *n += 1) }>{count}</button> } }) }} </Suspense> <Suspense fallback=|| { "Loading 2..." }> {move || { two_second .map(move |_| { view! { <p id="loaded-2">"Two Second: Loaded 2!"</p> <button id="second-count" on:click=move |_| set_count.update(|n| *n += 1) > {count} </button> } }) }} </Suspense> </div> } } #[component] fn Single() -> impl IntoView { let one_second = Resource::new(|| WAIT_ONE_SECOND, first_wait_fn); let (count, set_count) = signal(0); view! { <div> <Suspense fallback=|| { "Loading 1..." }> {move || { one_second.map(|_| view! { <p id="loaded-1">"One Second: Loaded 1!"</p> }) }} </Suspense> <p id="following-message">"Children following Suspense should hydrate properly."</p> <div> <button on:click=move |_| set_count.update(|n| *n += 1)>{count}</button> </div> </div> } } #[component] fn InsideComponent() -> impl IntoView { let (count, set_count) = signal(0); view! { <div> <p id="inside-message">"Suspense inside another component should work."</p> <InsideComponentChild/> <p id="following-message">"Children following Suspense should hydrate properly."</p> <div> <button on:click=move |_| set_count.update(|n| *n += 1)>{count}</button> </div> </div> } } #[component] fn InsideComponentChild() -> impl IntoView { let one_second = Resource::new(|| WAIT_ONE_SECOND, first_wait_fn); view! { <Suspense fallback=|| { "Loading 1..." }> {move || { one_second.map(|_| view! { <p id="loaded-1">"One Second: Loaded 1!"</p> }) }} </Suspense> } } #[component] fn LocalResource() -> impl IntoView { let one_second = Resource::new(|| WAIT_ONE_SECOND, first_wait_fn); let local = LocalResource::new(|| first_wait_fn(WAIT_ONE_SECOND)); let (count, set_count) = signal(0); view! { <div> <Suspense fallback=|| { "Loading 1..." }> {move || { one_second.map(|_| view! { <p id="loaded-1">"One Second: Loaded 1!"</p> }) }} {move || { Suspend::new(async move { let value = local.await; view! { <p id="loaded-2">"One Second: Local Loaded " {value} "!"</p> } }) }} </Suspense> <p id="following-message">"Children following Suspense should hydrate properly."</p> <div> <button on:click=move |_| set_count.update(|n| *n += 1)>{count}</button> </div> </div> } } #[component] fn None() -> impl IntoView { let (count, set_count) = signal(0); view! { <div> <Suspense fallback=|| "Loading 1..."> <p id="inside-message">"Children inside Suspense should hydrate properly."</p> <button on:click=move |_| set_count.update(|n| *n += 1)>{count}</button> </Suspense> <p id="following-message">"Children following Suspense should hydrate properly."</p> <div> <button id="second-count" on:click=move |_| set_count.update(|n| *n += 1)> {count} </button> </div> </div> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/src/lib.rs
examples/suspense_tests/src/lib.rs
pub mod app; mod instrumented; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use app::*; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/src/main.rs
examples/suspense_tests/src/main.rs
#[cfg(feature = "ssr")] #[actix_web::main] async fn main() -> std::io::Result<()> { use actix_files::Files; use actix_web::*; use leptos::prelude::*; use leptos_actix::{generate_route_list, LeptosRoutes}; use suspense_tests::app::*; let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; println!("listening on http://{}", &addr); HttpServer::new(move || { // Generate the list of routes in your Leptos App let routes = generate_route_list(App); let leptos_options = &conf.leptos_options; let site_root = &leptos_options.site_root; App::new() .leptos_routes(routes, { let leptos_options = leptos_options.clone(); move || { use leptos::prelude::*; view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <AutoReload options=leptos_options.clone()/> <HydrationScripts options=leptos_options.clone()/> </head> <body> <App/> </body> </html> } }}) .service(Files::new("/", site_root.as_ref())) }) .bind(addr)? .workers(1) .run() .await } #[cfg(not(feature = "ssr"))] pub fn main() { // no client-side main function // unless we want this to work with e.g., Trunk for pure client-side testing // see lib.rs for hydration function instead }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/src/instrumented.rs
examples/suspense_tests/src/instrumented.rs
use leptos::prelude::*; use leptos_router::{ components::{ParentRoute, Route, A}, hooks::use_params, nested_router::Outlet, params::Params, ParamSegment, SsrMode, StaticSegment, WildcardSegment, }; #[cfg(feature = "ssr")] pub(super) mod counter { use std::{ collections::HashMap, sync::{ atomic::{AtomicU32, Ordering}, LazyLock, Mutex, }, }; #[derive(Default)] pub struct Counter(AtomicU32); impl Counter { #[allow(dead_code)] pub const fn new() -> Self { Self(AtomicU32::new(0)) } pub fn get(&self) -> u32 { self.0.load(Ordering::SeqCst) } pub fn inc(&self) -> u32 { self.0.fetch_add(1, Ordering::SeqCst) } pub fn reset(&self) { self.0.store(0, Ordering::SeqCst); } } #[derive(Default)] pub struct Counters { pub list_items: Counter, pub get_item: Counter, pub inspect_item_root: Counter, pub inspect_item_field: Counter, } impl From<&mut Counters> for super::Counters { fn from(counter: &mut Counters) -> Self { Self { get_item: counter.get_item.get(), inspect_item_root: counter.inspect_item_root.get(), inspect_item_field: counter.inspect_item_field.get(), list_items: counter.list_items.get(), } } } impl Counters { pub fn reset(&self) { self.get_item.reset(); self.inspect_item_root.reset(); self.inspect_item_field.reset(); self.list_items.reset(); } } pub static COUNTERS: LazyLock<Mutex<HashMap<u64, Counters>>> = LazyLock::new(|| Mutex::new(HashMap::new())); } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct Item { id: i64, name: Option<String>, field: Option<String>, } #[server] async fn list_items(ticket: u64) -> Result<Vec<i64>, ServerFnError> { // emulate database query overhead tokio::time::sleep(std::time::Duration::from_millis(25)).await; (*counter::COUNTERS) .lock() .expect("somehow panicked elsewhere") .entry(ticket) .or_default() .list_items .inc(); Ok(vec![1, 2, 3, 4]) } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct GetItemResult(pub Item, pub Vec<String>); #[server] async fn get_item( ticket: u64, id: i64, ) -> Result<GetItemResult, ServerFnError> { // emulate database query overhead tokio::time::sleep(std::time::Duration::from_millis(25)).await; (*counter::COUNTERS) .lock() .expect("somehow panicked elsewhere") .entry(ticket) .or_default() .get_item .inc(); let name = None::<String>; let field = None::<String>; Ok(GetItemResult( Item { id, name, field }, ["path1", "path2", "path3"] .into_iter() .map(str::to_string) .collect::<Vec<_>>(), )) } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct InspectItemResult(pub Item, pub String, pub Vec<String>); #[server] async fn inspect_item( ticket: u64, id: i64, path: String, ) -> Result<InspectItemResult, ServerFnError> { // emulate database query overhead tokio::time::sleep(std::time::Duration::from_millis(25)).await; let mut split = path.split('/'); let name = split.next().map(str::to_string); let path = name .clone() .expect("name should have been defined at this point"); let field = split .next() .and_then(|s| (!s.is_empty()).then(|| s.to_string())); if field.is_none() { (*counter::COUNTERS) .lock() .expect("somehow panicked elsewhere") .entry(ticket) .or_default() .inspect_item_root .inc(); } else { (*counter::COUNTERS) .lock() .expect("somehow panicked elsewhere") .entry(ticket) .or_default() .inspect_item_field .inc(); } Ok(InspectItemResult( Item { id, name, field }, path, ["field1", "field2", "field3"] .into_iter() .map(str::to_string) .collect::<Vec<_>>(), )) } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct Counters { pub get_item: u32, pub inspect_item_root: u32, pub inspect_item_field: u32, pub list_items: u32, } #[server] async fn get_counters(ticket: u64) -> Result<Counters, ServerFnError> { Ok((*counter::COUNTERS) .lock() .expect("somehow panicked elsewhere") .entry(ticket) .or_default() .into()) } #[server(ResetCounters)] async fn reset_counters(ticket: u64) -> Result<(), ServerFnError> { (*counter::COUNTERS) .lock() .expect("somehow panicked elsewhere") .entry(ticket) .or_default() .reset(); // leptos::logging::log!("counters for ticket {ticket} have been reset"); Ok(()) } #[derive(Clone, Default)] pub struct SuspenseCounters { item_overview: u32, item_inspect: u32, item_listing: u32, } #[component] pub fn InstrumentedRoutes() -> impl leptos_router::MatchNestedRoutes + Clone { // TODO should make this mode configurable via feature flag? let ssr = SsrMode::Async; view! { <ParentRoute path=StaticSegment("instrumented") view=InstrumentedRoot ssr> <Route path=StaticSegment("/") view=InstrumentedTop /> <ParentRoute path=StaticSegment("item") view=ItemRoot> <Route path=StaticSegment("/") view=ItemListing /> <ParentRoute path=ParamSegment("id") view=ItemTop> <Route path=StaticSegment("/") view=ItemOverview /> <Route path=WildcardSegment("path") view=ItemInspect /> </ParentRoute> </ParentRoute> <Route path=StaticSegment("counters") view=ShowCounters /> </ParentRoute> } .into_inner() } #[derive(Copy, Clone)] pub struct Ticket(pub u64); #[derive(Copy, Clone)] pub struct CSRTicket(pub u64); #[cfg(feature = "ssr")] fn inst_ticket() -> u64 { // SSR will always use 0 for the ticket 0 } #[cfg(not(feature = "ssr"))] fn inst_ticket() -> u64 { // CSR will use a random number for the ticket (js_sys::Math::random() * ((u64::MAX - 1) as f64) + 1f64) as u64 } #[component] fn InstrumentedRoot() -> impl IntoView { let counters = RwSignal::new(SuspenseCounters::default()); provide_context(counters); provide_field_nav_portlet_context(); // Generate a ID directly on this component. Rather than relying on // additional server functions, doing it this way emulates more // standard workflows better and to avoid having to add another // thing to instrument/interfere with the typical use case. // Downside is that randomness has a chance to conflict. // // Furthermore, this approach **will** result in unintuitive // behavior when it isn't accounted for - specifically, the reason // for this design is that when SSR it will guarantee usage of `0` // as the ticket, while CSR it will be of some other value as the // version it uses will be random. However, when trying to get back // the counters associated with the ticket, rendering using SSR will // always produce the SSR version and this quirk will need to be // accounted for. let ticket = inst_ticket(); // leptos::logging::log!( // "Ticket for this InstrumentedRoot instance: {ticket}" // ); provide_context(Ticket(ticket)); let csr_ticket = RwSignal::<Option<CSRTicket>>::new(None); let reset_counters = ServerAction::<ResetCounters>::new(); Effect::new(move |_| { let ticket = expect_context::<Ticket>().0; csr_ticket.set(Some(CSRTicket(ticket))); }); view! { <section id="instrumented"> <nav> <a href="/">"Site Root"</a> <A href="./" exact=true> "Instrumented Root" </A> <A href="item/" strict_trailing_slash=true> "Item Listing" </A> <A href="counters" strict_trailing_slash=true> "Counters" </A> </nav> <FieldNavPortlet /> <Outlet /> <Suspense> {move || Suspend::new(async move { let clear_suspense_counters = move |_| { counters.update(|c| *c = SuspenseCounters::default()); }; csr_ticket .get() .map(|ticket| { let ticket = ticket.0; view! { <ActionForm action=reset_counters> <input type="hidden" name="ticket" value=format!("{ticket}") /> <input id="reset-csr-counters" type="submit" value="Reset CSR Counters" on:click=clear_suspense_counters /> </ActionForm> } }) })} </Suspense> <footer> <nav> <A href="item/3/">"Target 3##"</A> <A href="item/4/">"Target 4##"</A> <A href="item/4/path1/">"Target 41#"</A> <A href="item/4/path2/">"Target 42#"</A> <A href="item/4/path2/field1">"Target 421"</A> <A href="item/1/path2/field3">"Target 123"</A> </nav> </footer> </section> } } #[component] fn InstrumentedTop() -> impl IntoView { view! { <h1>"Instrumented Tests"</h1> <p> "These tests validates the number of invocations of server functions and suspenses per access." </p> <ul> // not using `A` because currently some bugs with artix <li> <a href="item/">"Item Listing"</a> </li> <li> <a href="item/4/path1/">"Target 41#"</a> </li> </ul> } } #[component] fn ItemRoot() -> impl IntoView { let ticket = expect_context::<Ticket>().0; provide_context(Resource::new_blocking( move || (), move |_| async move { list_items(ticket).await }, )); view! { <h2>"<ItemRoot/>"</h2> <Outlet /> } } #[component] fn ItemListing() -> impl IntoView { let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>(); let resource = expect_context::<Resource<Result<Vec<i64>, ServerFnError>>>(); let item_listing = move || { Suspend::new(async move { let result = resource.await.map(|items| items .into_iter() .map(move |item| // FIXME seems like relative link isn't working, it is currently // adding an extra `/` in artix; manually construct `a` instead. // <li><A href=format!("./{item}/")>"Item "{item}</A></li> view! { <li> <a href=format!("/instrumented/item/{item}/")>"Item "{item}</a> </li> } ) .collect_view() ); suspense_counters.update_untracked(|c| c.item_listing += 1); result }) }; view! { <h3>"<ItemListing/>"</h3> <ul> <Suspense>{item_listing}</Suspense> </ul> } } #[derive(Params, PartialEq, Clone, Debug)] struct ItemTopParams { id: Option<i64>, } #[component] fn ItemTop() -> impl IntoView { let ticket = expect_context::<Ticket>().0; let params = use_params::<ItemTopParams>(); // map result to an option as the focus isn't error rendering provide_context(Resource::new_blocking( move || params.get().map(|p| p.id), move |id| async move { match id { Err(_) => None, Ok(Some(id)) => get_item(ticket, id).await.ok(), _ => None, } }, )); view! { <h4>"<ItemTop/>"</h4> <Outlet /> } } #[component] fn ItemOverview() -> impl IntoView { let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>(); let resource = expect_context::<Resource<Option<GetItemResult>>>(); let item_view = move || { Suspend::new(async move { let result = resource.await.map(|GetItemResult(item, names)| { view! { <p>{format!("Viewing {item:?}")}</p> <ul> {names .into_iter() .map(|name| { let id = item.id; // FIXME seems like relative link isn't working, it is currently // adding an extra `/` in artix; manually construct `a` instead. // <li><A href=format!("./{name}/")>{format!("Inspect {name}")}</A></li> view! { <li> <a href=format!( "/instrumented/item/{id}/{name}/", )>"Inspect "{name.clone()}</a> </li> } }) .collect_view()} </ul> } }); suspense_counters.update_untracked(|c| c.item_overview += 1); result }) }; view! { <h5>"<ItemOverview/>"</h5> <Suspense>{item_view}</Suspense> } } #[derive(Params, PartialEq, Clone, Debug)] struct ItemInspectParams { path: Option<String>, } #[component] fn ItemInspect() -> impl IntoView { let ticket = expect_context::<Ticket>().0; let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>(); let params = use_params::<ItemInspectParams>(); let res_overview = expect_context::<Resource<Option<GetItemResult>>>(); let res_inspect = Resource::new_blocking( move || params.get().map(|p| p.path), move |p| async move { // leptos::logging::log!("res_inspect: res_overview.await"); // Note: this resource is untracked here, though `params` changing // will nonetheless results in the "expected" tracked updates. let overview = res_overview.await; // leptos::logging::log!("res_inspect: resolved res_overview.await"); // let result = match (overview, p) { (Some(item), Ok(Some(path))) => { // leptos::logging::log!("res_inspect: inspect_item().await"); inspect_item(ticket, item.0.id, path.clone()).await.ok() } _ => None, } // ; // leptos::logging::log!("res_inspect: resolved inspect_item().await"); // result }, ); let ws = use_context::<WriteSignal<Option<FieldNavCtx>>>(); on_cleanup(move || { if let Some(c) = ws { c.set(None); } }); let inspect_view = move || { // leptos::logging::log!("inspect_view closure invoked"); Suspend::new(async move { // leptos::logging::log!("inspect_view Suspend::new() called"); let result = res_inspect.await.map(|InspectItemResult(item, name, fields)| { // leptos::logging::log!("inspect_view res_inspect awaited"); let id = item.id; expect_context::<WriteSignal<Option<FieldNavCtx>>>().set(Some( fields.iter() .map(|field| FieldNavItem { href: format!("/instrumented/item/{id}/{name}/{field}"), text: field.to_string(), }) .collect::<Vec<_>>() .into() )); view! { <p>{format!("Inspecting {item:?}")}</p> <ul> {fields .iter() .map(|field| { // FIXME seems like relative link to root for a wildcard isn't // working as expected, so manually construct `a` instead. // let text = format!("Inspect {name}/{field}"); // view! { // <li><A href=format!("{field}")>{text}</A></li> // } view! { <li> <a href=format!( "/instrumented/item/{id}/{name}/{field}", )>{format!("Inspect {name}/{field}")}</a> </li> } }) .collect_view()} </ul> } }); suspense_counters.update_untracked(|c| c.item_inspect += 1); // leptos::logging::log!( // "returning result, result.is_some() = {}, count = {}", // result.is_some(), // suspense_counters.get().item_inspect, // ); result }) }; view! { <h5>"<ItemInspect/>"</h5> <Suspense>{inspect_view}</Suspense> } } #[component] fn ShowCounters() -> impl IntoView { // There is _weirdness_ in this view. The `Server Calls` counters // will be acquired via the expected mode and be rendered as such. // // However, upon `Reset Counters`, the mode from which the reset // was issued will result in the rendering be reflected as such, so // if the initial state was SSR, resetting under CSR will result in // the CSR counters be rendered after. However for the intents and // purpose for the testing only the CSR is cared for. // // At the end of the day, it is possible to have both these be // separated out, but for the purpose of this test the focus is not // on the SSR side of things (at least until further regression is // discovered that affects SSR directly). let ticket = expect_context::<Ticket>().0; let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>(); let reset_counters = ServerAction::<ResetCounters>::new(); let res_counter = Resource::new( move || reset_counters.version().get(), move |_| async move { ( get_counters(ticket).await, if ticket == 0 { "SSR" } else { "CSR" }.to_string(), ticket, ) }, ); let counter_view = move || { Suspend::new(async move { // ensure current mode and ticket are both updated let (counters, mode, ticket) = res_counter.await; counters.map(|counters| { let clear_suspense_counters = move |_| { suspense_counters.update(|c| { // leptos::logging::log!("resetting suspense counters"); *c = SuspenseCounters::default(); }); }; view! { <h3 id="server-calls">"Server Calls ("{mode}")"</h3> <dl> <dt>"list_items"</dt> <dd id="list_items">{counters.list_items}</dd> <dt>"get_item"</dt> <dd id="get_item">{counters.get_item}</dd> <dt>"inspect_item_root"</dt> <dd id="inspect_item_root">{counters.inspect_item_root}</dd> <dt>"inspect_item_field"</dt> <dd id="inspect_item_field">{counters.inspect_item_field}</dd> </dl> <ActionForm action=reset_counters> <input type="hidden" name="ticket" value=format!("{ticket}") /> <input id="reset-counters" type="submit" value="Reset Counters" on:click=clear_suspense_counters /> </ActionForm> } }) }) }; view! { <h2>"Counters"</h2> <h3 id="suspend-calls">"Suspend Calls"</h3> {move || { suspense_counters .with(|c| { view! { <dl> <dt>"item_listing"</dt> <dd id="item_listing">{c.item_listing}</dd> <dt>"item_overview"</dt> <dd id="item_overview">{c.item_overview}</dd> <dt>"item_inspect"</dt> <dd id="item_inspect">{c.item_inspect}</dd> </dl> } }) }} <Suspense>{counter_view}</Suspense> } } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct FieldNavItem { pub href: String, pub text: String, } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)] pub struct FieldNavCtx(pub Option<Vec<FieldNavItem>>); impl From<Vec<FieldNavItem>> for FieldNavCtx { fn from(item: Vec<FieldNavItem>) -> Self { Self(Some(item)) } } #[component] pub fn FieldNavPortlet() -> impl IntoView { let ctx = expect_context::<ReadSignal<Option<FieldNavCtx>>>(); view! { <ShowLet some=ctx let:ctx> <div id="FieldNavPortlet"> <span>"FieldNavPortlet:"</span> <nav> {ctx .0 .map(|ctx| { ctx.into_iter() .map(|FieldNavItem { href, text }| { view! { <A href=href>{text}</A> } }) .collect_view() })} </nav> </div> </ShowLet> } } pub fn provide_field_nav_portlet_context() { // wrapping the Ctx in an Option allows better ergonomics whenever it isn't needed let (ctx, set_ctx) = signal(None::<FieldNavCtx>); provide_context(ctx); provide_context(set_ctx); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/app_suite.rs
examples/suspense_tests/e2e/tests/app_suite.rs
mod fixtures; use anyhow::Result; use cucumber::World; use fixtures::world::AppWorld; use std::{ffi::OsStr, fs::read_dir}; #[tokio::main] async fn main() -> Result<()> { // Normally the below is done, but it's now gotten to the point of // having a sufficient number of tests where the resource contention // of the concurrently running browsers will cause failures on CI. // AppWorld::cucumber() // .fail_on_skipped() // .run_and_exit("./features") // .await; // Mitigate the issue by manually stepping through each feature, // rather than letting cucumber glob them and dispatch all at once. for entry in read_dir("./features")? { let path = entry?.path(); if path.extension() == Some(OsStr::new("feature")) { AppWorld::cucumber() .fail_on_skipped() .run_and_exit(path) .await; } } Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/check.rs
examples/suspense_tests/e2e/tests/fixtures/check.rs
use crate::fixtures::find; use anyhow::{Ok, Result}; use fantoccini::Client; use pretty_assertions::assert_eq; pub async fn page_title_is(client: &Client, expected_text: &str) -> Result<()> { let actual = find::page_title(client).await?; assert_eq!(&actual, expected_text); Ok(()) } pub async fn loaded_one_message_is( client: &Client, expected_text: &str, ) -> Result<()> { let actual = find::loaded_one_message(client).await?; assert_eq!(&actual, expected_text); Ok(()) } pub async fn loaded_two_message_is( client: &Client, expected_text: &str, ) -> Result<()> { let actual = find::loaded_two_message(client).await?; assert_eq!(&actual, expected_text); Ok(()) } pub async fn inside_message_is( client: &Client, expected_text: &str, ) -> Result<()> { let actual = find::inside_message(client).await?; assert_eq!(&actual, expected_text); Ok(()) } pub async fn following_message_is( client: &Client, expected_text: &str, ) -> Result<()> { let actual = find::following_message(client).await?; assert_eq!(&actual, expected_text); Ok(()) } pub async fn first_count_is(client: &Client, expected: u32) -> Result<()> { let actual = find::first_count(client).await?; assert_eq!(actual, expected); Ok(()) } pub async fn second_count_is(client: &Client, expected: u32) -> Result<()> { let actual = find::second_count(client).await?; assert_eq!(actual, expected); Ok(()) } pub async fn instrumented_counts( client: &Client, expected: &[(&str, u32)], ) -> Result<()> { let mut actual = Vec::<(&str, u32)>::new(); for (selector, _) in expected.iter() { actual .push((selector, find::instrumented_count(client, selector).await?)) } assert_eq!(actual, expected); Ok(()) } pub async fn link_text_is_aria_current( client: &Client, text: &str, ) -> Result<()> { let link = find::link_with_text(client, text).await?; link.attr("aria-current") .await? .expect(format!("aria-current missing for {text}").as_str()); Ok(()) } pub async fn link_text_is_not_aria_current( client: &Client, text: &str, ) -> Result<()> { let link = find::link_with_text(client, text).await?; link.attr("aria-current") .await? .map(|_| anyhow::bail!("aria-current mistakenly set for {text}")) .unwrap_or(Ok(())) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/find.rs
examples/suspense_tests/e2e/tests/fixtures/find.rs
use anyhow::{Ok, Result}; use fantoccini::{elements::Element, Client, Locator}; pub async fn page_title(client: &Client) -> Result<String> { let selector = "h1"; let element = client .wait() .for_element(Locator::Css(selector)) .await .expect( format!("Page title not found by Css selector `{}`", selector) .as_str(), ); let text = element.text().await?; Ok(text) } pub async fn loaded_one_message(client: &Client) -> Result<String> { let text = component_message(client, "loaded-1").await?; Ok(text) } pub async fn loaded_two_message(client: &Client) -> Result<String> { let text = component_message(client, "loaded-2").await?; Ok(text) } pub async fn following_message(client: &Client) -> Result<String> { let text = component_message(client, "following-message").await?; Ok(text) } pub async fn inside_message(client: &Client) -> Result<String> { let text = component_message(client, "inside-message").await?; Ok(text) } pub async fn first_count(client: &Client) -> Result<u32> { let element = first_button(client).await?; let text = element.text().await?; let count = text.parse::<u32>().unwrap(); Ok(count) } pub async fn first_button(client: &Client) -> Result<Element> { let counter_button = client .wait() .for_element(Locator::Css("button")) .await .expect("First button not found"); Ok(counter_button) } pub async fn second_count(client: &Client) -> Result<u32> { let element = second_button(client).await?; let text = element.text().await?; let count = text.parse::<u32>().unwrap(); Ok(count) } pub async fn second_button(client: &Client) -> Result<Element> { let counter_button = client .wait() .for_element(Locator::Id("second-count")) .await .expect("Second button not found"); Ok(counter_button) } pub async fn instrumented_count( client: &Client, selector: &str, ) -> Result<u32> { let element = client .wait() .for_element(Locator::Id(selector)) .await .expect(format!("Element #{selector} not found.").as_str()); let text = element.text().await?; let count = text.parse::<u32>().expect( format!("Element #{selector} does not contain a number.").as_str(), ); Ok(count) } pub async fn reset_counter(client: &Client) -> Result<Element> { let reset_button = client .wait() .for_element(Locator::Id("reset-counters")) .await .expect("Reset counter input not found"); Ok(reset_button) } pub async fn reset_csr_counter(client: &Client) -> Result<Element> { let reset_button = client .wait() .for_element(Locator::Id("reset-csr-counters")) .await .expect("Reset CSR counter input not found"); Ok(reset_button) } async fn component_message(client: &Client, id: &str) -> Result<String> { let element = client.wait().for_element(Locator::Id(id)).await.expect( format!("loaded message not found by id `{}`", id).as_str(), ); let text = element.text().await?; Ok(text) } pub async fn link_with_text(client: &Client, text: &str) -> Result<Element> { let link = client .wait() .for_element(Locator::LinkText(text)) .await .expect(format!("Link not found by `{}`", text).as_str()); Ok(link) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/mod.rs
examples/suspense_tests/e2e/tests/fixtures/mod.rs
pub mod action; pub mod check; pub mod find; pub mod world;
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/action.rs
examples/suspense_tests/e2e/tests/fixtures/action.rs
use super::{find, world::HOST}; use anyhow::Result; use fantoccini::{Client, Locator}; use std::result::Result::Ok; pub async fn goto_path(client: &Client, path: &str) -> Result<()> { let url = format!("{}{}", HOST, path); client.goto(&url).await?; Ok(()) } pub async fn click_link(client: &Client, text: &str) -> Result<()> { let link = client .wait() .for_element(Locator::LinkText(text)) .await .expect(format!("Link not found by `{}`", text).as_str()); link.click().await?; Ok(()) } pub async fn click_first_button(client: &Client) -> Result<()> { let counter_button = find::first_button(client).await?; counter_button.click().await?; Ok(()) } pub async fn click_second_button(client: &Client) -> Result<()> { let counter_button = find::second_button(client).await?; counter_button.click().await?; Ok(()) } pub async fn click_reset_counters_button(client: &Client) -> Result<()> { let reset_counter = find::reset_counter(client).await?; reset_counter.click().await?; Ok(()) } pub async fn click_reset_csr_counters_button(client: &Client) -> Result<()> { let reset_counter = find::reset_csr_counter(client).await?; reset_counter.click().await?; Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/world/check_steps.rs
examples/suspense_tests/e2e/tests/fixtures/world/check_steps.rs
use crate::fixtures::{check, world::AppWorld}; use anyhow::{Ok, Result}; use cucumber::{gherkin::Step, then}; #[then(regex = r"^I see the page title is (.*)$")] async fn i_see_the_page_title_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::page_title_is(client, &text).await?; Ok(()) } #[then(regex = r"^I see the one second message is (.*)$")] async fn i_see_the_one_second_message_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::loaded_one_message_is(client, &text).await?; Ok(()) } #[then(regex = r"^I see the two second message is (.*)$")] async fn i_see_the_two_second_message_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::loaded_two_message_is(client, &text).await?; Ok(()) } #[then(regex = r"^I see the following message is (.*)$")] async fn i_see_the_following_message_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::following_message_is(client, &text).await?; Ok(()) } #[then(regex = r"^I see the inside message is (.*)$")] async fn i_see_the_inside_message_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::inside_message_is(client, &text).await?; Ok(()) } #[then(expr = "I see the first count is {int}")] #[then(expr = "I see the count is {int}")] async fn i_see_the_first_count_is( world: &mut AppWorld, expected: u32, ) -> Result<()> { let client = &world.client; check::first_count_is(client, expected).await?; Ok(()) } #[then(expr = "I see the second count is {int}")] async fn i_see_the_second_count_is( world: &mut AppWorld, expected: u32, ) -> Result<()> { let client = &world.client; check::second_count_is(client, expected).await?; Ok(()) } #[then(regex = r"^I see the (.*) link being bolded$")] async fn i_see_the_link_being_bolded( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::link_text_is_aria_current(client, &text).await?; Ok(()) } #[then(expr = "I see the following links being bolded")] async fn i_see_the_following_links_being_bolded( world: &mut AppWorld, step: &Step, ) -> Result<()> { let client = &world.client; if let Some(table) = step.table.as_ref() { for row in table.rows.iter() { check::link_text_is_aria_current(client, &row[0]).await?; } } Ok(()) } #[then(regex = r"^I see the (.*) link not being bolded$")] async fn i_see_the_link_being_not_bolded( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::link_text_is_not_aria_current(client, &text).await?; Ok(()) } #[then(expr = "I see the following links not being bolded")] async fn i_see_the_following_links_not_being_bolded( world: &mut AppWorld, step: &Step, ) -> Result<()> { let client = &world.client; if let Some(table) = step.table.as_ref() { for row in table.rows.iter() { check::link_text_is_not_aria_current(client, &row[0]).await?; } } Ok(()) } #[then(expr = "I see the following counters under section")] #[then(expr = "the following counters under section")] async fn i_see_the_following_counters_under_section( world: &mut AppWorld, step: &Step, ) -> Result<()> { // FIXME ideally check the mode; for now leave it because effort let client = &world.client; if let Some(table) = step.table.as_ref() { let expected = table .rows .iter() .skip(1) .map(|row| (row[0].as_str(), row[1].parse::<u32>().unwrap())) .collect::<Vec<_>>(); check::instrumented_counts(client, &expected).await?; } Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/world/action_steps.rs
examples/suspense_tests/e2e/tests/fixtures/world/action_steps.rs
use crate::fixtures::{action, world::AppWorld}; use anyhow::{Ok, Result}; use cucumber::{gherkin::Step, given, when}; #[given("I see the app")] #[when("I open the app")] async fn i_open_the_app(world: &mut AppWorld) -> Result<()> { let client = &world.client; action::goto_path(client, "").await?; Ok(()) } #[given(regex = r"^I select the mode (.*)$")] #[given(regex = r"^I select the component (.*)$")] #[when(regex = "^I select the component (.*)$")] #[given(regex = "^I select the link (.*)$")] #[when(regex = "^I select the link (.*)$")] #[when(regex = "^I click on the link (.*)$")] #[when(regex = "^I go check the (.*)$")] async fn i_select_the_link(world: &mut AppWorld, text: String) -> Result<()> { let client = &world.client; action::click_link(client, &text).await?; Ok(()) } #[when(expr = "I click the first count {int} times")] #[when(expr = "I click the count {int} times")] async fn i_click_the_first_button_n_times( world: &mut AppWorld, times: u32, ) -> Result<()> { let client = &world.client; for _ in 1..=times { action::click_first_button(client).await?; } Ok(()) } #[when(expr = "I click the second count {int} times")] async fn i_click_the_second_button_n_times( world: &mut AppWorld, times: u32, ) -> Result<()> { let client = &world.client; for _ in 1..=times { action::click_second_button(client).await?; } Ok(()) } #[given(regex = "^I (refresh|reload) the (browser|page)$")] #[when(regex = "^I (refresh|reload) the (browser|page)$")] async fn i_refresh_the_browser(world: &mut AppWorld) -> Result<()> { let client = &world.client; client.refresh().await?; Ok(()) } #[when(expr = "I click on Reset Counters")] async fn i_click_on_reset_counters(world: &mut AppWorld) -> Result<()> { let client = &world.client; action::click_reset_counters_button(client).await?; Ok(()) } #[given(expr = "I click on Reset CSR Counters")] #[when(expr = "I click on Reset CSR Counters")] async fn i_click_on_reset_csr_counters(world: &mut AppWorld) -> Result<()> { let client = &world.client; action::click_reset_csr_counters_button(client).await?; Ok(()) } #[when(expr = "I access the instrumented counters via SSR")] async fn i_access_the_instrumented_counters_page_via_ssr( world: &mut AppWorld, ) -> Result<()> { let client = &world.client; action::click_link(client, "Instrumented").await?; action::click_link(client, "Counters").await?; client.refresh().await?; Ok(()) } #[when(expr = "I access the instrumented counters via CSR")] async fn i_access_the_instrumented_counters_page_via_csr( world: &mut AppWorld, ) -> Result<()> { let client = &world.client; action::click_link(client, "Instrumented").await?; action::click_link(client, "Counters").await?; Ok(()) } #[given(expr = "I select the following links")] #[when(expr = "I select the following links")] async fn i_select_the_following_links( world: &mut AppWorld, step: &Step, ) -> Result<()> { let client = &world.client; if let Some(table) = step.table.as_ref() { for row in table.rows.iter() { action::click_link(client, &row[0]).await?; } } Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/suspense_tests/e2e/tests/fixtures/world/mod.rs
examples/suspense_tests/e2e/tests/fixtures/world/mod.rs
pub mod action_steps; pub mod check_steps; use anyhow::Result; use cucumber::World; use fantoccini::{ error::NewSessionError, wd::Capabilities, Client, ClientBuilder, }; pub const HOST: &str = "http://127.0.0.1:3000"; #[derive(Debug, World)] #[world(init = Self::new)] pub struct AppWorld { pub client: Client, } impl AppWorld { async fn new() -> Result<Self, anyhow::Error> { let webdriver_client = build_client().await?; Ok(Self { client: webdriver_client, }) } } async fn build_client() -> Result<Client, NewSessionError> { let mut cap = Capabilities::new(); let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap(); cap.insert("goog:chromeOptions".to_string(), arg); let client = ClientBuilder::native() .capabilities(cap) .connect("http://localhost:4444") .await?; Ok(client) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/src/errors.rs
examples/todo_app_sqlite_axum/src/errors.rs
use http::status::StatusCode; use thiserror::Error; #[derive(Debug, Clone, Error)] pub enum TodoAppError { #[error("Not Found")] NotFound, #[error("Internal Server Error")] InternalServerError, } impl TodoAppError { pub fn status_code(&self) -> StatusCode { match self { TodoAppError::NotFound => StatusCode::NOT_FOUND, TodoAppError::InternalServerError => { StatusCode::INTERNAL_SERVER_ERROR } } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/src/lib.rs
examples/todo_app_sqlite_axum/src/lib.rs
pub mod error_template; pub mod errors; pub mod todo; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use crate::todo::TodoApp; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(TodoApp); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/src/todo.rs
examples/todo_app_sqlite_axum/src/todo.rs
use crate::error_template::ErrorTemplate; use leptos::{either::Either, prelude::*}; use serde::{Deserialize, Serialize}; use server_fn::ServerFnError; pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=options.clone() /> <HydrationScripts options/> <link rel="stylesheet" id="leptos" href="/pkg/todo_app_sqlite_axum.css"/> <link rel="shortcut icon" type="image/ico" href="/favicon.ico"/> </head> <body> <TodoApp/> </body> </html> } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "ssr", derive(sqlx::FromRow))] pub struct Todo { id: u16, title: String, completed: bool, } #[cfg(feature = "ssr")] pub mod ssr { // use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode}; use leptos::server_fn::ServerFnError; use sqlx::{Connection, SqliteConnection}; pub async fn db() -> Result<SqliteConnection, ServerFnError> { Ok(SqliteConnection::connect("sqlite:Todos.db").await?) } } #[server] pub async fn get_todos() -> Result<Vec<Todo>, ServerFnError> { use self::ssr::*; use http::request::Parts; // this is just an example of how to access server context injected in the handlers let req_parts = use_context::<Parts>(); if let Some(req_parts) = req_parts { println!("Uri = {:?}", req_parts.uri); } use futures::TryStreamExt; let mut conn = db().await?; let mut todos = Vec::new(); let mut rows = sqlx::query_as::<_, Todo>("SELECT * FROM todos").fetch(&mut conn); while let Some(row) = rows.try_next().await? { todos.push(row); } // Lines below show how to set status code and headers on the response // let resp = expect_context::<ResponseOptions>(); // resp.set_status(StatusCode::IM_A_TEAPOT); // resp.insert_header(SET_COOKIE, HeaderValue::from_str("fizz=buzz").unwrap()); Ok(todos) } #[server] pub async fn add_todo(title: String) -> Result<(), ServerFnError> { use self::ssr::*; let mut conn = db().await?; // fake API delay std::thread::sleep(std::time::Duration::from_millis(250)); match sqlx::query("INSERT INTO todos (title, completed) VALUES ($1, false)") .bind(title) .execute(&mut conn) .await { Ok(_row) => Ok(()), Err(e) => Err(ServerFnError::ServerError(e.to_string())), } } #[server] pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> { use self::ssr::*; let mut conn = db().await?; Ok(sqlx::query("DELETE FROM todos WHERE id = $1") .bind(id) .execute(&mut conn) .await .map(|_| ())?) } #[component] pub fn TodoApp() -> impl IntoView { view! { <header> <h1>"My Tasks"</h1> </header> <main> <Todos/> </main> } } #[component] pub fn Todos() -> impl IntoView { let add_todo = ServerMultiAction::<AddTodo>::new(); let submissions = add_todo.submissions(); let delete_todo = ServerAction::<DeleteTodo>::new(); // list of todos is loaded from the server in reaction to changes let todos = Resource::new( move || { ( delete_todo.version().get(), add_todo.version().get(), delete_todo.version().get(), ) }, move |_| get_todos(), ); let existing_todos = move || { Suspend::new(async move { todos .await .map(|todos| { if todos.is_empty() { Either::Left(view! { <p>"No tasks were found."</p> }) } else { Either::Right( todos .iter() .map(move |todo| { let id = todo.id; view! { <li> {todo.title.clone()} <ActionForm action=delete_todo> <input type="hidden" name="id" value=id/> <input type="submit" value="X"/> </ActionForm> </li> } }) .collect::<Vec<_>>(), ) } }) }) }; view! { <MultiActionForm action=add_todo> <label>"Add a Todo" <input type="text" name="title"/></label> <input type="submit" value="Add"/> </MultiActionForm> <div> <Transition fallback=move || view! { <p>"Loading..."</p> }> <ErrorBoundary fallback=|errors| view! { <ErrorTemplate errors/> }> <ul> {existing_todos} {move || { submissions .get() .into_iter() .filter(|submission| submission.pending().get()) .map(|submission| { view! { <li class="pending"> {move || submission.input().get().map(|data| data.title)} </li> } }) .collect::<Vec<_>>() }} </ul> </ErrorBoundary> </Transition> </div> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/src/error_template.rs
examples/todo_app_sqlite_axum/src/error_template.rs
use leptos::prelude::*; // A basic function to display errors served by the error boundaries. Feel free to do more complicated things // here than just displaying them #[component] pub fn ErrorTemplate( #[prop(optional)] outside_errors: Option<Errors>, #[prop(optional, into)] errors: Option<RwSignal<Errors>>, ) -> impl IntoView { let errors = match outside_errors { Some(e) => RwSignal::new(e), None => match errors { Some(e) => e, None => panic!("No Errors found and we expected errors!"), }, }; // Get Errors from Signal // Downcast lets us take a type that implements `std::error::Error` let errors = move || errors.get().into_iter().map(|(_, v)| v).collect::<Vec<_>>(); // Only the response code for the first error is actually sent from the server // this may be customized by the specific application /*#[cfg(feature = "ssr")] { let response = use_context::<ResponseOptions>(); if let Some(response) = response { response.set_status(errors[0].status_code()); } }*/ view! { <h1>"Errors"</h1> {move || { errors() .into_iter() .map(|error| { view! { <p>"Error: " {error.to_string()}</p> } }) .collect::<Vec<_>>() }} } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/src/main.rs
examples/todo_app_sqlite_axum/src/main.rs
#[cfg(feature = "ssr")] use axum::{ body::Body, extract::Path, http::Request, response::{IntoResponse, Response}, routing::get, Router, }; use leptos::prelude::*; use todo_app_sqlite_axum::*; //Define a handler to test extractor with state #[cfg(feature = "ssr")] async fn custom_handler( Path(id): Path<String>, req: Request<Body>, ) -> Response { let handler = leptos_axum::render_app_to_stream_with_context( move || { provide_context(id.clone()); }, todo::TodoApp, ); handler(req).await.into_response() } #[cfg(feature = "ssr")] #[tokio::main] async fn main() { use crate::todo::{ssr::db, *}; use leptos_axum::{generate_route_list, LeptosRoutes}; simple_logger::init_with_level(log::Level::Error) .expect("couldn't initialize logging"); let mut conn = db().await.expect("couldn't connect to DB"); if let Err(e) = sqlx::migrate!().run(&mut conn).await { eprintln!("{e:?}"); } // Setting this to None means we'll be using cargo-leptos and its env vars let conf = get_configuration(None).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(TodoApp); // build our application with a route let app = Router::new() .route("/special/{id}", get(custom_handler)) .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); println!("listening on http://{}", &addr); axum::serve(listener, app.into_make_service()) .await .unwrap(); } #[cfg(not(feature = "ssr"))] pub fn main() { use leptos::mount::mount_to_body; _ = console_log::init_with_level(log::Level::Debug); console_error_panic_hook::set_once(); mount_to_body(todo::TodoApp); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/app_suite.rs
examples/todo_app_sqlite_axum/e2e/tests/app_suite.rs
mod fixtures; use anyhow::Result; use cucumber::World; use fixtures::world::AppWorld; #[tokio::main] async fn main() -> Result<()> { AppWorld::cucumber() .fail_on_skipped() .run_and_exit("./features") .await; Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/check.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/check.rs
use super::find; use anyhow::{Ok, Result}; use fantoccini::{Client, Locator}; use pretty_assertions::assert_eq; pub async fn text_on_element( client: &Client, selector: &str, expected_text: &str, ) -> Result<()> { let element = client .wait() .for_element(Locator::Css(selector)) .await .expect( format!("Element not found by Css selector `{}`", selector) .as_str(), ); let actual = element.text().await?; assert_eq!(&actual, expected_text); Ok(()) } pub async fn todo_present( client: &Client, text: &str, expected: bool, ) -> Result<()> { let todo_present = is_todo_present(client, text).await; assert_eq!(todo_present, expected); Ok(()) } async fn is_todo_present(client: &Client, text: &str) -> bool { let todos = find::todos(client).await; for todo in todos { let todo_title = todo.text().await.expect("Todo title not found"); if todo_title == text { return true; } } false } pub async fn todo_is_pending(client: &Client) -> Result<()> { if let None = find::pending_todo(client).await { assert!(false, "Pending todo not found"); } Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/find.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/find.rs
use fantoccini::{elements::Element, Client, Locator}; pub async fn todo_input(client: &Client) -> Element { let textbox = client .wait() .for_element(Locator::Css("input[name='title")) .await .expect("Todo textbox not found"); textbox } pub async fn add_button(client: &Client) -> Element { let button = client .wait() .for_element(Locator::Css("input[value='Add']")) .await .expect(""); button } pub async fn first_delete_button(client: &Client) -> Option<Element> { if let Ok(element) = client .wait() .for_element(Locator::Css("li:first-child input[value='X']")) .await { return Some(element); } None } pub async fn delete_button(client: &Client, text: &str) -> Option<Element> { let selector = format!("//*[text()='{text}']//input[@value='X']"); if let Ok(element) = client.wait().for_element(Locator::XPath(&selector)).await { return Some(element); } None } pub async fn pending_todo(client: &Client) -> Option<Element> { if let Ok(element) = client.wait().for_element(Locator::Css(".pending")).await { return Some(element); } None } pub async fn todos(client: &Client) -> Vec<Element> { let todos = client .find_all(Locator::Css("li")) .await .expect("Todo List not found"); todos }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/mod.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/mod.rs
pub mod action; pub mod check; pub mod find; pub mod world;
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/action.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/action.rs
use super::{find, world::HOST}; use anyhow::Result; use fantoccini::Client; use std::result::Result::Ok; use tokio::{self, time}; pub async fn goto_path(client: &Client, path: &str) -> Result<()> { let url = format!("{}{}", HOST, path); client.goto(&url).await?; Ok(()) } pub async fn add_todo(client: &Client, text: &str) -> Result<()> { fill_todo(client, text).await?; click_add_button(client).await?; Ok(()) } pub async fn fill_todo(client: &Client, text: &str) -> Result<()> { let textbox = find::todo_input(client).await; textbox.send_keys(text).await?; Ok(()) } pub async fn click_add_button(client: &Client) -> Result<()> { let add_button = find::add_button(client).await; add_button.click().await?; Ok(()) } pub async fn empty_todo_list(client: &Client) -> Result<()> { let todos = find::todos(client).await; for _todo in todos { let _ = delete_first_todo(client).await?; } Ok(()) } pub async fn delete_first_todo(client: &Client) -> Result<()> { if let Some(element) = find::first_delete_button(client).await { element.click().await.expect("Failed to delete todo"); time::sleep(time::Duration::from_millis(250)).await; } Ok(()) } pub async fn delete_todo(client: &Client, text: &str) -> Result<()> { if let Some(element) = find::delete_button(client, text).await { element.click().await?; time::sleep(time::Duration::from_millis(250)).await; } Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/world/check_steps.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/world/check_steps.rs
use crate::fixtures::{check, world::AppWorld}; use anyhow::{Ok, Result}; use cucumber::then; #[then(regex = "^I see the page title is (.*)$")] async fn i_see_the_page_title_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::text_on_element(client, "h1", &text).await?; Ok(()) } #[then(regex = "^I see the label of the input is (.*)$")] async fn i_see_the_label_of_the_input_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::text_on_element(client, "label", &text).await?; Ok(()) } #[then(regex = "^I see the todo named (.*)$")] async fn i_see_the_todo_is_present( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::todo_present(client, text.as_str(), true).await?; Ok(()) } #[then("I see the pending todo")] async fn i_see_the_pending_todo(world: &mut AppWorld) -> Result<()> { let client = &world.client; check::todo_is_pending(client).await?; Ok(()) } #[then(regex = "^I see the empty list message is (.*)$")] async fn i_see_the_empty_list_message_is( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::text_on_element(client, "ul p", &text).await?; Ok(()) } #[then(regex = "^I do not see the todo named (.*)$")] async fn i_do_not_see_the_todo_is_present( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; check::todo_present(client, text.as_str(), false).await?; Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/world/action_steps.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/world/action_steps.rs
use crate::fixtures::{action, world::AppWorld}; use anyhow::{Ok, Result}; use cucumber::{given, when}; #[given("I see the app")] #[when("I open the app")] async fn i_open_the_app(world: &mut AppWorld) -> Result<()> { let client = &world.client; action::goto_path(client, "").await?; Ok(()) } #[given(regex = "^I add a todo as (.*)$")] #[when(regex = "^I add a todo as (.*)$")] async fn i_add_a_todo_titled(world: &mut AppWorld, text: String) -> Result<()> { let client = &world.client; action::add_todo(client, text.as_str()).await?; Ok(()) } #[given(regex = "^I set the todo as (.*)$")] async fn i_set_the_todo_as(world: &mut AppWorld, text: String) -> Result<()> { let client = &world.client; action::fill_todo(client, &text).await?; Ok(()) } #[when(regex = "I click the Add button$")] async fn i_click_the_button(world: &mut AppWorld) -> Result<()> { let client = &world.client; action::click_add_button(client).await?; Ok(()) } #[when(regex = "^I delete the todo named (.*)$")] async fn i_delete_the_todo_named( world: &mut AppWorld, text: String, ) -> Result<()> { let client = &world.client; action::delete_todo(client, text.as_str()).await?; Ok(()) } #[given("the todo list is empty")] #[when("I empty the todo list")] async fn i_empty_the_todo_list(world: &mut AppWorld) -> Result<()> { let client = &world.client; action::empty_todo_list(client).await?; Ok(()) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_axum/e2e/tests/fixtures/world/mod.rs
examples/todo_app_sqlite_axum/e2e/tests/fixtures/world/mod.rs
pub mod action_steps; pub mod check_steps; use anyhow::Result; use cucumber::World; use fantoccini::{ error::NewSessionError, wd::Capabilities, Client, ClientBuilder, }; pub const HOST: &str = "http://127.0.0.1:3000"; #[derive(Debug, World)] #[world(init = Self::new)] pub struct AppWorld { pub client: Client, } impl AppWorld { async fn new() -> Result<Self, anyhow::Error> { let webdriver_client = build_client().await?; Ok(Self { client: webdriver_client, }) } } async fn build_client() -> Result<Client, NewSessionError> { let mut cap = Capabilities::new(); let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap(); cap.insert("goog:chromeOptions".to_string(), arg); let client = ClientBuilder::native() .capabilities(cap) .connect("http://localhost:4444") .await?; Ok(client) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/errors_axum/src/errors.rs
examples/errors_axum/src/errors.rs
use http::status::StatusCode; use thiserror::Error; #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum AppError { #[error("Not Found")] NotFound, #[error("Internal Server Error")] InternalServerError, } impl AppError { pub fn status_code(&self) -> StatusCode { match self { AppError::NotFound => StatusCode::NOT_FOUND, AppError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR, } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/errors_axum/src/lib.rs
examples/errors_axum/src/lib.rs
pub mod error_template; pub mod errors; pub mod landing; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use crate::landing::App; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/errors_axum/src/landing.rs
examples/errors_axum/src/landing.rs
use crate::{error_template::ErrorTemplate, errors::AppError}; use leptos::prelude::*; use leptos_meta::*; use leptos_router::{ components::{Route, Router, Routes}, StaticSegment, }; #[server(CauseInternalServerError, "/api")] pub async fn cause_internal_server_error() -> Result<(), ServerFnError> { // fake API delay std::thread::sleep(std::time::Duration::from_millis(1250)); Err(ServerFnError::ServerError( "Generic Server Error".to_string(), )) } pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=options.clone() /> <HydrationScripts options/> <MetaTags/> </head> <body> <App/> </body> </html> } } #[component] pub fn App() -> impl IntoView { provide_meta_context(); view! { <Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/> <Stylesheet id="leptos" href="/pkg/errors_axum.css"/> <Router> <header> <h1>"Error Examples:"</h1> </header> <main> <Routes fallback=|| { let mut errors = Errors::default(); errors.insert_with_default_key(AppError::NotFound); view! { <ErrorTemplate errors/> } .into_view() }> <Route path=StaticSegment("") view=ExampleErrors/> </Routes> </main> </Router> } } #[component] pub fn ExampleErrors() -> impl IntoView { let generate_internal_error = ServerAction::<CauseInternalServerError>::new(); view! { <p> "These links will load 404 pages since they do not exist. Verify with browser development tools: " <br/> <a href="/404">"This links to a page that does not exist"</a><br/> <a href="/404" target="_blank">"Same link, but in a new tab"</a> </p> <p> "After pressing this button check browser network tools. Can be used even when WASM is blocked:" </p> <ActionForm action=generate_internal_error> <input name="error1" type="submit" value="Generate Internal Server Error"/> </ActionForm> <p>"The following <div> will always contain an error and cause this page to produce status 500. Check browser dev tools. "</p> <div> // note that the error boundaries could be placed above in the Router or lower down // in a particular route. The generated errors on the entire page contribute to the // final status code sent by the server when producing ssr pages. <ErrorBoundary fallback=|errors| view!{ <ErrorTemplate errors/>}> <ReturnsError/> </ErrorBoundary> </div> } } #[component] pub fn ReturnsError() -> impl IntoView { Err::<String, AppError>(AppError::InternalServerError) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/errors_axum/src/error_template.rs
examples/errors_axum/src/error_template.rs
use crate::errors::AppError; use leptos::{logging::log, prelude::*}; #[cfg(feature = "ssr")] use leptos_axum::ResponseOptions; // A basic function to display errors served by the error boundaries. // Feel free to do more complicated things here than just displaying them. #[component] pub fn ErrorTemplate(#[prop(into)] errors: Signal<Errors>) -> impl IntoView { // Get Errors from Signal // Downcast lets us take a type that implements `std::error::Error` let errors = Memo::new(move |_| { errors .get_untracked() .into_iter() .filter_map(|(_, v)| v.downcast_ref::<AppError>().cloned()) .collect::<Vec<_>>() }); log!("Errors: {:#?}", &*errors.read_untracked()); // Only the response code for the first error is actually sent from the server // this may be customized by the specific application #[cfg(feature = "ssr")] { let response = use_context::<ResponseOptions>(); if let Some(response) = response { response.set_status(errors.read_untracked()[0].status_code()); } } view! { <h1>{move || { if errors.read().len() > 1 { "Errors" } else { "Error" }}} </h1> {move || { errors.get() .into_iter() .map(|error| { let error_string = error.to_string(); let error_code= error.status_code(); view! { <h2>{error_code.to_string()}</h2> <p>"Error: " {error_string}</p> } }) .collect_view() }} } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/errors_axum/src/main.rs
examples/errors_axum/src/main.rs
#[cfg(feature = "ssr")] mod ssr_imports { use axum::extract::State; pub use axum::{ body::Body as AxumBody, extract::Path, http::Request, response::{IntoResponse, Response}, routing::get, Router, }; use errors_axum::landing::shell; pub use errors_axum::landing::App; use leptos::{config::LeptosOptions, context::provide_context}; pub use leptos_axum::{generate_route_list, LeptosRoutes}; // This custom handler lets us provide Axum State via context pub async fn custom_handler( Path(id): Path<String>, State(options): State<LeptosOptions>, req: Request<AxumBody>, ) -> Response { let handler = leptos_axum::render_app_to_stream_with_context( move || { provide_context(id.clone()); }, move || shell(options.clone()), ); handler(req).await.into_response() } } #[cfg(feature = "ssr")] #[tokio::main] async fn main() { use errors_axum::landing::shell; use leptos::config::get_configuration; use ssr_imports::*; // Setting this to None means we'll be using cargo-leptos and its env vars let conf = get_configuration(None).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(App); // build our application with a route let app = Router::new() .route("/special/{id}", get(custom_handler)) .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` println!("listening on http://{}", &addr); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve(listener, app.into_make_service()) .await .unwrap(); } // this is if we were using client-only rending with Trunk #[cfg(not(feature = "ssr"))] pub fn main() { // This example cannot be built as a trunk standalone CSR-only app. // The server is needed to demonstrate the error statuses. }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_isomorphic/src/lib.rs
examples/counter_isomorphic/src/lib.rs
pub mod counters; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use crate::counters::Counters; _ = console_log::init_with_level(log::Level::Debug); console_error_panic_hook::set_once(); leptos::mount::hydrate_body(Counters); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_isomorphic/src/counters.rs
examples/counter_isomorphic/src/counters.rs
use leptos::prelude::*; use leptos_router::{ components::{FlatRoutes, Route, Router, A}, StaticSegment, }; #[cfg(feature = "ssr")] use tracing::instrument; #[cfg(feature = "ssr")] pub mod ssr_imports { pub use broadcaster::BroadcastChannel; pub use std::sync::atomic::{AtomicI32, Ordering}; use std::sync::LazyLock; pub static COUNT: AtomicI32 = AtomicI32::new(0); pub static COUNT_CHANNEL: LazyLock<BroadcastChannel<i32>> = LazyLock::new(BroadcastChannel::<i32>::new); } #[server] #[cfg_attr(feature = "ssr", instrument)] pub async fn get_server_count() -> Result<i32, ServerFnError> { use ssr_imports::*; Ok(COUNT.load(Ordering::Relaxed)) } #[server] #[cfg_attr(feature = "ssr", instrument)] pub async fn adjust_server_count( delta: i32, msg: String, ) -> Result<i32, ServerFnError> { use ssr_imports::*; let new = COUNT.load(Ordering::Relaxed) + delta; COUNT.store(new, Ordering::Relaxed); _ = COUNT_CHANNEL.send(&new).await; println!("message = {:?}", msg); Ok(new) } #[server] #[cfg_attr(feature = "ssr", instrument)] pub async fn clear_server_count() -> Result<i32, ServerFnError> { use ssr_imports::*; COUNT.store(0, Ordering::Relaxed); _ = COUNT_CHANNEL.send(&0).await; Ok(0) } #[component] pub fn Counters() -> impl IntoView { view! { <Router> <header> <h1>"Server-Side Counters"</h1> <p>"Each of these counters stores its data in the same variable on the server."</p> <p> "The value is shared across connections. Try opening this is another browser tab to see what I mean." </p> </header> <nav> <ul> <li> <A href="">"Simple"</A> </li> <li> <A href="form">"Form-Based"</A> </li> <li> <A href="multi">"Multi-User"</A> </li> </ul> </nav> <main> <FlatRoutes fallback=|| "Not found."> <Route path=StaticSegment("") view=Counter/> <Route path=StaticSegment("form") view=FormCounter/> <Route path=StaticSegment("multi") view=MultiuserCounter/> </FlatRoutes> </main> </Router> } } // This is an example of "single-user" server functions // The counter value is loaded from the server, and re-fetches whenever // it's invalidated by one of the user's own actions // This is the typical pattern for a CRUD app #[component] pub fn Counter() -> impl IntoView { let dec = Action::new(|_: &()| adjust_server_count(-1, "decing".into())); let inc = Action::new(|_: &()| adjust_server_count(1, "incing".into())); let clear = Action::new(|_: &()| clear_server_count()); let counter = Resource::new( move || { ( dec.version().get(), inc.version().get(), clear.version().get(), ) }, |_| get_server_count(), ); view! { <div> <h2>"Simple Counter"</h2> <p> "This counter sets the value on the server and automatically reloads the new value." </p> <ErrorBoundary fallback=|errors| move || format!("Error: {:#?}", errors.get())> <div> <button on:click=move |_| { clear.dispatch(()); }>"Clear"</button> <button on:click=move |_| { dec.dispatch(()); }>"-1"</button> <span>"Value: " <Suspense>{counter} "!"</Suspense></span> <button on:click=move |_| { inc.dispatch(()); }>"+1"</button> </div> </ErrorBoundary> </div> } } // This is the <Form/> counter // It uses the same invalidation pattern as the plain counter, // but uses HTML forms to submit the actions #[component] pub fn FormCounter() -> impl IntoView { // these struct names are auto-generated by #[server] // they are just the PascalCased versions of the function names let adjust = ServerAction::<AdjustServerCount>::new(); let clear = ServerAction::<ClearServerCount>::new(); let counter = Resource::new( move || (adjust.version().get(), clear.version().get()), |_| { log::debug!("FormCounter running fetcher"); get_server_count() }, ); let value = move || { log::debug!("FormCounter looking for value"); counter.get().and_then(|n| n.ok()).unwrap_or(0) }; view! { <div> <h2>"Form Counter"</h2> <p> "This counter uses forms to set the value on the server. When progressively enhanced, it should behave identically to the “Simple Counter.”" </p> <div> // calling a server function is the same as POSTing to its API URL // so we can just do that with a form and button <ActionForm action=clear> <input type="submit" value="Clear"/> </ActionForm> // We can submit named arguments to the server functions // by including them as input values with the same name <ActionForm action=adjust> <input type="hidden" name="delta" value="-1"/> <input type="hidden" name="msg" value="form value down"/> <input type="submit" value="-1"/> </ActionForm> <span>"Value: " <Suspense>{value} "!"</Suspense></span> <ActionForm action=adjust> <input type="hidden" name="delta" value="1"/> <input type="hidden" name="msg" value="form value up"/> <input type="submit" value="+1"/> </ActionForm> </div> </div> } } // This is a kind of "multi-user" counter // It relies on a stream of server-sent events (SSE) for the counter's value // Whenever another user updates the value, it will update here // This is the primitive pattern for live chat, collaborative editing, etc. #[component] pub fn MultiuserCounter() -> impl IntoView { let dec = Action::new(|_: &()| adjust_server_count(-1, "dec dec goose".into())); let inc = Action::new(|_: &()| adjust_server_count(1, "inc inc moose".into())); let clear = Action::new(|_: &()| clear_server_count()); #[cfg(not(feature = "ssr"))] let multiplayer_value = { use futures::StreamExt; use send_wrapper::SendWrapper; let mut source = SendWrapper::new( gloo_net::eventsource::futures::EventSource::new("/api/events") .expect("couldn't connect to SSE stream"), ); let s = ReadSignal::from_stream_unsync( source .subscribe("message") .unwrap() .map(|value| match value { Ok(value) => value .1 .data() .as_string() .expect("expected string value"), Err(_) => "0".to_string(), }), ); on_cleanup(move || source.take().close()); s }; #[cfg(feature = "ssr")] let (multiplayer_value, _) = signal(None::<i32>); view! { <div> <h2>"Multi-User Counter"</h2> <p> "This one uses server-sent events (SSE) to live-update when other users make changes." </p> <div> <button on:click=move |_| { clear.dispatch(()); }>"Clear"</button> <button on:click=move |_| { dec.dispatch(()); }>"-1"</button> <span> "Multiplayer Value: " {move || multiplayer_value.get().unwrap_or_default()} </span> <button on:click=move |_| { inc.dispatch(()); }>"+1"</button> </div> </div> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_isomorphic/src/main.rs
examples/counter_isomorphic/src/main.rs
mod counters; use crate::counters::*; use actix_files::Files; use actix_web::*; use leptos_actix::{generate_route_list, LeptosRoutes}; #[get("/api/events")] async fn counter_events() -> impl Responder { use crate::counters::ssr_imports::*; use futures::StreamExt; let stream = futures::stream::once(async { crate::counters::get_server_count().await.unwrap_or(0) }) .chain(COUNT_CHANNEL.clone()) .map(|value| { Ok(web::Bytes::from(format!( "event: message\ndata: {value}\n\n" ))) as Result<web::Bytes> }); HttpResponse::Ok() .insert_header(("Content-Type", "text/event-stream")) .streaming(stream) } #[actix_web::main] async fn main() -> std::io::Result<()> { use leptos::prelude::*; // Setting this to None means we'll be using cargo-leptos and its env vars. // when not using cargo-leptos None must be replaced with Some("Cargo.toml") let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; println!("listening on http://{}", &addr); HttpServer::new(move || { // Generate the list of routes in your Leptos App let routes = generate_route_list(Counters); let leptos_options = &conf.leptos_options; let site_root = &leptos_options.site_root; App::new() .service(counter_events) .leptos_routes(routes, { let leptos_options = leptos_options.clone(); move || { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <AutoReload options=leptos_options.clone()/> <HydrationScripts options=leptos_options.clone()/> </head> <body> <Counters/> </body> </html> } }}) .service(Files::new("/", site_root.as_ref())) }) .bind(&addr)? .run() .await }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/islands_router/src/app.rs
examples/islands_router/src/app.rs
use leptos::{ either::{Either, EitherOf3}, prelude::*, }; use leptos_router::{ components::{Route, Router, Routes}, hooks::{use_params_map, use_query_map}, path, }; use serde::{Deserialize, Serialize}; pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=options.clone()/> <HydrationScripts options=options islands=true islands_router=true/> <link rel="stylesheet" id="leptos" href="/pkg/islands.css"/> <link rel="shortcut icon" type="image/ico" href="/favicon.ico"/> </head> <body> <App/> </body> </html> } } #[component] pub fn App() -> impl IntoView { view! { <Router> <header> <h1>"My Contacts"</h1> </header> <nav> <a href="/">"Home"</a> <a href="/about">"About"</a> </nav> <main> <Routes fallback=|| "Not found."> <Route path=path!("") view=Home/> <Route path=path!("user/:id") view=Details/> <Route path=path!("about") view=About/> </Routes> </main> </Router> } } #[server] pub async fn search(query: String) -> Result<Vec<User>, ServerFnError> { let users = tokio::fs::read_to_string("./mock_data.json").await?; let data: Vec<User> = serde_json::from_str(&users)?; let query = query.to_ascii_lowercase(); Ok(data .into_iter() .filter(|user| { user.first_name.to_ascii_lowercase().contains(&query) || user.last_name.to_ascii_lowercase().contains(&query) || user.email.to_ascii_lowercase().contains(&query) }) .collect()) } #[server] pub async fn delete_user(id: u32) -> Result<(), ServerFnError> { let users = tokio::fs::read_to_string("./mock_data.json").await?; let mut data: Vec<User> = serde_json::from_str(&users)?; data.retain(|user| user.id != id); let new_json = serde_json::to_string(&data)?; tokio::fs::write("./mock_data.json", &new_json).await?; Ok(()) } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct User { id: u32, first_name: String, last_name: String, email: String, } #[component] pub fn Home() -> impl IntoView { let q = use_query_map(); let q = move || q.read().get("q"); let data = Resource::new(q, |q| async move { if let Some(q) = q { search(q).await } else { Ok(vec![]) } }); let delete_user_action = ServerAction::<DeleteUser>::new(); let view = move || { Suspend::new(async move { let users = data.await.unwrap(); if q().is_none() { EitherOf3::A(view! { <p class="note">"Enter a search to begin viewing contacts."</p> }) } else if users.is_empty() { EitherOf3::B(view! { <p class="note">"No users found matching that search."</p> }) } else { EitherOf3::C(view! { <table> <tbody> <For each=move || users.clone() key=|user| user.id let:user > <tr> <td>{user.first_name}</td> <td>{user.last_name}</td> <td>{user.email}</td> <td> <a href=format!("/user/{}", user.id)>"Details"</a> <input type="checkbox"/> <ActionForm action=delete_user_action> <input type="hidden" name="id" value=user.id/> <input type="submit" value="Delete"/> </ActionForm> </td> </tr> </For> </tbody> </table> }) } }) }; view! { <section class="page"> <form method="GET" class="search"> <input type="search" name="q" value=q autofocus oninput="this.form.requestSubmit()"/> <input type="submit"/> </form> <Suspense fallback=|| view! { <p>"Loading..."</p> }>{view}</Suspense> </section> } } #[component] pub fn Details() -> impl IntoView { #[server] pub async fn get_user(id: u32) -> Result<Option<User>, ServerFnError> { let users = tokio::fs::read_to_string("./mock_data.json").await?; let data: Vec<User> = serde_json::from_str(&users)?; Ok(data.iter().find(|user| user.id == id).cloned()) } let params = use_params_map(); let id = move || { params .read() .get("id") .and_then(|id| id.parse::<u32>().ok()) }; let user = Resource::new(id, |id| async move { match id { None => Ok(None), Some(id) => get_user(id).await, } }); move || { Suspend::new(async move { user.await.map(|user| match user { None => Either::Left(view! { <section class="page"> <h2>"Not found."</h2> <p>"Sorry — we couldn’t find that user."</p> </section> }), Some(user) => Either::Right(view! { <section class="page"> <h2>{user.first_name} " " { user.last_name}</h2> <p class="email">{user.email}</p> </section> }), }) }) } } #[component] pub fn About() -> impl IntoView { view! { <section class="page"> <h2>"About"</h2> <p>"This demo is intended to show off an experimental “islands router” feature, which mimics the smooth transitions and user experience of client-side routing while minimizing the amount of code that actually runs in the browser."</p> <p>"By default, all the content in this application is only rendered on the server. But you can add client-side interactivity via islands like this one:"</p> <Counter/> </section> } } #[island] pub fn Counter() -> impl IntoView { let count = RwSignal::new(0); view! { <button class="counter" on:click=move |_| *count.write() += 1>{count}</button> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/islands_router/src/lib.rs
examples/islands_router/src/lib.rs
pub mod app; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { console_error_panic_hook::set_once(); leptos::mount::hydrate_islands(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/islands_router/src/main.rs
examples/islands_router/src/main.rs
use axum::Router; use islands::app::{shell, App}; use leptos::prelude::*; use leptos_axum::{generate_route_list, LeptosRoutes}; #[tokio::main] async fn main() { // Setting this to None means we'll be using cargo-leptos and its env vars let conf = get_configuration(None).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(App); // build our application with a route let app = Router::new() .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); println!("listening on http://{}", &addr); axum::serve(listener, app.into_make_service()) .await .unwrap(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/static_routing/src/app.rs
examples/static_routing/src/app.rs
use futures::{channel::mpsc, Stream}; use leptos::prelude::*; use leptos_meta::{MetaTags, *}; use leptos_router::{ components::{FlatRoutes, Redirect, Route, Router}, hooks::use_params, params::Params, path, static_routes::StaticRoute, SsrMode, }; use serde::{Deserialize, Serialize}; use std::path::Path; use thiserror::Error; pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <AutoReload options=options.clone()/> <HydrationScripts options/> <MetaTags/> </head> <body> <App/> </body> </html> } } #[component] pub fn App() -> impl IntoView { // Provides context that manages stylesheets, titles, meta tags, etc. provide_meta_context(); let fallback = || view! { "Page not found." }.into_view(); view! { <Stylesheet id="leptos" href="/pkg/ssr_modes.css"/> <Title text="Welcome to Leptos"/> <Meta name="color-scheme" content="dark light"/> <Router> <nav> <a href="/">"Home"</a> </nav> <main> <FlatRoutes fallback> <Route path=path!("/") view=HomePage ssr=SsrMode::Static( StaticRoute::new().regenerate(|_| watch_path(Path::new("./posts"))), ) /> <Route path=path!("/about") view=move || view! { <Redirect path="/"/> } ssr=SsrMode::Static(StaticRoute::new()) /> <Route path=path!("/post/:slug/") view=Post ssr=SsrMode::Static( StaticRoute::new() .prerender_params(|| async move { [("slug".into(), list_slugs().await.unwrap_or_default())] .into_iter() .collect() }) .regenerate(|params| { let slug = params.get("slug").unwrap(); watch_path(Path::new(&format!("./posts/{slug}.md"))) }), ) /> </FlatRoutes> </main> </Router> } } #[component] fn HomePage() -> impl IntoView { // load the posts let posts = Resource::new(|| (), |_| list_posts()); let posts = move || { posts .get() .map(|n| n.unwrap_or_default()) .unwrap_or_default() }; view! { <h1>"My Great Blog"</h1> <Suspense fallback=move || view! { <p>"Loading posts..."</p> }> <ul> <For each=posts key=|post| post.slug.clone() let:post> <li> <a href=format!("/post/{}/", post.slug)>{post.title.clone()}</a> </li> </For> </ul> </Suspense> } } #[derive(Params, Clone, Debug, PartialEq, Eq)] pub struct PostParams { slug: Option<String>, } #[component] fn Post() -> impl IntoView { let query = use_params::<PostParams>(); let slug = move || { query .get() .map(|q| q.slug.unwrap_or_default()) .map_err(|_| PostError::InvalidId) }; let post_resource = Resource::new_blocking(slug, |slug| async move { match slug { Err(e) => Err(e), Ok(slug) => get_post(slug) .await .map(|data| data.ok_or(PostError::PostNotFound)) .map_err(|e| PostError::ServerError(e.to_string())), } }); let post_view = move || { Suspend::new(async move { match post_resource.await { Ok(Ok(post)) => { Ok(view! { <h1>{post.title.clone()}</h1> <p>{post.content.clone()}</p> // since we're using async rendering for this page, // this metadata should be included in the actual HTML <head> // when it's first served <Title text=post.title/> <Meta name="description" content=post.content/> }) } Ok(Err(e)) | Err(e) => { Err(PostError::ServerError(e.to_string())) } } }) }; view! { <em>"The world's best content."</em> <Suspense fallback=move || view! { <p>"Loading post..."</p> }> <ErrorBoundary fallback=|errors| { #[cfg(feature = "ssr")] expect_context::<leptos_axum::ResponseOptions>() .set_status(http::StatusCode::NOT_FOUND); view! { <div class="error"> <h1>"Something went wrong."</h1> <ul> {move || { errors .get() .into_iter() .map(|(_, error)| view! { <li>{error.to_string()}</li> }) .collect::<Vec<_>>() }} </ul> </div> } }>{post_view}</ErrorBoundary> </Suspense> } } #[derive(Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum PostError { #[error("Invalid post ID.")] InvalidId, #[error("Post not found.")] PostNotFound, #[error("Server error: {0}.")] ServerError(String), } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Post { slug: String, title: String, content: String, } #[server] pub async fn list_slugs() -> Result<Vec<String>, ServerFnError> { use tokio::fs; use tokio_stream::{wrappers::ReadDirStream, StreamExt}; let files = ReadDirStream::new(fs::read_dir("./posts").await?); Ok(files .filter_map(|entry| { let entry = entry.ok()?; let path = entry.path(); if !path.is_file() { return None; } let extension = path.extension()?; if extension != "md" { return None; } let slug = path .file_name() .and_then(|n| n.to_str()) .unwrap_or_default() .replace(".md", ""); Some(slug) }) .collect() .await) } #[server] pub async fn list_posts() -> Result<Vec<Post>, ServerFnError> { println!("calling list_posts"); use futures::TryStreamExt; use tokio::fs; use tokio_stream::wrappers::ReadDirStream; let files = ReadDirStream::new(fs::read_dir("./posts").await?); files .try_filter_map(|entry| async move { let path = entry.path(); if !path.is_file() { return Ok(None); } let Some(extension) = path.extension() else { return Ok(None); }; if extension != "md" { return Ok(None); } let slug = path .file_name() .and_then(|n| n.to_str()) .unwrap_or_default() .replace(".md", ""); let content = fs::read_to_string(path).await?; // world's worst Markdown frontmatter parser let title = content.lines().next().unwrap().replace("# ", ""); Ok(Some(Post { slug, title, content, })) }) .try_collect() .await .map_err(ServerFnError::from) } #[server] pub async fn get_post(slug: String) -> Result<Option<Post>, ServerFnError> { println!("reading ./posts/{slug}.md"); let content = tokio::fs::read_to_string(&format!("./posts/{slug}.md")).await?; // world's worst Markdown frontmatter parser let title = content.lines().next().unwrap().replace("# ", ""); Ok(Some(Post { slug, title, content, })) } #[allow(unused)] // path is not used in non-SSR fn watch_path(path: &Path) -> impl Stream<Item = ()> { #[allow(unused)] let (mut tx, rx) = mpsc::channel(0); #[cfg(feature = "ssr")] { use notify::{RecursiveMode, Watcher}; let mut watcher = notify::recommended_watcher(move |res: Result<_, _>| { if res.is_ok() { // if this fails, it's because the buffer is full // this means we've already notified before it's regenerated, // so this page will be queued for regeneration already _ = tx.try_send(()); } }) .expect("could not create watcher"); // Add a path to be watched. All files and directories at that path and // below will be monitored for changes. watcher .watch(path, RecursiveMode::NonRecursive) .expect("could not watch path"); // we want this to run as long as the server is alive std::mem::forget(watcher); } rx }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/static_routing/src/lib.rs
examples/static_routing/src/lib.rs
pub mod app; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use app::*; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/static_routing/src/main.rs
examples/static_routing/src/main.rs
#[cfg(feature = "ssr")] #[tokio::main] async fn main() { use axum::Router; use leptos::{logging::log, prelude::*}; use leptos_axum::{generate_route_list_with_ssg, LeptosRoutes}; use static_routing::app::*; let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; let leptos_options = conf.leptos_options; // Generate the list of routes in your Leptos App let (routes, static_routes) = generate_route_list_with_ssg({ let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }); static_routes.generate(&leptos_options).await; let app = Router::new() .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` log!("listening on http://{}", &addr); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); axum::serve(listener, app.into_make_service()) .await .unwrap(); } #[cfg(not(feature = "ssr"))] pub fn main() { // no client-side main function // unless we want this to work with e.g., Trunk for pure client-side testing // see lib.rs for hydration function instead }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/error_boundary/src/lib.rs
examples/error_boundary/src/lib.rs
use leptos::prelude::*; #[component] pub fn App() -> impl IntoView { let (value, set_value) = signal("".parse::<i32>()); view! { <h1>"Error Handling"</h1> <label> "Type an integer (or something that's not an integer!)" <input type="number" value=move || value.get().unwrap_or_default() // when input changes, try to parse a number from the input on:input:target=move |ev| set_value.set(ev.target().value().parse::<i32>()) /> // If an `Err(_) has been rendered inside the <ErrorBoundary/>, // the fallback will be displayed. Otherwise, the children of the // <ErrorBoundary/> will be displayed. // the fallback receives a signal containing current errors <ErrorBoundary fallback=|errors| { let errors = errors.clone(); view! { <div class="error"> <p>"Not an integer! Errors: "</p> // we can render a list of errors // as strings, if we'd like <ul> {move || { errors .read() .iter() .map(|(_, e)| view! { <li>{e.to_string()}</li> }) .collect::<Vec<_>>() }} </ul> </div> } }> <p> "You entered " // because `value` is `Result<i32, _>`, // it will render the `i32` if it is `Ok`, // and render nothing and trigger the error boundary // if it is `Err`. It's a signal, so this will dynamically // update when `value` changes <strong>{value}</strong> </p> </ErrorBoundary> </label> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/error_boundary/src/main.rs
examples/error_boundary/src/main.rs
use error_boundary::*; use leptos::prelude::*; pub fn main() { _ = console_log::init_with_level(log::Level::Debug); console_error_panic_hook::set_once(); mount_to_body(App) }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/router/src/lib.rs
examples/router/src/lib.rs
mod api; use crate::api::*; use leptos::{either::Either, prelude::*}; use leptos_router::{ components::{ Form, Outlet, ParentRoute, ProtectedRoute, Redirect, Route, Router, Routes, RoutingProgress, A, }, hooks::{use_navigate, use_params, use_query_map}, params::Params, }; use leptos_router_macro::path; use std::time::Duration; use tracing::info; #[derive(Copy, Clone, Debug, PartialEq, Eq)] struct ExampleContext(i32); #[component] pub fn RouterExample() -> impl IntoView { info!("rendering <RouterExample/>"); // contexts are passed down through the route tree provide_context(ExampleContext(0)); // this signal will be used to set whether we are allowed to access a protected route let (logged_in, set_logged_in) = signal(true); let (is_routing, set_is_routing) = signal(false); view! { <Router set_is_routing> // shows a progress bar while async data are loading <div class="routing-progress"> <RoutingProgress is_routing max_time=Duration::from_millis(250) /> </div> <nav> // ordinary <a> elements can be used for client-side navigation // using <A> has two effects: // 1) ensuring that relative routing works properly for nested routes // 2) setting the `aria-current` attribute on the current link, // for a11y and styling purposes <A href="/">"Contacts"</A> <A href="/about">"About"</A> <A href="/settings">"Settings"</A> <A href="/redirect-home">"Redirect to Home"</A> <button on:click=move |_| { set_logged_in.update(|n| *n = !*n) }>{move || if logged_in.get() { "Log Out" } else { "Log In" }}</button> </nav> <main> <Routes transition=true fallback=|| "This page could not be found."> // paths can be created using the path!() macro, or provided as types like // StaticSegment("about") <Route path=path!("about") view=About /> <ProtectedRoute path=path!("settings") condition=move || Some(logged_in.get()) redirect_path=|| "/" view=Settings /> <Route path=path!("redirect-home") view=|| view! { <Redirect path="/" /> } /> <ContactRoutes /> </Routes> </main> </Router> } } // You can define other routes in their own component. // Routes implement the MatchNestedRoutes #[component(transparent)] pub fn ContactRoutes() -> impl leptos_router::MatchNestedRoutes + Clone { view! { <ParentRoute path=path!("") view=ContactList> <Route path=path!("/") view=|| "Select a contact." /> <Route path=path!("/:id") view=Contact /> </ParentRoute> } .into_inner() } #[component] pub fn ContactList() -> impl IntoView { info!("rendering <ContactList/>"); // contexts are passed down through the route tree provide_context(ExampleContext(42)); Owner::on_cleanup(|| { info!("cleaning up <ContactList/>"); }); let query = use_query_map(); let search = Memo::new(move |_| query.read().get("q").unwrap_or_default()); let contacts = AsyncDerived::new(move || { leptos::logging::log!("reloading contacts"); get_contacts(search.get()) }); let contacts = move || { Suspend::new(async move { // this data doesn't change frequently so we can use .map().collect() instead of a keyed <For/> contacts.await .into_iter() .map(|contact| { view! { <li> <A href=contact.id.to_string()> <span>{contact.first_name} " " {contact.last_name}</span> </A> </li> } }) .collect::<Vec<_>>() }) }; view! { <div class="contact-list"> <h1>"Contacts"</h1> <Suspense fallback=move || view! { <p>"Loading contacts..."</p> }> <ul>{contacts}</ul> </Suspense> <Outlet /> </div> } } #[derive(Params, PartialEq, Clone, Debug)] pub struct ContactParams { // Params isn't implemented for usize, only Option<usize> id: Option<usize>, } #[component] pub fn Contact() -> impl IntoView { info!("rendering <Contact/>"); info!( "ExampleContext should be Some(42). It is {:?}", use_context::<ExampleContext>() ); Owner::on_cleanup(|| { info!("cleaning up <Contact/>"); }); let params = use_params::<ContactParams>(); let contact = AsyncDerived::new(move || { get_contact( params .get() .map(|params| params.id.unwrap_or_default()) .ok(), ) }); let contact_display = move || { Suspend::new(async move { match contact.await { None => Either::Left( view! { <p>"No contact with this ID was found."</p> }, ), Some(contact) => Either::Right(view! { <section class="card"> <h1>{contact.first_name} " " {contact.last_name}</h1> <p>{contact.address_1} <br /> {contact.address_2}</p> </section> }), } }) }; view! { <div class="contact"> <Transition fallback=move || { view! { <p>"Loading..."</p> } }>{contact_display}</Transition> </div> } } #[component] pub fn About() -> impl IntoView { info!("rendering <About/>"); Owner::on_cleanup(|| { info!("cleaning up <About/>"); }); info!( "ExampleContext should be Some(0). It is {:?}", use_context::<ExampleContext>() ); // use_navigate allows you to navigate programmatically by calling a function let navigate = use_navigate(); // note: this is just an illustration of how to use `use_navigate` // <button on:click> to navigate is an *anti-pattern* // you should ordinarily use a link instead, // both semantically and so your link will work before WASM loads view! { <button on:click=move |_| navigate("/", Default::default())>"Home"</button> <h1>"About"</h1> <p> "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </p> } } #[component] pub fn Settings() -> impl IntoView { info!("rendering <Settings/>"); Owner::on_cleanup(|| { info!("cleaning up <Settings/>"); }); view! { <h1>"Settings"</h1> <Form action=""> <fieldset> <legend>"Name"</legend> <input type="text" name="first_name" placeholder="First" /> <input type="text" name="last_name" placeholder="Last" /> </fieldset> <input type="submit" /> <p> "This uses the " <code>"<Form/>"</code> " component, which enhances forms by using client-side navigation for " <code>"GET"</code> " requests, and client-side requests for " <code>"POST"</code> " requests, without requiring a full page reload." </p> </Form> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/router/src/api.rs
examples/router/src/api.rs
use futures::{ channel::oneshot::{self, Canceled}, Future, }; use leptos::leptos_dom::helpers::set_timeout; use serde::{Deserialize, Serialize}; use std::time::Duration; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ContactSummary { pub id: usize, pub first_name: String, pub last_name: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Contact { pub id: usize, pub first_name: String, pub last_name: String, pub address_1: String, pub address_2: String, pub city: String, pub state: String, pub zip: String, pub email: String, pub phone: String, } pub async fn get_contacts(_search: String) -> Vec<ContactSummary> { // fake an API call with an artificial delay _ = delay(Duration::from_millis(300)).await; vec![ ContactSummary { id: 0, first_name: "Bill".into(), last_name: "Smith".into(), }, ContactSummary { id: 1, first_name: "Tim".into(), last_name: "Jones".into(), }, ContactSummary { id: 2, first_name: "Sally".into(), last_name: "Stevens".into(), }, ] } pub async fn get_contact(id: Option<usize>) -> Option<Contact> { // fake an API call with an artificial delay _ = delay(Duration::from_millis(500)).await; match id { Some(0) => Some(Contact { id: 0, first_name: "Bill".into(), last_name: "Smith".into(), address_1: "12 Mulberry Lane".into(), address_2: "".into(), city: "Boston".into(), state: "MA".into(), zip: "02129".into(), email: "bill@smith.com".into(), phone: "617-121-1221".into(), }), Some(1) => Some(Contact { id: 1, first_name: "Tim".into(), last_name: "Jones".into(), address_1: "56 Main Street".into(), address_2: "".into(), city: "Chattanooga".into(), state: "TN".into(), zip: "13371".into(), email: "timjones@lmail.com".into(), phone: "232-123-1337".into(), }), Some(2) => Some(Contact { id: 2, first_name: "Sally".into(), last_name: "Stevens".into(), address_1: "404 E 123rd St".into(), address_2: "Apt 7E".into(), city: "New York".into(), state: "NY".into(), zip: "10082".into(), email: "sally.stevens@wahoo.net".into(), phone: "242-121-3789".into(), }), _ => None, } } fn delay( duration: Duration, ) -> impl Future<Output = Result<(), Canceled>> + Send { let (tx, rx) = oneshot::channel(); set_timeout( move || { _ = tx.send(()); }, duration, ); rx }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/router/src/main.rs
examples/router/src/main.rs
use leptos::prelude::*; use router::*; use tracing_subscriber::fmt; use tracing_subscriber_wasm::MakeConsoleWriter; pub fn main() { fmt() .with_writer( MakeConsoleWriter::default() .map_trace_level_to(tracing::Level::DEBUG), ) .without_time() .init(); console_error_panic_hook::set_once(); mount_to_body(RouterExample); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/server_fns_axum/src/app.rs
examples/server_fns_axum/src/app.rs
use futures::{Sink, Stream, StreamExt}; use http::Method; use leptos::{html::Input, prelude::*, task::spawn_local}; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use server_fn::{ client::{browser::BrowserClient, Client}, codec::{ Encoding, FromReq, FromRes, GetUrl, IntoReq, IntoRes, MultipartData, MultipartFormData, Postcard, Rkyv, RkyvEncoding, SerdeLite, StreamingText, TextStream, }, error::{FromServerFnError, IntoAppError, ServerFnErrorErr}, request::{browser::BrowserRequest, ClientReq, Req}, response::{browser::BrowserResponse, ClientRes, TryRes}, ContentType, Format, FormatType, }; use std::future::Future; #[cfg(feature = "ssr")] use std::sync::{ atomic::{AtomicU8, Ordering}, Mutex, }; use strum::{Display, EnumString}; use wasm_bindgen::JsCast; use web_sys::{FormData, HtmlFormElement, SubmitEvent}; pub fn shell(options: LeptosOptions) -> impl IntoView { view! { <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <AutoReload options=options.clone() /> <HydrationScripts options /> <meta name="color-scheme" content="dark light" /> <link rel="shortcut icon" type="image/ico" href="/favicon.ico" /> <link rel="stylesheet" id="leptos" href="/pkg/server_fns_axum.css" /> </head> <body> <App /> </body> </html> } } #[component] pub fn App() -> impl IntoView { view! { <header> <h1>"Server Function Demo"</h1> </header> <main> <HomePage /> </main> } } #[component] pub fn HomePage() -> impl IntoView { view! { <h2>"Some Simple Server Functions"</h2> <SpawnLocal /> <WithAnAction /> <WithActionForm /> <h2>"Custom Error Types"</h2> <CustomErrorTypes /> <h2>"Alternative Encodings"</h2> <ServerFnArgumentExample /> <RkyvExample /> <PostcardExample /> <FileUpload /> <FileUploadWithProgress /> <FileWatcher /> <CustomEncoding /> <CustomClientExample /> } } /// A server function is really just an API call to your server. But it provides a plain async /// function as a wrapper around that. This means you can call it like any other async code, just /// by spawning a task with `spawn_local`. /// /// In reality, you usually want to use a resource to load data from the server or an action to /// mutate data on the server. But a simple `spawn_local` can make it more obvious what's going on. #[component] pub fn SpawnLocal() -> impl IntoView { /// A basic server function can be called like any other async function. /// /// You can define a server function at any scope. This one, for example, is only available /// inside the SpawnLocal component. **However**, note that all server functions are publicly /// available API endpoints: This scoping means you can only call this server function /// from inside this component, but it is still available at its URL to any caller, from within /// your app or elsewhere. #[server] pub async fn shouting_text(input: String) -> Result<String, ServerFnError> { // insert a simulated wait tokio::time::sleep(std::time::Duration::from_millis(250)).await; Ok(input.to_ascii_uppercase()) } let input_ref = NodeRef::<Input>::new(); let (shout_result, set_shout_result) = signal("Click me".to_string()); view! { <h3>Using <code>spawn_local</code></h3> <p> "You can call a server function by using " <code>"spawn_local"</code> " in an event listener. " "Clicking this button should alert with the uppercase version of the input." </p> <input node_ref=input_ref placeholder="Type something here." /> <button on:click=move |_| { let value = input_ref.get().unwrap().value(); spawn_local(async move { let uppercase_text = shouting_text(value).await.unwrap_or_else(|e| e.to_string()); set_shout_result.set(uppercase_text); }); }> {shout_result} </button> } } /// Pretend this is a database and we're storing some rows in memory! /// This exists only on the server. #[cfg(feature = "ssr")] static ROWS: Mutex<Vec<String>> = Mutex::new(Vec::new()); /// Imagine this server function mutates some state on the server, like a database row. /// Every third time, it will return an error. /// /// This kind of mutation is often best handled by an Action. /// Remember, if you're loading data, use a resource; if you're running an occasional action, /// use an action. #[server] pub async fn add_row(text: String) -> Result<usize, ServerFnError> { static N: AtomicU8 = AtomicU8::new(0); // insert a simulated wait tokio::time::sleep(std::time::Duration::from_millis(250)).await; let nth_run = N.fetch_add(1, Ordering::Relaxed); // this will print on the server, like any server function println!("Adding {text:?} to the database!"); if nth_run % 3 == 2 { Err(ServerFnError::new("Oh no! Couldn't add to database!")) } else { let mut rows = ROWS.lock().unwrap(); rows.push(text); Ok(rows.len()) } } /// Simply returns the number of rows. #[server] pub async fn get_rows() -> Result<usize, ServerFnError> { // insert a simulated wait tokio::time::sleep(std::time::Duration::from_millis(250)).await; Ok(ROWS.lock().unwrap().len()) } /// An action abstracts over the process of spawning a future and setting a signal when it /// resolves. Its .input() signal holds the most recent argument while it's still pending, /// and its .value() signal holds the most recent result. Its .version() signal can be fed /// into a resource, telling it to refetch whenever the action has successfully resolved. /// /// This makes actions useful for mutations, i.e., some server function that invalidates /// loaded previously loaded from another server function. #[component] pub fn WithAnAction() -> impl IntoView { let input_ref = NodeRef::<Input>::new(); // a server action can be created by using the server function's type name as a generic // the type name defaults to the PascalCased function name let action = ServerAction::<AddRow>::new(); // this resource will hold the total number of rows // passing it action.version() means it will refetch whenever the action resolves successfully let row_count = Resource::new(move || action.version().get(), |_| get_rows()); view! { <h3>Using <code>Action::new</code></h3> <p> "Some server functions are conceptually \"mutations,\", which change something on the server. " "These often work well as actions." </p> <input node_ref=input_ref placeholder="Type something here." /> <button on:click=move |_| { let text = input_ref.get().unwrap().value(); action.dispatch(text.into()); }> Submit </button> <p>You submitted: {move || format!("{:?}", action.input().get())}</p> <p>The result was: {move || format!("{:?}", action.value().get())}</p> <Transition> <p>Total rows: {row_count}</p> </Transition> } } /// An <ActionForm/> lets you do the same thing as dispatching an action, but automates the /// creation of the dispatched argument struct using a <form>. This means it also gracefully /// degrades well when JS/WASM are not available. /// /// Try turning off WASM in your browser. The form still works, and successfully displays the error /// message if the server function returns an error. Otherwise, it loads the new resource data. #[component] pub fn WithActionForm() -> impl IntoView { let action = ServerAction::<AddRow>::new(); let row_count = Resource::new(move || action.version().get(), |_| get_rows()); view! { <h3>Using <code>"<ActionForm/>"</code></h3> <p> <code>"<ActionForm/>"</code> "lets you use an HTML " <code>"<form>"</code> "to call a server function in a way that gracefully degrades." </p> <ActionForm action> <input // the `name` of the input corresponds to the argument name name="text" placeholder="Type something here." /> <button>Submit</button> </ActionForm> <p>You submitted: {move || format!("{:?}", action.input().get())}</p> <p>The result was: {move || format!("{:?}", action.value().get())}</p> <Transition> archive underaligned: need alignment 4 but have alignment 1 <p>Total rows: {row_count}</p> </Transition> } } /// The plain `#[server]` macro gives sensible defaults for the settings needed to create a server /// function, but those settings can also be customized. For example, you can set a specific unique /// path rather than the hashed path, or you can choose a different combination of input and output /// encodings. /// /// Arguments to the server macro can be specified as named key-value pairs, like `name = value`. #[server( // this server function will be exposed at /api2/custom_path prefix = "/api2", endpoint = "custom_path", // it will take its arguments as a URL-encoded GET request (useful for caching) input = GetUrl, // it will return its output using SerdeLite // (this needs to be enabled with the `serde-lite` feature on the `server_fn` crate output = SerdeLite, )] // You can use the `#[middleware]` macro to add appropriate middleware // In this case, any `tower::Layer` that takes services of `Request<Body>` will work #[middleware(crate::middleware::LoggingLayer)] pub async fn length_of_input(input: String) -> Result<usize, ServerFnError> { println!("2. Running server function."); // insert a simulated wait tokio::time::sleep(std::time::Duration::from_millis(250)).await; Ok(input.len()) } #[component] pub fn ServerFnArgumentExample() -> impl IntoView { let input_ref = NodeRef::<Input>::new(); let (result, set_result) = signal(0); view! { <h3>Custom arguments to the <code>#[server]</code> " macro"</h3> <p>This example shows how to specify additional behavior, including:</p> <ul> <li>Specific server function <strong>paths</strong></li> <li>Mixing and matching input and output <strong>encodings</strong></li> <li>Adding custom <strong>middleware</strong>on a per-server-fn basis</li> </ul> <input node_ref=input_ref placeholder="Type something here." /> <button on:click=move |_| { let value = input_ref.get().unwrap().value(); spawn_local(async move { let length = length_of_input(value).await.unwrap_or(0); set_result.set(length); }); }> Click to see length </button> <p>Length is {result}</p> } } /// `server_fn` supports a wide variety of input and output encodings, each of which can be /// referred to as a PascalCased struct name /// - Toml /// - Cbor /// - Rkyv /// - etc. #[server( input = Rkyv, output = Rkyv )] pub async fn rkyv_example(input: String) -> Result<String, ServerFnError> { // insert a simulated wait tokio::time::sleep(std::time::Duration::from_millis(250)).await; Ok(input.to_ascii_uppercase()) } #[component] pub fn RkyvExample() -> impl IntoView { let input_ref = NodeRef::<Input>::new(); let (input, set_input) = signal(String::new()); let rkyv_result = Resource::new(move || input.get(), rkyv_example); view! { <h3>Using <code>rkyv</code>encoding</h3> <input node_ref=input_ref placeholder="Type something here." /> <button on:click=move |_| { let value = input_ref.get().unwrap().value(); set_input.set(value); }> Click to capitalize </button> <p>{input}</p> <Transition>{rkyv_result}</Transition> } } #[component] pub fn FileUpload() -> impl IntoView { /// A simple file upload function, which does just returns the length of the file. /// /// On the server, this uses the `multer` crate, which provides a streaming API. #[server( input = MultipartFormData, )] pub async fn file_length( data: MultipartData, ) -> Result<usize, ServerFnError> { // `.into_inner()` returns the inner `multer` stream // it is `None` if we call this on the client, but always `Some(_)` on the server, so is safe to // unwrap let mut data = data.into_inner().unwrap(); // this will just measure the total number of bytes uploaded let mut count = 0; while let Ok(Some(mut field)) = data.next_field().await { println!("\n[NEXT FIELD]\n"); let name = field.name().unwrap_or_default().to_string(); println!(" [NAME] {name}"); while let Ok(Some(chunk)) = field.chunk().await { let len = chunk.len(); count += len; println!(" [CHUNK] {len}"); // in a real server function, you'd do something like saving the file here } } Ok(count) } let upload_action = Action::new_local(|data: &FormData| { // `MultipartData` implements `From<FormData>` file_length(data.clone().into()) }); view! { <h3>File Upload</h3> <p>Uploading files is fairly easy using multipart form data.</p> <form on:submit=move |ev: SubmitEvent| { ev.prevent_default(); let target = ev.target().unwrap().unchecked_into::<HtmlFormElement>(); let form_data = FormData::new_with_form(&target).unwrap(); upload_action.dispatch_local(form_data); }> <input type="file" name="file_to_upload" /> <input type="submit" /> </form> <p> {move || { if upload_action.input().read().is_none() && upload_action.value().read().is_none() { "Upload a file.".to_string() } else if upload_action.pending().get() { "Uploading...".to_string() } else if let Some(Ok(value)) = upload_action.value().get() { value.to_string() } else { format!("{:?}", upload_action.value().get()) } }} </p> } } /// This component uses server functions to upload a file, while streaming updates on the upload /// progress. #[component] pub fn FileUploadWithProgress() -> impl IntoView { /// In theory, you could create a single server function which /// 1) received multipart form data /// 2) returned a stream that contained updates on the progress /// /// In reality, browsers do not actually support duplexing requests in this way. In other /// words, every existing browser actually requires that the request stream be complete before /// it begins processing the response stream. /// /// Instead, we can create two separate server functions: /// 1) one that receives multipart form data and begins processing the upload /// 2) a second that returns a stream of updates on the progress /// /// This requires us to store some global state of all the uploads. In a real app, you probably /// shouldn't do exactly what I'm doing here in the demo. For example, this map just /// distinguishes between files by filename, not by user. #[cfg(feature = "ssr")] mod progress { use async_broadcast::{broadcast, Receiver, Sender}; use dashmap::DashMap; use futures::Stream; use std::sync::LazyLock; struct File { total: usize, tx: Sender<usize>, rx: Receiver<usize>, } static FILES: LazyLock<DashMap<String, File>> = LazyLock::new(DashMap::new); pub async fn add_chunk(filename: &str, len: usize) { println!("[{filename}]\tadding {len}"); let mut entry = FILES.entry(filename.to_string()).or_insert_with(|| { println!("[{filename}]\tinserting channel"); // NOTE: this channel capacity is set arbitrarily for this demo code. // it allows for up to exactly 1048 chunks to be sent, which sets an upper cap // on upload size (the precise details vary by client) // in a real system, you will want to create some more reasonable ways of // sending and sharing notifications // // see https://github.com/leptos-rs/leptos/issues/4397 for related discussion let (tx, rx) = broadcast(1048); File { total: 0, tx, rx } }); entry.total += len; let new_total = entry.total; // we're about to do an async broadcast, so we don't want to hold a lock across it let tx = entry.tx.clone(); drop(entry); // now we send the message and don't have to worry about it tx.broadcast(new_total) .await .expect("couldn't send a message over channel"); } pub fn for_file(filename: &str) -> impl Stream<Item = usize> { let entry = FILES.entry(filename.to_string()).or_insert_with(|| { println!("[{filename}]\tinserting channel"); let (tx, rx) = broadcast(128); File { total: 0, tx, rx } }); entry.rx.clone() } } #[server( input = MultipartFormData, )] pub async fn upload_file(data: MultipartData) -> Result<(), ServerFnError> { let mut data = data.into_inner().unwrap(); while let Ok(Some(mut field)) = data.next_field().await { let name = field.file_name().expect("no filename on field").to_string(); while let Ok(Some(chunk)) = field.chunk().await { let len = chunk.len(); println!("[{name}]\t{len}"); progress::add_chunk(&name, len).await; // in a real server function, you'd do something like saving the file here } } Ok(()) } #[server(output = StreamingText)] pub async fn file_progress( filename: String, ) -> Result<TextStream, ServerFnError> { println!("getting progress on {filename}"); // get the stream of current length for the file let progress = progress::for_file(&filename); // separate each number with a newline // the HTTP response might pack multiple lines of this into a single chunk // we need some way of dividing them up let progress = progress.map(|bytes| Ok(format!("{bytes}\n"))); Ok(TextStream::new(progress)) } let (filename, set_filename) = signal(None); let (max, set_max) = signal(None); let (current, set_current) = signal(None); let on_submit = move |ev: SubmitEvent| { ev.prevent_default(); let target = ev.target().unwrap().unchecked_into::<HtmlFormElement>(); let form_data = FormData::new_with_form(&target).unwrap(); let file = form_data .get("file_to_upload") .unchecked_into::<web_sys::File>(); let filename = file.name(); let size = file.size() as usize; set_filename.set(Some(filename.clone())); set_max.set(Some(size)); set_current.set(None); spawn_local(async move { let mut progress = file_progress(filename) .await .expect("couldn't initialize stream") .into_inner(); while let Some(Ok(len)) = progress.next().await { // the TextStream from the server function will be a series of `usize` values // however, the response itself may pack those chunks into a smaller number of // chunks, each with more text in it // so we've padded them with newspace, and will split them out here // each value is the latest total, so we'll just take the last one let len = len .split('\n') .filter(|n| !n.is_empty()) .next_back() .expect( "expected at least one non-empty value from \ newline-delimited rows", ) .parse::<usize>() .expect("invalid length"); set_current.set(Some(len)); } }); spawn_local(async move { upload_file(form_data.into()) .await .expect("couldn't upload file"); }); }; view! { <h3>File Upload with Progress</h3> <p>A file upload with progress can be handled with two separate server functions.</p> <aside>See the doc comment on the component for an explanation.</aside> <form on:submit=on_submit> <input type="file" name="file_to_upload" /> <input type="submit" /> </form> {move || filename.get().map(|filename| view! { <p>Uploading {filename}</p> })} <ShowLet some=max let:max> <progress max=max value=move || current.get().unwrap_or_default() ></progress> </ShowLet> } } #[component] pub fn FileWatcher() -> impl IntoView { #[server(input = GetUrl, output = StreamingText)] pub async fn watched_files() -> Result<TextStream, ServerFnError> { use notify::{ Config, Error, Event, RecommendedWatcher, RecursiveMode, Watcher, }; use std::path::Path; let (tx, rx) = futures::channel::mpsc::unbounded(); let mut watcher = RecommendedWatcher::new( move |res: Result<Event, Error>| { if let Ok(ev) = res { if let Some(path) = ev.paths.last() { let filename = path .file_name() .unwrap() .to_str() .unwrap() .to_string(); _ = tx.unbounded_send(filename); //res); } } }, Config::default(), )?; watcher .watch(Path::new("./watched_files"), RecursiveMode::Recursive)?; std::mem::forget(watcher); Ok(TextStream::from(rx)) } let (files, set_files) = signal(Vec::new()); Effect::new(move |_| { spawn_local(async move { while let Some(res) = watched_files().await.unwrap().into_inner().next().await { if let Ok(filename) = res { set_files.update(|n| n.push(filename)); } } }); }); view! { <h3>Watching files and returning a streaming response</h3> <p>Files changed since you loaded the page:</p> <ul> {move || { files .get() .into_iter() .map(|file| { view! { <li> <code>{file}</code> </li> } }) .collect::<Vec<_>>() }} </ul> <p> <em> Add or remove some text files in the <code>watched_files</code> directory and see the list of changes here. </em> </p> } } /// The `ServerFnError` type is generic over a custom error type, which defaults to `NoCustomError` /// for backwards compatibility and to support the most common use case. /// /// A custom error type should implement `FromStr` and `Display`, which allows it to be converted /// into and from a string easily to be sent over the network. It does *not* need to implement /// `Serialize` and `Deserialize`, although these can be used to generate the `FromStr`/`Display` /// implementations if you'd like. However, it's much lighter weight to use something like `strum` /// simply to generate those trait implementations. #[server] pub async fn ascii_uppercase(text: String) -> Result<String, MyErrors> { other_error()?; Ok(ascii_uppercase_inner(text)?) } pub fn other_error() -> Result<(), String> { Ok(()) } pub fn ascii_uppercase_inner(text: String) -> Result<String, InvalidArgument> { if text.len() < 5 { Err(InvalidArgument::TooShort) } else if text.len() > 15 { Err(InvalidArgument::TooLong) } else if text.is_ascii() { Ok(text.to_ascii_uppercase()) } else { Err(InvalidArgument::NotAscii) } } #[server] pub async fn ascii_uppercase_classic( text: String, ) -> Result<String, ServerFnError<InvalidArgument>> { Ok(ascii_uppercase_inner(text)?) } // The EnumString and Display derive macros are provided by strum #[derive( thiserror::Error, Debug, Clone, Display, EnumString, Serialize, Deserialize, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, )] pub enum InvalidArgument { TooShort, TooLong, NotAscii, } #[derive( thiserror::Error, Debug, Clone, Display, Serialize, Deserialize, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, )] pub enum MyErrors { InvalidArgument(InvalidArgument), ServerFnError(ServerFnErrorErr), Other(String), } impl From<InvalidArgument> for MyErrors { fn from(value: InvalidArgument) -> Self { MyErrors::InvalidArgument(value) } } impl From<String> for MyErrors { fn from(value: String) -> Self { MyErrors::Other(value) } } impl FromServerFnError for MyErrors { type Encoder = RkyvEncoding; fn from_server_fn_error(value: ServerFnErrorErr) -> Self { MyErrors::ServerFnError(value) } } #[component] pub fn CustomErrorTypes() -> impl IntoView { let input_ref = NodeRef::<Input>::new(); let (result, set_result) = signal(None); let (result_classic, set_result_classic) = signal(None); view! { <h3>Using custom error types</h3> <p> "Server functions can use a custom error type that is preserved across the network boundary." </p> <p> "Try typing a message that is between 5 and 15 characters of ASCII text below. Then try breaking \ the rules!" </p> <input node_ref=input_ref placeholder="Type something here." /> <button on:click=move |_| { let value = input_ref.get().unwrap().value(); spawn_local(async move { let data = ascii_uppercase(value.clone()).await; let data_classic = ascii_uppercase_classic(value).await; set_result.set(Some(data)); set_result_classic.set(Some(data_classic)); }); }> "Submit" </button> <p>{move || format!("{:?}", result.get())}</p> <p>{move || format!("{:?}", result_classic.get())}</p> } } /// Server function encodings are just types that implement a few traits. /// This means that you can implement your own encodings, by implementing those traits! /// /// Here, we'll create a custom encoding that serializes and deserializes the server fn /// using TOML. Why would you ever want to do this? I don't know, but you can! pub struct Toml; /// A newtype wrapper around server fn data that will be TOML-encoded. /// /// This is needed because of Rust rules around implementing foreign traits for foreign types. /// It will be fed into the `custom = ` argument to the server fn below. #[derive(Serialize, Deserialize)] pub struct TomlEncoded<T>(T); impl ContentType for Toml { const CONTENT_TYPE: &'static str = "application/toml"; } impl FormatType for Toml { const FORMAT_TYPE: Format = Format::Text; } impl Encoding for Toml { const METHOD: Method = Method::POST; } impl<T, Request, Err> IntoReq<Toml, Request, Err> for TomlEncoded<T> where Request: ClientReq<Err>, T: Serialize, Err: FromServerFnError, { fn into_req(self, path: &str, accepts: &str) -> Result<Request, Err> { let data = toml::to_string(&self.0).map_err(|e| { ServerFnErrorErr::Serialization(e.to_string()).into_app_error() })?; Request::try_new_post(path, Toml::CONTENT_TYPE, accepts, data) } } impl<T, Request, Err> FromReq<Toml, Request, Err> for TomlEncoded<T> where Request: Req<Err> + Send, T: DeserializeOwned, Err: FromServerFnError, { async fn from_req(req: Request) -> Result<Self, Err> { let string_data = req.try_into_string().await?; toml::from_str::<T>(&string_data) .map(TomlEncoded) .map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error()) } } impl<T, Response, Err> IntoRes<Toml, Response, Err> for TomlEncoded<T> where Response: TryRes<Err>, T: Serialize + Send, Err: FromServerFnError, { async fn into_res(self) -> Result<Response, Err> { let data = toml::to_string(&self.0).map_err(|e| { ServerFnErrorErr::Serialization(e.to_string()).into_app_error() })?; Response::try_from_string(Toml::CONTENT_TYPE, data) } } impl<T, Response, Err> FromRes<Toml, Response, Err> for TomlEncoded<T> where Response: ClientRes<Err> + Send, T: DeserializeOwned, Err: FromServerFnError, { async fn from_res(res: Response) -> Result<Self, Err> { let data = res.try_into_string().await?; toml::from_str(&data).map(TomlEncoded).map_err(|e| { ServerFnErrorErr::Deserialization(e.to_string()).into_app_error() }) } } #[derive(Serialize, Deserialize)] pub struct WhyNotResult { original: String, modified: String, } #[server( input = Toml, output = Toml, custom = TomlEncoded )] pub async fn why_not( original: String, addition: String, ) -> Result<TomlEncoded<WhyNotResult>, ServerFnError> { // insert a simulated wait tokio::time::sleep(std::time::Duration::from_millis(250)).await; Ok(TomlEncoded(WhyNotResult { modified: format!("{original}{addition}"), original, })) } #[component] pub fn CustomEncoding() -> impl IntoView { let input_ref = NodeRef::<Input>::new(); let (result, set_result) = signal("foo".to_string()); view! { <h3>Custom encodings</h3> <p> "This example creates a custom encoding that sends server fn data using TOML. Why? Well... why not?" </p> <input node_ref=input_ref placeholder="Type something here." /> <button on:click=move |_| { let value = input_ref.get().unwrap().value(); spawn_local(async move { let new_value = why_not(value, ", but in TOML!!!".to_string()).await.unwrap(); set_result.set(new_value.0.modified); }); }> Submit </button> <p>{result}</p> } } /// Middleware lets you modify the request/response on the server. /// /// On the client, you might also want to modify the request. For example, you may need to add a /// custom header for authentication on every request. You can do this by creating a "custom /// client." #[component] pub fn CustomClientExample() -> impl IntoView { // Define a type for our client. pub struct CustomClient; // Implement the `Client` trait for it. impl<E, IS, OS> Client<E, IS, OS> for CustomClient where E: FromServerFnError, IS: FromServerFnError, OS: FromServerFnError, { // BrowserRequest and BrowserResponse are the defaults used by other server functions. // They are wrappers for the underlying Web Fetch API types. type Request = BrowserRequest;
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
true
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/server_fns_axum/src/errors.rs
examples/server_fns_axum/src/errors.rs
use http::status::StatusCode; use thiserror::Error; #[derive(Debug, Clone, Error)] pub enum TodoAppError { #[error("Not Found")] NotFound, #[error("Internal Server Error")] InternalServerError, } impl TodoAppError { pub fn status_code(&self) -> StatusCode { match self { TodoAppError::NotFound => StatusCode::NOT_FOUND, TodoAppError::InternalServerError => { StatusCode::INTERNAL_SERVER_ERROR } } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/server_fns_axum/src/lib.rs
examples/server_fns_axum/src/lib.rs
pub mod app; pub mod error_template; pub mod errors; #[cfg(feature = "ssr")] pub mod middleware; #[cfg(feature = "hydrate")] #[wasm_bindgen::prelude::wasm_bindgen] pub fn hydrate() { use crate::app::App; console_error_panic_hook::set_once(); leptos::mount::hydrate_body(App); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/server_fns_axum/src/middleware.rs
examples/server_fns_axum/src/middleware.rs
use axum::body::Body; use http::Request; use pin_project_lite::pin_project; use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use tower::{Layer, Service}; pub struct LoggingLayer; impl<S> Layer<S> for LoggingLayer { type Service = LoggingService<S>; fn layer(&self, inner: S) -> Self::Service { LoggingService { inner } } } pub struct LoggingService<T> { inner: T, } impl<T> Service<Request<Body>> for LoggingService<T> where T: Service<Request<Body>>, { type Response = T::Response; type Error = T::Error; type Future = LoggingServiceFuture<T::Future>; fn poll_ready( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>> { self.inner.poll_ready(cx) } fn call(&mut self, req: Request<Body>) -> Self::Future { println!("1. Running my middleware!"); LoggingServiceFuture { inner: self.inner.call(req), } } } pin_project! { pub struct LoggingServiceFuture<T> { #[pin] inner: T, } } impl<T> Future for LoggingServiceFuture<T> where T: Future, { type Output = T::Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); match this.inner.poll(cx) { Poll::Pending => Poll::Pending, Poll::Ready(output) => { println!("3. Running my middleware!"); Poll::Ready(output) } } } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/server_fns_axum/src/error_template.rs
examples/server_fns_axum/src/error_template.rs
use crate::errors::TodoAppError; use leptos::prelude::*; #[cfg(feature = "ssr")] use leptos_axum::ResponseOptions; // A basic function to display errors served by the error boundaries. Feel free to do more complicated things // here than just displaying them #[component] pub fn ErrorTemplate( #[prop(optional)] outside_errors: Option<Errors>, #[prop(optional)] errors: Option<RwSignal<Errors>>, ) -> impl IntoView { let errors = match outside_errors { Some(e) => RwSignal::new(e), None => match errors { Some(e) => e, None => panic!("No Errors found and we expected errors!"), }, }; // Get Errors from Signal // Downcast lets us take a type that implements `std::error::Error` let errors: Vec<TodoAppError> = errors .get() .into_iter() .filter_map(|(_, v)| v.downcast_ref::<TodoAppError>().cloned()) .collect(); // Only the response code for the first error is actually sent from the server // this may be customized by the specific application #[cfg(feature = "ssr")] { let response = use_context::<ResponseOptions>(); if let Some(response) = response { response.set_status(errors[0].status_code()); } } view! { <h1>"Errors"</h1> <For // a function that returns the items we're iterating over; a signal is fine each=move || { errors.clone().into_iter().enumerate() } // a unique key for each item as a reference key=|(index, _error)| *index // renders each item to a view children=move |error| { let error_string = error.1.to_string(); let error_code = error.1.status_code(); view! { <h2>{error_code.to_string()}</h2> <p>"Error: " {error_string}</p> } } /> } }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false
leptos-rs/leptos
https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/server_fns_axum/src/main.rs
examples/server_fns_axum/src/main.rs
use crate::app::*; use axum::Router; use leptos::{config::get_configuration, logging}; use leptos_axum::{generate_route_list, LeptosRoutes}; use server_fns_axum::*; // cargo make cli: error: unneeded `return` statement #[allow(clippy::needless_return)] #[tokio::main] async fn main() { simple_logger::init_with_level(log::Level::Error) .expect("couldn't initialize logging"); // Setting this to None means we'll be using cargo-leptos and its env vars let conf = get_configuration(None).unwrap(); let leptos_options = conf.leptos_options; let addr = leptos_options.site_addr; let routes = generate_route_list(App); // build our application with a route let app = Router::new() .leptos_routes(&leptos_options, routes, { let leptos_options = leptos_options.clone(); move || shell(leptos_options.clone()) }) .fallback(leptos_axum::file_and_error_handler(shell)) .with_state(leptos_options); // run our app with hyper // `axum::Server` is a re-export of `hyper::Server` let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); logging::log!("listening on http://{}", &addr); axum::serve(listener, app.into_make_service()) .await .unwrap(); }
rust
MIT
dd507168fa47b5eead64339431b0bd654bd1c951
2026-01-04T15:41:20.302544Z
false