blob: 8baedf16385b7dc3cc0447e6206a2ccab6a9fe45 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
import { html, Component } from "../lib/index.js";
let store = new Map();
export default class ScrollManager extends Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
}
isAtBottom() {
let target = this.props.target.current;
return Math.abs(target.scrollHeight - target.clientHeight - target.scrollTop) <= 10;
}
saveScrollPosition(scrollKey) {
let target = this.props.target.current;
let sticky = target.querySelectorAll(this.props.stickTo);
let stickToKey = null;
if (!this.isAtBottom()) {
for (let i = 0; i < sticky.length; i++) {
let el = sticky[i];
if (el.offsetTop >= target.scrollTop + target.offsetTop) {
stickToKey = el.dataset.key;
break;
}
}
}
store.set(scrollKey, stickToKey);
}
restoreScrollPosition() {
let target = this.props.target.current;
if (!target.firstChild) {
return;
}
let stickToKey = store.get(this.props.scrollKey);
if (!stickToKey) {
target.firstChild.scrollIntoView({ block: "end" });
} else {
let stickTo = target.querySelector("[data-key=\"" + stickToKey + "\"]");
if (stickTo) {
stickTo.scrollIntoView();
}
}
if (target.scrollTop == 0) {
this.props.onScrollTop();
}
}
handleScroll() {
if (this.props.target.current.scrollTop == 0) {
this.props.onScrollTop();
}
}
componentDidMount() {
this.restoreScrollPosition();
this.props.target.current.addEventListener("scroll", this.handleScroll);
}
getSnapshotBeforeUpdate(prevProps) {
if (this.props.scrollKey !== prevProps.scrollKey || this.props.children !== prevProps.children) {
this.saveScrollPosition(prevProps.scrollKey);
}
}
componentDidUpdate(prevProps) {
if (!this.props.target.current) {
return;
}
this.restoreScrollPosition();
}
componentWillUnmount() {
this.props.target.current.removeEventListener("scroll", this.handleScroll);
this.saveScrollPosition(this.props.scrollKey);
}
render() {
return this.props.children;
}
}
|