diff --git a/CHANGELOG.md b/CHANGELOG.md index c37f1ad..23dd824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,20 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] - + +### New Functions 🚀 + +- `use_infinite_scroll` + +### Breaking Changes 🛠 + +- `use_scroll` returns `impl Fn(T) + Clone` instead of `Box`. + +### Other Changes 🔥 + +- `UseScrollReturn` is now documented + ## [0.7.2] - 2023-10-21 ### Fixes 🍕 diff --git a/Cargo.toml b/Cargo.toml index ee22cf8..582fa0a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,69 +13,71 @@ repository = "https://github.com/Synphonyte/leptos-use" homepage = "https://leptos-use.rs" [dependencies] -leptos = "0.5" -wasm-bindgen = "0.2" -js-sys = "0.3" +cfg-if = "1" default-struct-builder = "0.5" +futures-util = "0.3" +gloo-timers = { version = "0.3.0", features = ["futures"] } +js-sys = "0.3" +lazy_static = "1" +leptos = "0.5" num = { version = "0.4", optional = true } +paste = "1" serde = { version = "1", optional = true } serde_json = { version = "1", optional = true } -paste = "1" -lazy_static = "1" -cfg-if = "1" +wasm-bindgen = "0.2" [dependencies.web-sys] version = "0.3" features = [ - "AddEventListenerOptions", - "BinaryType", - "Coordinates", - "CloseEvent", - "CssStyleDeclaration", - "CustomEvent", - "CustomEventInit", - "DomRect", - "DomRectReadOnly", - "DataTransfer", - "DragEvent", - "Element", - "EventListener", - "EventListenerOptions", - "EventTarget", - "File", - "FileList", - "Geolocation", - "HtmlElement", - "HtmlLinkElement", - "HtmlStyleElement", - "IntersectionObserver", - "IntersectionObserverInit", - "IntersectionObserverEntry", - "MediaQueryList", - "MouseEvent", - "MutationObserver", - "MutationObserverInit", - "MutationRecord", - "Navigator", - "NodeList", - "PointerEvent", - "Position", - "PositionError", - "PositionOptions", - "ResizeObserver", - "ResizeObserverBoxOptions", - "ResizeObserverEntry", - "ResizeObserverOptions", - "ResizeObserverSize", - "ScrollBehavior", - "ScrollToOptions", - "Storage", - "Touch", - "TouchEvent", - "TouchList", - "VisibilityState", - "WebSocket", - "Window", + "AddEventListenerOptions", + "BinaryType", + "Coordinates", + "CloseEvent", + "CssStyleDeclaration", + "CustomEvent", + "CustomEventInit", + "DomRect", + "DomRectReadOnly", + "DataTransfer", + "DragEvent", + "Element", + "EventListener", + "EventListenerOptions", + "EventTarget", + "File", + "FileList", + "Geolocation", + "HtmlElement", + "HtmlLinkElement", + "HtmlStyleElement", + "IntersectionObserver", + "IntersectionObserverInit", + "IntersectionObserverEntry", + "MediaQueryList", + "MouseEvent", + "MutationObserver", + "MutationObserverInit", + "MutationRecord", + "Navigator", + "NodeList", + "PointerEvent", + "Position", + "PositionError", + "PositionOptions", + "ResizeObserver", + "ResizeObserverBoxOptions", + "ResizeObserverEntry", + "ResizeObserverOptions", + "ResizeObserverSize", + "ScrollBehavior", + "ScrollToOptions", + "Storage", + "Touch", + "TouchEvent", + "TouchList", + "VisibilityState", + "WebSocket", + "Window", ] [features] diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index dbb23c8..ea74e15 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -45,6 +45,7 @@ - [use_element_hover](sensors/use_element_hover.md) - [use_geolocation](sensors/use_geolocation.md) - [use_idle](sensors/use_idle.md) +- [use_infinite_scroll](sensors/use_infinite_scroll.md) - [use_mouse](sensors/use_mouse.md) - [use_scroll](sensors/use_scroll.md) diff --git a/docs/book/src/sensors/use_infinite_scroll.md b/docs/book/src/sensors/use_infinite_scroll.md new file mode 100644 index 0000000..1810384 --- /dev/null +++ b/docs/book/src/sensors/use_infinite_scroll.md @@ -0,0 +1,3 @@ +# use_infinite_scroll + + diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 930d976..d367ba8 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -24,6 +24,7 @@ members = [ "use_floor", "use_geolocation", "use_idle", + "use_infinite_scroll", "use_intersection_observer", "use_interval", "use_interval_fn", diff --git a/examples/signal_debounced/src/main.rs b/examples/signal_debounced/src/main.rs index 4e42d6c..cce81fc 100644 --- a/examples/signal_debounced/src/main.rs +++ b/examples/signal_debounced/src/main.rs @@ -15,17 +15,9 @@ fn Demo() -> impl IntoView { on:input=move |event| set_input(event_target_value(&event)) placeholder="Try to type quickly, then stop..." /> - - Delay is set to 1000ms for this demo. - -

- Input signal: - {input} -

-

- Debounced signal: - {debounced} -

+ Delay is set to 1000ms for this demo. +

Input signal: {input}

+

Debounced signal: {debounced}

} } diff --git a/examples/signal_throttled/src/main.rs b/examples/signal_throttled/src/main.rs index 2ff7366..0fc9058 100644 --- a/examples/signal_throttled/src/main.rs +++ b/examples/signal_throttled/src/main.rs @@ -15,17 +15,9 @@ fn Demo() -> impl IntoView { on:input=move |event| set_input(event_target_value(&event)) placeholder="Try to type quickly..." /> - - Delay is set to 1000ms for this demo. - -

- Input signal: - {input} -

-

- Throttled signal: - {throttled} -

+ Delay is set to 1000ms for this demo. +

Input signal: {input}

+

Throttled signal: {throttled}

} } diff --git a/examples/ssr/src/app.rs b/examples/ssr/src/app.rs index 91e95b8..29e62fc 100644 --- a/examples/ssr/src/app.rs +++ b/examples/ssr/src/app.rs @@ -64,24 +64,10 @@ fn HomePage() -> impl IntoView { debounced_fn(); view! { -

- Leptos-Use SSR Example -

- -

- Locale zh-Hans-CN-u-nu-hanidec: - {zh_count} -

-

- Press any key: - {key} -

-

- Debounced called: - {debounce_value} -

+

Leptos-Use SSR Example

+ +

Locale zh-Hans-CN-u-nu-hanidec: {zh_count}

+

Press any key: {key}

+

Debounced called: {debounce_value}

} } diff --git a/examples/use_active_element/src/main.rs b/examples/use_active_element/src/main.rs index e18fe28..8678475 100644 --- a/examples/use_active_element/src/main.rs +++ b/examples/use_active_element/src/main.rs @@ -19,11 +19,7 @@ fn Demo() -> impl IntoView { "Select the inputs below to see the changes"
- + diff --git a/examples/use_draggable/src/main.rs b/examples/use_draggable/src/main.rs index 9ed1bfb..f7cec80 100644 --- a/examples/use_draggable/src/main.rs +++ b/examples/use_draggable/src/main.rs @@ -24,20 +24,14 @@ fn Demo() -> impl IntoView { ); view! { -

- Check the floating box -

+

Check the floating box

"👋 Drag me!" -
- I am - {move || x().round()}, - {move || y().round()} -
+
I am {move || x().round()} , {move || y().round()}
} } diff --git a/examples/use_drop_zone/src/main.rs b/examples/use_drop_zone/src/main.rs index d70c460..52f31d4 100644 --- a/examples/use_drop_zone/src/main.rs +++ b/examples/use_drop_zone/src/main.rs @@ -22,45 +22,21 @@ fn Demo() -> impl IntoView { view! {
-

- Drop files into dropZone -

+

Drop files into dropZone

Drop me
-
- is_over_drop_zone: - -
-
- dropped: - -
+
is_over_drop_zone:
+
dropped:
- +
-

- Name: - {file.name()} -

-

- Size: - {file.size()} -

-

- Type: - {file.type_()} -

-

- Last modified: - {file.last_modified()} -

+

Name: {file.name()}

+

Size: {file.size()}

+

Type: {file.type_()}

+

Last modified: {file.last_modified()}

diff --git a/examples/use_geolocation/src/main.rs b/examples/use_geolocation/src/main.rs index ea2187a..895aa7e 100644 --- a/examples/use_geolocation/src/main.rs +++ b/examples/use_geolocation/src/main.rs @@ -27,20 +27,22 @@ fn Demo() -> impl IntoView { heading: {:?}, speed: {:?}, }}"#, - coords.accuracy(), coords.latitude(), coords.longitude(), coords.altitude(), - coords.altitude_accuracy(), coords.heading(), coords.speed() + coords.accuracy(), + coords.latitude(), + coords.longitude(), + coords.altitude(), + coords.altitude_accuracy(), + coords.heading(), + coords.speed(), ) } else { "None".to_string() } }} , - located_at: - {located_at} - , + located_at: {located_at} , error: - {move || if let Some(error) = error() { error.message() } else { "None".to_string() }} - , + {move || if let Some(error) = error() { error.message() } else { "None".to_string() }} , diff --git a/examples/use_idle/src/main.rs b/examples/use_idle/src/main.rs index 3ad03cb..26fb5af 100644 --- a/examples/use_idle/src/main.rs +++ b/examples/use_idle/src/main.rs @@ -14,20 +14,11 @@ fn Demo() -> impl IntoView { view! { - For demonstration purpose, the idle timeout is set to - - 5s - + For demonstration purpose, the idle timeout is set to 5s in this demo (default 1min). -
- Idle: - -
-
- Inactive: - {idled_for} s -
+
Idle:
+
Inactive: {idled_for} s
} } diff --git a/examples/use_infinite_scroll/Cargo.toml b/examples/use_infinite_scroll/Cargo.toml new file mode 100644 index 0000000..93b5074 --- /dev/null +++ b/examples/use_infinite_scroll/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "use_infinite_scroll" +version = "0.1.0" +edition = "2021" + +[dependencies] +leptos = { version = "0.5", features = ["nightly", "csr"] } +console_error_panic_hook = "0.1" +console_log = "1" +log = "0.4" +leptos-use = { path = "../..", features = ["docs"] } +web-sys = "0.3" + +[dev-dependencies] +wasm-bindgen = "0.2" +wasm-bindgen-test = "0.3.0" diff --git a/examples/use_infinite_scroll/README.md b/examples/use_infinite_scroll/README.md new file mode 100644 index 0000000..48fe6ea --- /dev/null +++ b/examples/use_infinite_scroll/README.md @@ -0,0 +1,23 @@ +A simple example for `use_infinite_scroll`. + +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_infinite_scroll/Trunk.toml b/examples/use_infinite_scroll/Trunk.toml new file mode 100644 index 0000000..3e4be08 --- /dev/null +++ b/examples/use_infinite_scroll/Trunk.toml @@ -0,0 +1,2 @@ +[build] +public_url = "/demo/" \ No newline at end of file diff --git a/examples/use_infinite_scroll/index.html b/examples/use_infinite_scroll/index.html new file mode 100644 index 0000000..ae249a6 --- /dev/null +++ b/examples/use_infinite_scroll/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/examples/use_infinite_scroll/input.css b/examples/use_infinite_scroll/input.css new file mode 100644 index 0000000..bd6213e --- /dev/null +++ b/examples/use_infinite_scroll/input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; \ No newline at end of file diff --git a/examples/use_infinite_scroll/rust-toolchain.toml b/examples/use_infinite_scroll/rust-toolchain.toml new file mode 100644 index 0000000..271800c --- /dev/null +++ b/examples/use_infinite_scroll/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" \ No newline at end of file diff --git a/examples/use_infinite_scroll/src/main.rs b/examples/use_infinite_scroll/src/main.rs new file mode 100644 index 0000000..57121ca --- /dev/null +++ b/examples/use_infinite_scroll/src/main.rs @@ -0,0 +1,40 @@ +use leptos::html::Div; +use leptos::*; +use leptos_use::docs::demo_or_body; +use leptos_use::{use_infinite_scroll_with_options, UseInfiniteScrollOptions}; + +#[component] +fn Demo() -> impl IntoView { + let el = create_node_ref::
(); + + let (data, set_data) = create_signal(vec![1, 2, 3, 4, 5, 6]); + + let _ = use_infinite_scroll_with_options( + el, + move |_| async move { + let len = data.with_untracked(|d| d.len()); + set_data.update(|data| *data = (1..len + 6).collect()); + }, + UseInfiniteScrollOptions::default().distance(10.0), + ); + + view! { +
+ +
{item}
+
+
+ } +} + +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_infinite_scroll/style/output.css b/examples/use_infinite_scroll/style/output.css new file mode 100644 index 0000000..33e91d6 --- /dev/null +++ b/examples/use_infinite_scroll/style/output.css @@ -0,0 +1,338 @@ +[type='text'],input:where(:not([type])),[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, input:where(:not([type])):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; + text-align: inherit; +} + +::-webkit-datetime-edit { + display: inline-flex; +} + +::-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],[size]:where(select:not([size="1"])) { + 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: ; +} + +.static { + position: static; +} + +.m-auto { + margin: auto; +} + +.flex { + display: flex; +} + +.h-\[300px\] { + height: 300px; +} + +.w-\[300px\] { + width: 300px; +} + +.flex-col { + flex-direction: column; +} + +.gap-2 { + gap: 0.5rem; +} + +.overflow-y-scroll { + overflow-y: scroll; +} + +.rounded { + border-radius: 0.25rem; +} + +.bg-gray-500\/5 { + background-color: rgb(107 114 128 / 0.05); +} + +.p-3 { + padding: 0.75rem; +} + +.p-4 { + padding: 1rem; +} + +.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_infinite_scroll/tailwind.config.js b/examples/use_infinite_scroll/tailwind.config.js new file mode 100644 index 0000000..bc09f5e --- /dev/null +++ b/examples/use_infinite_scroll/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_mouse/src/main.rs b/examples/use_mouse/src/main.rs index e96ac32..7269145 100644 --- a/examples/use_mouse/src/main.rs +++ b/examples/use_mouse/src/main.rs @@ -42,8 +42,10 @@ fn Demo() -> impl IntoView { r#" x: {} y: {} source_type: {:?} -"#, mouse_default.x.get(), - mouse_default.y.get(), mouse_default.source_type.get() +"#, + mouse_default.x.get(), + mouse_default.y.get(), + mouse_default.source_type.get(), ) }} @@ -56,8 +58,10 @@ fn Demo() -> impl IntoView { r#" x: {} y: {} source_type: {:?} -"#, mouse_with_extractor.x - .get(), mouse_with_extractor.y.get(), mouse_with_extractor.source_type.get() +"#, + mouse_with_extractor.x.get(), + mouse_with_extractor.y.get(), + mouse_with_extractor.source_type.get(), ) }} diff --git a/examples/use_raf_fn/src/main.rs b/examples/use_raf_fn/src/main.rs index 4e794a2..5c8b14f 100644 --- a/examples/use_raf_fn/src/main.rs +++ b/examples/use_raf_fn/src/main.rs @@ -15,10 +15,7 @@ fn Demo() -> impl IntoView { }); view! { -
- Count: - {count} -
+
Count: {count}
diff --git a/examples/use_timestamp/src/main.rs b/examples/use_timestamp/src/main.rs index b1e79ad..f67a8eb 100644 --- a/examples/use_timestamp/src/main.rs +++ b/examples/use_timestamp/src/main.rs @@ -6,12 +6,7 @@ use leptos_use::use_timestamp; fn Demo() -> impl IntoView { let timestamp = use_timestamp(); - view! { -
- Timestamp: - {timestamp} -
- } + view! {
Timestamp: {timestamp}
} } fn main() { diff --git a/examples/use_window_scroll/src/main.rs b/examples/use_window_scroll/src/main.rs index 627db6d..f659c54 100644 --- a/examples/use_window_scroll/src/main.rs +++ b/examples/use_window_scroll/src/main.rs @@ -16,20 +16,10 @@ fn Demo() -> impl IntoView { document().body().unwrap().append_child(&div).unwrap(); view! { -
- See scroll values in the lower right corner of the screen. -
+
See scroll values in the lower right corner of the screen.
- - Scroll value - -
- x: - {move || format!("{:.1}", x())} -
- y: - {move || format!("{:.1}", y())} -
+ Scroll value +
x: {move || format!("{:.1}", x())}
y: {move || format!("{:.1}", y())}
} } diff --git a/src/core/direction.rs b/src/core/direction.rs new file mode 100644 index 0000000..a6d1b23 --- /dev/null +++ b/src/core/direction.rs @@ -0,0 +1,41 @@ +/// Direction enum +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +pub enum Direction { + Top, + Bottom, + Left, + Right, +} + +#[derive(Copy, Clone, Default, Debug)] +/// Directions flags +pub struct Directions { + pub left: bool, + pub right: bool, + pub top: bool, + pub bottom: bool, +} + +impl Directions { + /// Returns the value of the provided direction + pub fn get_direction(&self, direction: Direction) -> bool { + match direction { + Direction::Top => self.top, + Direction::Bottom => self.bottom, + Direction::Left => self.left, + Direction::Right => self.right, + } + } + + /// Sets the value of the provided direction + pub fn set_direction(mut self, direction: Direction, value: bool) -> Self { + match direction { + Direction::Top => self.top = value, + Direction::Bottom => self.bottom = value, + Direction::Left => self.left = value, + Direction::Right => self.right = value, + } + + self + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index ea1f1b7..25d7d04 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -1,4 +1,5 @@ mod connection_ready_state; +mod direction; mod element_maybe_signal; mod elements_maybe_signal; mod maybe_rw_signal; @@ -9,6 +10,7 @@ mod ssr_safe_method; mod storage; pub use connection_ready_state::*; +pub use direction::*; pub use element_maybe_signal::*; pub use elements_maybe_signal::*; pub use maybe_rw_signal::*; diff --git a/src/lib.rs b/src/lib.rs index c3384c8..aaea588 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -43,6 +43,7 @@ mod use_event_listener; mod use_favicon; mod use_geolocation; mod use_idle; +mod use_infinite_scroll; mod use_intersection_observer; mod use_interval; mod use_interval_fn; @@ -92,6 +93,7 @@ pub use use_event_listener::*; pub use use_favicon::*; pub use use_geolocation::*; pub use use_idle::*; +pub use use_infinite_scroll::*; pub use use_intersection_observer::*; pub use use_interval::*; pub use use_interval_fn::*; diff --git a/src/use_infinite_scroll.rs b/src/use_infinite_scroll.rs new file mode 100644 index 0000000..8153c4f --- /dev/null +++ b/src/use_infinite_scroll.rs @@ -0,0 +1,250 @@ +use crate::core::{Direction, Directions, ElementMaybeSignal}; +use crate::{ + use_element_visibility, use_scroll_with_options, ScrollOffset, UseEventListenerOptions, + UseScrollOptions, UseScrollReturn, +}; +use default_struct_builder::DefaultBuilder; +use futures_util::join; +use gloo_timers::future::sleep; +use leptos::*; +use std::future::Future; +use std::rc::Rc; +use std::time::Duration; +use wasm_bindgen::JsCast; + +/// Infinite scrolling of the element. +/// +/// ## Demo +/// +/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_infinite_scroll) +/// +/// ## Usage +/// +/// ``` +/// # use leptos::*; +/// use leptos::html::Div; +/// # use leptos_use::{use_infinite_scroll_with_options, UseInfiniteScrollOptions}; +/// # +/// # #[component] +/// # fn Demo() -> impl IntoView { +/// let el = create_node_ref::
(); +/// +/// let (data, set_data) = create_signal(vec![1, 2, 3, 4, 5, 6]); +/// +/// let _ = use_infinite_scroll_with_options( +/// el, +/// move |_| async move { +/// let len = data.with(|d| d.len()); +/// set_data.update(|data| *data = (1..len+6).collect()); +/// }, +/// UseInfiniteScrollOptions::default().distance(10.0), +/// ); +/// +/// view! { +///
+/// { item } +///
+/// } +/// # } +/// ``` +/// +/// The returned signal is `true` while new data is being loaded. +pub fn use_infinite_scroll(el: El, on_load_more: LFn) -> Signal +where + El: Into> + Clone + 'static, + T: Into + Clone + 'static, + LFn: Fn(ScrollState) -> LFut + 'static, + LFut: Future, +{ + use_infinite_scroll_with_options(el, on_load_more, UseInfiniteScrollOptions::default()) +} + +/// Version of [`use_infinite_scroll`] that takes a `UseInfiniteScrollOptions`. See [`use_infinite_scroll`] for how to use. +pub fn use_infinite_scroll_with_options( + el: El, + on_load_more: LFn, + options: UseInfiniteScrollOptions, +) -> Signal +where + El: Into> + Clone + 'static, + T: Into + Clone + 'static, + LFn: Fn(ScrollState) -> LFut + 'static, + LFut: Future, +{ + let UseInfiniteScrollOptions { + distance, + direction, + interval, + on_scroll, + event_listener_options, + } = options; + + let on_load_more = store_value(on_load_more); + + let UseScrollReturn { + x, + y, + is_scrolling, + arrived_state, + directions, + measure, + .. + } = use_scroll_with_options( + el.clone(), + UseScrollOptions::default() + .on_scroll(move |evt| on_scroll(evt)) + .event_listener_options(event_listener_options) + .offset(ScrollOffset::default().set_direction(direction, distance)), + ); + + let state = ScrollState { + x, + y, + is_scrolling, + arrived_state, + directions, + }; + + let (is_loading, set_loading) = create_signal(false); + + let el = el.into(); + let observed_element = create_memo(move |_| { + let el = el.get(); + + el.map(|el| { + let el = el.into(); + + if el.is_instance_of::() || el.is_instance_of::() { + document() + .document_element() + .expect("document element not found") + } else { + el + } + }) + }); + + let is_element_visible = use_element_visibility(observed_element); + + let check_and_load = store_value(None::>); + + check_and_load.set_value(Some(Rc::new({ + let measure = measure.clone(); + + move || { + let observed_element = observed_element.get_untracked(); + + if !is_element_visible.get_untracked() { + return; + } + + if let Some(observed_element) = observed_element { + let scroll_height = observed_element.scroll_height(); + let client_height = observed_element.client_height(); + let scroll_width = observed_element.scroll_width(); + let client_width = observed_element.client_width(); + + let is_narrower = if direction == Direction::Bottom || direction == Direction::Top { + scroll_height <= client_height + } else { + scroll_width <= client_width + }; + + if state.arrived_state.get_untracked().get_direction(direction) || is_narrower { + if !is_loading.get_untracked() { + set_loading.set(true); + + let state = state.clone(); + let measure = measure.clone(); + spawn_local(async move { + join!( + on_load_more.with_value(|f| f(state)), + sleep(Duration::from_millis(interval as u64)) + ); + + set_loading.set(false); + sleep(Duration::ZERO).await; + measure(); + if let Some(check_and_load) = check_and_load.get_value() { + check_and_load(); + } + }); + } + } + } + } + }))); + + let _ = watch( + move || is_element_visible.get(), + move |visible, prev_visible, _| { + if *visible && !prev_visible.map(|v| *v).unwrap_or_default() { + measure(); + } + }, + true, + ); + + let _ = watch( + move || state.arrived_state.get().get_direction(direction), + move |_, _, _| { + check_and_load + .get_value() + .expect("check_and_load is set above")() + }, + true, + ); + + is_loading.into() +} + +/// Options for [`use_infinite_scroll_with_options`]. +#[derive(DefaultBuilder)] +pub struct UseInfiniteScrollOptions { + /// Callback when scrolling is happening. + on_scroll: Rc, + + /// Options passed to the `addEventListener("scroll", ...)` call + event_listener_options: UseEventListenerOptions, + + /// The minimum distance between the bottom of the element and the bottom of the viewport. Default is 0.0. + distance: f64, + + /// The direction in which to listen the scroll. Defaults to `Direction::Bottom`. + direction: Direction, + + /// The interval time between two load more (to avoid too many invokes). Default is 100.0. + interval: f64, +} + +impl Default for UseInfiniteScrollOptions { + fn default() -> Self { + Self { + on_scroll: Rc::new(|_| {}), + event_listener_options: Default::default(), + distance: 0.0, + direction: Direction::Bottom, + interval: 100.0, + } + } +} + +/// The scroll state being passed into the `on_load_more` callback of [`use_infinite_scroll`]. +#[derive(Copy, Clone)] +pub struct ScrollState { + /// X coordinate of scroll position + pub x: Signal, + + /// Y coordinate of scroll position + pub y: Signal, + + /// Is true while the element is being scrolled. + pub is_scrolling: Signal, + + /// Sets the field that represents a direction to true if the + /// element is scrolled all the way to that side. + pub arrived_state: Signal, + + /// The directions in which the element is being scrolled are set to true. + pub directions: Signal, +} diff --git a/src/use_scroll.rs b/src/use_scroll.rs index 94c2c12..d25467b 100644 --- a/src/use_scroll.rs +++ b/src/use_scroll.rs @@ -1,4 +1,4 @@ -use crate::core::ElementMaybeSignal; +use crate::core::{Direction, Directions, ElementMaybeSignal}; use crate::UseEventListenerOptions; use cfg_if::cfg_if; use default_struct_builder::DefaultBuilder; @@ -174,7 +174,9 @@ const ARRIVED_STATE_THRESHOLD_PIXELS: f64 = 1.0; /// ## Server-Side Rendering /// /// On the server this returns signals that don't change and setters that are noops. -pub fn use_scroll(element: El) -> UseScrollReturn +pub fn use_scroll( + element: El, +) -> UseScrollReturn where El: Clone, El: Into>, @@ -185,7 +187,10 @@ where /// Version of [`use_scroll`] with options. See [`use_scroll`] for how to use. #[cfg_attr(feature = "ssr", allow(unused_variables))] -pub fn use_scroll_with_options(element: El, options: UseScrollOptions) -> UseScrollReturn +pub fn use_scroll_with_options( + element: El, + options: UseScrollOptions, +) -> UseScrollReturn where El: Clone, El: Into>, @@ -210,9 +215,9 @@ where }); cfg_if! { if #[cfg(feature = "ssr")] { - let set_x = Box::new(|_| {}); - let set_y = Box::new(|_| {}); - let measure = Box::new(|| {}); + let set_x = |_| {}; + let set_y = |_| {}; + let measure = || {}; } else { let signal = element.into(); let behavior = options.behavior; @@ -243,10 +248,10 @@ where let set_x = { let scroll_to = scroll_to.clone(); - Box::new(move |x| scroll_to(Some(x), None)) + move |x| scroll_to(Some(x), None) }; - let set_y = Box::new(move |y| scroll_to(None, Some(y))); + let set_y = move |y| scroll_to(None, Some(y)); let on_scroll_end = { let on_stop = Rc::clone(&options.on_stop); @@ -417,13 +422,12 @@ where options.event_listener_options, ); - let measure = Box::new(move || { - let el = signal.get_untracked(); - if let Some(el) = el { + let measure = move || { + if let Some(el) = signal.get_untracked() { let el = el.into(); set_arrived_state(el); } - }); + }; }} UseScrollReturn { @@ -501,26 +505,39 @@ impl From for web_sys::ScrollBehavior { } /// The return value of [`use_scroll`]. -pub struct UseScrollReturn { +pub struct UseScrollReturn +where + SetXFn: Fn(f64) + Clone, + SetYFn: Fn(f64) + Clone, + MFn: Fn() + Clone, +{ + /// X coordinate of scroll position pub x: Signal, - pub set_x: Box, + + /// Sets the value of `x`. This does also scroll the element. + pub set_x: SetXFn, + + /// Y coordinate of scroll position pub y: Signal, - pub set_y: Box, + + /// Sets the value of `y`. This does also scroll the element. + pub set_y: SetYFn, + + /// Is true while the element is being scrolled. pub is_scrolling: Signal, + + /// Sets the field that represents a direction to true if the + /// element is scrolled all the way to that side. pub arrived_state: Signal, + + /// The directions in which the element is being scrolled are set to true. pub directions: Signal, - pub measure: Box, + + /// Re-evaluates the `arrived_state`. + pub measure: MFn, } -#[derive(Copy, Clone)] -pub struct Directions { - pub left: bool, - pub right: bool, - pub top: bool, - pub bottom: bool, -} - -#[derive(Default, Copy, Clone)] +#[derive(Default, Copy, Clone, Debug)] /// Threshold in pixels when we consider a side to have arrived (`UseScrollReturn::arrived_state`). pub struct ScrollOffset { pub left: f64, @@ -528,3 +545,17 @@ pub struct ScrollOffset { pub right: f64, pub bottom: f64, } + +impl ScrollOffset { + /// Sets the value of the provided direction + pub fn set_direction(mut self, direction: Direction, value: f64) -> Self { + match direction { + Direction::Top => self.top = value, + Direction::Bottom => self.bottom = value, + Direction::Left => self.left = value, + Direction::Right => self.right = value, + } + + self + } +}