Adrien Denat commited on
Commit
df5aa22
1 Parent(s): 69830ae

use Svelte $navigating state to update button visibility on navigation (#145)

Browse files

* use Svelte $navigating state to update button visibility on navigation

* use ResizeObserver to detect changes instead of props

* remove useless intermediate function

* properly handle scrollNode prop changes

src/lib/components/ScrollToBottomBtn.svelte CHANGED
@@ -1,27 +1,39 @@
1
  <script lang="ts">
2
  import { fade } from "svelte/transition";
3
- import IconChevron from "./icons/IconChevron.svelte";
4
  import { onDestroy } from "svelte";
 
5
 
6
  export let scrollNode: HTMLElement;
7
  export { className as class };
8
 
9
  let visible: boolean = false;
10
  let className = "";
 
11
 
12
  $: if (scrollNode) {
13
- scrollNode.addEventListener("scroll", onScroll);
 
 
 
 
 
 
 
 
14
  }
15
 
16
- function onScroll() {
 
17
  visible =
18
  Math.ceil(scrollNode.scrollTop) + 200 < scrollNode.scrollHeight - scrollNode.clientHeight;
19
  }
20
 
21
- onDestroy(() => {
22
- if (!scrollNode) return;
23
- scrollNode.removeEventListener("scroll", onScroll);
24
- });
 
 
25
  </script>
26
 
27
  {#if visible}
 
1
  <script lang="ts">
2
  import { fade } from "svelte/transition";
 
3
  import { onDestroy } from "svelte";
4
+ import IconChevron from "./icons/IconChevron.svelte";
5
 
6
  export let scrollNode: HTMLElement;
7
  export { className as class };
8
 
9
  let visible: boolean = false;
10
  let className = "";
11
+ let observer: ResizeObserver | null = null;
12
 
13
  $: if (scrollNode) {
14
+ destroy();
15
+
16
+ if (window.ResizeObserver) {
17
+ observer = new ResizeObserver(() => {
18
+ updateVisibility();
19
+ });
20
+ observer.observe(scrollNode);
21
+ }
22
+ scrollNode.addEventListener("scroll", updateVisibility);
23
  }
24
 
25
+ function updateVisibility() {
26
+ if (!scrollNode) return;
27
  visible =
28
  Math.ceil(scrollNode.scrollTop) + 200 < scrollNode.scrollHeight - scrollNode.clientHeight;
29
  }
30
 
31
+ function destroy() {
32
+ observer?.disconnect();
33
+ scrollNode?.removeEventListener("scroll", updateVisibility);
34
+ }
35
+
36
+ onDestroy(destroy);
37
  </script>
38
 
39
  {#if visible}