-
-
Notifications
You must be signed in to change notification settings - Fork 552
Expand file tree
/
Copy pathMobileWebAppContainer.tsx
More file actions
467 lines (405 loc) · 15.5 KB
/
Copy pathMobileWebAppContainer.tsx
File metadata and controls
467 lines (405 loc) · 15.5 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ApplicationEvent, ReactNativeToWebEvent } from '@standardnotes/snjs'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Button, Dimensions, Keyboard, KeyboardEvent, Platform, Text, View } from 'react-native'
import VersionInfo from 'react-native-version-info'
import { WebView, WebViewMessageEvent } from 'react-native-webview'
import { OnShouldStartLoadWithRequest, WebViewNativeConfig } from 'react-native-webview/lib/WebViewTypes'
import { AndroidBackHandlerService } from './AndroidBackHandlerService'
import { AppStateObserverService } from './AppStateObserverService'
import { ColorSchemeObserverService } from './ColorSchemeObserverService'
import CustomAndroidWebView from './CustomAndroidWebView'
import { MobileDevice, MobileDeviceEvent } from './Lib/MobileDevice'
import { IsDev } from './Lib/Utils'
import { ReceivedSharedItemsHandler } from './ReceivedSharedItemsHandler'
import { ReviewService } from './ReviewService'
import notifee, { EventType } from '@notifee/react-native'
import { useSafeAreaInsets } from 'react-native-safe-area-context'
const LoggingEnabled = IsDev
export const MobileWebAppContainer = () => {
const [identifier, setIdentifier] = useState(Math.random())
const destroyAndReload = useCallback(() => {
setIdentifier(Math.random())
}, [])
return <MobileWebAppContents key={`${identifier}`} destroyAndReload={destroyAndReload} />
}
const MobileWebAppContents = ({ destroyAndReload }: { destroyAndReload: () => void }) => {
const webViewRef = useRef<WebView>(null)
const sourceUri = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + 'Web.bundle/src/index.html'
const stateService = useMemo(() => new AppStateObserverService(), [])
const androidBackHandlerService = useMemo(() => new AndroidBackHandlerService(), [])
const colorSchemeService = useMemo(() => new ColorSchemeObserverService(), [])
const device = useMemo(
() => new MobileDevice(stateService, androidBackHandlerService, colorSchemeService),
[androidBackHandlerService, colorSchemeService, stateService],
)
const _reviewService = useRef(new ReviewService(device))
const [showAndroidWebviewUpdatePrompt, setShowAndroidWebviewUpdatePrompt] = useState(false)
const [didLoadEnd, setDidLoadEnd] = useState(false)
const insets = useSafeAreaInsets()
useEffect(() => {
const removeStateServiceListener = stateService.addEventObserver((event: ReactNativeToWebEvent) => {
webViewRef.current?.postMessage(JSON.stringify({ reactNativeEvent: event, messageType: 'event' }))
})
const removeBackHandlerServiceListener = androidBackHandlerService.addEventObserver(
(event: ReactNativeToWebEvent) => {
webViewRef.current?.postMessage(JSON.stringify({ reactNativeEvent: event, messageType: 'event' }))
},
)
const removeColorSchemeServiceListener = colorSchemeService.addEventObserver((event: ReactNativeToWebEvent) => {
webViewRef.current?.postMessage(JSON.stringify({ reactNativeEvent: event, messageType: 'event' }))
})
const keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', () => {
device.reloadStatusBarStyle(false)
webViewRef.current?.postMessage(
JSON.stringify({
reactNativeEvent: ReactNativeToWebEvent.KeyboardWillShow,
messageType: 'event',
}),
)
})
const keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', () => {
device.reloadStatusBarStyle(false)
webViewRef.current?.postMessage(
JSON.stringify({
reactNativeEvent: ReactNativeToWebEvent.KeyboardWillHide,
messageType: 'event',
}),
)
})
const fireKeyboardSizeChangeEvent = (e: KeyboardEvent) => {
webViewRef.current?.postMessage(
JSON.stringify({
reactNativeEvent: ReactNativeToWebEvent.KeyboardSizeChanged,
messageType: 'event',
messageData: {
height: e.endCoordinates.height,
contentHeight: e.endCoordinates.screenY,
isFloatingKeyboard: Math.floor(e.endCoordinates.width) !== Math.floor(Dimensions.get('window').width),
},
}),
)
}
const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', (e) => {
// iOS handles this using the `willChangeFrame` event instead
if (Platform.OS === 'android' && insets.bottom > 0) {
fireKeyboardSizeChangeEvent(e)
webViewRef.current?.postMessage(
JSON.stringify({
reactNativeEvent: ReactNativeToWebEvent.KeyboardDidShow,
messageType: 'event',
}),
)
}
device.reloadStatusBarStyle(false)
})
const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
// iOS handles this using the `willChangeFrame` event instead
if (Platform.OS === 'android' && insets.bottom > 0) {
webViewRef.current?.postMessage(
JSON.stringify({
reactNativeEvent: ReactNativeToWebEvent.KeyboardDidHide,
messageType: 'event',
}),
)
}
device.reloadStatusBarStyle(false)
})
const keyboardWillChangeFrame = Keyboard.addListener('keyboardWillChangeFrame', (e) => {
fireKeyboardSizeChangeEvent(e)
})
return () => {
removeStateServiceListener()
removeBackHandlerServiceListener()
removeColorSchemeServiceListener()
keyboardWillShowListener.remove()
keyboardWillHideListener.remove()
keyboardDidShowListener.remove()
keyboardDidHideListener.remove()
keyboardWillChangeFrame.remove()
}
}, [webViewRef, stateService, device, androidBackHandlerService, colorSchemeService, insets.bottom])
useEffect(() => {
return notifee.onForegroundEvent(({ type, detail }) => {
if (type !== EventType.ACTION_PRESS) {
return
}
const { notification, pressAction } = detail
if (!notification || !pressAction) {
return
}
if (pressAction.id !== 'open-file') {
return
}
webViewRef.current?.postMessage(
JSON.stringify({
reactNativeEvent: ReactNativeToWebEvent.OpenFilePreview,
messageType: 'event',
messageData: {
id: notification.id,
},
}),
)
})
}, [])
useEffect(() => {
const observer = device.addMobileDeviceEventReceiver((event) => {
if (event === MobileDeviceEvent.RequestsWebViewReload) {
destroyAndReload()
}
})
return () => {
observer()
}
}, [device, destroyAndReload])
const functions = Object.getOwnPropertyNames(Object.getPrototypeOf(device))
const baselineFunctions: Record<string, any> = {
isDeviceDestroyed: `(){
return false
}`,
}
let stringFunctions = ''
for (const [key, value] of Object.entries(baselineFunctions)) {
stringFunctions += `${key}${value}`
}
for (const functionName of functions) {
if (functionName === 'constructor' || baselineFunctions[functionName]) {
continue
}
stringFunctions += `
${functionName}(...args) {
return this.askReactNativeToInvokeInterfaceMethod('${functionName}', args);
}
`
}
const WebProcessDeviceInterface = `
class WebProcessDeviceInterface {
constructor(messageSender) {
this.appVersion = '${VersionInfo.appVersion} (${VersionInfo.buildVersion})'
this.environment = 3
this.platform = ${device.platform}
this.databases = []
this.messageSender = messageSender
}
askReactNativeToInvokeInterfaceMethod(functionName, args) {
return this.messageSender.askReactNativeToInvokeInterfaceMethod(functionName, args)
}
${stringFunctions}
}
`
const WebProcessMessageSender = `
class WebProcessMessageSender {
constructor() {
this.pendingMessages = []
}
handleReplyFromReactNative( messageId, returnValue) {
const pendingMessage = this.pendingMessages.find((m) => m.messageId === messageId)
pendingMessage.resolve(returnValue)
this.pendingMessages.splice(this.pendingMessages.indexOf(pendingMessage), 1)
}
askReactNativeToInvokeInterfaceMethod(functionName, args) {
const messageId = Math.random()
window.ReactNativeWebView.postMessage(JSON.stringify({ functionName: functionName, args: args, messageId }))
return new Promise((resolve) => {
this.pendingMessages.push({
messageId,
resolve,
})
})
}
}
`
const injectedJS = `
console.log = (...args) => {
window.ReactNativeWebView.postMessage('[web log] ' + args.join(' '));
}
console.error = (...args) => {
window.ReactNativeWebView.postMessage('[web log] ' + args.join(' '));
}
${WebProcessDeviceInterface}
${WebProcessMessageSender}
const messageSender = new WebProcessMessageSender();
window.reactNativeDevice = new WebProcessDeviceInterface(messageSender);
const handleMessageFromReactNative = (event) => {
const message = event.data
try {
const parsed = JSON.parse(message)
const { messageId, returnValue, messageType } = parsed
if (messageType === 'reply') {
messageSender.handleReplyFromReactNative(messageId, returnValue)
}
} catch (error) {
console.log('Error parsing message from React Native', message, error)
}
}
window.addEventListener('message', handleMessageFromReactNative)
document.addEventListener('message', handleMessageFromReactNative)
true;
`
const onMessage = (event: WebViewMessageEvent) => {
const message = event.nativeEvent.data
if (message === 'appLoadError' && Platform.OS === 'android') {
setShowAndroidWebviewUpdatePrompt(true)
return
}
if (message === 'appLoaded') {
setDidLoadEnd(true)
return
}
try {
const functionData = JSON.parse(message)
void onFunctionMessage(functionData.functionName, functionData.messageId, functionData.args)
} catch (error) {
if (LoggingEnabled) {
// eslint-disable-next-line no-console
console.log('onGeneralMessage', JSON.stringify(message))
}
}
}
const onFunctionMessage = async (functionName: string, messageId: string, args: any) => {
const returnValue = await (device as any)[functionName](...args)
if (LoggingEnabled && functionName !== 'consoleLog') {
// eslint-disable-next-line no-console
console.log(`Native device function ${functionName} called`)
}
webViewRef.current?.postMessage(JSON.stringify({ messageId, returnValue, messageType: 'reply' }))
}
const onShouldStartLoadWithRequest: OnShouldStartLoadWithRequest = (request) => {
/**
* We want to handle link clicks within an editor by opening the browser
* instead of loading inline. On iOS, onShouldStartLoadWithRequest is
* called for all requests including the initial request to load the editor.
* On iOS, clicks in the editors have a navigationType of 'click', but on
* Android, this is not the case (no navigationType).
* However, on Android, this function is not called for the initial request.
* So that might be one way to determine if this request is a click or the
* actual editor load request. But I don't think it's safe to rely on this
* being the case in the future. So on Android, we'll handle url loads only
* if the url isn't equal to the editor url.
*/
const shouldStopRequest =
(Platform.OS === 'ios' && request.navigationType === 'click') ||
(Platform.OS === 'android' && request.url !== sourceUri)
const isComponentUrl = device.isUrlRegisteredComponentUrl(request.url)
if (shouldStopRequest && !isComponentUrl) {
device.openUrl(request.url)
return false
}
return true
}
const requireInlineMediaPlaybackForMomentsFeature = true
const requireMediaUserInteractionForMomentsFeature = false
const receivedSharedItemsHandler = useRef(new ReceivedSharedItemsHandler(webViewRef))
useEffect(() => {
const receivedSharedItemsHandlerInstance = receivedSharedItemsHandler.current
return () => {
receivedSharedItemsHandlerInstance.deinit()
}
}, [])
useEffect(() => {
return device.addApplicationEventReceiver((event) => {
if (event === ApplicationEvent.Launched) {
receivedSharedItemsHandler.current.setIsApplicationLaunched(true)
}
})
}, [device])
const injectJS = `
document.documentElement.style.setProperty('--safe-area-inset-top', '${insets.top}px');
document.documentElement.style.setProperty('--safe-area-inset-bottom', '${insets.bottom}px');
document.documentElement.style.setProperty('--safe-area-inset-left', '${insets.left}px');
document.documentElement.style.setProperty('--safe-area-inset-right', '${insets.right}px');
true;
`
if (Platform.OS === 'android') {
webViewRef.current?.injectJavaScript(injectJS)
}
if (showAndroidWebviewUpdatePrompt) {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'black',
}}
>
<Text
style={{
color: 'white',
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
}}
>
Could not load app
</Text>
<Text
style={{
color: 'white',
fontSize: 16,
marginBottom: 20,
textAlign: 'center',
}}
>
Please make sure your Android System Webview is updated to the latest version
</Text>
<Button
title={'Update'}
onPress={() => {
setShowAndroidWebviewUpdatePrompt(false)
device.openUrl('https://play.google.com/store/apps/details?id=com.google.android.webview')
}}
/>
</View>
)
}
return (
<View
style={{
flex: 1,
backgroundColor: '#000000',
}}
>
<WebView
ref={webViewRef}
source={{ uri: sourceUri }}
style={{
backgroundColor: Platform.OS === 'ios' ? 'transparent' : '#000000',
opacity: didLoadEnd ? 1 : 0,
}}
originWhitelist={['*']}
onError={(err) => console.error('An error has occurred', err)}
onHttpError={() => console.error('An HTTP error occurred')}
onMessage={onMessage}
onContentProcessDidTerminate={() => {
webViewRef.current?.reload()
}}
onRenderProcessGone={() => {
webViewRef.current?.reload()
}}
hideKeyboardAccessoryView={true}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
allowFileAccess={true}
allowUniversalAccessFromFileURLs={true}
injectedJavaScriptBeforeContentLoaded={injectedJS}
bounces={false}
keyboardDisplayRequiresUserAction={false}
allowsInlineMediaPlayback={requireInlineMediaPlaybackForMomentsFeature}
mediaPlaybackRequiresUserAction={requireMediaUserInteractionForMomentsFeature}
scalesPageToFit={true}
/**
* This disables the global window scroll but keeps scroll within div elements like lists and textareas.
* This is needed to prevent the keyboard from pushing the webview up and down when it appears and disappears.
*/
scrollEnabled={false}
overScrollMode="never"
nativeConfig={Platform.select({
android: {
component: CustomAndroidWebView,
} as WebViewNativeConfig,
})}
webviewDebuggingEnabled
/>
</View>
)
}