added use_clipboard, use_permission, use_timeout_fn

closes #72
This commit is contained in:
Maccesch 2024-02-09 03:18:53 +00:00
parent 0bc7d41953
commit 27f516898c
52 changed files with 1744 additions and 100 deletions

3
.idea/leptos-use.iml generated
View file

@ -69,6 +69,9 @@
<sourceFolder url="file://$MODULE_DIR$/examples/use_element_bounding/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/examples/use_element_bounding/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_mouse_in_element/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/examples/use_mouse_in_element/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_device_orientation/src" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/examples/use_device_orientation/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_clipboard/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_permission/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/examples/use_timeout_fn/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/examples/use_event_listener/target" /> <excludeFolder url="file://$MODULE_DIR$/examples/use_event_listener/target" />
<excludeFolder url="file://$MODULE_DIR$/target" /> <excludeFolder url="file://$MODULE_DIR$/target" />
<excludeFolder url="file://$MODULE_DIR$/docs/book/book" /> <excludeFolder url="file://$MODULE_DIR$/docs/book/book" />

View file

@ -3,6 +3,14 @@
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] -
### New Functions 🚀
- `use_permission`
- `use_clipboard`
- `use_timeout_fn`
## [0.10.1] - 2024-010-31 ## [0.10.1] - 2024-010-31
### Fix 🍕 ### Fix 🍕

View file

@ -46,6 +46,7 @@ features = [
"BinaryType", "BinaryType",
"BroadcastChannel", "BroadcastChannel",
"Coordinates", "Coordinates",
"Clipboard",
"CloseEvent", "CloseEvent",
"CssStyleDeclaration", "CssStyleDeclaration",
"CustomEvent", "CustomEvent",
@ -84,6 +85,9 @@ features = [
"NotificationDirection", "NotificationDirection",
"NotificationOptions", "NotificationOptions",
"NotificationPermission", "NotificationPermission",
"Permissions",
"PermissionState",
"PermissionStatus",
"PointerEvent", "PointerEvent",
"Position", "Position",
"PositionError", "PositionError",

View file

@ -35,6 +35,7 @@
- [use_breakpoints](browser/use_breakpoints.md) - [use_breakpoints](browser/use_breakpoints.md)
- [use_broadcast_channel](browser/use_broadcast_channel.md) - [use_broadcast_channel](browser/use_broadcast_channel.md)
- [use_clipboard](browser/use_clipboard.md)
- [use_color_mode](browser/use_color_mode.md) - [use_color_mode](browser/use_color_mode.md)
- [use_cookie](browser/use_cookie.md) - [use_cookie](browser/use_cookie.md)
- [use_css_var](browser/use_css_var.md) - [use_css_var](browser/use_css_var.md)
@ -42,6 +43,7 @@
- [use_event_listener](browser/use_event_listener.md) - [use_event_listener](browser/use_event_listener.md)
- [use_favicon](browser/use_favicon.md) - [use_favicon](browser/use_favicon.md)
- [use_media_query](browser/use_media_query.md) - [use_media_query](browser/use_media_query.md)
- [use_permission](browser/use_permission.md)
- [use_preferred_contrast](browser/use_preferred_contrast.md) - [use_preferred_contrast](browser/use_preferred_contrast.md)
- [use_preferred_dark](browser/use_preferred_dark.md) - [use_preferred_dark](browser/use_preferred_dark.md)
- [use_service_worker](browser/use_service_worker.md) - [use_service_worker](browser/use_service_worker.md)
@ -69,6 +71,7 @@
- [use_interval](animation/use_interval.md) - [use_interval](animation/use_interval.md)
- [use_interval_fn](animation/use_interval_fn.md) - [use_interval_fn](animation/use_interval_fn.md)
- [use_raf_fn](animation/use_raf_fn.md) - [use_raf_fn](animation/use_raf_fn.md)
- [use_timeout_fn](animation/use_timeout_fn.md)
- [use_timestamp](animation/use_timestamp.md) - [use_timestamp](animation/use_timestamp.md)
# Watch # Watch

View file

@ -0,0 +1,3 @@
# use_timeout_fn
<!-- cmdrun python3 ../extract_doc_comment.py use_timeout_fn -->

View file

@ -0,0 +1,3 @@
# use_clipboard
<!-- cmdrun python3 ../extract_doc_comment.py use_clipboard -->

View file

@ -0,0 +1,3 @@
# use_permission
<!-- cmdrun python3 ../extract_doc_comment.py use_permission -->

View file

@ -10,6 +10,7 @@ members = [
"use_breakpoints", "use_breakpoints",
"use_broadcast_channel", "use_broadcast_channel",
"use_ceil", "use_ceil",
"use_clipboard",
"use_color_mode", "use_color_mode",
"use_cookie", "use_cookie",
"use_css_var", "use_css_var",
@ -39,6 +40,7 @@ members = [
"use_mouse", "use_mouse",
"use_mouse_in_element", "use_mouse_in_element",
"use_mutation_observer", "use_mutation_observer",
"use_permission",
"use_raf_fn", "use_raf_fn",
"use_resize_observer", "use_resize_observer",
"use_round", "use_round",
@ -47,6 +49,7 @@ members = [
"use_sorted", "use_sorted",
"use_storage", "use_storage",
"use_throttle_fn", "use_throttle_fn",
"use_timeout_fn",
"use_timestamp", "use_timestamp",
"use_web_notification", "use_web_notification",
"use_websocket", "use_websocket",

View file

@ -0,0 +1,2 @@
[build]
rustflags = ["--cfg=web_sys_unstable_apis"]

View file

@ -0,0 +1,16 @@
[package]
name = "use_clipboard"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { version = "0.6", features = ["nightly", "csr"] }
console_error_panic_hook = "0.1"
console_log = "1"
log = "0.4"
leptos-use = { path = "../..", features = ["docs"] }
web-sys = "0.3"
[dev-dependencies]
wasm-bindgen = "0.2"
wasm-bindgen-test = "0.3.0"

View file

@ -0,0 +1,23 @@
A simple example for `use_clipboard`.
If you don't have it installed already, install [Trunk](https://trunkrs.dev/) and [Tailwind](https://tailwindcss.com/docs/installation)
as well as the nightly toolchain for Rust and the wasm32-unknown-unknown target:
```bash
cargo install trunk
npm install -D tailwindcss @tailwindcss/forms
rustup toolchain install nightly
rustup target add wasm32-unknown-unknown
```
Then, open two terminals. In the first one, run:
```
npx tailwindcss -i ./input.css -o ./style/output.css --watch
```
In the second one, run:
```bash
trunk serve --open
```

View file

@ -0,0 +1,2 @@
[build]
public_url = "/demo/"

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="css" href="style/output.css">
</head>
<body></body>
</html>

View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View file

@ -0,0 +1,2 @@
[toolchain]
channel = "nightly"

View file

@ -0,0 +1,50 @@
use leptos::*;
use leptos_use::docs::{demo_or_body, Note};
use leptos_use::{use_clipboard, use_permission, UseClipboardReturn};
#[component]
fn Demo() -> impl IntoView {
let (input, set_input) = create_signal("".to_owned());
let UseClipboardReturn {
is_supported,
text,
copied,
copy,
} = use_clipboard();
let permission_read = use_permission("clipboard-read");
let permission_write = use_permission("clipboard-write");
view! {
<Show
when=is_supported
fallback=|| view! { <p>Your browser does not support the Clipboard API</p> }
>
<Note>
Clipboard Permission:
read <b>{move || permission_read().to_string()}</b> |
write <b>{move || permission_write().to_string()}</b>
</Note>
<p>Currently copied: <code>{move || text().unwrap_or("none".to_owned())}</code></p>
<input value=input on:input=move |e| set_input(event_target_value(&e)) type="text" />
<button on:click={
let copy = copy.clone();
move |_| copy(&input())
}>
<Show when=copied fallback=|| "Copy">
Copied!
</Show>
</button>
</Show>
}
}
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to(demo_or_body(), || {
view! { <Demo/> }
})
}

View file

@ -0,0 +1,289 @@
[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
border-radius: 0px;
padding-top: 0.5rem;
padding-right: 0.75rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-shadow: 0 0 #0000;
}
[type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
border-color: #2563eb;
}
input::-moz-placeholder, textarea::-moz-placeholder {
color: #6b7280;
opacity: 1;
}
input::placeholder,textarea::placeholder {
color: #6b7280;
opacity: 1;
}
::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
::-webkit-date-and-time-value {
min-height: 1.5em;
}
::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field {
padding-top: 0;
padding-bottom: 0;
}
select {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
[multiple] {
background-image: initial;
background-position: initial;
background-repeat: unset;
background-size: initial;
padding-right: 0.75rem;
-webkit-print-color-adjust: unset;
print-color-adjust: unset;
}
[type='checkbox'],[type='radio'] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
padding: 0;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
display: inline-block;
vertical-align: middle;
background-origin: border-box;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
flex-shrink: 0;
height: 1rem;
width: 1rem;
color: #2563eb;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
--tw-shadow: 0 0 #0000;
}
[type='checkbox'] {
border-radius: 0px;
}
[type='radio'] {
border-radius: 100%;
}
[type='checkbox']:focus,[type='radio']:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 2px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
[type='checkbox']:checked,[type='radio']:checked {
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
}
[type='radio']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e");
}
[type='checkbox']:checked:hover,[type='checkbox']:checked:focus,[type='radio']:checked:hover,[type='radio']:checked:focus {
border-color: transparent;
background-color: currentColor;
}
[type='checkbox']:indeterminate {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3e%3c/svg%3e");
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:indeterminate:hover,[type='checkbox']:indeterminate:focus {
border-color: transparent;
background-color: currentColor;
}
[type='file'] {
background: unset;
border-color: inherit;
border-width: 0;
border-radius: 0;
padding: 0;
font-size: unset;
line-height: inherit;
}
[type='file']:focus {
outline: 1px solid ButtonText;
outline: 1px auto -webkit-focus-ring-color;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.block {
display: block;
}
.text-\[--brand-color\] {
color: var(--brand-color);
}
.text-green-600 {
--tw-text-opacity: 1;
color: rgb(22 163 74 / var(--tw-text-opacity));
}
.opacity-75 {
opacity: 0.75;
}
@media (prefers-color-scheme: dark) {
.dark\:text-green-500 {
--tw-text-opacity: 1;
color: rgb(34 197 94 / var(--tw-text-opacity));
}
}

View file

@ -0,0 +1,15 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"],
},
theme: {
extend: {},
},
corePlugins: {
preflight: false,
},
plugins: [
require('@tailwindcss/forms'),
],
}

View file

@ -0,0 +1,16 @@
[package]
name = "use_permission"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { version = "0.6", features = ["nightly", "csr"] }
console_error_panic_hook = "0.1"
console_log = "1"
log = "0.4"
leptos-use = { path = "../..", features = ["docs"] }
web-sys = "0.3"
[dev-dependencies]
wasm-bindgen = "0.2"
wasm-bindgen-test = "0.3.0"

View file

@ -0,0 +1,23 @@
A simple example for `use_permission`.
If you don't have it installed already, install [Trunk](https://trunkrs.dev/) and [Tailwind](https://tailwindcss.com/docs/installation)
as well as the nightly toolchain for Rust and the wasm32-unknown-unknown target:
```bash
cargo install trunk
npm install -D tailwindcss @tailwindcss/forms
rustup toolchain install nightly
rustup target add wasm32-unknown-unknown
```
Then, open two terminals. In the first one, run:
```
npx tailwindcss -i ./input.css -o ./style/output.css --watch
```
In the second one, run:
```bash
trunk serve --open
```

View file

@ -0,0 +1,2 @@
[build]
public_url = "/demo/"

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="css" href="style/output.css">
</head>
<body></body>
</html>

View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View file

@ -0,0 +1,2 @@
[toolchain]
channel = "nightly"

View file

@ -0,0 +1,51 @@
use leptos::*;
use leptos_use::docs::demo_or_body;
use leptos_use::use_permission;
#[component]
fn Demo() -> impl IntoView {
let accelerometer = use_permission("accelerometer");
let accessibility_events = use_permission("accessibility-events");
let ambient_light_sensor = use_permission("ambient-light-sensor");
let background_sync = use_permission("background-sync");
let camera = use_permission("camera");
let clipboard_read = use_permission("clipboard-read");
let clipboard_write = use_permission("clipboard-write");
let gyroscope = use_permission("gyroscope");
let magnetometer = use_permission("magnetometer");
let microphone = use_permission("microphone");
let notifications = use_permission("notifications");
let payment_handler = use_permission("payment-handler");
let persistent_storage = use_permission("persistent-storage");
let push = use_permission("push");
let speaker = use_permission("speaker");
view! {
<pre>
"accelerometer: " {move || accelerometer().to_string()}
"\naccessibility_events: " {move || accessibility_events().to_string()}
"\nambient_light_sensor: " {move || ambient_light_sensor().to_string()}
"\nbackground_sync: " {move || background_sync().to_string()}
"\ncamera: " {move || camera().to_string()}
"\nclipboard_read: " {move || clipboard_read().to_string()}
"\nclipboard_write: " {move || clipboard_write().to_string()}
"\ngyroscope: " {move || gyroscope().to_string()}
"\nmagnetometer: " {move || magnetometer().to_string()}
"\nmicrophone: " {move || microphone().to_string()}
"\nnotifications: " {move || notifications().to_string()}
"\npayment_handler: " {move || payment_handler().to_string()}
"\npersistent_storage: " {move || persistent_storage().to_string()}
"\npush: " {move || push().to_string()}
"\nspeaker: " {move || speaker().to_string()}
</pre>
}
}
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to(demo_or_body(), || {
view! { <Demo/> }
})
}

View file

@ -0,0 +1,289 @@
[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
border-radius: 0px;
padding-top: 0.5rem;
padding-right: 0.75rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-shadow: 0 0 #0000;
}
[type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
border-color: #2563eb;
}
input::-moz-placeholder, textarea::-moz-placeholder {
color: #6b7280;
opacity: 1;
}
input::placeholder,textarea::placeholder {
color: #6b7280;
opacity: 1;
}
::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
::-webkit-date-and-time-value {
min-height: 1.5em;
}
::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field {
padding-top: 0;
padding-bottom: 0;
}
select {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
[multiple] {
background-image: initial;
background-position: initial;
background-repeat: unset;
background-size: initial;
padding-right: 0.75rem;
-webkit-print-color-adjust: unset;
print-color-adjust: unset;
}
[type='checkbox'],[type='radio'] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
padding: 0;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
display: inline-block;
vertical-align: middle;
background-origin: border-box;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
flex-shrink: 0;
height: 1rem;
width: 1rem;
color: #2563eb;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
--tw-shadow: 0 0 #0000;
}
[type='checkbox'] {
border-radius: 0px;
}
[type='radio'] {
border-radius: 100%;
}
[type='checkbox']:focus,[type='radio']:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 2px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
[type='checkbox']:checked,[type='radio']:checked {
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
}
[type='radio']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e");
}
[type='checkbox']:checked:hover,[type='checkbox']:checked:focus,[type='radio']:checked:hover,[type='radio']:checked:focus {
border-color: transparent;
background-color: currentColor;
}
[type='checkbox']:indeterminate {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3e%3c/svg%3e");
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:indeterminate:hover,[type='checkbox']:indeterminate:focus {
border-color: transparent;
background-color: currentColor;
}
[type='file'] {
background: unset;
border-color: inherit;
border-width: 0;
border-radius: 0;
padding: 0;
font-size: unset;
line-height: inherit;
}
[type='file']:focus {
outline: 1px solid ButtonText;
outline: 1px auto -webkit-focus-ring-color;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.block {
display: block;
}
.text-\[--brand-color\] {
color: var(--brand-color);
}
.text-green-600 {
--tw-text-opacity: 1;
color: rgb(22 163 74 / var(--tw-text-opacity));
}
.opacity-75 {
opacity: 0.75;
}
@media (prefers-color-scheme: dark) {
.dark\:text-green-500 {
--tw-text-opacity: 1;
color: rgb(34 197 94 / var(--tw-text-opacity));
}
}

View file

@ -0,0 +1,15 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"],
},
theme: {
extend: {},
},
corePlugins: {
preflight: false,
},
plugins: [
require('@tailwindcss/forms'),
],
}

View file

@ -0,0 +1,16 @@
[package]
name = "use_timeout_fn"
version = "0.1.0"
edition = "2021"
[dependencies]
leptos = { version = "0.6", features = ["nightly", "csr"] }
console_error_panic_hook = "0.1"
console_log = "1"
log = "0.4"
leptos-use = { path = "../..", features = ["docs"] }
web-sys = "0.3"
[dev-dependencies]
wasm-bindgen = "0.2"
wasm-bindgen-test = "0.3.0"

View file

@ -0,0 +1,23 @@
A simple example for `use_timeout_fn`.
If you don't have it installed already, install [Trunk](https://trunkrs.dev/) and [Tailwind](https://tailwindcss.com/docs/installation)
as well as the nightly toolchain for Rust and the wasm32-unknown-unknown target:
```bash
cargo install trunk
npm install -D tailwindcss @tailwindcss/forms
rustup toolchain install nightly
rustup target add wasm32-unknown-unknown
```
Then, open two terminals. In the first one, run:
```
npx tailwindcss -i ./input.css -o ./style/output.css --watch
```
In the second one, run:
```bash
trunk serve --open
```

View file

@ -0,0 +1,2 @@
[build]
public_url = "/demo/"

View file

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<link data-trunk rel="css" href="style/output.css">
</head>
<body></body>
</html>

View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View file

@ -0,0 +1,2 @@
[toolchain]
channel = "nightly"

View file

@ -0,0 +1,37 @@
use leptos::*;
use leptos_use::docs::demo_or_body;
use leptos_use::{use_timeout_fn, UseTimeoutFnReturn};
#[component]
fn Demo() -> impl IntoView {
const DEFAULT_TEXT: &str = "Please wait for 3 seconds";
let (text, set_text) = create_signal(DEFAULT_TEXT.to_string());
let UseTimeoutFnReturn {
start, is_pending, ..
} = use_timeout_fn(
move |_| {
set_text("Fired!".to_string());
},
3000.0,
);
let restart = move |_| {
set_text(DEFAULT_TEXT.to_string());
start(());
};
view! {
<p>{text}</p>
<button on:click=restart disabled=is_pending>"Restart"</button>
}
}
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to(demo_or_body(), || {
view! { <Demo/> }
})
}

View file

@ -0,0 +1,289 @@
[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
border-radius: 0px;
padding-top: 0.5rem;
padding-right: 0.75rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-shadow: 0 0 #0000;
}
[type='text']:focus, [type='email']:focus, [type='url']:focus, [type='password']:focus, [type='number']:focus, [type='date']:focus, [type='datetime-local']:focus, [type='month']:focus, [type='search']:focus, [type='tel']:focus, [type='time']:focus, [type='week']:focus, [multiple]:focus, textarea:focus, select:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
border-color: #2563eb;
}
input::-moz-placeholder, textarea::-moz-placeholder {
color: #6b7280;
opacity: 1;
}
input::placeholder,textarea::placeholder {
color: #6b7280;
opacity: 1;
}
::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
::-webkit-date-and-time-value {
min-height: 1.5em;
}
::-webkit-datetime-edit,::-webkit-datetime-edit-year-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-meridiem-field {
padding-top: 0;
padding-bottom: 0;
}
select {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
[multiple] {
background-image: initial;
background-position: initial;
background-repeat: unset;
background-size: initial;
padding-right: 0.75rem;
-webkit-print-color-adjust: unset;
print-color-adjust: unset;
}
[type='checkbox'],[type='radio'] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
padding: 0;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
display: inline-block;
vertical-align: middle;
background-origin: border-box;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
flex-shrink: 0;
height: 1rem;
width: 1rem;
color: #2563eb;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
--tw-shadow: 0 0 #0000;
}
[type='checkbox'] {
border-radius: 0px;
}
[type='radio'] {
border-radius: 100%;
}
[type='checkbox']:focus,[type='radio']:focus {
outline: 2px solid transparent;
outline-offset: 2px;
--tw-ring-inset: var(--tw-empty,/*!*/ /*!*/);
--tw-ring-offset-width: 2px;
--tw-ring-offset-color: #fff;
--tw-ring-color: #2563eb;
--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);
box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);
}
[type='checkbox']:checked,[type='radio']:checked {
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e");
}
[type='radio']:checked {
background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e");
}
[type='checkbox']:checked:hover,[type='checkbox']:checked:focus,[type='radio']:checked:hover,[type='radio']:checked:focus {
border-color: transparent;
background-color: currentColor;
}
[type='checkbox']:indeterminate {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 16 16'%3e%3cpath stroke='white' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 8h8'/%3e%3c/svg%3e");
border-color: transparent;
background-color: currentColor;
background-size: 100% 100%;
background-position: center;
background-repeat: no-repeat;
}
[type='checkbox']:indeterminate:hover,[type='checkbox']:indeterminate:focus {
border-color: transparent;
background-color: currentColor;
}
[type='file'] {
background: unset;
border-color: inherit;
border-width: 0;
border-radius: 0;
padding: 0;
font-size: unset;
line-height: inherit;
}
[type='file']:focus {
outline: 1px solid ButtonText;
outline: 1px auto -webkit-focus-ring-color;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.block {
display: block;
}
.text-\[--brand-color\] {
color: var(--brand-color);
}
.text-green-600 {
--tw-text-opacity: 1;
color: rgb(22 163 74 / var(--tw-text-opacity));
}
.opacity-75 {
opacity: 0.75;
}
@media (prefers-color-scheme: dark) {
.dark\:text-green-500 {
--tw-text-opacity: 1;
color: rgb(34 197 94 / var(--tw-text-opacity));
}
}

View file

@ -0,0 +1,15 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"],
},
theme: {
extend: {},
},
corePlugins: {
preflight: false,
},
plugins: [
require('@tailwindcss/forms'),
],
}

View file

@ -14,11 +14,17 @@ pub mod utils;
// #[cfg(web_sys_unstable_apis)] // #[cfg(web_sys_unstable_apis)]
// pub use use_webtransport::*; // pub use use_webtransport::*;
#[cfg(web_sys_unstable_apis)]
mod use_clipboard;
#[cfg(web_sys_unstable_apis)]
pub use use_clipboard::*;
mod is_err; mod is_err;
mod is_none; mod is_none;
mod is_ok; mod is_ok;
mod is_some; mod is_some;
mod on_click_outside; mod on_click_outside;
mod use_permission;
mod signal_debounced; mod signal_debounced;
mod signal_throttled; mod signal_throttled;
mod use_active_element; mod use_active_element;
@ -62,6 +68,7 @@ mod use_service_worker;
mod use_sorted; mod use_sorted;
mod use_supported; mod use_supported;
mod use_throttle_fn; mod use_throttle_fn;
mod use_timeout_fn;
mod use_timestamp; mod use_timestamp;
mod use_to_string; mod use_to_string;
mod use_web_notification; mod use_web_notification;
@ -80,6 +87,7 @@ pub use is_none::*;
pub use is_ok::*; pub use is_ok::*;
pub use is_some::*; pub use is_some::*;
pub use on_click_outside::*; pub use on_click_outside::*;
pub use use_permission::*;
pub use signal_debounced::*; pub use signal_debounced::*;
pub use signal_throttled::*; pub use signal_throttled::*;
pub use use_active_element::*; pub use use_active_element::*;
@ -123,6 +131,7 @@ pub use use_service_worker::*;
pub use use_sorted::*; pub use use_sorted::*;
pub use use_supported::*; pub use use_supported::*;
pub use use_throttle_fn::*; pub use use_throttle_fn::*;
pub use use_timeout_fn::*;
pub use use_timestamp::*; pub use use_timestamp::*;
pub use use_to_string::*; pub use use_to_string::*;
pub use use_web_notification::*; pub use use_web_notification::*;

View file

@ -1,6 +1,6 @@
use crate::utils::StringCodec; use crate::utils::StringCodec;
use crate::{ use crate::{
use_event_listener, use_event_listener_with_options, use_supported, UseEventListenerOptions, js, use_event_listener, use_event_listener_with_options, use_supported, UseEventListenerOptions,
}; };
use leptos::*; use leptos::*;
use thiserror::Error; use thiserror::Error;
@ -75,7 +75,7 @@ pub fn use_broadcast_channel<T, C>(
where where
C: StringCodec<T> + Default + Clone, C: StringCodec<T> + Default + Clone,
{ {
let is_supported = use_supported(|| JsValue::from("BroadcastChannel").js_in(&window())); let is_supported = use_supported(|| js!("BroadcastChannel" in &window()));
let (is_closed, set_closed) = create_signal(false); let (is_closed, set_closed) = create_signal(false);
let (channel, set_channel) = create_signal(None::<web_sys::BroadcastChannel>); let (channel, set_channel) = create_signal(None::<web_sys::BroadcastChannel>);

159
src/use_clipboard.rs Normal file
View file

@ -0,0 +1,159 @@
use crate::{js, js_fut, use_event_listener, use_supported, UseTimeoutFnReturn};
use default_struct_builder::DefaultBuilder;
use leptos::ev::{copy, cut};
use leptos::*;
/// Reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API).
/// Provides the ability to respond to clipboard commands (cut, copy, and paste)
/// as well as to asynchronously read from and write to the system clipboard.
/// Access to the contents of the clipboard is gated behind the
/// [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API).
/// Without user permission, reading or altering the clipboard contents is not permitted.
///
/// > This function requires `--cfg=web_sys_unstable_apis` to be activated as
/// [described in the wasm-bindgen guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html).
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_clipboard)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_clipboard, UseClipboardReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let UsClipboardReturn { is_supported, text, copied, copy } = use_clipboard();
///
/// view! {
/// <Show
/// when=is_supported
/// fallback=move || view! { <p>Your browser does not support Clipboard API</p> }
/// >
/// <button on:click=move |_| copy("Hello!")>
/// <Show when=copied fallback=move || "Copy">
/// "Copied!"
/// </Show>
/// </button>
/// </Show>
/// }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server the returnd `text` signal will always be `None` and `copy` is a no-op.
pub fn use_clipboard() -> UseClipboardReturn<impl Fn(&str) + Clone> {
use_clipboard_with_options(UseClipboardOptions::default())
}
/// Version of [`use_clipboard`] that takes a `UseClipboardOptions`. See [`use_clipboard`] for how to use.
pub fn use_clipboard_with_options(
options: UseClipboardOptions,
) -> UseClipboardReturn<impl Fn(&str) + Clone> {
let UseClipboardOptions {
copied_reset_delay,
read,
} = options;
let is_supported = use_supported(|| {
js!("clipboard" in &window()
.navigator())
});
let (text, set_text) = create_signal(None);
let (copied, set_copied) = create_signal(false);
let UseTimeoutFnReturn { start, .. } = crate::use_timeout_fn::use_timeout_fn(
move |_: ()| {
set_copied.set(false);
},
copied_reset_delay,
);
let update_text = move |_| {
if is_supported.get() {
spawn_local(async move {
if let Some(clipboard) = window().navigator().clipboard() {
if let Ok(text) = js_fut!(clipboard.read_text()).await {
set_text.set(text.as_string());
}
}
})
}
};
if is_supported.get() && read {
let _ = use_event_listener(window(), copy, update_text.clone());
let _ = use_event_listener(window(), cut, update_text);
}
let do_copy = {
let start = start.clone();
move |value: &str| {
if is_supported.get() {
let start = start.clone();
let value = value.to_owned();
spawn_local(async move {
if let Some(clipboard) = window().navigator().clipboard() {
if js_fut!(clipboard.write_text(&value)).await.is_ok() {
set_text.set(Some(value));
set_copied.set(true);
start(());
}
}
});
}
}
};
UseClipboardReturn {
is_supported,
text: text.into(),
copied: copied.into(),
copy: do_copy,
}
}
/// Options for [`use_clipboard_with_options`].
#[derive(DefaultBuilder)]
pub struct UseClipboardOptions {
/// When `true` event handlers are added so that the returned signal `text` is updated whenever the clipboard changes.
/// Defaults to `false`.
read: bool,
/// After how many milliseconds after copying should the returned signal `copied` be set to `false`?
/// Defaults to 1500.
copied_reset_delay: f64,
}
impl Default for UseClipboardOptions {
fn default() -> Self {
Self {
read: false,
copied_reset_delay: 1500.0,
}
}
}
/// Return type of [`use_clipboard`].
pub struct UseClipboardReturn<CopyFn>
where
CopyFn: Fn(&str) + Clone,
{
/// Whether the Clipboard API is supported.
pub is_supported: Signal<bool>,
/// The current state of the clipboard.
pub text: Signal<Option<String>>,
/// `true` for [`UseClipboardOptions::copied_reset_delay`] milliseconds after copying.
pub copied: Signal<bool>,
/// Copy the given text to the clipboard.
pub copy: CopyFn,
}

View file

@ -41,14 +41,10 @@ pub fn use_device_orientation() -> UseDeviceOrientationReturn {
let beta = || None; let beta = || None;
let gamma = || None; let gamma = || None;
} else { } else {
use crate::{use_event_listener_with_options, UseEventListenerOptions, use_supported}; use crate::{use_event_listener_with_options, UseEventListenerOptions, use_supported, js};
use leptos::ev::deviceorientation; use leptos::ev::deviceorientation;
use wasm_bindgen::JsValue;
let is_supported = use_supported(|| js_sys::Reflect::has( let is_supported = use_supported(|| js!("DeviceOrientationEvent" in &window()));
&window(),
&JsValue::from_str("DeviceOrientationEvent"),
).unwrap_or(false));
let (absolute, set_absolute) = create_signal(false); let (absolute, set_absolute) = create_signal(false);
let (alpha, set_alpha) = create_signal(None); let (alpha, set_alpha) = create_signal(None);
let (beta, set_beta) = create_signal(None); let (beta, set_beta) = create_signal(None);

View file

@ -123,6 +123,7 @@ pub fn use_display_media_with_options(
#[cfg(not(feature = "ssr"))] #[cfg(not(feature = "ssr"))]
async fn create_media(audio: bool) -> Result<web_sys::MediaStream, JsValue> { async fn create_media(audio: bool) -> Result<web_sys::MediaStream, JsValue> {
use crate::js_fut;
use crate::use_window::use_window; use crate::use_window::use_window;
let media = use_window() let media = use_window()
@ -136,7 +137,7 @@ async fn create_media(audio: bool) -> Result<web_sys::MediaStream, JsValue> {
} }
let promise = media.get_display_media_with_constraints(&constraints)?; let promise = media.get_display_media_with_constraints(&constraints)?;
let res = wasm_bindgen_futures::JsFuture::from(promise).await?; let res = js_fut!(promise).await?;
Ok::<_, JsValue>(web_sys::MediaStream::unchecked_from_js(res)) Ok::<_, JsValue>(web_sys::MediaStream::unchecked_from_js(res))
} }

View file

@ -1,9 +1,9 @@
#![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports, dead_code))] #![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports, dead_code))]
use crate::js;
use crate::utils::js_value_from_to_string; use crate::utils::js_value_from_to_string;
use cfg_if::cfg_if; use cfg_if::cfg_if;
use default_struct_builder::DefaultBuilder; use default_struct_builder::DefaultBuilder;
use js_sys::Reflect;
use leptos::*; use leptos::*;
use std::fmt::Display; use std::fmt::Display;
use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::{JsCast, JsValue};
@ -712,94 +712,48 @@ impl From<UseIntlNumberFormatOptions> for js_sys::Object {
fn from(options: UseIntlNumberFormatOptions) -> Self { fn from(options: UseIntlNumberFormatOptions) -> Self {
let obj = Self::new(); let obj = Self::new();
let _ = Reflect::set( js!(obj["compactDisplay"] = options.compact_display);
&obj,
&"compactDisplay".into(),
&options.compact_display.into(),
);
if let Some(currency) = options.currency { if let Some(currency) = options.currency {
let _ = Reflect::set(&obj, &"currency".into(), &currency.into()); js!(obj["currency"] = currency);
} }
let _ = Reflect::set( js!(obj["currencyDisplay"] = options.currency_display);
&obj, js!(obj["currencySign"] = options.currency_sign);
&"currencyDisplay".into(), js!(obj["localeMatcher"] = options.locale_matcher);
&options.currency_display.into(), js!(obj["notation"] = options.notation);
);
let _ = Reflect::set(&obj, &"currencySign".into(), &options.currency_sign.into());
let _ = Reflect::set(
&obj,
&"localeMatcher".into(),
&options.locale_matcher.into(),
);
let _ = Reflect::set(&obj, &"notation".into(), &options.notation.into());
if let Some(numbering_system) = options.numbering_system { if let Some(numbering_system) = options.numbering_system {
let _ = Reflect::set(&obj, &"numberingSystem".into(), &numbering_system.into()); js!(obj["numberingSystem"] = numbering_system);
} }
let _ = Reflect::set(&obj, &"signDisplay".into(), &options.sign_display.into()); js!(obj["signDisplay"] = options.sign_display);
let _ = Reflect::set(&obj, &"style".into(), &options.style.into()); js!(obj["style"] = options.style);
if let Some(unit) = options.unit { if let Some(unit) = options.unit {
let _ = Reflect::set(&obj, &"unit".into(), &unit.into()); js!(obj["unit"] = unit);
} }
let _ = Reflect::set(&obj, &"unitDisplay".into(), &options.unit_display.into()); js!(obj["unitDisplay"] = options.unit_display);
let _ = Reflect::set(&obj, &"useGrouping".into(), &options.use_grouping.into()); js!(obj["useGrouping"] = options.use_grouping);
js!(obj["roundingMode"] = options.rounding_mode);
js!(obj["roundingPriority"] = options.rounding_priority);
js!(obj["roundingIncrement"] = options.rounding_increment);
js!(obj["trailingZeroDisplay"] = options.trailing_zero_display);
js!(obj["minimumIntegerDigits"] = options.minimum_integer_digits);
let _ = Reflect::set(&obj, &"roundingMode".into(), &options.rounding_mode.into());
let _ = Reflect::set(
&obj,
&"roundingPriority".into(),
&options.rounding_priority.into(),
);
let _ = Reflect::set(
&obj,
&"roundingIncrement".into(),
&options.rounding_increment.into(),
);
let _ = Reflect::set(
&obj,
&"trailingZeroDisplay".into(),
&options.trailing_zero_display.into(),
);
let _ = Reflect::set(
&obj,
&"minimumIntegerDigits".into(),
&options.minimum_integer_digits.into(),
);
if let Some(minimum_fraction_digits) = options.minimum_fraction_digits { if let Some(minimum_fraction_digits) = options.minimum_fraction_digits {
let _ = Reflect::set( js!(obj["minimumFractionDigits"] = minimum_fraction_digits);
&obj,
&"minimumFractionDigits".into(),
&minimum_fraction_digits.into(),
);
} }
if let Some(maximum_fraction_digits) = options.maximum_fraction_digits { if let Some(maximum_fraction_digits) = options.maximum_fraction_digits {
let _ = Reflect::set( js!(obj["maximumFractionDigits"] = maximum_fraction_digits);
&obj,
&"maximumFractionDigits".into(),
&maximum_fraction_digits.into(),
);
} }
if let Some(minimum_significant_digits) = options.minimum_significant_digits { if let Some(minimum_significant_digits) = options.minimum_significant_digits {
let _ = Reflect::set( js!(obj["minimumSignificantDigits"] = minimum_significant_digits);
&obj,
&"minimumSignificantDigits".into(),
&minimum_significant_digits.into(),
);
} }
if let Some(maximum_significant_digits) = options.maximum_significant_digits { if let Some(maximum_significant_digits) = options.maximum_significant_digits {
let _ = Reflect::set( js!(obj["maximumSignificantDigits"] = maximum_significant_digits);
&obj,
&"maximumSignificantDigits".into(),
&maximum_significant_digits.into(),
);
} }
obj obj
@ -915,7 +869,7 @@ impl UseIntlNumberFormatReturn {
let number_format = self.js_intl_number_format.clone(); let number_format = self.js_intl_number_format.clone();
Signal::derive(move || { Signal::derive(move || {
if let Ok(function) = Reflect::get(&number_format, &"formatRange".into()) { if let Ok(function) = js!(number_format["formatRange"]) {
let function = function.unchecked_into::<js_sys::Function>(); let function = function.unchecked_into::<js_sys::Function>();
if let Ok(result) = function.call2( if let Ok(result) = function.call2(

View file

@ -79,6 +79,8 @@ where
stop: || {}, stop: || {},
} }
} else { } else {
use crate::js;
let closure_js = Closure::<dyn FnMut(js_sys::Array, web_sys::MutationObserver)>::new( let closure_js = Closure::<dyn FnMut(js_sys::Array, web_sys::MutationObserver)>::new(
move |entries: js_sys::Array, observer| { move |entries: js_sys::Array, observer| {
callback( callback(
@ -95,7 +97,7 @@ where
let observer: Rc<RefCell<Option<web_sys::MutationObserver>>> = Rc::new(RefCell::new(None)); let observer: Rc<RefCell<Option<web_sys::MutationObserver>>> = Rc::new(RefCell::new(None));
let is_supported = use_supported(|| JsValue::from("MutationObserver").js_in(&window())); let is_supported = use_supported(|| js!("MutationObserver" in &window()));
let cleanup = { let cleanup = {
let observer = Rc::clone(&observer); let observer = Rc::clone(&observer);

132
src/use_permission.rs Normal file
View file

@ -0,0 +1,132 @@
use leptos::*;
use std::fmt::Display;
/// Reactive [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API).
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_permission)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::use_permission;
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let microphone_access = use_permission("microphone");
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server the returned signal will always be `PermissionState::Unknown`.
pub fn use_permission(permission_name: &str) -> Signal<PermissionState> {
let (state, set_state) = create_signal(PermissionState::Unknown);
#[cfg(not(feature = "ssr"))]
{
use crate::use_event_listener;
use std::cell::RefCell;
use std::rc::Rc;
let permission_status = Rc::new(RefCell::new(None::<web_sys::PermissionStatus>));
let on_change = {
let permission_status = Rc::clone(&permission_status);
move || {
if let Some(permission_status) = permission_status.borrow().as_ref() {
set_state.set(PermissionState::from(permission_status.state()));
}
}
};
spawn_local({
let permission_name = permission_name.to_owned();
async move {
if let Ok(status) = query_permission(permission_name).await {
let _ = use_event_listener(status.clone(), ev::change, {
let on_change = on_change.clone();
move |_| on_change()
});
permission_status.replace(Some(status));
on_change();
} else {
set_state.set(PermissionState::Prompt);
}
}
});
}
#[cfg(feature = "ssr")]
{
let _ = set_state;
let _ = permission_name;
}
state.into()
}
/// Return type of [`use_permission`].
#[derive(Copy, Clone, Default, Eq, PartialEq)]
pub enum PermissionState {
/// State hasn't been requested yet. This is the initial value.
#[default]
Unknown,
/// The permission has been granted by the user.
Granted,
/// The user will automatically be prompted to give permission once the relevant API is called.
Prompt,
/// The user has denied permission.
Denied,
}
impl Display for PermissionState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
PermissionState::Unknown => write!(f, "unknown"),
PermissionState::Granted => write!(f, "granted"),
PermissionState::Prompt => write!(f, "prompt"),
PermissionState::Denied => write!(f, "denied"),
}
}
}
impl From<web_sys::PermissionState> for PermissionState {
fn from(permission_state: web_sys::PermissionState) -> Self {
match permission_state {
web_sys::PermissionState::Granted => PermissionState::Granted,
web_sys::PermissionState::Prompt => PermissionState::Prompt,
web_sys::PermissionState::Denied => PermissionState::Denied,
_ => PermissionState::Unknown,
}
}
}
#[cfg(not(feature = "ssr"))]
async fn query_permission(
permission: String,
) -> Result<web_sys::PermissionStatus, wasm_bindgen::JsValue> {
use crate::{js, js_fut};
use wasm_bindgen::JsCast;
let permission_object = js_sys::Object::new();
js!(permission_object["name"] = permission);
let permission_state: web_sys::PermissionStatus = js_fut!(window()
.navigator()
.permissions()?
.query(&permission_object)?)
.await?
.unchecked_into();
Ok(permission_state)
}

View file

@ -85,6 +85,8 @@ where
#[cfg(not(feature = "ssr"))] #[cfg(not(feature = "ssr"))]
{ {
use crate::js;
let closure_js = Closure::<dyn FnMut(js_sys::Array, web_sys::ResizeObserver)>::new( let closure_js = Closure::<dyn FnMut(js_sys::Array, web_sys::ResizeObserver)>::new(
move |entries: js_sys::Array, observer| { move |entries: js_sys::Array, observer| {
callback( callback(
@ -101,7 +103,7 @@ where
let observer: Rc<RefCell<Option<web_sys::ResizeObserver>>> = Rc::new(RefCell::new(None)); let observer: Rc<RefCell<Option<web_sys::ResizeObserver>>> = Rc::new(RefCell::new(None));
let is_supported = use_supported(|| JsValue::from("ResizeObserver").js_in(&window())); let is_supported = use_supported(|| js!("ResizeObserver" in &window()));
let cleanup = { let cleanup = {
let observer = Rc::clone(&observer); let observer = Rc::clone(&observer);

View file

@ -4,7 +4,7 @@ use std::rc::Rc;
use wasm_bindgen::{prelude::Closure, JsCast, JsValue}; use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
use web_sys::ServiceWorkerRegistration; use web_sys::ServiceWorkerRegistration;
use crate::use_window; use crate::{js_fut, use_window};
/// Reactive [ServiceWorker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API). /// Reactive [ServiceWorker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
/// ///
@ -239,7 +239,7 @@ fn create_action_update(
let registration = registration.clone(); let registration = registration.clone();
async move { async move {
match registration.update() { match registration.update() {
Ok(promise) => wasm_bindgen_futures::JsFuture::from(promise) Ok(promise) => js_fut!(promise)
.await .await
.and_then(|ok| ok.dyn_into::<ServiceWorkerRegistration>()), .and_then(|ok| ok.dyn_into::<ServiceWorkerRegistration>()),
Err(err) => Err(err), Err(err) => Err(err),
@ -255,8 +255,7 @@ fn create_action_create_or_update_registration(
let script_url = script_url.0.to_owned(); let script_url = script_url.0.to_owned();
async move { async move {
if let Some(navigator) = use_window().navigator() { if let Some(navigator) = use_window().navigator() {
let promise = navigator.service_worker().register(script_url.as_str()); js_fut!(navigator.service_worker().register(script_url.as_str()))
wasm_bindgen_futures::JsFuture::from(promise)
.await .await
.and_then(|ok| ok.dyn_into::<ServiceWorkerRegistration>()) .and_then(|ok| ok.dyn_into::<ServiceWorkerRegistration>())
} else { } else {
@ -270,8 +269,7 @@ fn create_action_create_or_update_registration(
fn create_action_get_registration() -> Action<(), Result<ServiceWorkerRegistration, JsValue>> { fn create_action_get_registration() -> Action<(), Result<ServiceWorkerRegistration, JsValue>> {
create_action(move |(): &()| async move { create_action(move |(): &()| async move {
if let Some(navigator) = use_window().navigator() { if let Some(navigator) = use_window().navigator() {
let promise = navigator.service_worker().get_registration(); js_fut!(navigator.service_worker().get_registration())
wasm_bindgen_futures::JsFuture::from(promise)
.await .await
.and_then(|ok| ok.dyn_into::<ServiceWorkerRegistration>()) .and_then(|ok| ok.dyn_into::<ServiceWorkerRegistration>())
} else { } else {

View file

@ -6,12 +6,12 @@ use leptos::*;
/// ///
/// ``` /// ```
/// # use leptos::*; /// # use leptos::*;
/// # use leptos_use::use_supported; /// # use leptos_use::{use_supported, js};
/// # use wasm_bindgen::JsValue; /// # use wasm_bindgen::JsValue;
/// # /// #
/// # pub fn Demo() -> impl IntoView { /// # pub fn Demo() -> impl IntoView {
/// let is_supported = use_supported( /// let is_supported = use_supported(
/// || JsValue::from("getBattery").js_in(&window().navigator()) /// || js!("getBattery" in &window().navigator())
/// ); /// );
/// ///
/// if is_supported.get() { /// if is_supported.get() {
@ -21,5 +21,14 @@ use leptos::*;
/// # } /// # }
/// ``` /// ```
pub fn use_supported(callback: impl Fn() -> bool + 'static) -> Signal<bool> { pub fn use_supported(callback: impl Fn() -> bool + 'static) -> Signal<bool> {
Signal::derive(callback) #[cfg(feature = "ssr")]
{
let _ = callback;
Signal::derive(|| false)
}
#[cfg(not(feature = "ssr"))]
{
Signal::derive(callback)
}
} }

121
src/use_timeout_fn.rs Normal file
View file

@ -0,0 +1,121 @@
use leptos::leptos_dom::helpers::TimeoutHandle;
use leptos::*;
use std::cell::Cell;
use std::marker::PhantomData;
use std::rc::Rc;
use std::time::Duration;
/// Wrapper for `setTimeout` with controls.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_timeout_fn)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_timeout_fn, UseTimeoutFnReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let UseTimeoutFnReturn { start, stop, is_pending, .. } = use_timeout_fn(
/// |i: i32| {
/// // do sth
/// },
/// 3000.0
/// );
///
/// start(3);
/// #
/// # view! { }
/// # }
/// ```
pub fn use_timeout_fn<CbFn, Arg, D>(
callback: CbFn,
delay: D,
) -> UseTimeoutFnReturn<impl Fn(Arg) + Clone, Arg, impl Fn() + Clone>
where
CbFn: Fn(Arg) + Clone + 'static,
Arg: 'static,
D: Into<MaybeSignal<f64>>,
{
let delay = delay.into();
let (is_pending, set_pending) = create_signal(false);
let timer = Rc::new(Cell::new(None::<TimeoutHandle>));
let clear = {
let timer = Rc::clone(&timer);
move || {
if let Some(timer) = timer.take() {
timer.clear();
}
}
};
let stop = {
let clear = clear.clone();
move || {
set_pending.set(false);
clear();
}
};
let start = {
let timer = Rc::clone(&timer);
let callback = callback.clone();
move |arg: Arg| {
set_pending.set(true);
let handle = set_timeout_with_handle(
{
let timer = Rc::clone(&timer);
let callback = callback.clone();
move || {
set_pending.set(false);
timer.set(None);
callback(arg);
}
},
Duration::from_millis(delay.get_untracked() as u64),
)
.ok();
timer.set(handle);
}
};
on_cleanup(clear);
UseTimeoutFnReturn {
is_pending: is_pending.into(),
start,
stop,
_marker: PhantomData,
}
}
/// Return type of [`use_timeout_fn`].
pub struct UseTimeoutFnReturn<StartFn, StartArg, StopFn>
where
StartFn: Fn(StartArg) + Clone,
StopFn: Fn() + Clone,
{
/// Whether the timeout is pending. When the `callback` is called this is set to `false`.
pub is_pending: Signal<bool>,
/// Start the timeout. The `callback` will be called after `delay` milliseconds.
pub start: StartFn,
/// Stop the timeout. If the timeout was still pending the `callback` is not called.
pub stop: StopFn,
_marker: PhantomData<StartArg>,
}

View file

@ -435,7 +435,7 @@ impl From<web_sys::NotificationPermission> for NotificationPermission {
#[cfg(not(feature = "ssr"))] #[cfg(not(feature = "ssr"))]
async fn request_web_notification_permission() -> NotificationPermission { async fn request_web_notification_permission() -> NotificationPermission {
if let Ok(notification_permission) = web_sys::Notification::request_permission() { if let Ok(notification_permission) = web_sys::Notification::request_permission() {
let _ = wasm_bindgen_futures::JsFuture::from(notification_permission).await; let _ = crate::js_fut!(notification_permission).await;
} }
web_sys::Notification::permission().into() web_sys::Notification::permission().into()

View file

@ -130,7 +130,7 @@ pub fn use_webtransport_with_options(
let transport = transport.borrow(); let transport = transport.borrow();
let transport = transport.as_ref().expect("Transport should be set"); let transport = transport.as_ref().expect("Transport should be set");
match JsFuture::from(transport.ready()).await { match js_fut!(transport.ready()).await {
Ok(_) => { Ok(_) => {
set_ready_state.set(ConnectionReadyState::Open); set_ready_state.set(ConnectionReadyState::Open);
on_open(); on_open();
@ -213,7 +213,7 @@ pub fn use_webtransport_with_options(
set_ready_state.set(ConnectionReadyState::Closing); set_ready_state.set(ConnectionReadyState::Closing);
spawn_local(async move { spawn_local(async move {
let result = JsFuture::from(transport.closed()).await; let result = js_fut!(transport.closed()).await;
set_ready_state.set(ConnectionReadyState::Closed); set_ready_state.set(ConnectionReadyState::Closed);
on_closed(); on_closed();
@ -345,10 +345,10 @@ fn listen_to_stream(
spawn_local(async move { spawn_local(async move {
loop { loop {
let result = JsFuture::from(reader.read()).await; let result = js_fut!(reader.read()).await;
match result { match result {
Ok(result) => { Ok(result) => {
let done = Reflect::get(&result, &"done".into()) let done = js!(result["done"])
.expect("done should always be there") .expect("done should always be there")
.as_bool() .as_bool()
.unwrap_or(true); .unwrap_or(true);
@ -358,8 +358,7 @@ fn listen_to_stream(
break; break;
} }
let value = Reflect::get(&result, &"value".into()) let value = js!(result["value"]).expect("if not done there should be a value");
.expect("if not done there should be a value");
on_value(value); on_value(value);
} }
@ -460,7 +459,7 @@ pub trait SendableStream: CloseableStream {
} }
let arr = js_sys::Uint8Array::from(data); let arr = js_sys::Uint8Array::from(data);
let _ = JsFuture::from(self.writer().write_with_chunk(&arr)) let _ = js_fut!(self.writer().write_with_chunk(&arr))
.await .await
.map_err(|e| SendError::FailedToWrite(e)); .map_err(|e| SendError::FailedToWrite(e));
@ -598,7 +597,7 @@ macro_rules! impl_closable_stream {
} }
async fn close_async(&self) -> Result<(), WebTransportError> { async fn close_async(&self) -> Result<(), WebTransportError> {
let _ = JsFuture::from(self.writer.close()).await.map_err(|e| { let _ = js_fut!(self.writer.close()).await.map_err(|e| {
let error = WebTransportError::OnCloseWriter(e); let error = WebTransportError::OnCloseWriter(e);
self.set_state.set(StreamState::Closed); self.set_state.set(StreamState::Closed);
error error
@ -650,7 +649,7 @@ impl UseWebTransportReturn {
/// Open a unidirectional send stream /// Open a unidirectional send stream
pub async fn open_send_stream(&self) -> Result<SendStream, WebTransportError> { pub async fn open_send_stream(&self) -> Result<SendStream, WebTransportError> {
if let Some(transport) = self.transport.borrow().as_ref() { if let Some(transport) = self.transport.borrow().as_ref() {
let result = JsFuture::from(transport.create_unidirectional_stream()) let result = js_fut!(transport.create_unidirectional_stream())
.await .await
.map_err(|e| WebTransportError::FailedToOpenStream(e))?; .map_err(|e| WebTransportError::FailedToOpenStream(e))?;
let stream: web_sys::WritableStream = result.unchecked_into(); let stream: web_sys::WritableStream = result.unchecked_into();
@ -673,7 +672,7 @@ impl UseWebTransportReturn {
/// Open a bidirectional stream /// Open a bidirectional stream
pub async fn open_bidir_stream(&self) -> Result<BidirStream, WebTransportError> { pub async fn open_bidir_stream(&self) -> Result<BidirStream, WebTransportError> {
if let Some(transport) = self.transport.borrow().as_ref() { if let Some(transport) = self.transport.borrow().as_ref() {
let result = JsFuture::from(transport.create_bidirectional_stream()) let result = js_fut!(transport.create_bidirectional_stream())
.await .await
.map_err(|e| WebTransportError::FailedToOpenStream(e))?; .map_err(|e| WebTransportError::FailedToOpenStream(e))?;
let stream: web_sys::WebTransportBidirectionalStream = result.unchecked_into(); let stream: web_sys::WebTransportBidirectionalStream = result.unchecked_into();

20
src/utils/js.rs Normal file
View file

@ -0,0 +1,20 @@
#[macro_export]
macro_rules! js {
($attr:literal in $($obj:tt)*) => {
wasm_bindgen::JsValue::from($attr).js_in($($obj)*)
};
($obj:ident[$attr:literal] = $($val:tt)*) => {
let _ = js_sys::Reflect::set(&$obj, &$attr.into(), &($($val)*).into());
};
($obj:ident[$attr:literal]) => {
js_sys::Reflect::get(&$obj, &$attr.into())
};
}
#[macro_export]
macro_rules! js_fut {
($($obj:tt)*) => {
wasm_bindgen_futures::JsFuture::from($($obj)*)
};
}

View file

@ -1,6 +1,7 @@
mod codecs; mod codecs;
mod filters; mod filters;
mod is; mod is;
mod js;
mod js_value_from_to_string; mod js_value_from_to_string;
mod pausable; mod pausable;
mod signal_filtered; mod signal_filtered;