Skip to content

Commit

Permalink
feat: use_interval (#33)
Browse files Browse the repository at this point in the history
* feat: `use_interval`

* update readme

* clippy

* clean up
  • Loading branch information
marc2332 authored Apr 22, 2024
1 parent 57c6ff6 commit f214e4d
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 4 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@
- [x] Utility Hooks
- [x] use_channel
- [x] use_window_size
- [ ] use_interval
- [x] use_interval
- [ ] use_timeout
- [ ] use_debouncer
- [ ] Camera
- [ ] WiFi
- [ ] Bluetooth
Expand Down
14 changes: 14 additions & 0 deletions examples/interval/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "interval"
version = "0.1.0"
edition = "2021"

[dependencies]
dioxus-sdk = { workspace = true, features = ["interval"] }
dioxus = { workspace = true, features = ["web"] }

log = "0.4.6"

# WebAssembly Debug
wasm-logger = "0.2.0"
console_error_panic_hook = "0.1.7"
42 changes: 42 additions & 0 deletions examples/interval/Dioxus.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[application]

# App (Project) Name
name = "interval"

# Dioxus App Default Platform
# desktop, web, mobile, ssr
default_platform = "web"

# `build` & `serve` dist path
out_dir = "dist"

# resource (public) file folder
asset_dir = "public"

[web.app]

# HTML title tag content
title = "dioxus | ⛺"

[web.watcher]

# when watcher trigger, regenerate the `index.html`
reload_html = true

# which files or dirs will be watcher monitoring
watch_path = ["src", "public"]

# include `assets` in web platform
[web.resource]

# CSS style file
style = []

# Javascript code file
script = []

[web.resource.dev]

# Javascript code file
# serve: [dev-server] only
script = []
7 changes: 7 additions & 0 deletions examples/interval/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# use_interval

Learn how to use `use_interval`.

Run:

```dioxus serve```
Binary file added examples/interval/public/favicon.ico
Binary file not shown.
21 changes: 21 additions & 0 deletions examples/interval/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use dioxus::prelude::*;
use dioxus_sdk::utils::interval::use_interval;
use std::time::Duration;

fn main() {
// init debug tool for WebAssembly
wasm_logger::init(wasm_logger::Config::default());
console_error_panic_hook::set_once();

launch(app);
}

fn app() -> Element {
let mut count = use_signal(|| 0);

use_interval(Duration::from_millis(100), move || {
count += 1;
});

rsx!( p { "{count}" } )
}
18 changes: 16 additions & 2 deletions sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ storage = [
"dep:once_cell",
"dep:dioxus-signals",
"dep:tokio",
"tokio/sync",
"dep:yazi",
"web-sys/StorageEvent",
"dep:serde",
Expand All @@ -79,6 +80,14 @@ storage = [
# Not WASM
"dep:directories",
]
interval = [
# Desktop
"dep:tokio",
"tokio/time",

# Wasm
"dep:gloo-timers"
]

# CI testing
wasm-testing = [
Expand Down Expand Up @@ -133,10 +142,16 @@ once_cell = { version = "1.17.0", optional = true }
dioxus-signals = { version = "0.5.0-alpha.2", features = [
"serialize",
], optional = true }
tokio = { version = "1.33.0", features = ["sync"], optional = true }

yazi = { version = "0.1.4", optional = true }
tracing = "0.1.40"

# Used by: interval
gloo-timers = { version = "0.3.0", optional = true }

# Used by: interval & storage
tokio = { version = "1.33.0", optional = true }

# # # # # # # # #
# Windows Deps. #
# # # # # # # # #
Expand Down Expand Up @@ -164,7 +179,6 @@ js-sys = "0.3.62"
# Used by: channel
uuid = { version = "1.3.2", features = ["js"] }


[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Used by: storage
directories = { version = "4.0.1", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ cfg_if::cfg_if! {
}

cfg_if::cfg_if! {
if #[cfg(any(feature = "channel", feature = "use_window_size"))] {
if #[cfg(any(feature = "channel", feature = "use_window_size", feature = "interval"))] {
pub mod utils;
}
}
Expand Down
64 changes: 64 additions & 0 deletions sdk/src/utils/interval/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use std::time::Duration;

use dioxus::prelude::{use_hook, Writable};

#[derive(Clone, PartialEq, Copy)]
pub struct UseInterval {
inner: dioxus::prelude::Signal<InnerUseInterval>,
}

struct InnerUseInterval {
#[cfg(target_family = "wasm")]
pub(crate) interval: Option<gloo_timers::callback::Interval>,

#[cfg(not(target_family = "wasm"))]
pub(crate) interval: Option<dioxus::prelude::Task>,
}

#[cfg(target_family = "wasm")]
impl Drop for InnerUseInterval {
fn drop(&mut self) {
if let Some(interval) = self.interval.take() {
interval.cancel();
}
}
}

impl UseInterval {
/// Cancel the interval
pub fn cancel(&mut self) {
if let Some(interval) = self.inner.write().interval.take() {
interval.cancel();
}
}
}

/// Repeatedly calls a function every a certain period.
pub fn use_interval(period: Duration, action: impl FnMut() + 'static) -> UseInterval {
let inner = use_hook(|| {
let mut action = Box::new(action);

#[cfg(target_family = "wasm")]
return dioxus::prelude::Signal::new(InnerUseInterval {
interval: Some(gloo_timers::callback::Interval::new(
period.as_millis() as u32,
move || {
action();
},
)),
});

#[cfg(not(target_family = "wasm"))]
dioxus::prelude::Signal::new(InnerUseInterval {
interval: Some(dioxus::prelude::spawn(async move {
let mut interval = tokio::time::interval(period);
loop {
interval.tick().await;
action();
}
})),
})
});

UseInterval { inner }
}
6 changes: 6 additions & 0 deletions sdk/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@ cfg_if::cfg_if! {
pub mod window;
}
}

cfg_if::cfg_if! {
if #[cfg(feature = "interval")] {
pub mod interval;
}
}

0 comments on commit f214e4d

Please sign in to comment.