|
| 1 | +use std::time::Duration; |
| 2 | + |
| 3 | +use gloo_timers::callback::Timeout; |
| 4 | +use web_sys::wasm_bindgen::JsCast; |
| 5 | +use web_sys::HtmlInputElement; |
| 6 | +use yew::*; |
| 7 | + |
| 8 | +#[component] |
| 9 | +fn App() -> Html { |
| 10 | + #[derive(PartialEq, Default, Clone)] |
| 11 | + enum Search { |
| 12 | + #[default] |
| 13 | + Idle, |
| 14 | + Fetching(AttrValue), |
| 15 | + Fetched(AttrValue), |
| 16 | + } |
| 17 | + |
| 18 | + let search = use_state(Search::default); |
| 19 | + |
| 20 | + use_effect_with(search.clone(), { |
| 21 | + move |search| { |
| 22 | + // here you would typically do a REST call to send the search input to backend |
| 23 | + // for simplicity sake here we just set back the original input |
| 24 | + if let Search::Fetching(query) = &**search { |
| 25 | + yew::platform::spawn_local({ |
| 26 | + let query = query.clone(); |
| 27 | + let search = search.setter(); |
| 28 | + async move { |
| 29 | + // Simulate a network delay |
| 30 | + gloo_timers::future::sleep(Duration::from_millis(500)).await; |
| 31 | + search.set(Search::Fetched( |
| 32 | + format!("Placeholder response for: {}", query).into(), |
| 33 | + )); |
| 34 | + } |
| 35 | + }); |
| 36 | + } |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + let oninput = { |
| 41 | + let timeout_ref = use_mut_ref(|| None); |
| 42 | + use_callback((), { |
| 43 | + let search = search.clone(); |
| 44 | + move |e: InputEvent, _| { |
| 45 | + if let Some(target) = e.target() { |
| 46 | + let input = target.dyn_into::<HtmlInputElement>().ok(); |
| 47 | + if let Some(input) = input { |
| 48 | + let value = input.value(); |
| 49 | + if !value.is_empty() { |
| 50 | + let search = search.setter(); |
| 51 | + let timeout = Timeout::new(1_000, move || { |
| 52 | + search.set(Search::Fetching(value.into())); |
| 53 | + }); |
| 54 | + (*timeout_ref.borrow_mut()) = Some(timeout); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + }) |
| 60 | + }; |
| 61 | + |
| 62 | + html! { |
| 63 | + <div class="container p-2"> |
| 64 | + <div class="row"> |
| 65 | + <div class="p-2"> |
| 66 | + <form class="input-group bg-dark border border-white rounded"> |
| 67 | + <input id="search" autocomplete="off" type="search" class="form-control" placeholder="Type something here..." aria-label="Search" {oninput}/> |
| 68 | + </form> |
| 69 | + </div> |
| 70 | + <div class="p-2 border border-black rounded"> |
| 71 | + <p>{ |
| 72 | + match &*search { |
| 73 | + Search::Idle => "Type something to search...".into(), |
| 74 | + Search::Fetching(query) => format!("Searching for: {}", query).into(), |
| 75 | + Search::Fetched(response) => response.clone(), |
| 76 | + } |
| 77 | + }</p> |
| 78 | + </div> |
| 79 | + </div> |
| 80 | + </div> |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +fn main() { |
| 85 | + yew::Renderer::<App>::new().render(); |
| 86 | +} |
0 commit comments