Skip to content

add wasm example #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/wasm/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/target
/pkg
161 changes: 161 additions & 0 deletions examples/wasm/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions examples/wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "wasm"
version = "0.1.0"
edition = "2021"

[dependencies]
wasm-bindgen = { version = "0.2" }
web-sys = { version = "0.3.69", features = ["Window", "Document", "Element", "MouseEvent"] }
button-driver = { path = "../../" }
log = "0.4.22"
wasm-logger = "0.2.0"

[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]

[features]
27 changes: 27 additions & 0 deletions examples/wasm/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<html>
<head>
<meta charset="utf-8" />
<title>Button example</title>
<style>
.clickable-area {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 100px;
background-color: lightgray;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not override the default style to have a standard "animation" visible

user-select: none; /* Don't copy text */
}
</style>
</head>
<body>
<script type="module" src="index.js"></script>
<div class="clickable-area">
<span>Press Area</span>
</div>
Comment on lines +19 to +21
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's change this to

Suggested change
<div class="clickable-area">
<span>Press Area</span>
</div>
<button class="clickable-area" type="button">Button</button>

<br>
<p>
Please open developer tools console to view log.
</p>
</body>
</html>
3 changes: 3 additions & 0 deletions examples/wasm/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import init from "./pkg/wasm.js";

init();
117 changes: 117 additions & 0 deletions examples/wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
use std::{cell::RefCell, ops::Sub, rc::Rc, time::Duration};
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add a top-level comment similar to other examples? For example how to run this (trunk serve?)


use button_driver::{Button, ButtonConfig, InstantProvider, Mode, PinWrapper};
use log::info;
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{js_sys::Date, MouseEvent};

#[derive(PartialEq, Clone)]
struct WasmInstant(u64);

impl WasmInstant {
fn now() -> WasmInstant {
WasmInstant(Date::now() as u64)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this! I think you can even implement impl InstantProvider<Duration> for Date in the crate istef and guard it by a feature "wasm" as it already implements Sub

}
}

impl Sub for WasmInstant {
type Output = Duration;

fn sub(self, rhs: Self) -> Self::Output {
let delta_ms = self.0 - rhs.0;
return Duration::from_millis(delta_ms);
}
}

impl InstantProvider<Duration> for WasmInstant {
fn now() -> Self {
WasmInstant::now()
}
}

#[derive(Clone, Default)]
struct MockButtonPin(Rc<RefCell<bool>>);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't feel like it is a mock, let's change the name to ButtonInput or something


impl PinWrapper for MockButtonPin {
fn is_high(&mut self) -> bool {
*self.0.borrow()
}
}

#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn main() {
wasm_logger::init(wasm_logger::Config::default());
let document = web_sys::window().unwrap().document().unwrap();
let clickable_area = document.query_selector(".clickable-area").unwrap().unwrap();
let pin_state = MockButtonPin::default();
{
let pin_state_ref = pin_state.clone();
let mouse_down_handler = Closure::wrap(Box::new(move |_: MouseEvent| {
*pin_state_ref.0.borrow_mut() = true;
}) as Box<dyn FnMut(_)>);
clickable_area
.add_event_listener_with_callback(
"mousedown",
mouse_down_handler.as_ref().unchecked_ref(),
)
.unwrap();
mouse_down_handler.forget();
}
{
let pin_state_ref = pin_state.clone();
let mouse_up_handler = Closure::wrap(Box::new(move |_: MouseEvent| {
*pin_state_ref.0.borrow_mut() = false;
}) as Box<dyn FnMut(_)>);

clickable_area
.add_event_listener_with_callback("mouseup", mouse_up_handler.as_ref().unchecked_ref())
.unwrap();
mouse_up_handler.forget();
}
{
let mut button = Button::<_, WasmInstant>::new(
pin_state,
ButtonConfig {
mode: Mode::PullDown,
..Default::default()
},
);
let callback = Closure::wrap(Box::new(move || {
button.tick();

if let Some(dur) = button.held_time() {
info!("Total holding time {:?}", dur);
if button.is_clicked() {
info!("Clicked + held");
} else if button.is_double_clicked() {
info!("Double clicked + held");
} else if button.holds() == 2 && button.clicks() > 0 {
info!("Held twice with {} clicks", button.clicks());
} else if button.holds() == 2 {
info!("Held twice");
}
} else {
if button.is_clicked() {
info!("Click");
} else if button.is_double_clicked() {
info!("Double click");
} else if button.is_triple_clicked() {
info!("Triple click");
} else if let Some(dur) = button.current_holding_time() {
info!("Held for {:?}", dur);
}
}

button.reset();
}) as Box<dyn FnMut()>);

web_sys::window()
.unwrap()
.set_interval_with_callback_and_timeout_and_arguments_0(
callback.as_ref().unchecked_ref(),
20,
)
.unwrap();
callback.forget();
}
}
Loading