diff --git a/.idea/leptos-use.iml b/.idea/leptos-use.iml index 19adbd1..5009c87 100644 --- a/.idea/leptos-use.iml +++ b/.idea/leptos-use.iml @@ -81,6 +81,10 @@ + + + + diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cc0814..c28526f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,19 +3,45 @@ 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] - +## [0.13.2] - 2024-09-02 + +### Fix 🍕 + +- Fixed web-sys `unstable_apis` flag for `use_web_lock` + +## [0.13.1] - 2024-09-01 ### New Functions 🚀 -- `use_prefers_reduced_motion` - -### Breaking Change 🛠 - -- `use_websocket` now supports different types for sending and receiving messages +- `use_web_lock` +- `use_window_size` ### Change 🔥 -- There is now a feature for almost every function to get better compile and rust-analyzer times. +- `UseWebsocket::protocols` now supports a signal. It is read right before `open` is called. (thanks to @zakstucke) + +## [0.13.0] - 2024-08-28 + +### New Functions 🚀 + +- `use_toggle` +- `use_prefers_reduced_motion` (thanks to @hcandelaria) + +### Breaking Changes 🛠 + +- `use_websocket` now supports different types for sending and receiving messages +- `SyncSignalOptions` now can take now either transformations or assignment functions but not both. +- updated to `codee` version 0.2.0 + +### Fixes 🍕 + +- `use_websocket` fixed error with cleanup and reconnect (thanks to @BakerNet). + +### New Features 🚀 + +- There is now a feature for almost every function to get better compile and rust-analyzer times. +- `use_web_notification` now supports the `vibrate` option (thanks to @hcandelaria). +- `UseDocument` now supports a whole bunch of methods more from `document` (thanks to @luckynumberke7in). ## [0.12.0] - 2024-08-14 diff --git a/Cargo.toml b/Cargo.toml index d85d31d..a5c0885 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "leptos-use" -version = "0.12.0" +version = "0.13.2" edition = "2021" authors = ["Marc-Stefan Cassola"] categories = ["gui", "web-programming"] @@ -54,6 +54,8 @@ unic-langid = { version = "0.9", features = ["macros"] } [features] default = [ + "use_web_lock", + "use_window_size", "is_err", "is_none", "is_ok", @@ -112,6 +114,7 @@ default = [ "use_throttle_fn", "use_timeout_fn", "use_timestamp", + "use_toggle", "use_to_string", "use_user_media", "use_web_notification", @@ -125,6 +128,15 @@ default = [ "watch_with_options", "whenever" ] +use_web_lock = [ + "web-sys/AbortSignal", + "web-sys/Lock", + "web-sys/LockManager", + "web-sys/LockMode", + "web-sys/LockOptions", + "web-sys/Navigator", +] +use_window_size = ["use_media_query"] actix = ["dep:actix-web", "dep:leptos_actix", "dep:http0_2"] axum = ["dep:leptos_axum", "dep:http1"] docs = ["dep:web-sys"] @@ -323,6 +335,7 @@ use_supported = [] use_throttle_fn = [] use_timeout_fn = [] use_timestamp = ["use_interval_fn", "use_raf_fn"] +use_toggle = [] use_to_string = [] use_user_media = [ "use_window", @@ -341,7 +354,7 @@ use_web_notification = [ "web-sys/NotificationDirection", "web-sys/VisibilityState" ] -use_websocket = ["dep:codee"] +use_websocket = ["dep:web-sys", "dep:codee"] use_window = ["use_document", "dep:web-sys", "web-sys/Navigator", "web-sys/MediaQueryList"] use_window_focus = ["use_event_listener"] use_window_scroll = ["use_event_listener", "use_window"] diff --git a/README.md b/README.md index de776b8..5caf07f 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Crates.io SSR Docs & Demos - 82 Functions + 86 Functions


@@ -87,9 +87,9 @@ This will create the function file in the src directory, scaffold an example dir ## Leptos compatibility -| Crate version | Compatible Leptos version | -|------------------|---------------------------| -| <= 0.3 | 0.3 | -| 0.4, 0.5, 0.6 | 0.4 | -| 0.7, 0.8, 0.9 | 0.5 | -| 0.10, 0.11, 0.12 | 0.6 | +| Crate version | Compatible Leptos version | +|---------------|---------------------------| +| <= 0.3 | 0.3 | +| 0.4, 0.5, 0.6 | 0.4 | +| 0.7, 0.8, 0.9 | 0.5 | +| 0.10 – 0.13 | 0.6 | diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index ebbb19f..db94782 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -32,6 +32,7 @@ - [use_window](elements/use_window.md) - [use_window_focus](elements/use_window_focus.md) - [use_window_scroll](elements/use_window_scroll.md) +- [use_window_size](elements/use_window_size.md) # Browser @@ -51,6 +52,7 @@ - [use_prefers_reduced_motion](browser/use_prefers_reduced_motion.md) - [use_service_worker](browser/use_service_worker.md) - [use_user_media](browser/use_user_media.md) +- [use_web_lock](browser/use_web_lock.md) - [use_web_notification](browser/use_web_notification.md) # Sensors @@ -111,6 +113,7 @@ - [use_supported](utilities/use_supported.md) - [use_throttle_fn](utilities/use_throttle_fn.md) - [use_to_string](utilities/use_to_string.md) +- [use_toggle](utilities/use_toggle.md) # Intl diff --git a/docs/book/src/animation/use_interval.md b/docs/book/src/animation/use_interval.md index 7c6b277..fc7d209 100644 --- a/docs/book/src/animation/use_interval.md +++ b/docs/book/src/animation/use_interval.md @@ -1,3 +1,3 @@ # use_interval - + diff --git a/docs/book/src/animation/use_interval_fn.md b/docs/book/src/animation/use_interval_fn.md index abe3791..392a0fa 100644 --- a/docs/book/src/animation/use_interval_fn.md +++ b/docs/book/src/animation/use_interval_fn.md @@ -1,3 +1,3 @@ # use_interval_fn - + diff --git a/docs/book/src/animation/use_raf_fn.md b/docs/book/src/animation/use_raf_fn.md index 5bc4ff4..0d65286 100644 --- a/docs/book/src/animation/use_raf_fn.md +++ b/docs/book/src/animation/use_raf_fn.md @@ -1,3 +1,3 @@ # use_raf_fn - + diff --git a/docs/book/src/animation/use_timeout_fn.md b/docs/book/src/animation/use_timeout_fn.md index 30f9740..6fa66ad 100644 --- a/docs/book/src/animation/use_timeout_fn.md +++ b/docs/book/src/animation/use_timeout_fn.md @@ -1,3 +1,3 @@ # use_timeout_fn - + diff --git a/docs/book/src/animation/use_timestamp.md b/docs/book/src/animation/use_timestamp.md index e080cdb..f3eec16 100644 --- a/docs/book/src/animation/use_timestamp.md +++ b/docs/book/src/animation/use_timestamp.md @@ -1,3 +1,3 @@ # use_timestamp - + diff --git a/docs/book/src/browser/use_breakpoints.md b/docs/book/src/browser/use_breakpoints.md index df342b8..cb1d4b9 100644 --- a/docs/book/src/browser/use_breakpoints.md +++ b/docs/book/src/browser/use_breakpoints.md @@ -1,3 +1,3 @@ # use_breakpoints - + diff --git a/docs/book/src/browser/use_broadcast_channel.md b/docs/book/src/browser/use_broadcast_channel.md index 8a2393a..9865f1b 100644 --- a/docs/book/src/browser/use_broadcast_channel.md +++ b/docs/book/src/browser/use_broadcast_channel.md @@ -1,3 +1,3 @@ # use_broadcast_channel - + diff --git a/docs/book/src/browser/use_clipboard.md b/docs/book/src/browser/use_clipboard.md index f3df1c8..4766ce2 100644 --- a/docs/book/src/browser/use_clipboard.md +++ b/docs/book/src/browser/use_clipboard.md @@ -1,3 +1,3 @@ # use_clipboard - + diff --git a/docs/book/src/browser/use_color_mode.md b/docs/book/src/browser/use_color_mode.md index 7d2775d..2fb9166 100644 --- a/docs/book/src/browser/use_color_mode.md +++ b/docs/book/src/browser/use_color_mode.md @@ -1,3 +1,3 @@ # use_color_mode - + diff --git a/docs/book/src/browser/use_cookie.md b/docs/book/src/browser/use_cookie.md index b125e32..ef410d8 100644 --- a/docs/book/src/browser/use_cookie.md +++ b/docs/book/src/browser/use_cookie.md @@ -1,3 +1,3 @@ # use_cookie - + diff --git a/docs/book/src/browser/use_css_var.md b/docs/book/src/browser/use_css_var.md index e977dcd..283eff0 100644 --- a/docs/book/src/browser/use_css_var.md +++ b/docs/book/src/browser/use_css_var.md @@ -1,3 +1,3 @@ # use_css_var - + diff --git a/docs/book/src/browser/use_display_media.md b/docs/book/src/browser/use_display_media.md index 6a2d3ed..b4dc837 100644 --- a/docs/book/src/browser/use_display_media.md +++ b/docs/book/src/browser/use_display_media.md @@ -1,3 +1,3 @@ # use_display_media - + diff --git a/docs/book/src/browser/use_event_listener.md b/docs/book/src/browser/use_event_listener.md index 783bca1..071551f 100644 --- a/docs/book/src/browser/use_event_listener.md +++ b/docs/book/src/browser/use_event_listener.md @@ -1,3 +1,3 @@ # use_event_listener - + diff --git a/docs/book/src/browser/use_favicon.md b/docs/book/src/browser/use_favicon.md index 079edc3..b5f0a8a 100644 --- a/docs/book/src/browser/use_favicon.md +++ b/docs/book/src/browser/use_favicon.md @@ -1,3 +1,3 @@ # use_favicon - + diff --git a/docs/book/src/browser/use_media_query.md b/docs/book/src/browser/use_media_query.md index d986055..bff3478 100644 --- a/docs/book/src/browser/use_media_query.md +++ b/docs/book/src/browser/use_media_query.md @@ -1,3 +1,3 @@ # use_media_query - + diff --git a/docs/book/src/browser/use_permission.md b/docs/book/src/browser/use_permission.md index ec8c074..3273b12 100644 --- a/docs/book/src/browser/use_permission.md +++ b/docs/book/src/browser/use_permission.md @@ -1,3 +1,3 @@ # use_permission - + diff --git a/docs/book/src/browser/use_preferred_contrast.md b/docs/book/src/browser/use_preferred_contrast.md index 8570548..e73997b 100644 --- a/docs/book/src/browser/use_preferred_contrast.md +++ b/docs/book/src/browser/use_preferred_contrast.md @@ -1,3 +1,3 @@ # use_preferred_contrast - + diff --git a/docs/book/src/browser/use_preferred_dark.md b/docs/book/src/browser/use_preferred_dark.md index 9883ba1..250f824 100644 --- a/docs/book/src/browser/use_preferred_dark.md +++ b/docs/book/src/browser/use_preferred_dark.md @@ -1,3 +1,3 @@ # use_preferred_dark - + diff --git a/docs/book/src/browser/use_prefers_reduced_motion.md b/docs/book/src/browser/use_prefers_reduced_motion.md index d6aa3ae..89b9030 100644 --- a/docs/book/src/browser/use_prefers_reduced_motion.md +++ b/docs/book/src/browser/use_prefers_reduced_motion.md @@ -1,3 +1,3 @@ # use_prefers_reduced_motion - + diff --git a/docs/book/src/browser/use_service_worker.md b/docs/book/src/browser/use_service_worker.md index 93f8a0a..a931604 100644 --- a/docs/book/src/browser/use_service_worker.md +++ b/docs/book/src/browser/use_service_worker.md @@ -1,3 +1,3 @@ # use_service_worker - + diff --git a/docs/book/src/browser/use_user_media.md b/docs/book/src/browser/use_user_media.md index 3e39cca..d11f42f 100644 --- a/docs/book/src/browser/use_user_media.md +++ b/docs/book/src/browser/use_user_media.md @@ -1,3 +1,3 @@ # use_user_media - + diff --git a/docs/book/src/browser/use_web_lock.md b/docs/book/src/browser/use_web_lock.md new file mode 100644 index 0000000..2d8295b --- /dev/null +++ b/docs/book/src/browser/use_web_lock.md @@ -0,0 +1,3 @@ +# use_web_lock + + diff --git a/docs/book/src/browser/use_web_notification.md b/docs/book/src/browser/use_web_notification.md index ceef60c..20ee97e 100644 --- a/docs/book/src/browser/use_web_notification.md +++ b/docs/book/src/browser/use_web_notification.md @@ -1,3 +1,3 @@ # use_web_notification - + diff --git a/docs/book/src/elements/use_active_element.md b/docs/book/src/elements/use_active_element.md index c14fb19..7b3b2c7 100644 --- a/docs/book/src/elements/use_active_element.md +++ b/docs/book/src/elements/use_active_element.md @@ -1,3 +1,3 @@ # use_active_element - + diff --git a/docs/book/src/elements/use_document.md b/docs/book/src/elements/use_document.md index 838ae90..f86aab0 100644 --- a/docs/book/src/elements/use_document.md +++ b/docs/book/src/elements/use_document.md @@ -1,3 +1,3 @@ # use_document - + diff --git a/docs/book/src/elements/use_document_visibility.md b/docs/book/src/elements/use_document_visibility.md index 9bba161..162606d 100644 --- a/docs/book/src/elements/use_document_visibility.md +++ b/docs/book/src/elements/use_document_visibility.md @@ -1,3 +1,3 @@ # use_document_visibility - + diff --git a/docs/book/src/elements/use_draggable.md b/docs/book/src/elements/use_draggable.md index 124d9c6..08db592 100644 --- a/docs/book/src/elements/use_draggable.md +++ b/docs/book/src/elements/use_draggable.md @@ -1,3 +1,3 @@ # use_draggable - + diff --git a/docs/book/src/elements/use_drop_zone.md b/docs/book/src/elements/use_drop_zone.md index c2b037b..1916316 100644 --- a/docs/book/src/elements/use_drop_zone.md +++ b/docs/book/src/elements/use_drop_zone.md @@ -1,3 +1,3 @@ # use_drop_zone - + diff --git a/docs/book/src/elements/use_element_bounding.md b/docs/book/src/elements/use_element_bounding.md index ca3c015..12ae862 100644 --- a/docs/book/src/elements/use_element_bounding.md +++ b/docs/book/src/elements/use_element_bounding.md @@ -1,3 +1,3 @@ # use_element_bounding - + diff --git a/docs/book/src/elements/use_element_size.md b/docs/book/src/elements/use_element_size.md index b59e781..5c212e4 100644 --- a/docs/book/src/elements/use_element_size.md +++ b/docs/book/src/elements/use_element_size.md @@ -1,3 +1,3 @@ # use_element_size - + diff --git a/docs/book/src/elements/use_element_visibility.md b/docs/book/src/elements/use_element_visibility.md index 1e58d8d..1428bda 100644 --- a/docs/book/src/elements/use_element_visibility.md +++ b/docs/book/src/elements/use_element_visibility.md @@ -1,3 +1,3 @@ # use_element_visibility - + diff --git a/docs/book/src/elements/use_intersection_observer.md b/docs/book/src/elements/use_intersection_observer.md index cee0fcb..fc8551e 100644 --- a/docs/book/src/elements/use_intersection_observer.md +++ b/docs/book/src/elements/use_intersection_observer.md @@ -1,3 +1,3 @@ # use_intersection_observer - + diff --git a/docs/book/src/elements/use_mouse_in_element.md b/docs/book/src/elements/use_mouse_in_element.md index 0be1884..3db5236 100644 --- a/docs/book/src/elements/use_mouse_in_element.md +++ b/docs/book/src/elements/use_mouse_in_element.md @@ -1,3 +1,3 @@ # use_mouse_in_element - + diff --git a/docs/book/src/elements/use_mutation_observer.md b/docs/book/src/elements/use_mutation_observer.md index 65a585b..7c603c4 100644 --- a/docs/book/src/elements/use_mutation_observer.md +++ b/docs/book/src/elements/use_mutation_observer.md @@ -1,3 +1,3 @@ # use_mutation_observer - + diff --git a/docs/book/src/elements/use_resize_observer.md b/docs/book/src/elements/use_resize_observer.md index 1fc17bc..922c42f 100644 --- a/docs/book/src/elements/use_resize_observer.md +++ b/docs/book/src/elements/use_resize_observer.md @@ -1,3 +1,3 @@ # use_resize_observer - + diff --git a/docs/book/src/elements/use_window.md b/docs/book/src/elements/use_window.md index ee5e14a..708bd06 100644 --- a/docs/book/src/elements/use_window.md +++ b/docs/book/src/elements/use_window.md @@ -1,3 +1,3 @@ # use_window - + diff --git a/docs/book/src/elements/use_window_focus.md b/docs/book/src/elements/use_window_focus.md index 3aa9063..3c38bb5 100644 --- a/docs/book/src/elements/use_window_focus.md +++ b/docs/book/src/elements/use_window_focus.md @@ -1,3 +1,3 @@ # use_window_focus - + diff --git a/docs/book/src/elements/use_window_scroll.md b/docs/book/src/elements/use_window_scroll.md index 84ff90d..a25a456 100644 --- a/docs/book/src/elements/use_window_scroll.md +++ b/docs/book/src/elements/use_window_scroll.md @@ -1,3 +1,3 @@ # use_window_scroll - + diff --git a/docs/book/src/elements/use_window_size.md b/docs/book/src/elements/use_window_size.md new file mode 100644 index 0000000..0ab6613 --- /dev/null +++ b/docs/book/src/elements/use_window_size.md @@ -0,0 +1,3 @@ +# use_window_size + + diff --git a/docs/book/src/intl/use_intl_number_format.md b/docs/book/src/intl/use_intl_number_format.md index 3a87258..8aaa5c0 100644 --- a/docs/book/src/intl/use_intl_number_format.md +++ b/docs/book/src/intl/use_intl_number_format.md @@ -1,3 +1,3 @@ # use_intl_number_format - + diff --git a/docs/book/src/intl/use_locale.md b/docs/book/src/intl/use_locale.md index 56b32d7..a0e04d2 100644 --- a/docs/book/src/intl/use_locale.md +++ b/docs/book/src/intl/use_locale.md @@ -1,3 +1,3 @@ # use_locale - + diff --git a/docs/book/src/intl/use_locales.md b/docs/book/src/intl/use_locales.md index 084b0fd..5cd8525 100644 --- a/docs/book/src/intl/use_locales.md +++ b/docs/book/src/intl/use_locales.md @@ -1,3 +1,3 @@ # use_locales - + diff --git a/docs/book/src/introduction.md b/docs/book/src/introduction.md index 8bcc1c1..25cf3d5 100644 --- a/docs/book/src/introduction.md +++ b/docs/book/src/introduction.md @@ -12,6 +12,6 @@ Crates.io SSR Docs & Demos - 82 Functions + 86 Functions

\ No newline at end of file diff --git a/docs/book/src/iterable/use_sorted.md b/docs/book/src/iterable/use_sorted.md index ad6b740..b436259 100644 --- a/docs/book/src/iterable/use_sorted.md +++ b/docs/book/src/iterable/use_sorted.md @@ -1,3 +1,3 @@ # use_sorted - + diff --git a/docs/book/src/network/use_event_source.md b/docs/book/src/network/use_event_source.md index 8ab75c8..84596e9 100644 --- a/docs/book/src/network/use_event_source.md +++ b/docs/book/src/network/use_event_source.md @@ -1,3 +1,3 @@ # use_event_source - + diff --git a/docs/book/src/network/use_websocket.md b/docs/book/src/network/use_websocket.md index 1dac32f..148a673 100644 --- a/docs/book/src/network/use_websocket.md +++ b/docs/book/src/network/use_websocket.md @@ -1,3 +1,3 @@ # use_websocket - + diff --git a/docs/book/src/reactivity/signal_debounced.md b/docs/book/src/reactivity/signal_debounced.md index 007a914..fbc9b4a 100644 --- a/docs/book/src/reactivity/signal_debounced.md +++ b/docs/book/src/reactivity/signal_debounced.md @@ -1,3 +1,3 @@ # signal_debounced - + diff --git a/docs/book/src/reactivity/signal_throttled.md b/docs/book/src/reactivity/signal_throttled.md index 44e84ef..7ee837b 100644 --- a/docs/book/src/reactivity/signal_throttled.md +++ b/docs/book/src/reactivity/signal_throttled.md @@ -1,3 +1,3 @@ # signal_throttled - + diff --git a/docs/book/src/reactivity/sync_signal.md b/docs/book/src/reactivity/sync_signal.md index 0a3f77b..dc9cb1c 100644 --- a/docs/book/src/reactivity/sync_signal.md +++ b/docs/book/src/reactivity/sync_signal.md @@ -1,3 +1,3 @@ # sync_signal - + diff --git a/docs/book/src/sensors/on_click_outside.md b/docs/book/src/sensors/on_click_outside.md index 37bf082..adaea81 100644 --- a/docs/book/src/sensors/on_click_outside.md +++ b/docs/book/src/sensors/on_click_outside.md @@ -1,3 +1,3 @@ # on_click_outside - + diff --git a/docs/book/src/sensors/use_device_orientation.md b/docs/book/src/sensors/use_device_orientation.md index 7f6f7dc..ba2cf1d 100644 --- a/docs/book/src/sensors/use_device_orientation.md +++ b/docs/book/src/sensors/use_device_orientation.md @@ -1,3 +1,3 @@ # use_device_orientation - + diff --git a/docs/book/src/sensors/use_device_pixel_ratio.md b/docs/book/src/sensors/use_device_pixel_ratio.md index e032e92..468919b 100644 --- a/docs/book/src/sensors/use_device_pixel_ratio.md +++ b/docs/book/src/sensors/use_device_pixel_ratio.md @@ -1,3 +1,3 @@ # use_device_pixel_ratio - + diff --git a/docs/book/src/sensors/use_element_hover.md b/docs/book/src/sensors/use_element_hover.md index 07ba3d7..9d8e5b4 100644 --- a/docs/book/src/sensors/use_element_hover.md +++ b/docs/book/src/sensors/use_element_hover.md @@ -1,3 +1,3 @@ # use_element_hover - + diff --git a/docs/book/src/sensors/use_geolocation.md b/docs/book/src/sensors/use_geolocation.md index f27d246..7749100 100644 --- a/docs/book/src/sensors/use_geolocation.md +++ b/docs/book/src/sensors/use_geolocation.md @@ -1,3 +1,3 @@ # use_geolocation - + diff --git a/docs/book/src/sensors/use_idle.md b/docs/book/src/sensors/use_idle.md index 1088373..c79b748 100644 --- a/docs/book/src/sensors/use_idle.md +++ b/docs/book/src/sensors/use_idle.md @@ -1,3 +1,3 @@ # use_idle - + diff --git a/docs/book/src/sensors/use_infinite_scroll.md b/docs/book/src/sensors/use_infinite_scroll.md index 1810384..7b73179 100644 --- a/docs/book/src/sensors/use_infinite_scroll.md +++ b/docs/book/src/sensors/use_infinite_scroll.md @@ -1,3 +1,3 @@ # use_infinite_scroll - + diff --git a/docs/book/src/sensors/use_mouse.md b/docs/book/src/sensors/use_mouse.md index e5646a0..84370bd 100644 --- a/docs/book/src/sensors/use_mouse.md +++ b/docs/book/src/sensors/use_mouse.md @@ -1,3 +1,3 @@ # use_mouse - + diff --git a/docs/book/src/sensors/use_scroll.md b/docs/book/src/sensors/use_scroll.md index 1e27f2a..d6df5d0 100644 --- a/docs/book/src/sensors/use_scroll.md +++ b/docs/book/src/sensors/use_scroll.md @@ -1,3 +1,3 @@ # use_scroll - + diff --git a/docs/book/src/storage/use_local_storage.md b/docs/book/src/storage/use_local_storage.md index 3256f85..d39b415 100644 --- a/docs/book/src/storage/use_local_storage.md +++ b/docs/book/src/storage/use_local_storage.md @@ -1,3 +1,3 @@ # use_local_storage - + diff --git a/docs/book/src/storage/use_session_storage.md b/docs/book/src/storage/use_session_storage.md index 03ddbab..f04e6e5 100644 --- a/docs/book/src/storage/use_session_storage.md +++ b/docs/book/src/storage/use_session_storage.md @@ -1,3 +1,3 @@ # use_session_storage - + diff --git a/docs/book/src/storage/use_storage.md b/docs/book/src/storage/use_storage.md index 316df04..f937ee4 100644 --- a/docs/book/src/storage/use_storage.md +++ b/docs/book/src/storage/use_storage.md @@ -1,3 +1,3 @@ # use_storage - + diff --git a/docs/book/src/utilities/header.md b/docs/book/src/utilities/header.md index 2bd2d1f..440d4fb 100644 --- a/docs/book/src/utilities/header.md +++ b/docs/book/src/utilities/header.md @@ -1,3 +1,3 @@ # header - + diff --git a/docs/book/src/utilities/is_err.md b/docs/book/src/utilities/is_err.md index bdf2ae7..a74a034 100644 --- a/docs/book/src/utilities/is_err.md +++ b/docs/book/src/utilities/is_err.md @@ -1,3 +1,3 @@ # is_err - + diff --git a/docs/book/src/utilities/is_none.md b/docs/book/src/utilities/is_none.md index 9dc8c84..113b257 100644 --- a/docs/book/src/utilities/is_none.md +++ b/docs/book/src/utilities/is_none.md @@ -1,3 +1,3 @@ # is_none - + diff --git a/docs/book/src/utilities/is_ok.md b/docs/book/src/utilities/is_ok.md index 6897289..100573f 100644 --- a/docs/book/src/utilities/is_ok.md +++ b/docs/book/src/utilities/is_ok.md @@ -1,3 +1,3 @@ # is_ok - + diff --git a/docs/book/src/utilities/is_some.md b/docs/book/src/utilities/is_some.md index 0258188..2ec6b08 100644 --- a/docs/book/src/utilities/is_some.md +++ b/docs/book/src/utilities/is_some.md @@ -1,3 +1,3 @@ # is_some - + diff --git a/docs/book/src/utilities/use_cycle_list.md b/docs/book/src/utilities/use_cycle_list.md index 005c361..643b3ed 100644 --- a/docs/book/src/utilities/use_cycle_list.md +++ b/docs/book/src/utilities/use_cycle_list.md @@ -1,3 +1,3 @@ # use_cycle_list - + diff --git a/docs/book/src/utilities/use_debounce_fn.md b/docs/book/src/utilities/use_debounce_fn.md index bcd5ec8..5d7ee1d 100644 --- a/docs/book/src/utilities/use_debounce_fn.md +++ b/docs/book/src/utilities/use_debounce_fn.md @@ -1,3 +1,3 @@ # use_debounce_fn - + diff --git a/docs/book/src/utilities/use_supported.md b/docs/book/src/utilities/use_supported.md index 581e8bd..15c9d2b 100644 --- a/docs/book/src/utilities/use_supported.md +++ b/docs/book/src/utilities/use_supported.md @@ -1,3 +1,3 @@ # use_supported - + diff --git a/docs/book/src/utilities/use_throttle_fn.md b/docs/book/src/utilities/use_throttle_fn.md index faf261f..f6a5748 100644 --- a/docs/book/src/utilities/use_throttle_fn.md +++ b/docs/book/src/utilities/use_throttle_fn.md @@ -1,3 +1,3 @@ # use_throttle_fn - + diff --git a/docs/book/src/utilities/use_to_string.md b/docs/book/src/utilities/use_to_string.md index 18e2a28..91238f9 100644 --- a/docs/book/src/utilities/use_to_string.md +++ b/docs/book/src/utilities/use_to_string.md @@ -1,3 +1,3 @@ # use_to_string - + diff --git a/docs/book/src/utilities/use_toggle.md b/docs/book/src/utilities/use_toggle.md new file mode 100644 index 0000000..3ecd99c --- /dev/null +++ b/docs/book/src/utilities/use_toggle.md @@ -0,0 +1,3 @@ +# use_toggle + + diff --git a/docs/book/src/watch/watch_debounced.md b/docs/book/src/watch/watch_debounced.md index cb2b45f..5e06b5f 100644 --- a/docs/book/src/watch/watch_debounced.md +++ b/docs/book/src/watch/watch_debounced.md @@ -1,3 +1,3 @@ # watch_debounced - + diff --git a/docs/book/src/watch/watch_pausable.md b/docs/book/src/watch/watch_pausable.md index 7cc5419..aeca106 100644 --- a/docs/book/src/watch/watch_pausable.md +++ b/docs/book/src/watch/watch_pausable.md @@ -1,3 +1,3 @@ # watch_pausable - + diff --git a/docs/book/src/watch/watch_throttled.md b/docs/book/src/watch/watch_throttled.md index 062d941..e6aa8fb 100644 --- a/docs/book/src/watch/watch_throttled.md +++ b/docs/book/src/watch/watch_throttled.md @@ -1,3 +1,3 @@ # watch_throttled - + diff --git a/docs/book/src/watch/watch_with_options.md b/docs/book/src/watch/watch_with_options.md index b45a7d3..045f3c4 100644 --- a/docs/book/src/watch/watch_with_options.md +++ b/docs/book/src/watch/watch_with_options.md @@ -1,3 +1,3 @@ # watch_with_options - + diff --git a/docs/book/src/watch/whenever.md b/docs/book/src/watch/whenever.md index af39dd3..681a193 100644 --- a/docs/book/src/watch/whenever.md +++ b/docs/book/src/watch/whenever.md @@ -1,3 +1,3 @@ # whenever - + diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 59ccdad..a124eee 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -55,11 +55,14 @@ members = [ "use_throttle_fn", "use_timeout_fn", "use_timestamp", + "use_toggle", "use_user_media", + "use_web_lock", "use_web_notification", "use_websocket", "use_window_focus", "use_window_scroll", + "use_window_size", "watch_debounced", "watch_pausable", "watch_throttled", diff --git a/examples/use_toggle/Cargo.toml b/examples/use_toggle/Cargo.toml new file mode 100644 index 0000000..f97f972 --- /dev/null +++ b/examples/use_toggle/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "use_toggle" +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 = ["use_toggle", "docs"] } +web-sys = "0.3" + +[dev-dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-test = "0.3.0" diff --git a/examples/use_toggle/README.md b/examples/use_toggle/README.md new file mode 100644 index 0000000..f3e2725 --- /dev/null +++ b/examples/use_toggle/README.md @@ -0,0 +1,23 @@ +A simple example for `use_toggle`. + +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_toggle/Trunk.toml b/examples/use_toggle/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_toggle/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_toggle/index.html b/examples/use_toggle/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_toggle/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_toggle/input.css b/examples/use_toggle/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_toggle/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_toggle/rust-toolchain.toml b/examples/use_toggle/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_toggle/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_toggle/src/main.rs b/examples/use_toggle/src/main.rs new file mode 100644 index 0000000..eacec55 --- /dev/null +++ b/examples/use_toggle/src/main.rs @@ -0,0 +1,24 @@ +use leptos::*; +use leptos_use::docs::{demo_or_body, BooleanDisplay}; +use leptos_use::{use_toggle, UseToggleReturn}; + +#[component] +fn Demo() -> impl IntoView { + let UseToggleReturn { toggle, value, set_value } = use_toggle(true); + + view! { +

Value:

+ + + + } +} + +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_toggle/style/output.css b/examples/use_toggle/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_toggle/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_toggle/tailwind.config.js b/examples/use_toggle/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_toggle/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_web_lock/Cargo.toml b/examples/use_web_lock/Cargo.toml new file mode 100644 index 0000000..7d97f04 --- /dev/null +++ b/examples/use_web_lock/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "use_web_lock" +version = "0.1.0" +edition = "2021" + +[dependencies] +gloo-timers = { version = "0.3", features = ["futures"] } +leptos = { version = "0.6", features = ["nightly", "csr"] } +console_error_panic_hook = "0.1" +console_log = "1" +log = "0.4" +leptos-use = { path = "../..", features = ["use_web_lock", "docs"] } +web-sys = { version = "0.3", features = ["Lock"] } + +[dev-dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-test = "0.3.0" diff --git a/examples/use_web_lock/README.md b/examples/use_web_lock/README.md new file mode 100644 index 0000000..d820284 --- /dev/null +++ b/examples/use_web_lock/README.md @@ -0,0 +1,23 @@ +A simple example for `use_web_lock`. + +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_web_lock/Trunk.toml b/examples/use_web_lock/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_web_lock/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_web_lock/index.html b/examples/use_web_lock/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_web_lock/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_web_lock/input.css b/examples/use_web_lock/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_web_lock/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_web_lock/rust-toolchain.toml b/examples/use_web_lock/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_web_lock/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_web_lock/src/main.rs b/examples/use_web_lock/src/main.rs new file mode 100644 index 0000000..c84c047 --- /dev/null +++ b/examples/use_web_lock/src/main.rs @@ -0,0 +1,47 @@ +use gloo_timers::future::sleep; +use leptos::*; +use leptos_use::docs::demo_or_body; +use leptos_use::use_web_lock; +use std::time::Duration; + +async fn my_process(_lock: web_sys::Lock) -> i32 { + sleep(Duration::from_millis(2000)).await; + + 42 +} + +#[component] +fn Demo() -> impl IntoView { + let (res, set_res) = create_signal("Not started yet".to_string()); + + let on_click = move |_| { + set_res.set("Running...".to_string()); + + spawn_local(async move { + let res = use_web_lock("my_lock", my_process).await; + + match res { + Ok(res) => { + set_res.set(format!("Result: {}", res)); + } + Err(e) => { + set_res.set(format!("Error: {:?}", e)); + } + } + }); + }; + + view! { + +

{res}

+ } +} + +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_web_lock/style/output.css b/examples/use_web_lock/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_web_lock/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_web_lock/tailwind.config.js b/examples/use_web_lock/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_web_lock/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_window_size/Cargo.toml b/examples/use_window_size/Cargo.toml new file mode 100644 index 0000000..f59a15e --- /dev/null +++ b/examples/use_window_size/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "use_window_size" +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 = ["use_window_size", "docs"] } +web-sys = "0.3" + +[dev-dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-test = "0.3.0" diff --git a/examples/use_window_size/README.md b/examples/use_window_size/README.md new file mode 100644 index 0000000..8dac560 --- /dev/null +++ b/examples/use_window_size/README.md @@ -0,0 +1,23 @@ +A simple example for `use_window_size`. + +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_window_size/Trunk.toml b/examples/use_window_size/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_window_size/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_window_size/index.html b/examples/use_window_size/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_window_size/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_window_size/input.css b/examples/use_window_size/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_window_size/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_window_size/rust-toolchain.toml b/examples/use_window_size/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_window_size/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_window_size/src/main.rs b/examples/use_window_size/src/main.rs new file mode 100644 index 0000000..a253011 --- /dev/null +++ b/examples/use_window_size/src/main.rs @@ -0,0 +1,21 @@ +use leptos::*; +use leptos_use::docs::demo_or_body; +use leptos_use::{use_window_size, UseWindowSizeReturn}; + +#[component] +fn Demo() -> impl IntoView { + let UseWindowSizeReturn { width, height } = use_window_size(); + + view! { +

{{ width }} x {{ height }}

+ } +} + +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_window_size/style/output.css b/examples/use_window_size/style/output.css new file mode 100644 index 0000000..ab5191f --- /dev/null +++ b/examples/use_window_size/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_window_size/tailwind.config.js b/examples/use_window_size/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_window_size/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 a8c46b1..b0bcef0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,8 +134,13 @@ mod use_timeout_fn; mod use_timestamp; #[cfg(feature = "use_to_string")] mod use_to_string; +#[cfg(feature = "use_toggle")] +mod use_toggle; #[cfg(feature = "use_user_media")] mod use_user_media; +#[cfg(feature = "use_web_lock")] +#[cfg(web_sys_unstable_apis)] +mod use_web_lock; #[cfg(feature = "use_web_notification")] mod use_web_notification; #[cfg(feature = "use_websocket")] @@ -146,6 +151,8 @@ mod use_window; mod use_window_focus; #[cfg(feature = "use_window_scroll")] mod use_window_scroll; +#[cfg(feature = "use_window_size")] +mod use_window_size; #[cfg(feature = "watch_debounced")] mod watch_debounced; #[cfg(feature = "watch_pausable")] @@ -273,8 +280,13 @@ pub use use_timeout_fn::*; pub use use_timestamp::*; #[cfg(feature = "use_to_string")] pub use use_to_string::*; +#[cfg(feature = "use_toggle")] +pub use use_toggle::*; #[cfg(feature = "use_user_media")] pub use use_user_media::*; +#[cfg(feature = "use_web_lock")] +#[cfg(web_sys_unstable_apis)] +pub use use_web_lock::*; #[cfg(feature = "use_web_notification")] pub use use_web_notification::*; #[cfg(feature = "use_websocket")] @@ -285,6 +297,8 @@ pub use use_window::*; pub use use_window_focus::*; #[cfg(feature = "use_window_scroll")] pub use use_window_scroll::*; +#[cfg(feature = "use_window_size")] +pub use use_window_size::*; #[cfg(feature = "watch_debounced")] pub use watch_debounced::*; #[cfg(feature = "watch_pausable")] diff --git a/src/sync_signal.rs b/src/sync_signal.rs index 70a55ca..0ad0e29 100644 --- a/src/sync_signal.rs +++ b/src/sync_signal.rs @@ -7,8 +7,8 @@ use std::rc::Rc; /// /// > Note: Please consider first if you can achieve your goals with the /// > ["Good Options" described in the Leptos book](https://book.leptos.dev/reactivity/working_with_signals.html#making-signals-depend-on-each-other) -/// > firstly. Only if you really have to, use this function. This is in effect the -/// > ["If you really must..."](https://book.leptos.dev/reactivity/working_with_signals.html#if-you-really-must). +/// > Only if you really have to, use this function. This is, in effect, the +/// > ["If you really must..." option](https://book.leptos.dev/reactivity/working_with_signals.html#if-you-really-must). /// /// ## Demo /// @@ -112,9 +112,10 @@ use std::rc::Rc; /// let stop = sync_signal_with_options( /// (a, set_a), /// (b, set_b), -/// SyncSignalOptions::default() -/// .transform_ltr(|left| *left * 2) -/// .transform_rtl(|right| *right / 2) +/// SyncSignalOptions::with_transforms( +/// |left| *left * 2, +/// |right| *right / 2, +/// ), /// ); /// /// log!("a: {}, b: {}", a.get(), b.get()); // a: 10, b: 20 @@ -129,28 +130,68 @@ use std::rc::Rc; /// /// #### Different Types /// -/// `SyncSignalOptions::default()` is only defined if the two signal types are identical or -/// implement `From` for each other. Otherwise, you have to initialize the options with -/// `with_transforms` instead of `default`. +/// `SyncSignalOptions::default()` is only defined if the two signal types are identical. +/// Otherwise, you have to initialize the options with `with_transforms` or `with_assigns` instead +/// of `default`. /// /// ``` -/// # use leptos_use::SyncSignalOptions; +/// # use leptos::*; +/// # use leptos_use::{sync_signal_with_options, SyncSignalOptions}; /// # use std::str::FromStr; /// # -/// let options = SyncSignalOptions::with_transforms( -/// |left: &String| i32::from_str(left).unwrap_or_default(), -/// |right: &i32| right.to_string(), +/// # #[component] +/// # fn Demo() -> impl IntoView { +/// let (a, set_a) = create_signal("10".to_string()); +/// let (b, set_b) = create_signal(2); +/// +/// let stop = sync_signal_with_options( +/// (a, set_a), +/// (b, set_b), +/// SyncSignalOptions::with_transforms( +/// |left: &String| i32::from_str(left).unwrap_or_default(), +/// |right: &i32| right.to_string(), +/// ), /// ); +/// # +/// # view! { } +/// # } /// ``` /// +/// ``` +/// # use leptos::*; +/// # use leptos_use::{sync_signal_with_options, SyncSignalOptions}; +/// # use std::str::FromStr; +/// # +/// #[derive(Clone)] +/// pub struct Foo { +/// bar: i32, +/// } +/// +/// # #[component] +/// # fn Demo() -> impl IntoView { +/// let (a, set_a) = create_signal(Foo { bar: 10 }); +/// let (b, set_b) = create_signal(2); +/// +/// let stop = sync_signal_with_options( +/// (a, set_a), +/// (b, set_b), +/// SyncSignalOptions::with_assigns( +/// |b: &mut i32, a: &Foo| *b = a.bar, +/// |a: &mut Foo, b: &i32| a.bar = *b, +/// ), +/// ); +/// # +/// # view! { } +/// # } +/// ``` pub fn sync_signal( left: impl Into>, right: impl Into>, ) -> impl Fn() + Clone where - T: Clone + PartialEq + Send + Sync + 'static, + T: Clone + Send + Sync + 'static, { - sync_signal_with_options(left, right, SyncSignalOptions::default()) + sync_signal_with_options(left, right, SyncSignalOptions::::default()) } /// Version of [`sync_signal`] that takes a `SyncSignalOptions`. See [`sync_signal`] for how to use. @@ -160,32 +201,33 @@ pub fn sync_signal_with_options( options: SyncSignalOptions, ) -> impl Fn() + Clone where - L: Clone + PartialEq + Send + Sync + 'static, - R: Clone + PartialEq + Send + Sync + 'static, + L: Clone + Send + Sync + 'static, + R: Clone + Send + Sync + 'static, { let SyncSignalOptions { immediate, direction, - transform_ltr, - transform_rtl, - assign_ltr, - assign_rtl, + transforms, } = options; + let (assign_ltr, assign_rtl) = transforms.assigns(); + let left = left.into(); let right = right.into(); let mut stop_watch_left = None; let mut stop_watch_right = None; + let is_sync_update = StoredValue::new(false); + if matches!(direction, SyncDirection::Both | SyncDirection::LeftToRight) { stop_watch_left = Some(Effect::watch( move || left.get(), move |new_value, _, _| { - let new_value = (*transform_ltr)(new_value); - - if right.with_untracked(|right| right != &new_value) { + if !is_sync_update.get_value() { + is_sync_update.set_value(true); right.update(|right| assign_ltr(right, new_value)); + is_sync_update.set_value(false); } }, immediate, @@ -196,10 +238,10 @@ where stop_watch_right = Some(Effect::watch( move || right.get(), move |new_value, _, _| { - let new_value = (*transform_rtl)(new_value); - - if left.with_untracked(|left| left != &new_value) { + if !is_sync_update.get_value() { + is_sync_update.set_value(true); left.update(|left| assign_rtl(left, new_value)); + is_sync_update.set_value(false); } }, immediate, @@ -217,13 +259,69 @@ where } /// Direction of syncing. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum SyncDirection { LeftToRight, RightToLeft, + #[default] Both, } -pub type AssignFn = Rc; +pub type AssignFn = Rc; + +/// Transforms or assigns for syncing. +pub enum SyncTransforms { + /// Transform the signal into each other by calling the transform functions. + /// The values are then simply assigned. + Transforms { + /// Transforms the left signal into the right signal. + ltr: Rc R>, + /// Transforms the right signal into the left signal. + rtl: Rc L>, + }, + + /// Assign the signals to each other. Instead of using `=` to assign the signals, + /// these functions are called. + Assigns { + /// Assigns the left signal to the right signal. + ltr: AssignFn, + /// Assigns the right signal to the left signal. + rtl: AssignFn, + }, +} + +impl Default for SyncTransforms +where + T: Clone, +{ + fn default() -> Self { + Self::Assigns { + ltr: Rc::new(|right, left| *right = left.clone()), + rtl: Rc::new(|left, right| *left = right.clone()), + } + } +} + +impl SyncTransforms +where + L: 'static, + R: 'static, +{ + /// Returns assign functions for both directions that respect the value of this enum. + pub fn assigns(&self) -> (AssignFn, AssignFn) { + match self { + SyncTransforms::Transforms { ltr, rtl } => { + let ltr = Rc::clone(ltr); + let rtl = Rc::clone(rtl); + ( + Rc::new(move |right, left| *right = ltr(left)), + Rc::new(move |left, right| *left = rtl(right)), + ) + } + SyncTransforms::Assigns { ltr, rtl } => (Rc::clone(ltr), Rc::clone(rtl)), + } + } +} /// Options for [`sync_signal_with_options`]. #[derive(DefaultBuilder)] @@ -236,64 +334,16 @@ pub struct SyncSignalOptions { /// Direction of syncing. Defaults to `SyncDirection::Both`. direction: SyncDirection, - /// Transforms the left signal into the right signal. - /// Defaults to identity. + /// How to transform or assign the values to each other + /// If `L` and `R` are identical this defaults to the simple `=` operator. If the types are + /// not the same, then you have to choose to either use [`SyncSignalOptions::with_transforms`] + /// or [`SyncSignalOptions::with_assigns`]. #[builder(skip)] - transform_ltr: Rc R>, - - /// Transforms the right signal into the left signal. - /// Defaults to identity. - #[builder(skip)] - transform_rtl: Rc L>, - - /// Assigns the left signal to the right signal. - /// Defaults to `*r = l`. - #[builder(skip)] - assign_ltr: AssignFn, - - /// Assigns the right signal to the left signal. - /// Defaults to `*l = r`. - #[builder(skip)] - assign_rtl: AssignFn, + transforms: SyncTransforms, } impl SyncSignalOptions { - /// Transforms the left signal into the right signal. - /// Defaults to identity. - pub fn transform_ltr(self, transform_ltr: impl Fn(&L) -> R + 'static) -> Self { - Self { - transform_ltr: Rc::new(transform_ltr), - ..self - } - } - - /// Transforms the right signal into the left signal. - /// Defaults to identity. - pub fn transform_rtl(self, transform_rtl: impl Fn(&R) -> L + 'static) -> Self { - Self { - transform_rtl: Rc::new(transform_rtl), - ..self - } - } - - /// Assigns the left signal to the right signal. - /// Defaults to `*r = l`. - pub fn assign_ltr(self, assign_ltr: impl Fn(&mut R, R) + 'static) -> Self { - Self { - assign_ltr: Rc::new(assign_ltr), - ..self - } - } - - /// Assigns the right signal to the left signal. - /// Defaults to `*l = r`. - pub fn assign_rtl(self, assign_rtl: impl Fn(&mut L, L) + 'static) -> Self { - Self { - assign_rtl: Rc::new(assign_rtl), - ..self - } - } - /// Initializes options with transforms + /// Initializes options with transforms functions that convert the signals into each other. pub fn with_transforms( transform_ltr: impl Fn(&L) -> R + 'static, transform_rtl: impl Fn(&R) -> L + 'static, @@ -301,27 +351,38 @@ impl SyncSignalOptions { Self { immediate: true, direction: SyncDirection::Both, - transform_ltr: Rc::new(transform_ltr), - transform_rtl: Rc::new(transform_rtl), - assign_ltr: Rc::new(|right, left| *right = left), - assign_rtl: Rc::new(|left, right| *left = right), + transforms: SyncTransforms::Transforms { + ltr: Rc::new(transform_ltr), + rtl: Rc::new(transform_rtl), + }, + } + } + + /// Initializes options with assign functions that replace the default `=` operator. + pub fn with_assigns( + assign_ltr: impl Fn(&mut R, &L) + 'static, + assign_rtl: impl Fn(&mut L, &R) + 'static, + ) -> Self { + Self { + immediate: true, + direction: SyncDirection::Both, + transforms: SyncTransforms::Assigns { + ltr: Rc::new(assign_ltr), + rtl: Rc::new(assign_rtl), + }, } } } -impl Default for SyncSignalOptions +impl Default for SyncSignalOptions where - L: Clone + From, - R: Clone + From, + T: Clone, { fn default() -> Self { Self { immediate: true, - direction: SyncDirection::Both, - transform_ltr: Rc::new(|x| x.clone().into()), - transform_rtl: Rc::new(|x| x.clone().into()), - assign_ltr: Rc::new(|right, left| *right = left), - assign_rtl: Rc::new(|left, right| *left = right), + direction: Default::default(), + transforms: Default::default(), } } } diff --git a/src/use_clipboard.rs b/src/use_clipboard.rs index d20dfe7..1bb9bac 100644 --- a/src/use_clipboard.rs +++ b/src/use_clipboard.rs @@ -5,6 +5,7 @@ use leptos::reactive_graph::wrappers::read::Signal; use leptos::prelude::*; /// 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 diff --git a/src/use_device_orientation.rs b/src/use_device_orientation.rs index 2d24807..4a70a04 100644 --- a/src/use_device_orientation.rs +++ b/src/use_device_orientation.rs @@ -2,6 +2,7 @@ use cfg_if::cfg_if; use leptos::reactive_graph::wrappers::read::Signal; /// Reactive [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent). +/// /// Provide web developers with information from the physical orientation of /// the device running the web page. /// diff --git a/src/use_event_listener.rs b/src/use_event_listener.rs index 2712831..407c1ef 100644 --- a/src/use_event_listener.rs +++ b/src/use_event_listener.rs @@ -13,6 +13,7 @@ cfg_if! { if #[cfg(not(feature = "ssr"))] { }} /// Use EventListener with ease. +/// /// Register using [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) on mounted, /// and [removeEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) automatically on cleanup. /// diff --git a/src/use_geolocation.rs b/src/use_geolocation.rs index f405534..0d52b94 100644 --- a/src/use_geolocation.rs +++ b/src/use_geolocation.rs @@ -4,6 +4,7 @@ use leptos::reactive_graph::wrappers::read::Signal; use leptos::prelude::*; /// Reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API). +/// /// It allows the user to provide their location to web applications if they so desire. For privacy reasons, /// the user is asked for permission to report location information. /// diff --git a/src/use_toggle.rs b/src/use_toggle.rs new file mode 100644 index 0000000..d3909fa --- /dev/null +++ b/src/use_toggle.rs @@ -0,0 +1,57 @@ +use crate::core::MaybeRwSignal; +use leptos::*; + +/// A boolean switcher with utility functions. +/// +/// ## Demo +/// +/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_toggle) +/// +/// ## Usage +/// +/// ``` +/// # use leptos::*; +/// # use leptos_use::{use_toggle, UseToggleReturn}; +/// # +/// # #[component] +/// # fn Demo() -> impl IntoView { +/// let UseToggleReturn { toggle, value, set_value } = use_toggle(true); +/// # +/// # view! { } +/// # } +/// ``` +/// +/// ## See also +/// +/// * [`fn@crate::use_cycle_list`] +// #[doc(cfg(feature = "use_toggle"))] +pub fn use_toggle( + initial_value: impl Into>, +) -> UseToggleReturn { + let initial_value = initial_value.into(); + let (value, set_value) = initial_value.into_signal(); + + let toggle = move || { + set_value.update(|v| *v = !*v); + }; + + UseToggleReturn { + toggle, + value, + set_value, + } +} + +/// Return type of [`fn@crate::use_toggle`]. +// #[doc(cfg(feature = "use_toggle"))] +pub struct UseToggleReturn +where + F: Fn() + Clone + 'static, +{ + /// Toggles the value between `true` and `false`. + pub toggle: F, + /// The current value as signal. + pub value: Signal, + /// Sets the current value to the given value. + pub set_value: WriteSignal, +} diff --git a/src/use_user_media.rs b/src/use_user_media.rs index 7a259c0..df13a46 100644 --- a/src/use_user_media.rs +++ b/src/use_user_media.rs @@ -151,6 +151,7 @@ async fn create_media(video: bool, audio: bool) -> Result 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_web_lock) +/// +/// ## Usage +/// +/// ``` +/// # use leptos::*; +/// # use leptos_use::use_web_lock; +/// # +/// async fn my_process(_lock: web_sys::Lock) -> i32 { +/// // do sth +/// 42 +/// } +/// +/// # #[component] +/// # fn Demo() -> impl IntoView { +/// spawn_local(async { +/// let res = use_web_lock("my_lock", my_process).await; +/// assert!(matches!(res, Ok(42))); +/// }); +/// # +/// # view! { } +/// # } +/// ``` +/// +/// ## Server-Side Rendering +/// +/// On the server this returns `Err(UseWebLockError::Server)` and the task is not executed. +// #[doc(cfg(feature = "use_web_lock"))] + +pub async fn use_web_lock(name: &str, callback: C) -> Result +where + C: FnOnce(web_sys::Lock) -> F + 'static, + F: Future, + R: 'static, +{ + use_web_lock_with_options(name, callback, UseWebLockOptions::default()).await +} + +/// Version of [`fn@crate::use_web_lock`] that takes a `UseWebLockOptions`. See [`fn@crate::use_web_lock`] for how to use. +// #[doc(cfg(feature = "use_web_lock"))] +pub async fn use_web_lock_with_options( + name: &str, + callback: C, + options: UseWebLockOptions, +) -> Result +where + C: FnOnce(web_sys::Lock) -> F + 'static, + F: Future, + R: 'static, +{ + #[cfg(feature = "ssr")] + { + let _ = name; + let _ = callback; + let _ = options; + + Err(UseWebLockError::Server) + } + + #[cfg(not(feature = "ssr"))] + { + use crate::js_fut; + use leptos::window; + use std::sync::{Arc, Mutex}; + use wasm_bindgen::closure::Closure; + use wasm_bindgen::JsCast; + use wasm_bindgen_futures::future_to_promise; + + let ret_value = Arc::new(Mutex::new(None)); + + let handler = Closure::once(Box::new({ + let ret_value = Arc::clone(&ret_value); + + move |lock| { + future_to_promise(async move { + let ret = callback(lock).await; + ret_value.lock().expect("Lock failed").replace(ret); + Ok(JsValue::null()) + }) + } + }) as Box _>) + .into_js_value(); + + let lock_promise = window() + .navigator() + .locks() + .request_with_options_and_callback( + name, + &options.to_web_sys(), + handler.unchecked_ref(), + ); + + js_fut!(lock_promise) + .await + .map(move |_| { + Arc::into_inner(ret_value) + .expect("Arc has more than one reference still") + .into_inner() + .expect("Lock failed") + .expect("Return value was None") + }) + .map_err(UseWebLockError::Failed) + } +} + +#[derive(Error, Debug)] +pub enum UseWebLockError { + #[error("Lock cannot be acquired on the server")] + Server, + + #[error("Lock failed")] + Failed(JsValue), +} + +/// Options for [`fn@crate::use_web_lock_with_options`]. +// #[doc(cfg(feature = "use_web_lock"))] +#[allow(dead_code)] +#[derive(DefaultBuilder)] +pub struct UseWebLockOptions { + /// The default mode is `LockMode::Exclusive`, but `LockMode::Shared` can be specified. + /// There can be only one `Exclusive` holder of a lock, but multiple `Shared` requests can be + /// granted at the same time. This can be used to implement the + /// [readers-writer pattern](https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock). + mode: LockMode, + + /// If `true`, the lock request will fail if the lock cannot be granted immediately without + /// waiting. The callback is invoked with `null`. Defaults to `false`. + if_available: bool, + + /// If `true`, then any held locks with the same name will be released, and the request will + /// be granted, preempting any queued requests for it. Defaults to `false`. + steal: bool, + // TODO : add abort signal (this also requires to create a wrapper for AbortSignal similar to UseWindow) +} + +#[cfg(not(feature = "ssr"))] +impl UseWebLockOptions { + fn to_web_sys(&self) -> web_sys::LockOptions { + let options = web_sys::LockOptions::new(); + options.set_mode(self.mode); + options.set_if_available(self.if_available); + options.set_steal(self.steal); + + options + } +} + +impl Default for UseWebLockOptions { + fn default() -> Self { + Self { + mode: LockMode::Exclusive, + if_available: false, + steal: false, + } + } +} diff --git a/src/use_web_notification.rs b/src/use_web_notification.rs index 6fcf55f..fb6ea86 100644 --- a/src/use_web_notification.rs +++ b/src/use_web_notification.rs @@ -351,6 +351,7 @@ impl From<&UseWebNotificationOptions> for web_sys::NotificationOptions { } /// Options for [`UseWebNotificationReturn::show`]. +/// /// This can be used to override options passed to [`use_web_notification`]. /// See [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/notification) for more info. /// diff --git a/src/use_websocket.rs b/src/use_websocket.rs index 1a3c0d5..581bb40 100644 --- a/src/use_websocket.rs +++ b/src/use_websocket.rs @@ -343,17 +343,19 @@ where } let web_socket = { - protocols.as_ref().map_or_else( - || WebSocket::new(&url).unwrap_throw(), - |protocols| { - let array = protocols - .iter() - .map(|p| JsValue::from(p.clone())) - .collect::(); - WebSocket::new_with_str_sequence(&url, &JsValue::from(&array)) - .unwrap_throw() - }, - ) + protocols.with_untracked(|protocols| { + protocols.as_ref().map_or_else( + || WebSocket::new(&url).unwrap_throw(), + |protocols| { + let array = protocols + .iter() + .map(|p| JsValue::from(p.clone())) + .collect::(); + WebSocket::new_with_str_sequence(&url, &JsValue::from(&array)) + .unwrap_throw() + }, + ) + }) }; web_socket.set_binary_type(BinaryType::Arraybuffer); set_ready_state.set(ConnectionReadyState::Connecting); @@ -649,7 +651,13 @@ where /// Defaults to `true`. immediate: bool, /// Sub protocols. See [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket#protocols). - protocols: Option>, + /// + /// Can be set as a signal to support protocols only available after the initial render. + /// + /// Note that protocols are only updated on the next websocket open() call, not whenever the signal is updated. + /// Therefore "lazy" protocols should use the `immediate(false)` option and manually call `open()`. + #[builder(into)] + protocols: MaybeSignal>>, } impl UseWebSocketOptions { diff --git a/src/use_window_size.rs b/src/use_window_size.rs new file mode 100644 index 0000000..66b185a --- /dev/null +++ b/src/use_window_size.rs @@ -0,0 +1,194 @@ +use crate::core::Size; +use crate::{ + use_event_listener_with_options, use_media_query, use_window, UseEventListenerOptions, +}; +use default_struct_builder::DefaultBuilder; +use leptos::ev::resize; +use leptos::*; + +/// Reactive window size. +/// +/// ## Demo +/// +/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_window_size) +/// +/// ## Usage +/// +/// ``` +/// # use leptos::*; +/// # use leptos_use::{use_window_size, UseWindowSizeReturn}; +/// # +/// # #[component] +/// # fn Demo() -> impl IntoView { +/// let UseWindowSizeReturn { width, height } = use_window_size(); +/// # +/// # view! { } +/// # } +/// ``` +/// +/// ## Server-Side Rendering +/// +/// On the server the width and height are always `initial_size` which defaults to +/// `Size { width: INFINITY, height: INFINITY }`. +// #[doc(cfg(feature = "use_window_size"))] +pub fn use_window_size() -> UseWindowSizeReturn { + use_window_size_with_options(UseWindowSizeOptions::default()) +} + +/// Version of [`fn@crate::use_window_size`] that takes a `UseWindowSizeOptions`. See [`fn@crate::use_window_size`] for how to use. +// #[doc(cfg(feature = "use_window_size"))] +pub fn use_window_size_with_options(options: UseWindowSizeOptions) -> UseWindowSizeReturn { + let UseWindowSizeOptions { + initial_size, + listen_orientation, + include_scrollbar, + measure_type, + } = options; + + let (width, set_width) = create_signal(initial_size.width); + let (height, set_height) = create_signal(initial_size.height); + + let update; + + #[cfg(not(feature = "ssr"))] + { + update = move || match measure_type { + MeasureType::Outer => { + set_width.set( + window() + .outer_width() + .expect("failed to get window width") + .as_f64() + .expect("width is not a f64"), + ); + set_height.set( + window() + .outer_height() + .expect("failed to get window height") + .as_f64() + .expect("height is not a f64"), + ); + } + MeasureType::Inner => { + if include_scrollbar { + set_width.set( + window() + .inner_width() + .expect("failed to get window width") + .as_f64() + .expect("width is not a f64"), + ); + set_height.set( + window() + .inner_height() + .expect("failed to get window height") + .as_f64() + .expect("height is not a f64"), + ); + } else { + set_width.set( + document() + .document_element() + .expect("no document element") + .client_width() as f64, + ); + set_height.set( + document() + .document_element() + .expect("no document element") + .client_height() as f64, + ); + } + } + }; + } + + #[cfg(feature = "ssr")] + { + update = || {}; + + let _ = initial_size; + let _ = include_scrollbar; + let _ = measure_type; + + let _ = set_width; + let _ = set_height; + } + + update(); + let _ = use_event_listener_with_options( + use_window(), + resize, + move |_| update(), + UseEventListenerOptions::default().passive(true), + ); + + if listen_orientation { + let matches = use_media_query("(orientation: portrait)"); + + create_effect(move |_| { + matches.track(); + + update(); + }); + } + + UseWindowSizeReturn { + width: width.into(), + height: height.into(), + } +} + +/// Options for [`fn@crate::use_window_size_with_options`]. +// #[doc(cfg(feature = "use_window_size"))] +#[derive(DefaultBuilder)] +pub struct UseWindowSizeOptions { + /// The initial size before anything is measured (like on the server side). + /// Defaults to `Size { width: INFINITY, height: INFINITY }`. + initial_size: Size, + + /// Listen to the window ` orientationchange ` event. Defaults to `true`. + listen_orientation: bool, + + /// Whether the scrollbar should be included in the width and height + /// Only effective when `measure_type` is `MeasureType::Inner`. + /// Defaults to `true`. + include_scrollbar: bool, + + /// Use `window.innerWidth` or `window.outerWidth`. + /// Defaults to `MeasureType::Inner`. + measure_type: MeasureType, +} + +/// Type of the `measure_type` option. +#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] +pub enum MeasureType { + /// Use `window.innerWidth` + #[default] + Inner, + /// Use `window.outerWidth` + Outer, +} + +impl Default for UseWindowSizeOptions { + fn default() -> Self { + Self { + initial_size: Size { + width: f64::INFINITY, + height: f64::INFINITY, + }, + listen_orientation: true, + include_scrollbar: true, + measure_type: MeasureType::default(), + } + } +} + +/// Return type of [`fn@crate::use_window_size`]. +// #[doc(cfg(feature = "use_window_size"))] +pub struct UseWindowSizeReturn { + /// The width of the window. + pub width: Signal, + /// The height of the window. + pub height: Signal, +} diff --git a/template/.ffizer.yaml b/template/.ffizer.yaml index cafee3e..b13294c 100644 --- a/template/.ffizer.yaml +++ b/template/.ffizer.yaml @@ -11,12 +11,12 @@ variables: default_value: "" ask: Module [optional] - name: feature - default_value: "" - ask: cfg feature [optional] + default_value: "{{ function_name }}" + ask: cfg feature ignores: - modify_files.py - createfn.sh scripts: - - cmd: python3 template/modify_files.py {{ function_name }} {{ category }}{{#if module}} --module {{ module }}{{/if}}{{#if feature}} --feature {{ feature }}{{/if}} + - cmd: python3 template/modify_files.py {{ function_name }} {{ category }}{{#if module}} --module {{ module }}{{/if}} --feature {{ feature }} --unstable_apis {{ unstable_apis }} diff --git a/template/modify_files.py b/template/modify_files.py index dd0c865..a54b852 100644 --- a/template/modify_files.py +++ b/template/modify_files.py @@ -10,9 +10,11 @@ def main(): parser.add_argument("category") parser.add_argument("--module", type=str) parser.add_argument("--feature", type=str) + parser.add_argument("--unstable_apis", type=lambda x: x.lower() == "true") args = parser.parse_args() + modify_cargo_toml(args) modify_changelog(args) modify_librs(args) modify_modrs(args) @@ -93,7 +95,14 @@ def modify_librs(args): with open("src/lib.rs", "r") as f: lib_source = f.read() - feature_prefix = "" if args.feature is None else f"#[cfg(feature = \"{args.feature}\"))]\n" + feature_prefix = [] + if args.feature is not None: + feature_prefix.append(f"#[cfg(feature = \"{args.feature}\")]\n") + + if args.unstable_apis: + feature_prefix.append("#[cfg(web_sys_unstable_apis)]\n") + + feature_prefix = "".join(feature_prefix) if args.module is None: lib_source = lib_source.replace("mod on_click_outside;", @@ -140,5 +149,28 @@ def modify_changelog(args): f.write("".join(changelog_source)) +def modify_cargo_toml(args): + with open("Cargo.toml", "r") as f: + cargo_toml_source = f.readlines() + + in_features = False + in_default = False + + for i, line in enumerate(cargo_toml_source): + if line.startswith("[features]"): + in_features = True + + if in_features and line.startswith("default = ["): + in_default = True + cargo_toml_source.insert(i + 1, f" \"{args.feature}\",\n") + + if in_default and line.startswith("]"): + cargo_toml_source.insert(i + 1, f"{args.feature} = []\n") + break + + with open("Cargo.toml", "w") as f: + f.write("".join(cargo_toml_source)) + + if __name__ == '__main__': main() diff --git a/template/src/{{ module }}/{{ function_name }}.ffizer.hbs.rs b/template/src/{{ module }}/{{ function_name }}.ffizer.hbs.rs index 1248179..8e27eeb 100644 --- a/template/src/{{ module }}/{{ function_name }}.ffizer.hbs.rs +++ b/template/src/{{ module }}/{{ function_name }}.ffizer.hbs.rs @@ -4,7 +4,7 @@ use leptos::prelude::*; ///{{#if (eq unstable_apis "true")}} /// /// > 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).{{/if}} +/// > [described in the wasm-bindgen guide](https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html).{{/if}} /// /// ## Demo /// @@ -25,9 +25,8 @@ use leptos::prelude::*; /// ``` /// /// ## Server-Side Rendering -/// {{#if feature}} -// #[doc(cfg(feature = "{{feature}}"))]{{/if}} - +/// +// #[doc(cfg(feature = "{{feature}}"))] pub fn {{ function_name }}() -> {{ to_pascal_case function_name }}Return { {{ function_name }}_with_options({{ to_pascal_case function_name }}Options::default()) }