-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebViewScreen.js
More file actions
272 lines (250 loc) · 9.34 KB
/
WebViewScreen.js
File metadata and controls
272 lines (250 loc) · 9.34 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import { useContext, useState, useRef, useEffect, memo, useMemo } from "react"
import { TouchableWithoutFeedback, Keyboard, View, StyleSheet, BackHandler, Platform, useWindowDimensions } from "react-native"
import Constants from 'expo-constants'
import SearchBar from "./SearchBar"
import BottomPanel from "./components/BottomPanel"
import WebView from "react-native-webview"
import { MainContext } from "./MainContext"
import Animated, {
useSharedValue,
withTiming,
withDelay,
useAnimatedStyle,
Easing,
} from "react-native-reanimated"
import { Feather } from "@expo/vector-icons"
const SERP_API_KEY = "116884dbb870ccefa61e93febe4a5e76343adc5a8e73d38caff77fdced70e0bd"
export default memo(function WebViewScreen({ idx }) {
const {
isDark,
tabs,
setTabs,
setTabsVisible,
bookMarks,
setBookMarks,
pinnedWebsites,
setPinnedWebsites,
setSheetArr,
setShowBottomSheet,
setShowSearchBar
} = useContext(MainContext)
const [url, setUrl] = useState(tabs[idx].tabUrl)
const [title, setTitle] = useState("")
const [webViewProps, setWebViewProps] = useState({
canGoBack: false,
canGoForward: false,
loading: true,
})
const [searchQuery, setSearchQuery] = useState("")
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestions, setSuggestions] = useState([])
const {width, height} = useWindowDimensions()
const TAB_WIDTH = useMemo(() => (width - 40 - 12) / 2, [width])
const DEFAULT_TOP = useMemo(() => 100 * idx, [idx])
const DEFAULT_LEFT = useMemo(() => idx % 2 === 0 ? 20 : 20 + TAB_WIDTH + 12, [idx, TAB_WIDTH])
const oAnim = useSharedValue(0)
const xAnim = useSharedValue(DEFAULT_LEFT)
const yAnim = useSharedValue(DEFAULT_TOP)
const wAnim = useSharedValue(TAB_WIDTH)
const hAnim = useSharedValue(128)
const brAnim = useSharedValue(12)
const dropDownYAnim = useSharedValue(webViewProps.loading ? 40 : Constants.statusBarHeight + 12)
const webViewRef = useRef(null)
const jsCode = `
const selector = 'head link[rel="shortcut icon"], head link[rel="icon"], head link[rel="apple-touch-icon"]'
const imagesTypes = [".ico", ".png", ".gif", ".svg"]
let favIcon = ""
const res = [...document.querySelectorAll(selector)].map(l => {
return imagesTypes.map(t => l.href && l.href.endsWith(t) ? l.href : null)
}).flat().filter(l => l && l)
favIcon = res.length > 0 ? res[0] : ""
window.ReactNativeWebView.postMessage(favIcon)
true // note: this is required, or you'll sometimes get silent failures
`
const animStyle = useAnimatedStyle(() => {
return {
opacity: withDelay(75, withTiming(oAnim.value, { duration: 75 })),
top: withTiming(yAnim.value, { duration: 150 }),
left: withTiming(xAnim.value, { duration: 150 }),
width: withTiming(wAnim.value, { duration: 150 }),
height: withTiming(hAnim.value, { duration: 150 }),
borderRadius: withTiming(brAnim.value, { duration: 150 }),
}
})
const onGoBackPress = () => {
if (webViewRef.current && webViewProps.canGoBack) {
webViewRef.current.goBack()
return true // prevent default behavior (exit app)
}
}
const onGoForwardPress = () => {
if (webViewRef.current && webViewProps.canGoForward) {
webViewRef.current.goForward()
return true // prevent default behavior (exit app)
}
}
// oAnim.value = tabs[idx].visible ? 1 : 0
// xAnim.value = tabs[idx].visible ? 0 : DEFAULT_LEFT
// yAnim.value = tabs[idx].visible ? 0 : DEFAULT_TOP
// wAnim.value = tabs[idx].visible ? width : TAB_WIDTH
// hAnim.value = tabs[idx].visible ? height : 128
// brAnim.value = tabs[idx].visible ? 0 : 12
// dropDownYAnim.value = webViewProps.loading ? -40 : Constants.statusBarHeight
oAnim.value = useMemo(() => tabs[idx].visible ? 1 : 0, [tabs[idx].visible, ])
xAnim.value = useMemo(() => tabs[idx].visible ? 0 : DEFAULT_LEFT, [tabs[idx].visible, DEFAULT_LEFT])
yAnim.value = useMemo(() => tabs[idx].visible ? 0 : DEFAULT_TOP, [tabs[idx].visible, DEFAULT_TOP])
wAnim.value = useMemo(() => tabs[idx].visible ? width : TAB_WIDTH, [tabs[idx].visible, width, TAB_WIDTH])
hAnim.value = useMemo(() => tabs[idx].visible ? height : 128, [tabs[idx].visible, height])
brAnim.value = useMemo(() => tabs[idx].visible ? 0 : 12, [tabs[idx].visible, ])
dropDownYAnim.value = useMemo(() => webViewProps.loading ? -40 : Constants.statusBarHeight, [webViewProps.loading, Constants.statusBarHeight])
useEffect(() => {
// console.log(url, bookMarks.map((b, i) => {console.log(i === idx && b.pageUrl);return b.pageUrl}).includes(url))
tabs[idx].visible && setSheetArr([
{ label: "Toogle SearchBar",
icon: <Feather name="search" size={24} color={isDark ? "white" : "#0b0b0c"}/>,
onPress: () => {setShowSearchBar(currVal => !currVal);setShowBottomSheet(false)},
},
{ label: bookMarks.map(b => b.pageUrl).includes(url) ? "Unbookmark" : "Bookmark",
icon: <Feather name="bookmark" size={24} color={isDark ? "white" : "#0b0b0c"}/>,
onPress: () => {toggleToBookMarks();setShowBottomSheet(false)}
},
{ label: pinnedWebsites.map(p => p.pageUrl).includes(url) ? "Unpin" : "Pin",
icon: <Feather name={`${pinnedWebsites.map(p => p.pageUrl).includes(url) ? "minus" : "plus"}-circle`} size={24} color={isDark ? "white" : "#0b0b0c"}/>,
onPress: () => {toggleToPinnedWebsites();setShowBottomSheet(false)}
}
])
}, [tabs, tabs[idx].visible, bookMarks, pinnedWebsites])
function onWebViewNavigationStateChange(navState) {
setWebViewProps(currProps => ({
...currProps,
...navState
}))
}
// console.log(bookMarks[idx], url, tabs[idx].tabUrl)
function toggleToBookMarks() {
setBookMarks(currVal => {
if(bookMarks.map(b => b.pageUrl).includes(url)) {
return [...currVal.filter(bookMark => bookMark.pageUrl !== url)]
} else {
return [
{ pageTitle: webViewProps.title, pageUrl: url },
...currVal
]
}
})
}
/*function toggleToPinnedWebsites() {
setPinnedWebsites(currVal => {
if(pinnedWebsites.length < 6) {
if(pinnedWebsites.map(p => p.pageUrl).includes(url)) {
return [...currVal.filter(pinnedWebsite => pinnedWebsite.pageUrl !== url)]
} else {
return [
{ pageTitle: webViewProps.title, pageUrl: url },
...currVal
]
}
} else {
setBookMarks(currVal => ([
{ pageTitle: webViewProps.title, pageUrl: url },
...currVal
]))
console.log('Saved to bookmarks')
}
})
}*/
function onLoadStart(e) {
const { nativeEvent } = e
setUrl(nativeEvent.url)
setWebViewProps(currProps => ({
...currProps,
title: nativeEvent.title,
canGoBack: nativeEvent.canGoBack,
canGoForward: nativeEvent.canGoForward,
loading: nativeEvent.loading
}))
}
function onLoadProgress(e) {
const { nativeEvent } = e
setWebViewProps(currProps => ({
...currProps,
progress: nativeEvent.progress
}))
}
function onLoadEnd(e) {
const { nativeEvent } = e
setUrl(nativeEvent.url)
setWebViewProps(currProps => ({
...currProps,
title: nativeEvent.title,
canGoBack: nativeEvent.canGoBack,
canGoForward: nativeEvent.canGoForward,
loading: nativeEvent.loading
}))
}
function onMessage(e) {
setWebViewProps(currVal => ({
...currVal,
favIcon: e.nativeEvent.data
}))
setTabs(currVal => ([
...currVal.map((tab, tIdx) => tIdx === idx ? { ...tab, favIcon: e.nativeEvent.data } : tab)
]))
// console.log(e.nativeEvent.data, 'this one')
}
async function getSuggestions(str) {
const data = await fetch(`https://serpapi.com/search.json?engine=google_autocomplete&q=${str}&api_key=${SERP_API_KEY}`)
.then(res => res.json())
.catch(err => console.log(err))
setSuggestions(data["suggestions"].slice(10))
}
function onChangeText(str) {
setShowSuggestions(true)
setTimeout(() => {setSearchQuery(str);getSuggestions(str)}, 250)
}
function onSuggestionPress(query) {
setTabsVisible(true)
setTabs(currVal => ([
...currVal,
{ tabName: `${query} - Google Search`, tabUrl: `https://google.com/search?q=${query}`, visible: true },
]))
Keyboard.dismiss()
setShowSuggestions(false)
}
return <Animated.View
onPress={() => {}}
pointerEvents={tabs[idx].visible ? "auto" : "none"}
style={[{
position: "absolute", overflow: "hidden",
backgroundColor: isDark ? "#171717" : "white"},
animStyle
]}
>
<SearchBar
isDark={isDark}
title={title}
url={url}
setUrl={setUrl}
webViewRef={webViewRef}
webViewProps={webViewProps}
setWebViewProps={setWebViewProps}
/>
<WebView
source={{ uri: url }}
style={{
flex: 1,
marginTop: Constants.statusBarHeight,
}}
ref={webViewRef}
onNavigationStateChange={onWebViewNavigationStateChange}
onLoadEnd={e => onLoadEnd(e)}
onLoadProgress={e => onLoadProgress(e)}
onLoadStart={e => onLoadStart(e)}
injectedJavaScript={jsCode}
onError={() => {}}
onMessage={onMessage}
/>
<BottomPanel isDark={isDark} webViewProps={webViewProps} onGoBackPress={onGoBackPress} onGoForwardPress={onGoForwardPress}/>
</Animated.View>
})
const styles = StyleSheet.create({})