diff --git a/.idea/leptos-use.iml b/.idea/leptos-use.iml index 6502715..a3f5219 100644 --- a/.idea/leptos-use.iml +++ b/.idea/leptos-use.iml @@ -69,6 +69,9 @@ + + + diff --git a/CHANGELOG.md b/CHANGELOG.md index fd47900..e6017d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ 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). +## [Unreleased] - + +### New Functions 🚀 + +- `use_permission` +- `use_clipboard` +- `use_timeout_fn` + ## [0.10.1] - 2024-010-31 ### Fix 🍕 diff --git a/Cargo.toml b/Cargo.toml index c53ee71..f131f83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,7 @@ features = [ "BinaryType", "BroadcastChannel", "Coordinates", + "Clipboard", "CloseEvent", "CssStyleDeclaration", "CustomEvent", @@ -84,6 +85,9 @@ features = [ "NotificationDirection", "NotificationOptions", "NotificationPermission", + "Permissions", + "PermissionState", + "PermissionStatus", "PointerEvent", "Position", "PositionError", diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index 6912e52..e5bcf1d 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -35,6 +35,7 @@ - [use_breakpoints](browser/use_breakpoints.md) - [use_broadcast_channel](browser/use_broadcast_channel.md) +- [use_clipboard](browser/use_clipboard.md) - [use_color_mode](browser/use_color_mode.md) - [use_cookie](browser/use_cookie.md) - [use_css_var](browser/use_css_var.md) @@ -42,6 +43,7 @@ - [use_event_listener](browser/use_event_listener.md) - [use_favicon](browser/use_favicon.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_dark](browser/use_preferred_dark.md) - [use_service_worker](browser/use_service_worker.md) @@ -69,6 +71,7 @@ - [use_interval](animation/use_interval.md) - [use_interval_fn](animation/use_interval_fn.md) - [use_raf_fn](animation/use_raf_fn.md) +- [use_timeout_fn](animation/use_timeout_fn.md) - [use_timestamp](animation/use_timestamp.md) # Watch diff --git a/docs/book/src/animation/use_timeout_fn.md b/docs/book/src/animation/use_timeout_fn.md new file mode 100644 index 0000000..30f9740 --- /dev/null +++ b/docs/book/src/animation/use_timeout_fn.md @@ -0,0 +1,3 @@ +# use_timeout_fn + + diff --git a/docs/book/src/browser/use_clipboard.md b/docs/book/src/browser/use_clipboard.md new file mode 100644 index 0000000..f3df1c8 --- /dev/null +++ b/docs/book/src/browser/use_clipboard.md @@ -0,0 +1,3 @@ +# use_clipboard + + diff --git a/docs/book/src/browser/use_permission.md b/docs/book/src/browser/use_permission.md new file mode 100644 index 0000000..ec8c074 --- /dev/null +++ b/docs/book/src/browser/use_permission.md @@ -0,0 +1,3 @@ +# use_permission + + diff --git a/examples/Cargo.toml b/examples/Cargo.toml index fdbad1d..b299063 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -10,6 +10,7 @@ members = [ "use_breakpoints", "use_broadcast_channel", "use_ceil", + "use_clipboard", "use_color_mode", "use_cookie", "use_css_var", @@ -39,6 +40,7 @@ members = [ "use_mouse", "use_mouse_in_element", "use_mutation_observer", + "use_permission", "use_raf_fn", "use_resize_observer", "use_round", @@ -47,6 +49,7 @@ members = [ "use_sorted", "use_storage", "use_throttle_fn", + "use_timeout_fn", "use_timestamp", "use_web_notification", "use_websocket", diff --git a/examples/use_clipboard/.cargo/config.toml b/examples/use_clipboard/.cargo/config.toml new file mode 100644 index 0000000..8467175 --- /dev/null +++ b/examples/use_clipboard/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +rustflags = ["--cfg=web_sys_unstable_apis"] diff --git a/examples/use_clipboard/Cargo.toml b/examples/use_clipboard/Cargo.toml new file mode 100644 index 0000000..d85ad83 --- /dev/null +++ b/examples/use_clipboard/Cargo.toml @@ -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" diff --git a/examples/use_clipboard/README.md b/examples/use_clipboard/README.md new file mode 100644 index 0000000..28aeb87 --- /dev/null +++ b/examples/use_clipboard/README.md @@ -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 +``` \ No newline at end of file diff --git a/examples/use_clipboard/Trunk.toml b/examples/use_clipboard/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_clipboard/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_clipboard/index.html b/examples/use_clipboard/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_clipboard/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_clipboard/input.css b/examples/use_clipboard/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_clipboard/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_clipboard/rust-toolchain.toml b/examples/use_clipboard/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_clipboard/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_clipboard/src/main.rs b/examples/use_clipboard/src/main.rs new file mode 100644 index 0000000..e7852b3 --- /dev/null +++ b/examples/use_clipboard/src/main.rs @@ -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! { + Your browser does not support the Clipboard API

} + > + + Clipboard Permission: + read {move || permission_read().to_string()} | + write {move || permission_write().to_string()} + +

Currently copied: {move || text().unwrap_or("none".to_owned())}

+ + +
+ } +} + +fn main() { + _ = console_log::init_with_level(log::Level::Debug); + console_error_panic_hook::set_once(); + + mount_to(demo_or_body(), || { + view! { } + }) +} diff --git a/examples/use_clipboard/style/output.css b/examples/use_clipboard/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_clipboard/style/output.css @@ -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)); + } +} \ No newline at end of file diff --git a/examples/use_clipboard/tailwind.config.js b/examples/use_clipboard/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_clipboard/tailwind.config.js @@ -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'), + ], +} \ No newline at end of file diff --git a/examples/use_permission/Cargo.toml b/examples/use_permission/Cargo.toml new file mode 100644 index 0000000..17f2388 --- /dev/null +++ b/examples/use_permission/Cargo.toml @@ -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" diff --git a/examples/use_permission/README.md b/examples/use_permission/README.md new file mode 100644 index 0000000..1e97c6e --- /dev/null +++ b/examples/use_permission/README.md @@ -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 +``` \ No newline at end of file diff --git a/examples/use_permission/Trunk.toml b/examples/use_permission/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_permission/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_permission/index.html b/examples/use_permission/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_permission/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_permission/input.css b/examples/use_permission/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_permission/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_permission/rust-toolchain.toml b/examples/use_permission/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_permission/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_permission/src/main.rs b/examples/use_permission/src/main.rs new file mode 100644 index 0000000..afa5889 --- /dev/null +++ b/examples/use_permission/src/main.rs @@ -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! { +
+            "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()}
+        
+ } +} + +fn main() { + _ = console_log::init_with_level(log::Level::Debug); + console_error_panic_hook::set_once(); + + mount_to(demo_or_body(), || { + view! { } + }) +} diff --git a/examples/use_permission/style/output.css b/examples/use_permission/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_permission/style/output.css @@ -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)); + } +} \ No newline at end of file diff --git a/examples/use_permission/tailwind.config.js b/examples/use_permission/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_permission/tailwind.config.js @@ -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'), + ], +} \ No newline at end of file diff --git a/examples/use_timeout_fn/Cargo.toml b/examples/use_timeout_fn/Cargo.toml new file mode 100644 index 0000000..9b0cfa4 --- /dev/null +++ b/examples/use_timeout_fn/Cargo.toml @@ -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" diff --git a/examples/use_timeout_fn/README.md b/examples/use_timeout_fn/README.md new file mode 100644 index 0000000..cde64e5 --- /dev/null +++ b/examples/use_timeout_fn/README.md @@ -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 +``` \ No newline at end of file diff --git a/examples/use_timeout_fn/Trunk.toml b/examples/use_timeout_fn/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_timeout_fn/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_timeout_fn/index.html b/examples/use_timeout_fn/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_timeout_fn/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_timeout_fn/input.css b/examples/use_timeout_fn/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_timeout_fn/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_timeout_fn/rust-toolchain.toml b/examples/use_timeout_fn/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_timeout_fn/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_timeout_fn/src/main.rs b/examples/use_timeout_fn/src/main.rs new file mode 100644 index 0000000..53e4842 --- /dev/null +++ b/examples/use_timeout_fn/src/main.rs @@ -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! { +

{text}

+ + } +} + +fn main() { + _ = console_log::init_with_level(log::Level::Debug); + console_error_panic_hook::set_once(); + + mount_to(demo_or_body(), || { + view! { } + }) +} diff --git a/examples/use_timeout_fn/style/output.css b/examples/use_timeout_fn/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_timeout_fn/style/output.css @@ -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)); + } +} \ No newline at end of file diff --git a/examples/use_timeout_fn/tailwind.config.js b/examples/use_timeout_fn/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_timeout_fn/tailwind.config.js @@ -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'), + ], +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index f677621..1578855 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,11 +14,17 @@ pub mod utils; // #[cfg(web_sys_unstable_apis)] // 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_none; mod is_ok; mod is_some; mod on_click_outside; +mod use_permission; mod signal_debounced; mod signal_throttled; mod use_active_element; @@ -62,6 +68,7 @@ mod use_service_worker; mod use_sorted; mod use_supported; mod use_throttle_fn; +mod use_timeout_fn; mod use_timestamp; mod use_to_string; mod use_web_notification; @@ -80,6 +87,7 @@ pub use is_none::*; pub use is_ok::*; pub use is_some::*; pub use on_click_outside::*; +pub use use_permission::*; pub use signal_debounced::*; pub use signal_throttled::*; pub use use_active_element::*; @@ -123,6 +131,7 @@ pub use use_service_worker::*; pub use use_sorted::*; pub use use_supported::*; pub use use_throttle_fn::*; +pub use use_timeout_fn::*; pub use use_timestamp::*; pub use use_to_string::*; pub use use_web_notification::*; diff --git a/src/use_broadcast_channel.rs b/src/use_broadcast_channel.rs index eed589b..f3d07d9 100644 --- a/src/use_broadcast_channel.rs +++ b/src/use_broadcast_channel.rs @@ -1,6 +1,6 @@ use crate::utils::StringCodec; 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 thiserror::Error; @@ -75,7 +75,7 @@ pub fn use_broadcast_channel( where C: StringCodec + 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 (channel, set_channel) = create_signal(None::); diff --git a/src/use_clipboard.rs b/src/use_clipboard.rs new file mode 100644 index 0000000..0bf11ae --- /dev/null +++ b/src/use_clipboard.rs @@ -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! { +/// Your browser does not support Clipboard API

} +/// > +/// +///
+/// } +/// # } +/// ``` +/// +/// ## 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 { + 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 { + 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 +where + CopyFn: Fn(&str) + Clone, +{ + /// Whether the Clipboard API is supported. + pub is_supported: Signal, + + /// The current state of the clipboard. + pub text: Signal>, + + /// `true` for [`UseClipboardOptions::copied_reset_delay`] milliseconds after copying. + pub copied: Signal, + + /// Copy the given text to the clipboard. + pub copy: CopyFn, +} diff --git a/src/use_device_orientation.rs b/src/use_device_orientation.rs index 9674220..7836a17 100644 --- a/src/use_device_orientation.rs +++ b/src/use_device_orientation.rs @@ -41,14 +41,10 @@ pub fn use_device_orientation() -> UseDeviceOrientationReturn { let beta = || None; let gamma = || None; } 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 wasm_bindgen::JsValue; - let is_supported = use_supported(|| js_sys::Reflect::has( - &window(), - &JsValue::from_str("DeviceOrientationEvent"), - ).unwrap_or(false)); + let is_supported = use_supported(|| js!("DeviceOrientationEvent" in &window())); let (absolute, set_absolute) = create_signal(false); let (alpha, set_alpha) = create_signal(None); let (beta, set_beta) = create_signal(None); diff --git a/src/use_display_media.rs b/src/use_display_media.rs index fb0ff8c..8174fba 100644 --- a/src/use_display_media.rs +++ b/src/use_display_media.rs @@ -123,6 +123,7 @@ pub fn use_display_media_with_options( #[cfg(not(feature = "ssr"))] async fn create_media(audio: bool) -> Result { + use crate::js_fut; use crate::use_window::use_window; let media = use_window() @@ -136,7 +137,7 @@ async fn create_media(audio: bool) -> Result { } 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)) } diff --git a/src/use_intl_number_format.rs b/src/use_intl_number_format.rs index 576651e..d7ad291 100644 --- a/src/use_intl_number_format.rs +++ b/src/use_intl_number_format.rs @@ -1,9 +1,9 @@ #![cfg_attr(feature = "ssr", allow(unused_variables, unused_imports, dead_code))] +use crate::js; use crate::utils::js_value_from_to_string; use cfg_if::cfg_if; use default_struct_builder::DefaultBuilder; -use js_sys::Reflect; use leptos::*; use std::fmt::Display; use wasm_bindgen::{JsCast, JsValue}; @@ -712,94 +712,48 @@ impl From for js_sys::Object { fn from(options: UseIntlNumberFormatOptions) -> Self { let obj = Self::new(); - let _ = Reflect::set( - &obj, - &"compactDisplay".into(), - &options.compact_display.into(), - ); + js!(obj["compactDisplay"] = options.compact_display); if let Some(currency) = options.currency { - let _ = Reflect::set(&obj, &"currency".into(), ¤cy.into()); + js!(obj["currency"] = currency); } - let _ = Reflect::set( - &obj, - &"currencyDisplay".into(), - &options.currency_display.into(), - ); - - 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()); + js!(obj["currencyDisplay"] = options.currency_display); + js!(obj["currencySign"] = options.currency_sign); + js!(obj["localeMatcher"] = options.locale_matcher); + js!(obj["notation"] = options.notation); 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()); - let _ = Reflect::set(&obj, &"style".into(), &options.style.into()); + js!(obj["signDisplay"] = options.sign_display); + js!(obj["style"] = options.style); 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()); - let _ = Reflect::set(&obj, &"useGrouping".into(), &options.use_grouping.into()); + js!(obj["unitDisplay"] = options.unit_display); + 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 { - let _ = Reflect::set( - &obj, - &"minimumFractionDigits".into(), - &minimum_fraction_digits.into(), - ); + js!(obj["minimumFractionDigits"] = minimum_fraction_digits); } if let Some(maximum_fraction_digits) = options.maximum_fraction_digits { - let _ = Reflect::set( - &obj, - &"maximumFractionDigits".into(), - &maximum_fraction_digits.into(), - ); + js!(obj["maximumFractionDigits"] = maximum_fraction_digits); } if let Some(minimum_significant_digits) = options.minimum_significant_digits { - let _ = Reflect::set( - &obj, - &"minimumSignificantDigits".into(), - &minimum_significant_digits.into(), - ); + js!(obj["minimumSignificantDigits"] = minimum_significant_digits); } if let Some(maximum_significant_digits) = options.maximum_significant_digits { - let _ = Reflect::set( - &obj, - &"maximumSignificantDigits".into(), - &maximum_significant_digits.into(), - ); + js!(obj["maximumSignificantDigits"] = maximum_significant_digits); } obj @@ -915,7 +869,7 @@ impl UseIntlNumberFormatReturn { let number_format = self.js_intl_number_format.clone(); 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::(); if let Ok(result) = function.call2( diff --git a/src/use_mutation_observer.rs b/src/use_mutation_observer.rs index 91f185a..a19571d 100644 --- a/src/use_mutation_observer.rs +++ b/src/use_mutation_observer.rs @@ -79,6 +79,8 @@ where stop: || {}, } } else { + use crate::js; + let closure_js = Closure::::new( move |entries: js_sys::Array, observer| { callback( @@ -95,7 +97,7 @@ where let observer: Rc>> = 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 observer = Rc::clone(&observer); diff --git a/src/use_permission.rs b/src/use_permission.rs new file mode 100644 index 0000000..2135842 --- /dev/null +++ b/src/use_permission.rs @@ -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 { + 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::)); + + 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 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 { + 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) +} diff --git a/src/use_resize_observer.rs b/src/use_resize_observer.rs index ce78e0d..dadd3b6 100644 --- a/src/use_resize_observer.rs +++ b/src/use_resize_observer.rs @@ -85,6 +85,8 @@ where #[cfg(not(feature = "ssr"))] { + use crate::js; + let closure_js = Closure::::new( move |entries: js_sys::Array, observer| { callback( @@ -101,7 +103,7 @@ where let observer: Rc>> = 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 observer = Rc::clone(&observer); diff --git a/src/use_service_worker.rs b/src/use_service_worker.rs index b9dda2d..d95c9ab 100644 --- a/src/use_service_worker.rs +++ b/src/use_service_worker.rs @@ -4,7 +4,7 @@ use std::rc::Rc; use wasm_bindgen::{prelude::Closure, JsCast, JsValue}; 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). /// @@ -239,7 +239,7 @@ fn create_action_update( let registration = registration.clone(); async move { match registration.update() { - Ok(promise) => wasm_bindgen_futures::JsFuture::from(promise) + Ok(promise) => js_fut!(promise) .await .and_then(|ok| ok.dyn_into::()), Err(err) => Err(err), @@ -255,8 +255,7 @@ fn create_action_create_or_update_registration( let script_url = script_url.0.to_owned(); async move { if let Some(navigator) = use_window().navigator() { - let promise = navigator.service_worker().register(script_url.as_str()); - wasm_bindgen_futures::JsFuture::from(promise) + js_fut!(navigator.service_worker().register(script_url.as_str())) .await .and_then(|ok| ok.dyn_into::()) } else { @@ -270,8 +269,7 @@ fn create_action_create_or_update_registration( fn create_action_get_registration() -> Action<(), Result> { create_action(move |(): &()| async move { if let Some(navigator) = use_window().navigator() { - let promise = navigator.service_worker().get_registration(); - wasm_bindgen_futures::JsFuture::from(promise) + js_fut!(navigator.service_worker().get_registration()) .await .and_then(|ok| ok.dyn_into::()) } else { diff --git a/src/use_supported.rs b/src/use_supported.rs index 4c3bcab..e266377 100644 --- a/src/use_supported.rs +++ b/src/use_supported.rs @@ -6,12 +6,12 @@ use leptos::*; /// /// ``` /// # use leptos::*; -/// # use leptos_use::use_supported; +/// # use leptos_use::{use_supported, js}; /// # use wasm_bindgen::JsValue; /// # /// # pub fn Demo() -> impl IntoView { /// let is_supported = use_supported( -/// || JsValue::from("getBattery").js_in(&window().navigator()) +/// || js!("getBattery" in &window().navigator()) /// ); /// /// if is_supported.get() { @@ -21,5 +21,14 @@ use leptos::*; /// # } /// ``` pub fn use_supported(callback: impl Fn() -> bool + 'static) -> Signal { - Signal::derive(callback) + #[cfg(feature = "ssr")] + { + let _ = callback; + Signal::derive(|| false) + } + + #[cfg(not(feature = "ssr"))] + { + Signal::derive(callback) + } } diff --git a/src/use_timeout_fn.rs b/src/use_timeout_fn.rs new file mode 100644 index 0000000..8dd8f1f --- /dev/null +++ b/src/use_timeout_fn.rs @@ -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( + callback: CbFn, + delay: D, +) -> UseTimeoutFnReturn +where + CbFn: Fn(Arg) + Clone + 'static, + Arg: 'static, + D: Into>, +{ + let delay = delay.into(); + + let (is_pending, set_pending) = create_signal(false); + + let timer = Rc::new(Cell::new(None::)); + + 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 +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, + + /// 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, +} diff --git a/src/use_web_notification.rs b/src/use_web_notification.rs index 44b52a6..08d3a25 100644 --- a/src/use_web_notification.rs +++ b/src/use_web_notification.rs @@ -435,7 +435,7 @@ impl From for NotificationPermission { #[cfg(not(feature = "ssr"))] async fn request_web_notification_permission() -> NotificationPermission { 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() diff --git a/src/use_webtransport.rs b/src/use_webtransport.rs index 7006fdc..b6b6c09 100644 --- a/src/use_webtransport.rs +++ b/src/use_webtransport.rs @@ -130,7 +130,7 @@ pub fn use_webtransport_with_options( let transport = transport.borrow(); let transport = transport.as_ref().expect("Transport should be set"); - match JsFuture::from(transport.ready()).await { + match js_fut!(transport.ready()).await { Ok(_) => { set_ready_state.set(ConnectionReadyState::Open); on_open(); @@ -213,7 +213,7 @@ pub fn use_webtransport_with_options( set_ready_state.set(ConnectionReadyState::Closing); spawn_local(async move { - let result = JsFuture::from(transport.closed()).await; + let result = js_fut!(transport.closed()).await; set_ready_state.set(ConnectionReadyState::Closed); on_closed(); @@ -345,10 +345,10 @@ fn listen_to_stream( spawn_local(async move { loop { - let result = JsFuture::from(reader.read()).await; + let result = js_fut!(reader.read()).await; match result { Ok(result) => { - let done = Reflect::get(&result, &"done".into()) + let done = js!(result["done"]) .expect("done should always be there") .as_bool() .unwrap_or(true); @@ -358,8 +358,7 @@ fn listen_to_stream( break; } - let value = Reflect::get(&result, &"value".into()) - .expect("if not done there should be a value"); + let value = js!(result["value"]).expect("if not done there should be a value"); on_value(value); } @@ -460,7 +459,7 @@ pub trait SendableStream: CloseableStream { } 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 .map_err(|e| SendError::FailedToWrite(e)); @@ -598,7 +597,7 @@ macro_rules! impl_closable_stream { } 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); self.set_state.set(StreamState::Closed); error @@ -650,7 +649,7 @@ impl UseWebTransportReturn { /// Open a unidirectional send stream pub async fn open_send_stream(&self) -> Result { 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 .map_err(|e| WebTransportError::FailedToOpenStream(e))?; let stream: web_sys::WritableStream = result.unchecked_into(); @@ -673,7 +672,7 @@ impl UseWebTransportReturn { /// Open a bidirectional stream pub async fn open_bidir_stream(&self) -> Result { 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 .map_err(|e| WebTransportError::FailedToOpenStream(e))?; let stream: web_sys::WebTransportBidirectionalStream = result.unchecked_into(); diff --git a/src/utils/js.rs b/src/utils/js.rs new file mode 100644 index 0000000..e33c64b --- /dev/null +++ b/src/utils/js.rs @@ -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)*) + }; + +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs index fc22bc5..25f19eb 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,6 +1,7 @@ mod codecs; mod filters; mod is; +mod js; mod js_value_from_to_string; mod pausable; mod signal_filtered;