-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
101 lines (88 loc) · 2.51 KB
/
index.js
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
89
90
91
92
93
94
95
96
97
98
99
100
101
import React, { useState, useCallback, useEffect } from 'react'
import ReactDOM from 'react-dom'
import BrowerBtn from './components/BrowseBtn'
import Gallery from './components/Gallery'
import useFetchImage from './components/hooks/fetchImageHook'
const fixBody = () => {
const scrollTop =
document.body.scrollTop || document.documentElement.scrollTop
document.body.style.cssText += 'position:fixed;top:-' + scrollTop + 'px;'
}
const looseBody = () => {
const body = document.body
body.style.position = ''
const top = body.style.top
document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top)
body.style.top = ''
}
const renderReactApp = canonicalUrl => {
if (
!!canonicalUrl &&
canonicalUrl.match(/\/(\d*$)/) &&
!document.getElementById('dcard-images-root')
) {
document.querySelector('article h1').innerHTML +=
'<span id="dcard-images-root"></span>'
ReactDOM.render(<App />, document.getElementById('dcard-images-root'))
}
}
const App = () => {
const [isOpen, setIsOpen] = useState(false)
const [isFetching, setIsFetching] = useState(false)
const [isFetchError, setIsFetchError] = useState(false)
const { fetchImagesByPostID, images } = useFetchImage()
useEffect(() => {
if (isOpen && !images.length && !isFetching) {
fetchImages()
}
}, [isOpen, images, fetchImages])
useEffect(() => {
if (isOpen && isFetchError) {
handleClose()
}
}, [isOpen, isFetchError, handleClose])
const fetchImages = useCallback(() => {
const postID = document
.querySelector('link[rel=canonical]')
.href.match(/(\d*$)/)[0]
setIsFetching(true)
setIsFetchError(false)
fetchImagesByPostID(postID)
.then(() => {
setIsFetching(false)
})
.catch(() => {
setIsFetchError(true)
})
setIsOpen(true)
fixBody()
}, [fetchImagesByPostID])
const handleOpen = useCallback(() => {
setIsOpen(true)
fixBody()
}, [])
const handleClose = useCallback(() => {
looseBody()
setIsOpen(false)
}, [])
return (
<React.Fragment>
<BrowerBtn onClick={handleOpen} />
<Gallery
isOpen={isOpen}
images={images}
isFetching={isFetching}
onClose={handleClose}
/>
</React.Fragment>
)
}
let canonicalUrl = ''
setInterval(() => {
const canonical = document.querySelector('link[rel=canonical]')
const url = canonical && canonical.href
if (url && url !== canonicalUrl) {
canonicalUrl = url
renderReactApp(canonicalUrl)
}
}, 500)