mirror of
https://github.com/adoyle0/leptos-use.git
synced 2025-01-23 00:59:22 -05:00
added use_infinite_scroll
This commit is contained in:
parent
f3af2ad9ea
commit
b8421f2186
31 changed files with 920 additions and 212 deletions
14
CHANGELOG.md
14
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<dyn Fn(T)>`.
|
||||
|
||||
### Other Changes 🔥
|
||||
|
||||
- `UseScrollReturn` is now documented
|
||||
|
||||
## [0.7.2] - 2023-10-21
|
||||
|
||||
### Fixes 🍕
|
||||
|
|
112
Cargo.toml
112
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]
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
3
docs/book/src/sensors/use_infinite_scroll.md
Normal file
3
docs/book/src/sensors/use_infinite_scroll.md
Normal file
|
@ -0,0 +1,3 @@
|
|||
# use_infinite_scroll
|
||||
|
||||
<!-- cmdrun python3 ../extract_doc_comment.py use_infinite_scroll -->
|
|
@ -24,6 +24,7 @@ members = [
|
|||
"use_floor",
|
||||
"use_geolocation",
|
||||
"use_idle",
|
||||
"use_infinite_scroll",
|
||||
"use_intersection_observer",
|
||||
"use_interval",
|
||||
"use_interval_fn",
|
||||
|
|
|
@ -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..."
|
||||
/>
|
||||
<Note>
|
||||
Delay is set to 1000ms for this demo.
|
||||
</Note>
|
||||
<p>
|
||||
Input signal:
|
||||
{input}
|
||||
</p>
|
||||
<p>
|
||||
Debounced signal:
|
||||
{debounced}
|
||||
</p>
|
||||
<Note>Delay is set to 1000ms for this demo.</Note>
|
||||
<p>Input signal: {input}</p>
|
||||
<p>Debounced signal: {debounced}</p>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
|
|
@ -15,17 +15,9 @@ fn Demo() -> impl IntoView {
|
|||
on:input=move |event| set_input(event_target_value(&event))
|
||||
placeholder="Try to type quickly..."
|
||||
/>
|
||||
<Note>
|
||||
Delay is set to 1000ms for this demo.
|
||||
</Note>
|
||||
<p>
|
||||
Input signal:
|
||||
{input}
|
||||
</p>
|
||||
<p>
|
||||
Throttled signal:
|
||||
{throttled}
|
||||
</p>
|
||||
<Note>Delay is set to 1000ms for this demo.</Note>
|
||||
<p>Input signal: {input}</p>
|
||||
<p>Throttled signal: {throttled}</p>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
|
|
@ -64,24 +64,10 @@ fn HomePage() -> impl IntoView {
|
|||
debounced_fn();
|
||||
|
||||
view! {
|
||||
<h1>
|
||||
Leptos-Use SSR Example
|
||||
</h1>
|
||||
<button on:click=on_click>
|
||||
Click Me:
|
||||
{count}
|
||||
</button>
|
||||
<p>
|
||||
Locale zh-Hans-CN-u-nu-hanidec:
|
||||
{zh_count}
|
||||
</p>
|
||||
<p>
|
||||
Press any key:
|
||||
{key}
|
||||
</p>
|
||||
<p>
|
||||
Debounced called:
|
||||
{debounce_value}
|
||||
</p>
|
||||
<h1>Leptos-Use SSR Example</h1>
|
||||
<button on:click=on_click>Click Me: {count}</button>
|
||||
<p>Locale zh-Hans-CN-u-nu-hanidec: {zh_count}</p>
|
||||
<p>Press any key: {key}</p>
|
||||
<p>Debounced called: {debounce_value}</p>
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,11 +19,7 @@ fn Demo() -> impl IntoView {
|
|||
<Note class="mb-3">"Select the inputs below to see the changes"</Note>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-2">
|
||||
<For
|
||||
each=move || (1..7)
|
||||
key=|i| *i
|
||||
let:i
|
||||
>
|
||||
<For each=move || (1..7) key=|i| *i let:i>
|
||||
<input type="text" data-id=i class="!my-0 !min-w-0" placeholder=i/>
|
||||
</For>
|
||||
|
||||
|
|
|
@ -24,20 +24,14 @@ fn Demo() -> impl IntoView {
|
|||
);
|
||||
|
||||
view! {
|
||||
<p class="italic op50 text-center">
|
||||
Check the floating box
|
||||
</p>
|
||||
<p class="italic op50 text-center">Check the floating box</p>
|
||||
<div
|
||||
node_ref=el
|
||||
class="px-4 py-2 border border-gray-400/30 rounded shadow hover:shadow-lg fixed bg-[--bg] select-none cursor-move z-24"
|
||||
style=move || format!("touch-action: none; {}", style())
|
||||
>
|
||||
"👋 Drag me!"
|
||||
<div class="text-sm opacity-50">
|
||||
I am
|
||||
{move || x().round()},
|
||||
{move || y().round()}
|
||||
</div>
|
||||
<div class="text-sm opacity-50">I am {move || x().round()} , {move || y().round()}</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
|
|
@ -22,45 +22,21 @@ fn Demo() -> impl IntoView {
|
|||
view! {
|
||||
<div class="flex">
|
||||
<div class="w-full h-auto relative">
|
||||
<p>
|
||||
Drop files into dropZone
|
||||
</p>
|
||||
<p>Drop files into dropZone</p>
|
||||
<img width="64" src="use_drop_zone/demo/img/leptos-use-logo.svg" alt="Drop me"/>
|
||||
<div
|
||||
node_ref=drop_zone_el
|
||||
class="flex flex-col w-full min-h-[200px] h-auto bg-gray-400/10 justify-center items-center pt-6"
|
||||
>
|
||||
<div>
|
||||
is_over_drop_zone:
|
||||
<BooleanDisplay value=is_over_drop_zone/>
|
||||
</div>
|
||||
<div>
|
||||
dropped:
|
||||
<BooleanDisplay value=dropped/>
|
||||
</div>
|
||||
<div>is_over_drop_zone: <BooleanDisplay value=is_over_drop_zone/></div>
|
||||
<div>dropped: <BooleanDisplay value=dropped/></div>
|
||||
<div class="flex flex-wrap justify-center items-center">
|
||||
<For
|
||||
each=files
|
||||
key=|f| f.name()
|
||||
let:file
|
||||
>
|
||||
<For each=files key=|f| f.name() let:file>
|
||||
<div class="w-200px bg-black-200/10 ma-2 pa-6">
|
||||
<p>
|
||||
Name:
|
||||
{file.name()}
|
||||
</p>
|
||||
<p>
|
||||
Size:
|
||||
{file.size()}
|
||||
</p>
|
||||
<p>
|
||||
Type:
|
||||
{file.type_()}
|
||||
</p>
|
||||
<p>
|
||||
Last modified:
|
||||
{file.last_modified()}
|
||||
</p>
|
||||
<p>Name: {file.name()}</p>
|
||||
<p>Size: {file.size()}</p>
|
||||
<p>Type: {file.type_()}</p>
|
||||
<p>Last modified: {file.last_modified()}</p>
|
||||
</div>
|
||||
</For>
|
||||
</div>
|
||||
|
|
|
@ -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() }} ,
|
||||
</pre>
|
||||
<button on:click=move |_| pause()>"Pause watch"</button>
|
||||
<button on:click=move |_| resume()>"Resume watch"</button>
|
||||
|
|
|
@ -14,20 +14,11 @@ fn Demo() -> impl IntoView {
|
|||
|
||||
view! {
|
||||
<Note class="mb-2">
|
||||
For demonstration purpose, the idle timeout is set to
|
||||
<b>
|
||||
5s
|
||||
</b>
|
||||
For demonstration purpose, the idle timeout is set to <b>5s</b>
|
||||
in this demo (default 1min).
|
||||
</Note>
|
||||
<div class="mb-2">
|
||||
Idle:
|
||||
<BooleanDisplay value=idle/>
|
||||
</div>
|
||||
<div>
|
||||
Inactive:
|
||||
<b>{idled_for} s</b>
|
||||
</div>
|
||||
<div class="mb-2">Idle: <BooleanDisplay value=idle/></div>
|
||||
<div>Inactive: <b>{idled_for} s</b></div>
|
||||
}
|
||||
}
|
||||
|
||||
|
|
16
examples/use_infinite_scroll/Cargo.toml
Normal file
16
examples/use_infinite_scroll/Cargo.toml
Normal file
|
@ -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"
|
23
examples/use_infinite_scroll/README.md
Normal file
23
examples/use_infinite_scroll/README.md
Normal file
|
@ -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
|
||||
```
|
2
examples/use_infinite_scroll/Trunk.toml
Normal file
2
examples/use_infinite_scroll/Trunk.toml
Normal file
|
@ -0,0 +1,2 @@
|
|||
[build]
|
||||
public_url = "/demo/"
|
7
examples/use_infinite_scroll/index.html
Normal file
7
examples/use_infinite_scroll/index.html
Normal file
|
@ -0,0 +1,7 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link data-trunk rel="css" href="style/output.css">
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
3
examples/use_infinite_scroll/input.css
Normal file
3
examples/use_infinite_scroll/input.css
Normal file
|
@ -0,0 +1,3 @@
|
|||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
2
examples/use_infinite_scroll/rust-toolchain.toml
Normal file
2
examples/use_infinite_scroll/rust-toolchain.toml
Normal file
|
@ -0,0 +1,2 @@
|
|||
[toolchain]
|
||||
channel = "nightly"
|
40
examples/use_infinite_scroll/src/main.rs
Normal file
40
examples/use_infinite_scroll/src/main.rs
Normal file
|
@ -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::<Div>();
|
||||
|
||||
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! {
|
||||
<div
|
||||
node_ref=el
|
||||
class="flex flex-col gap-2 p-4 w-[300px] h-[300px] m-auto overflow-y-scroll bg-gray-500/5 rounded"
|
||||
>
|
||||
<For each=move || data.get() key=|i| *i let:item>
|
||||
<div class="h-15 bg-gray-500/5 rounded p-3">{item}</div>
|
||||
</For>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
mount_to(demo_or_body(), || {
|
||||
view! { <Demo/> }
|
||||
})
|
||||
}
|
338
examples/use_infinite_scroll/style/output.css
Normal file
338
examples/use_infinite_scroll/style/output.css
Normal file
|
@ -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));
|
||||
}
|
||||
}
|
15
examples/use_infinite_scroll/tailwind.config.js
Normal file
15
examples/use_infinite_scroll/tailwind.config.js
Normal file
|
@ -0,0 +1,15 @@
|
|||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: {
|
||||
files: ["*.html", "./src/**/*.rs", "../../src/docs/**/*.rs"],
|
||||
},
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
corePlugins: {
|
||||
preflight: false,
|
||||
},
|
||||
plugins: [
|
||||
require('@tailwindcss/forms'),
|
||||
],
|
||||
}
|
|
@ -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(),
|
||||
)
|
||||
}}
|
||||
|
||||
|
|
|
@ -15,10 +15,7 @@ fn Demo() -> impl IntoView {
|
|||
});
|
||||
|
||||
view! {
|
||||
<div>
|
||||
Count:
|
||||
{count}
|
||||
</div>
|
||||
<div>Count: {count}</div>
|
||||
<button on:click=move |_| pause() disabled=move || !is_active()>
|
||||
Pause
|
||||
</button>
|
||||
|
|
|
@ -6,12 +6,7 @@ use leptos_use::use_timestamp;
|
|||
fn Demo() -> impl IntoView {
|
||||
let timestamp = use_timestamp();
|
||||
|
||||
view! {
|
||||
<div>
|
||||
Timestamp:
|
||||
{timestamp}
|
||||
</div>
|
||||
}
|
||||
view! { <div>Timestamp: {timestamp}</div> }
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
|
|
@ -16,20 +16,10 @@ fn Demo() -> impl IntoView {
|
|||
document().body().unwrap().append_child(&div).unwrap();
|
||||
|
||||
view! {
|
||||
<div>
|
||||
See scroll values in the lower right corner of the screen.
|
||||
</div>
|
||||
<div>See scroll values in the lower right corner of the screen.</div>
|
||||
<div class="float m-5 area shadow-lg">
|
||||
<Note class="mb-2">
|
||||
Scroll value
|
||||
</Note>
|
||||
<div>
|
||||
x:
|
||||
{move || format!("{:.1}", x())}
|
||||
<br/>
|
||||
y:
|
||||
{move || format!("{:.1}", y())}
|
||||
</div>
|
||||
<Note class="mb-2">Scroll value</Note>
|
||||
<div>x: {move || format!("{:.1}", x())} <br/> y: {move || format!("{:.1}", y())}</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
|
41
src/core/direction.rs
Normal file
41
src/core/direction.rs
Normal file
|
@ -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
|
||||
}
|
||||
}
|
|
@ -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::*;
|
||||
|
|
|
@ -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::*;
|
||||
|
|
250
src/use_infinite_scroll.rs
Normal file
250
src/use_infinite_scroll.rs
Normal file
|
@ -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::<Div>();
|
||||
///
|
||||
/// 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! {
|
||||
/// <div node_ref=el>
|
||||
/// <For each=move || data.get() key=|i| *i let:item>{ item }</For>
|
||||
/// </div>
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// The returned signal is `true` while new data is being loaded.
|
||||
pub fn use_infinite_scroll<El, T, LFn, LFut>(el: El, on_load_more: LFn) -> Signal<bool>
|
||||
where
|
||||
El: Into<ElementMaybeSignal<T, web_sys::Element>> + Clone + 'static,
|
||||
T: Into<web_sys::Element> + Clone + 'static,
|
||||
LFn: Fn(ScrollState) -> LFut + 'static,
|
||||
LFut: Future<Output = ()>,
|
||||
{
|
||||
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, T, LFn, LFut>(
|
||||
el: El,
|
||||
on_load_more: LFn,
|
||||
options: UseInfiniteScrollOptions,
|
||||
) -> Signal<bool>
|
||||
where
|
||||
El: Into<ElementMaybeSignal<T, web_sys::Element>> + Clone + 'static,
|
||||
T: Into<web_sys::Element> + Clone + 'static,
|
||||
LFn: Fn(ScrollState) -> LFut + 'static,
|
||||
LFut: Future<Output = ()>,
|
||||
{
|
||||
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::<web_sys::Window>() || el.is_instance_of::<web_sys::Document>() {
|
||||
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::<Rc<dyn Fn()>>);
|
||||
|
||||
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<dyn Fn(web_sys::Event)>,
|
||||
|
||||
/// 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<f64>,
|
||||
|
||||
/// Y coordinate of scroll position
|
||||
pub y: Signal<f64>,
|
||||
|
||||
/// Is true while the element is being scrolled.
|
||||
pub is_scrolling: Signal<bool>,
|
||||
|
||||
/// Sets the field that represents a direction to true if the
|
||||
/// element is scrolled all the way to that side.
|
||||
pub arrived_state: Signal<Directions>,
|
||||
|
||||
/// The directions in which the element is being scrolled are set to true.
|
||||
pub directions: Signal<Directions>,
|
||||
}
|
|
@ -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<El, T>(element: El) -> UseScrollReturn
|
||||
pub fn use_scroll<El, T>(
|
||||
element: El,
|
||||
) -> UseScrollReturn<impl Fn(f64) + Clone, impl Fn(f64) + Clone, impl Fn() + Clone>
|
||||
where
|
||||
El: Clone,
|
||||
El: Into<ElementMaybeSignal<T, web_sys::Element>>,
|
||||
|
@ -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<El, T>(element: El, options: UseScrollOptions) -> UseScrollReturn
|
||||
pub fn use_scroll_with_options<El, T>(
|
||||
element: El,
|
||||
options: UseScrollOptions,
|
||||
) -> UseScrollReturn<impl Fn(f64) + Clone, impl Fn(f64) + Clone, impl Fn() + Clone>
|
||||
where
|
||||
El: Clone,
|
||||
El: Into<ElementMaybeSignal<T, web_sys::Element>>,
|
||||
|
@ -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<ScrollBehavior> for web_sys::ScrollBehavior {
|
|||
}
|
||||
|
||||
/// The return value of [`use_scroll`].
|
||||
pub struct UseScrollReturn {
|
||||
pub struct UseScrollReturn<SetXFn, SetYFn, MFn>
|
||||
where
|
||||
SetXFn: Fn(f64) + Clone,
|
||||
SetYFn: Fn(f64) + Clone,
|
||||
MFn: Fn() + Clone,
|
||||
{
|
||||
/// X coordinate of scroll position
|
||||
pub x: Signal<f64>,
|
||||
pub set_x: Box<dyn Fn(f64)>,
|
||||
|
||||
/// Sets the value of `x`. This does also scroll the element.
|
||||
pub set_x: SetXFn,
|
||||
|
||||
/// Y coordinate of scroll position
|
||||
pub y: Signal<f64>,
|
||||
pub set_y: Box<dyn Fn(f64)>,
|
||||
|
||||
/// 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<bool>,
|
||||
|
||||
/// Sets the field that represents a direction to true if the
|
||||
/// element is scrolled all the way to that side.
|
||||
pub arrived_state: Signal<Directions>,
|
||||
|
||||
/// The directions in which the element is being scrolled are set to true.
|
||||
pub directions: Signal<Directions>,
|
||||
pub measure: Box<dyn Fn()>,
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue