Skip to content

Commit

Permalink
Clean up examples
Browse files Browse the repository at this point in the history
  • Loading branch information
RSSchermer committed Mar 22, 2022
1 parent 365bb68 commit 93f1abc
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 108 deletions.
14 changes: 8 additions & 6 deletions examples/animation_frame/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl FnOnce<(Result<f64, Aborted>,)> for FrameLoop {

extern "rust-call" fn call_once(mut self, args: (Result<f64, Aborted>,)) -> Self::Output {
// Only loop if the frame has not been cancelled.
if let Ok(time) = args.0 {
if let (Ok(time), ..) = args {
// Update the count and our displayed text.
self.count += 1;

Expand Down Expand Up @@ -88,12 +88,14 @@ pub fn start() -> Result<(), JsValue> {
.query_selector_first(&selector!("#cancel_button"))
.ok_or(JsError::new("No element with id `cancel_button`."))?;

// Respond to click events on the button by cancelling the loop.
spawn_local(button.on_click().take(1).for_each(move |_| {
abort_handle.borrow().abort();
let mut clicks = button.on_click();

// Respond to the first click event by cancelling the loop.
spawn_local(async move {
clicks.next().await;

futures::future::ready(())
}));
abort_handle.borrow().abort();
});

Ok(())
}
43 changes: 23 additions & 20 deletions examples/custom_elements/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use arwa::html::{custom_element_name, HtmlButtonElement, HtmlDocument};
use arwa::spawn_local;
use arwa::ui::UiEventTarget;
use arwa::window::window;
use futures::{FutureExt, StreamExt};
use futures::StreamExt;
use wasm_bindgen::prelude::*;

use crate::my_element::{MyElement, MyElementExt, MY_ELEMENT};
Expand All @@ -32,41 +32,44 @@ pub fn start() -> Result<(), JsValue> {
.ok_or(JsError::new("No element with id `reconnect_button`."))?
.try_into()?;

let reconnect_clicks = reconnect_button.on_click();
let my_element_clone = my_element.clone();
let body = document.body().unwrap();

spawn_local(
reconnect_button
.on_click()
.take(3)
.for_each(move |_| {
my_element_clone.disconnect();
body.prepend_child(&my_element_clone);

futures::future::ready(())
})
.map(move |_| {
my_element.disconnect();
reconnect_button.set_disabled(true);
}),
);
spawn_local(async move {
// Let's take just the first 3 clicks and then disconnect the custom element, so we can
// watch it get garbage collected (probably, eventually... there are essentially no
// guarantees for if and when a browser will perform a garbage collection pass).
let mut reconnect_clicks = reconnect_clicks.take(3);

while let Some(_) = reconnect_clicks.next().await {
my_element_clone.disconnect();
body.prepend_child(&my_element_clone);
}

my_element.disconnect();
reconnect_button.set_disabled(true);
});

let change_message_button: HtmlButtonElement = document
.query_selector_first(&selector!("#change_message_button"))
.ok_or(JsError::new("No element with id `change_message_button`."))?
.try_into()?;

spawn_local(change_message_button.on_click().take(1).for_each(move |_| {
let mut change_message_clicks = change_message_button.on_click();

spawn_local(async move {
// Wait for the first click, then try changing the message and then disable the button.
change_message_clicks.next().await;

if let Some(element) = document.query_selector_first(&selector!("my-element")) {
let element: MyElement = element.try_into().unwrap();

element.set_message("Goodbye!");
}

change_message_button.set_disabled(true);

futures::future::ready(())
}));
});

Ok(())
}
54 changes: 28 additions & 26 deletions examples/custom_events/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,39 +30,41 @@ pub fn start() -> Result<(), JsValue> {
.query_selector_first(&selector!("#inner"))
.ok_or(JsError::new("No element with id `inner`."))?;

spawn_local(
inner
.on_typed_event::<TypedCustomEvent<MyEvent, DynamicElement>>()
.for_each(async move |event| {
console::log!("Message from inner: %s", event.message);
}),
);
let mut inner_events = inner.on_typed_event::<TypedCustomEvent<MyEvent, DynamicElement>>();

spawn_local(
outer
.on_typed_event::<TypedCustomEvent<MyEvent, DynamicElement>>()
.for_each(async move |event| {
console::log!("Message from outer: %s", event.message);
}),
);
spawn_local(async move {
while let Some(event) = inner_events.next().await {
console::log!("Message from inner: %s", event.message);
}
});

let mut outer_events = outer.on_typed_event::<TypedCustomEvent<MyEvent, DynamicElement>>();

spawn_local(async move {
while let Some(event) = outer_events.next().await {
console::log!("Message from outer: %s", event.message);
}
});

let dispatch_button = document
.query_selector_first(&selector!("#dispatch_button"))
.ok_or(JsError::new("No element with id `dispatch_button`."))?;

spawn_local(dispatch_button.on_click().for_each(move |_| {
inner.dispatch_typed_event(
MyEvent {
message: "Hello!".to_string(),
},
EventOptions {
bubbles: true,
..Default::default()
},
);
let mut dispatch_clicks = dispatch_button.on_click();

futures::future::ready(())
}));
spawn_local(async move {
while let Some(_) = dispatch_clicks.next().await {
inner.dispatch_typed_event(
MyEvent {
message: "Hello!".to_string(),
},
EventOptions {
bubbles: true,
..Default::default()
},
);
}
});

Ok(())
}
34 changes: 16 additions & 18 deletions examples/events/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use arwa::dom::{selector, ChildNode, ParentNode};
use arwa::ui::UiEventTarget;
use arwa::window::window;
use arwa::{console, spawn_local};
use futures::{FutureExt, StreamExt};
use futures::StreamExt;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
Expand All @@ -16,31 +16,29 @@ pub fn start() -> Result<(), JsValue> {
.query_selector_first(&selector!("#button"))
.ok_or(JsError::new("No element with id `button`."))?;

spawn_local(
button
.on_click()
.for_each(async move |_| {
console::log!("Click!");
})
.map(|_| console::log!("Event target cleaned up")),
);
let mut click_events = button.on_click();

spawn_local(async move {
while let Some(_) = click_events.next().await {
console::log!("Click!");
}

console::log!("Event stream cleaned up")
});

let remove_event_target_button = document
.query_selector_first(&selector!("#remove_event_target_button"))
.ok_or(JsError::new(
"No element with id `remove_event_target_button`.",
))?;

spawn_local(
remove_event_target_button
.on_click()
.take(1)
.for_each(move |_| {
button.disconnect();
let mut remove_clicks = remove_event_target_button.on_click();

spawn_local(async move {
remove_clicks.next().await;

futures::future::ready(())
}),
);
button.disconnect();
});

Ok(())
}
36 changes: 17 additions & 19 deletions examples/geolocation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use arwa::dom::{selector, Element, ParentNode};
use arwa::window::window;
use arwa::{console, spawn_local};
use futures::{future, StreamExt};
use futures::StreamExt;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
Expand All @@ -17,26 +17,24 @@ pub fn start() -> Result<(), JsValue> {
.query_selector_first(&selector!("#position_container"))
.ok_or(JsError::new("No element with id `position_container`"))?;

spawn_local(
geolocation
.watch_position(Default::default())
.for_each(move |result| {
match result {
Ok(position) => {
let coordinates = position.coordinates();
let mut positions = geolocation.watch_position(Default::default());

position_container.deserialize_inner(&format!(
"Lat: {}, Long: {}",
coordinates.latitude(),
coordinates.longitude()
));
}
Err(err) => console::error!(err),
};
spawn_local(async move {
while let Some(result) = positions.next().await {
match result {
Ok(position) => {
let coordinates = position.coordinates();

future::ready(())
}),
);
position_container.deserialize_inner(&format!(
"Lat: {}, Long: {}",
coordinates.latitude(),
coordinates.longitude()
));
}
Err(err) => console::error!(err),
};
}
});

Ok(())
}
39 changes: 20 additions & 19 deletions examples/media_element/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use arwa::html::{HtmlAudioElement, MediaElement};
use arwa::ui::UiEventTarget;
use arwa::window::window;
use arwa::{console, spawn_local};
use futures::{FutureExt, StreamExt, TryFutureExt};
use futures::StreamExt;
use wasm_bindgen::prelude::*;

#[wasm_bindgen(start)]
Expand All @@ -22,29 +22,30 @@ pub fn start() -> Result<(), JsValue> {
.ok_or(JsError::new("No element with the id `play`"))?;

let audio_clone = audio.clone();
let mut play_clicks = play_button.on_click();

spawn_local(play_button.on_click().for_each(move |_| {
audio_clone
.play()
.map_ok(|_| {
console::log!("Started playing!");
})
.map_err(|err| {
console::error!(err);
})
.map(|_| ())
}));
spawn_local(async move {
while let Some(_) = play_clicks.next().await {
match audio_clone.play().await {
Ok(_) => console::log!("Started playing!"),
Err(err) => console::error!(err),
}
}
});

let pause_button = document
.query_selector_first(&selector!("#pause"))
.ok_or(JsError::new("No element with the id `pause`"))?;

spawn_local(pause_button.on_click().for_each(move |_| {
audio.pause();
console::log!("Paused...");

futures::future::ready(())
}));
let mut pause_clicks = pause_button.on_click();

spawn_local(async move {
while let Some(_) = pause_clicks.next().await {
if !audio.paused() {
audio.pause();
console::log!("Paused...");
}
}
});

Ok(())
}

0 comments on commit 93f1abc

Please sign in to comment.