-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathindex.jsx
More file actions
291 lines (263 loc) · 9.87 KB
/
Copy pathindex.jsx
File metadata and controls
291 lines (263 loc) · 9.87 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
import React, { useState, useRef, useEffect, useCallback, useMemo } from "react";
import { ActivityIndicator, AppState, Platform, Animated } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { WebView } from "react-native-webview";
import { useDispatch, useSelector } from "react-redux";
import PropTypes from "prop-types";
import {
constant,
actions,
logError,
SafeArea,
BottomNavigation,
useTheme,
useThemedStyles,
StatusBarComponent,
useBackHandler,
} from "@common";
import { Header, AutoScrollComponent, AudioPlayer } from "./components";
import { useBookmarks, useFetchShabad, useFooterAnimation } from "./hooks";
import createStyles from "./styles";
import { loadHTML } from "./utils";
const Reader = ({ navigation, route }) => {
const { theme } = useTheme();
const styles = useThemedStyles(createStyles);
const bookmarkPosition = useSelector((state) => state.bookmarkPosition);
const isAutoScroll = useSelector((state) => state.isAutoScroll);
const isAudio = useSelector((state) => state.isAudio);
const isTransliteration = useSelector((state) => state.isTransliteration);
const fontSize = useSelector((state) => state.fontSize);
const fontFace = useSelector((state) => state.fontFace);
const isLarivaar = useSelector((state) => state.isLarivaar);
const isLarivaarAssist = useSelector((state) => state.isLarivaarAssist);
const isEnglishTranslation = useSelector((state) => state.isEnglishTranslation);
const isPunjabiTranslation = useSelector((state) => state.isPunjabiTranslation);
const isSpanishTranslation = useSelector((state) => state.isSpanishTranslation);
const isParagraphMode = useSelector((state) => state.isParagraphMode);
const isVishraam = useSelector((state) => state.isVishraam);
const vishraamOption = useSelector((state) => state.vishraamOption);
const savePosition = useSelector((state) => state.savePosition);
const webViewRef = useRef(null);
const { webView } = styles;
const { title, id, titleUni } = route.params.params || {};
const [isHeader, toggleHeader] = useState(false);
const [viewLoaded, toggleViewLoaded] = useState(false);
const [shouldNavigateBack, setShouldNavigateBack] = useState(false);
const [dateKey, setDateKey] = useState(Date.now().toString());
const [titleText, setTitleText] = useState(null);
const currentElementIdRef = useRef(savePosition[id] || null);
const dispatch = useDispatch();
const { shabad, isLoading } = useFetchShabad(id);
const { bottom: insetBottom } = useSafeAreaInsets();
const { animationPosition } = useFooterAnimation(isHeader);
// Save element ID when leaving screen or app goes to background
const saveScrollPosition = useCallback(() => {
// Prefer element ID if available, otherwise fall back to currentElementId state
const elementIdToSave = currentElementIdRef.current;
if (elementIdToSave) {
dispatch(actions.setPosition(elementIdToSave, id));
}
}, [dispatch, id, currentElementIdRef.current]);
useEffect(() => {
dispatch(actions.setCurrentBani({ id, title, titleUni }));
}, [id, title, titleUni]);
useEffect(() => {
// Handle undefined titleUni gracefully - fallback to title if titleUni is not available
const displayTitle = fontFace === constant.BALOO_PAAJI ? titleUni || title : title;
setTitleText(displayTitle);
}, [fontFace, titleUni, title]);
// Cleanup on unmount
useEffect(() => {
return () => {
// Save position when component unmounts
saveScrollPosition();
};
}, [saveScrollPosition]);
// Memoize WebView key to prevent unnecessary remounts
const webViewKey = useMemo(() => {
return `${id}-${isParagraphMode}-${isLarivaar}-${isLarivaarAssist}-${isVishraam}-${vishraamOption}-${dateKey}`;
}, [id, isParagraphMode, isLarivaar, isLarivaarAssist, isVishraam, vishraamOption, dateKey]);
// Memoize WebView source to prevent unnecessary remounts
const webViewSource = useMemo(() => {
return {
html: loadHTML(
shabad,
isTransliteration,
fontSize,
fontFace,
isEnglishTranslation,
isPunjabiTranslation,
isSpanishTranslation,
theme,
isLarivaar
),
baseUrl: Platform.OS === "ios" ? "./" : "",
};
}, [
shabad,
isTransliteration,
fontSize,
fontFace,
isEnglishTranslation,
isPunjabiTranslation,
isSpanishTranslation,
theme,
isLarivaar,
]);
useBookmarks(webViewRef, shabad, bookmarkPosition);
// Handle app state changes
useEffect(() => {
let isMounted = true;
const subscription = AppState.addEventListener("change", (state) => {
if (!isMounted) return;
if (state === "active") {
// App came to foreground
} else if (state === "background") {
// App went to background - save scroll position
saveScrollPosition();
}
});
return () => {
isMounted = false;
subscription.remove();
};
}, [saveScrollPosition]);
// Set currentElementId from savePosition when it changes
useEffect(() => {
if (savePosition && id && savePosition[id]) {
const savedElementId = savePosition[id];
// Check if it's a number (old position format) or string (element ID)
if (typeof savedElementId === "string") {
currentElementIdRef.current = savedElementId;
} else if (typeof savedElementId === "number" && savedElementId > 0.9) {
// Old position format - reset to null if at end
currentElementIdRef.current = null;
}
}
}, [savePosition, id]);
const handleBackPress = useCallback(() => {
// Save position before navigating back
saveScrollPosition();
if (webViewRef?.current) {
navigation.goBack();
}
return true;
}, [saveScrollPosition]);
useBackHandler(handleBackPress);
const handleBookmarkPress = useCallback(() => {
navigation.navigate(constant.BOOKMARKS, { id });
}, [navigation, id]);
const handleMessage = useCallback(
(message) => {
// Update last activity timestamp
const { data } = message.nativeEvent;
// Handle UI messages (removed toggle since it's handled by onTouchStart)
if (data === "show") {
toggleHeader(true);
} else if (data === "hide") {
toggleHeader(false);
} else if (data.includes("scroll-elementId-")) {
// Capture element ID from WebView scroll events
const elementId = data.split("scroll-elementId-")[1];
currentElementIdRef.current = elementId;
// Save immediately when element ID changes
dispatch(actions.setPosition(elementId, id));
if (shouldNavigateBack) {
navigation.goBack();
setShouldNavigateBack(false);
}
} else if (data.includes("sequenceString-")) {
const sequenceStringData = data.split("-")[1];
dispatch(actions.setBookmarkSequenceString(sequenceStringData));
}
},
[dispatch, id, navigation, shouldNavigateBack]
);
const handleLoadStart = useCallback(() => {
setTimeout(() => {
toggleViewLoaded(true);
}, 100);
}, []);
const handleLoadEnd = useCallback(() => {
// Scroll to saved element ID after WebView is fully loaded
if (webViewRef.current && currentElementIdRef.current) {
const scrollMessage = {
action: "scrollToPosition",
elementId: currentElementIdRef.current,
};
webViewRef.current.postMessage(JSON.stringify(scrollMessage));
}
}, [currentElementIdRef.current]);
const handleError = useCallback((syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
logError(`Reader web View Error ${nativeEvent}`);
}, []);
const handleHttpError = useCallback((syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
logError("HTTP error status code:", nativeEvent.statusCode);
}, []);
const reloadWebView = useCallback(() => {
if (webViewRef.current) {
setDateKey(Date.now().toString());
}
}, []);
return (
<SafeArea backgroundColor={theme.colors.surface} edges={["left", "right"]}>
<StatusBarComponent backgroundColor={theme.colors.surface} />
<Header
title={titleText}
handleBackPress={handleBackPress}
handleBookmarkPress={handleBookmarkPress}
isHeader={isHeader}
/>
{isLoading && <ActivityIndicator size="small" color={theme.colors.primary} />}
<WebView
key={webViewKey}
webviewDebuggingEnabled
javaScriptEnabled
originWhitelist={["*"]}
onLoadStart={handleLoadStart}
onLoadEnd={handleLoadEnd}
ref={webViewRef}
onError={handleError}
onHttpError={handleHttpError}
decelerationRate={0.998}
scrollEnabled
bounces={false}
overScrollMode="never"
nestedScrollEnabled
onContentProcessDidTerminate={reloadWebView}
source={webViewSource}
backgroundColor={theme.colors.surface}
style={[
webView,
theme.mode === "dark" && { opacity: viewLoaded ? 1 : 0.1 },
{ backgroundColor: theme.colors.surface, marginTop: 60 },
]}
onMessage={handleMessage}
onTouchStart={() => {
// Toggle header when WebView is touched (not overlaid elements)
toggleHeader((prev) => !prev);
}}
/>
{isAudio && <AudioPlayer baniID={id} title={titleText} webViewRef={webViewRef} />}
<Animated.View
style={[
styles.autoScrollAnimatedView,
{
bottom: styles.autoScrollAnimatedView.bottom + insetBottom,
transform: [{ translateY: animationPosition }],
},
]}
>
{isAutoScroll && <AutoScrollComponent shabadID={id} webViewRef={webViewRef} />}
</Animated.View>
<BottomNavigation activeKey={isAudio ? "Music" : "Read"} />
</SafeArea>
);
};
Reader.propTypes = {
navigation: PropTypes.shape().isRequired,
route: PropTypes.shape().isRequired,
};
export default React.memo(Reader);