-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Misc.js
1637 lines (1545 loc) · 56.4 KB
/
Misc.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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
import PropTypes from 'prop-types';
import React, { useContext, useState, useEffect, useReducer, useCallback } from 'react';
import {
StyleSheet,
Text,
TouchableOpacity,
TouchableHighlight,
View,
Image,
ActivityIndicator,
Animated,
Platform,
TextInput,
Pressable,
FlatList,
useWindowDimensions,
} from 'react-native';
import {ViewPropTypes} from 'deprecated-react-native-prop-types';
import { GlobalStateContext, DispatchContext, STATE_ACTIONS, themeStr, getTheme } from './StateManager';
import {useGlobalState, useRenderersProps, useRtlFlexDir} from './Hooks';
import Sefaria from './sefaria';
import styles from './Styles.js';
import {iconData } from "./IconData";
import strings from './LocalizedStrings';
import { useHTMLViewStyles } from './useHTMLViewStyles';
import { RenderHTML } from 'react-native-render-html';
import BookSVG from './img/connection-book.svg';
import ActionSheet from "react-native-action-sheet";
const SYSTEM_FONTS = ["Taamey Frank Taamim Fix", "Amiri", "Heebo", "OpenSans", "SertoBatnan"]; // list of system fonts. needed for RenderHTML
const CSS_CLASS_STYLES = {
hebrew: {
fontFamily: "Taamey Frank Taamim Fix",
writingDirection: "rtl",
flex: -1,
textAlign: Platform.OS == "android" ? "right" : "justify",
},
english: {
fontFamily: "Amiri",
fontWeight: "normal",
textAlign: 'justify',
paddingTop: 0,
},
};
/**
* Renderes a page header with Styles to match all page headers and spacing
* @param headerProps the props that would be passed to <Header>
* @returns {JSX.Element}
* @constructor
*/
const PageHeader = ({children}) => {
return (
<View style={[styles.navRePageHeader]}>
{children}
</View>
)
}
/***
* Renders text styled as a header that has functionality
* @param titleKey the text to use for the header
* @returns {JSX.Element}
* @constructor
*/
const StatefulHeader = ({titleKey, icon = null, callbackFunc, active=true}) => {
const {themeStr, theme, interfaceLanguage} = useGlobalState();
const myIcon = iconData.get(icon, themeStr, active);
//this dance is bad. In react 0.71 we can use the 'gap' css directive on the container to do gaps betwwen the icon and text more unifromly.
const isHeb = interfaceLanguage == "hebrew";
const iconStyles = isHeb ? styles.navReStatefulHeaderIconHe : styles.navReStatefulHeaderIcon;
return(
<View style={styles.navReStatefulHeader}>
<TouchableOpacity onPress={callbackFunc}>
<FlexFrame alignItems={"center"}>
{icon ? <Image style={[iconStyles]} source={myIcon}/> : null}
<InterfaceText stringKey={titleKey} extraStyles={[styles.navReHeaderText, active ? theme.tertiaryText : theme.secondaryText]} />
</FlexFrame>
</TouchableOpacity>
</View>
);
}
/***
* Renders text styled as a header
* @param titleKey the text to use for the header
* @returns {JSX.Element}
* @constructor
*/
const Header = ({titleKey, icon = null}) => {
const { theme } = useGlobalState();
return(
<FlexFrame>
{icon ? <Icon name={icon}/> : null}
<InterfaceText stringKey={titleKey} extraStyles={[styles.navReHeaderText, theme.tertiaryText]} />
</FlexFrame>
);
}
const SystemHeader = ({ title, onBack, openNav, hideLangToggle }) => {
const { themeStr, interfaceLanguage } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
const showMenu = Platform.OS === 'android';
const LeftButtonComponent = showMenu ? MenuButton : DirectedButton;
const leftButtonProps = showMenu ? {onPress: openNav} : {
onPress: onBack,
imageStyle: [styles.menuButton, styles.directedButton],
direction: "back",
language: "english"
};
return (
<View style={[styles.header, styles.boxShadow, {borderBottomWidth: 0}, theme.header]}>
<LeftButtonComponent
{...leftButtonProps}
/>
<Text style={[interfaceLanguage === 'hebrew' ? styles.intHe : styles.intEn, styles.categoryTitle, theme.categoryTitle, {textTransform: "uppercase"}]}>
{title}
</Text>
{ hideLangToggle ? (
<LeftButtonComponent
{...leftButtonProps}
placeholder
/>
) : <LanguageToggleButton /> }
</View>
);
};
/**
* Component to render an interface string that is present in strings.js
* Please use this as opposed to InterfaceTextWithFallback when possible
* @param stringKey the key of the string to be rendered (must exist in all interface languages). If not passed, must pass `en` and `he`
* @param lang Optional explicit language to control which style of text is displayed. Either "english" or "hebrew".
* @param en Explicit text to be displayed when interfaceLanguage is English. Only used if stringKey is not supplied.
* @param he Explicit text to be displayed when interfaceLanguage is Hebrew. Only used if stringKey is not supplied.
* @param extraStyles additional styling directives to render this specific text (is it a header, a simple line of text, etc)
* @param allowFontScaling Equivalent to <Text>'s prop of the same name.
* @returns {Text}
*/
const InterfaceText = ({stringKey, lang, en, he, extraStyles = [], allowFontScaling=true}) => {
const { interfaceLanguage } = useContext(GlobalStateContext);
const intTextStyles = {
'english' : styles.enInt,
'hebrew' : styles.heInt
};
lang = lang || interfaceLanguage;
const langStyle = intTextStyles[lang];
let text;
if (stringKey) {
text = strings[stringKey];
} else {
text = lang === 'english' ? en : he;
}
return (
<Text style={[langStyle].concat(extraStyles)} allowFontScaling={allowFontScaling}>{text}</Text>
);
};
const InterfaceTextWithFallback = ({ en, he, extraStyles=[], lang }) => {
const { interfaceLanguage } = useContext(GlobalStateContext);
let langStyle = styles.enInt;
let text = en;
lang = lang || interfaceLanguage;
if ((lang === 'english' && !en) || (lang === 'hebrew' && !!he)) {
langStyle = styles.heInt;
text = he;
}
return (
<Text style={[langStyle].concat(extraStyles)}>{text}</Text>
);
}
const ContentTextWithFallback = ({ en, he, extraStyles=[], lang, ...stextProps }) => {
// default lang still governed by interfaceLanguage, but styles reflect content text styles
const { interfaceLanguage } = useContext(GlobalStateContext);
let langStyle = styles.ContentBodyEn;
let text = en;
lang = lang || interfaceLanguage
if ((lang === 'english' && !en) || (lang === 'hebrew' && !!he)) {
langStyle = styles.ContentBodyHe;
text = he;
}
return (
<SText lang={lang} style={[langStyle].concat(extraStyles)} {...stextProps} lineMultiplier={1.1}>{text}</SText>
);
}
const OrderedList = ({items, renderItem}) => {
let arrayOffset = 0;
return (
<>
{
items.map((item, index) => {
if (Array.isArray(item)) {
arrayOffset += 1;
return (
<View style={{marginLeft: 10}} key={`wrapper|${index}`}>
<OrderedList renderItem={renderItem} items={item}/>
</View>
);
}
return renderItem(item, index-arrayOffset);
})
}
</>
);
}
const DotSeparatedList = ({ items, renderItem, keyExtractor, flexDirection='row' }) => {
return (
items.map((item, i) => (
<View key={keyExtractor(item)} style={{flexDirection, alignItems: 'center'}} accessibilityLabel="A horizontal list of items separated by bullets">
{ renderItem(item, i) }
{ i < (items.length - 1) ? <Image source={require('./img/dot.png')} resizeMode={'contain'} style={{marginHorizontal: 5}}/> : null}
</View>
))
);
};
const SystemButton = ({ onPress, text, img, isHeb, isBlue, isLoading, extraStyles=[], extraImageStyles=[], placeholderImg=true }) => {
const { theme } = useGlobalState();
const flexDirection = isHeb ? "row-reverse" : "row";
return (
<TouchableOpacity disabled={isLoading} onPress={onPress} style={[styles.systemButton, theme.mainTextPanel, styles.boxShadow, (isBlue ? styles.systemButtonBlue : null)].concat(extraStyles)}>
{ isLoading ?
(<LoadingView size={'small'} height={20} color={isBlue ? '#ffffff' : undefined} />) :
(<View style={[styles.systemButtonInner, {flexDirection}]}>
{ !!img ?
<Image
source={img}
style={[isHeb ? styles.menuButtonMarginedHe : styles.menuButtonMargined].concat(extraImageStyles)}
resizeMode={'contain'}
/> : null
}
<Text
style={[
styles.systemButtonText,
theme.text,
(isBlue ? styles.systemButtonTextBlue : null),
(isHeb ? styles.heInt : styles.enInt)
]}
>
{ text }
</Text>
{ !!img && placeholderImg ?
<Image
source={img}
style={[isHeb ? styles.menuButtonMarginedHe : styles.menuButtonMargined, {opacity: 0}].concat(extraImageStyles)}
resizeMode={'contain'}
/> : null
}
</View>)
}
</TouchableOpacity>
);
}
SystemButton.whyDidYouRender = true;
const DynamicRepeatingText = ({ displayText, repeatText, maxCount }) => {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => setCount(count => count + 1), 1000);
return () => clearInterval(intervalId);
}, []);
return <Text>{`${displayText}${repeatText.repeat(Math.abs(count%(maxCount+1)))}`}</Text>
};
const SefariaProgressBar = ({ onPress, onClose, download, downloadNotification, identity, downloadSize }) => {
/*
* note on configuration: an object with keys {count, interval}. Count is the max number of times the progress bar
* will update, interval is the minimum elapsed time (ms) between updates. Hardcoding now, but we can turn this into a
* prop if needed.
* Configuration is supported by rn-fetch-blob. As the progressBar is designed to listen to the state of an ongoing
* process, I imagine this will generally be listening to libraries that support Stateful Promises. This can be
* revisited if reuseability becomes a problem.
*/
const { theme, themeStr, interfaceLanguage } = useGlobalState();
const [ progress, setProgress ] = useState(0);
const calculateProgress = (received, total) => !!(received) ? setProgress(received / total) : setProgress(0.0);
const downloadActive = !!downloadNotification ? downloadNotification.downloadActive : false;
const trueDownloadSize = !!(downloadSize) ? downloadSize : download.downloadSize;
useEffect(() => {
console.log('attaching Progress Tracker');
download.attachProgressTracker(calculateProgress, identity);
return function cleanup() {
console.log('attaching dummy Progress Tracker');
download.removeProgressTracker(identity);
};
}, [download]); // we only want to resubscribe if the downloader object changes. This shouldn't happen, but the condition is here for completeness sake
const downloadPercentage = (Math.round(progress * 1000) / 10).toFixed(1);
return (
<TouchableOpacity onPress={!!onPress ? onPress : () => {
}} disabled={!onPress} style={styles.sefariaProgressBar}>
<View style={{flex: 1, flexDirection: interfaceLanguage === "hebrew" ? "row-reverse" : "row", height: 50, alignSelf: 'stretch'}}>
<View style={[{flex: progress}, theme.mainTextPanel]}>
</View>
<View style={[{flex: 1 - progress}, theme.lighterGreyBackground]}>
</View>
</View>
<View
style={[{flexDirection: interfaceLanguage === "hebrew" ? "row-reverse" : "row"}, styles.sefariaProgressBarOverlay]}>
<Text
style={[{color: "#999"}, interfaceLanguage === "hebrew" ? styles.heInt : styles.enInt]}>{
downloadActive ? `${strings.downloading} (${downloadPercentage}% ${strings.of} ${parseInt(trueDownloadSize/ 1e6)}mb)`
: <DynamicRepeatingText displayText={strings.connecting} repeatText={'.'} maxCount={3} />
}</Text>
{!!onClose ?
<TouchableOpacity onPress={onClose} accessibilityLabel="Close">
<Image
source={iconData.get('close', themeStr)}
resizeMode={'contain'}
style={{width: 14, height: 14}}
/>
</TouchableOpacity>
: null
}
</View>
</TouchableOpacity>
);
};
const ConditionalProgressWrapper = ({ conditionMethod, initialValue, downloader, listenerName, children, ...otherProps }) => {
const enclosedCondition = state => {
return conditionMethod(state, otherProps)
};
const [downloadState, setDownload] = useState(initialValue);
useEffect(() => {
downloader.subscribe(listenerName, setDownload);
return function cleanup() {
downloader.unsubscribe(listenerName);
}
}, []);
if(enclosedCondition(downloadState)) {
return React.cloneElement(children, {downloadNotification: downloadState})
} else { return null }
};
class TwoBox extends React.Component {
static propTypes = {
language: PropTypes.oneOf(["hebrew", "bilingual", "english"]),
};
render() {
const rows = [];
let currRow = [];
const numChildren = React.Children.count(this.props.children);
React.Children.forEach(this.props.children, (child, index) => {
currRow.push(child);
if (currRow.length === 2 || index === numChildren - 1) {
rows.push(
<TwoBoxRow key={index} language={this.props.language}>
{ currRow }
</TwoBoxRow>
);
currRow = [];
}
});
return (<View style={styles.twoBox}>{rows}</View>);
}
}
class TwoBoxRow extends React.PureComponent {
static propTypes = {
language: PropTypes.oneOf(["hebrew","bilingual", "english"]),
};
render() {
const { children, language } = this.props;
const rowStyle = language == "hebrew" ? [styles.twoBoxRow, styles.rtlRow] : [styles.twoBoxRow];
const numChildren = React.Children.count(children);
const newChildren = React.Children.map(children, (child, index) => (
<View style={styles.twoBoxItem} key={index}>{child}</View>
));
if (numChildren < 2) {
newChildren.push(<View style={styles.twoBoxItem} key={1}></View>);
}
return (
<View style={rowStyle}>
{ newChildren }
</View>
);
}
}
const CategoryBlockLink = ({
category,
heCat,
style,
icon,
iconSide,
subtext,
upperCase,
withArrow,
isSans,
onPress,
onLongPress,
}) => {
const { themeStr, textLanguage, interfaceLanguage } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
const isHeb = Sefaria.util.get_menu_language(interfaceLanguage, textLanguage) == 'hebrew';
const iconOnLeft = iconSide ? iconSide === "start" ^ isHeb : isHeb;
style = style || {"borderColor": Sefaria.palette.categoryColor(category)};
var enText = upperCase ? category.toUpperCase() : category;
var heText = heCat || Sefaria.hebrewCategory(category);
subtext = !!subtext && !(subtext instanceof Array) ? [subtext] : subtext;
var textStyle = [styles.centerText, theme.text, upperCase ? styles.spacedText : null];
var content = isHeb ?
(<Text style={[isSans ? styles.heInt : styles.hebrewText].concat(textStyle)}>{heText}</Text>) :
(<Text style={[isSans ? styles.enInt : styles.englishText].concat(textStyle)}>{enText}</Text>);
return (
<TouchableOpacity onLongPress={onLongPress} onPress={onPress} style={[styles.readerNavCategory, theme.readerNavCategory, style]}>
<View style={styles.readerNavCategoryInner}>
{ iconOnLeft && (withArrow || icon) ? <Image source={withArrow || !icon ? iconData.get('back', themeStr) : icon }
style={[styles.moreArrowHe, isSans ? styles.categoryBlockLinkIconSansHe : null]}
resizeMode={'contain'} /> : null }
{content}
{ !iconOnLeft && (withArrow || icon) ? <Image source={ withArrow || !icon ? iconData.get('forward', themeStr) : icon }
style={[styles.moreArrowEn, isSans ? styles.categoryBlockLinkIconSansEn : null]}
resizeMode={'contain'} /> : null }
</View>
{
!!subtext ?
<View style={styles.readerNavCategorySubtext}>
{ subtext.map(x => (
<Text
key={x.en}
style={[isHeb ? styles.hebrewText : styles.englishText, {textAlign: "center"}, theme.secondaryText]}
>
{isHeb ? x.he : x.en}
</Text>
)) }
</View>
: null
}
</TouchableOpacity>
);
}
CategoryBlockLink.propTypes = {
category: PropTypes.string,
heCat: PropTypes.string,
language: PropTypes.string,
style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
isSans: PropTypes.bool,
upperCase: PropTypes.bool,
withArrow: PropTypes.bool,
subtext: PropTypes.oneOfType([PropTypes.shape({en: PropTypes.string, he: PropTypes.string}), PropTypes.arrayOf(PropTypes.shape({en: PropTypes.string, he: PropTypes.string}))]),
onPress: PropTypes.func,
icon: PropTypes.number,
iconSide: PropTypes.oneOf(["start", "end"])
};
CategoryBlockLink.whyDidYouRender = true;
const CategorySideColorLink = ({ language, category, enText, heText, sheetOwner, onPress }) => {
const { themeStr } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
const isHeb = language === 'hebrew';
const borderSide = isHeb ? "Right" : "Left";
const text = isHeb ? (heText || Sefaria.hebrewCategory(category)) : enText;
return (
<TouchableHighlight underlayColor={themeStr} style={{flex:1}} onPress={onPress}>
<View style={{flex:1, flexDirection: isHeb ? "row-reverse" : "row"}}>
<View style={{width: 6, [`border${borderSide}Color`]: Sefaria.palette.categoryColor(category), [`border${borderSide}Width`]: 6,}} />
<View style={[styles.categorySideColorLink, theme.menu, theme.borderedBottom]}>
<Text numberOfLines={1} ellipsizeMode={"middle"} style={[isHeb ? styles.hebrewText : styles.englishText, theme.text]}>
{text}
<Text style={isHeb ? {fontWeight: 'bold'} : {fontStyle: 'italic'}}>
{sheetOwner}
</Text>
</Text>
</View>
</View>
</TouchableHighlight>
);
}
CategorySideColorLink.propTypes = {
language: PropTypes.string.isRequired,
category: PropTypes.string.isRequired,
enText: PropTypes.string.isRequired,
heText: PropTypes.string,
onPress: PropTypes.func.isRequired,
};
class AnimatedRow extends React.Component {
static propTypes = {
children: PropTypes.any.isRequired,
animationDuration: PropTypes.number.isRequired,
onRemove: PropTypes.func,
}
constructor(props) {
super(props);
this._position = new Animated.Value(1);
this._height = new Animated.Value(1);
}
remove = () => {
const { onRemove, animationDuration } = this.props;
if (onRemove) {
Animated.sequence([
Animated.timing(this._position, {
toValue: 0,
duration: animationDuration,
useNativeDriver: false,
}),
Animated.timing(this._height, {
toValue: 0,
duration: animationDuration,
useNativeDriver: false,
})
]).start(onRemove);
}
}
render() {
const rowStyles = [
{
height: this._height.interpolate({
inputRange: [0, 1],
outputRange: [0, 50],
extrapolate: 'clamp',
}),
left: this._position.interpolate({
inputRange: [0, 1],
outputRange: [-200, 0],
extrapolate: 'clamp',
}),
opacity: this._position,
},
];
return (
<Animated.View style={rowStyles}>
{this.props.children}
</Animated.View>
)
}
}
/**
* Horizontal line that has the corresponding category color of `category`, based on Sefaria.palette.categoryColor()
* @param category: string top-level category name.
* @param thickness: int, how thick the category line is.
* @returns {JSX.Element}
* @constructor
*/
const CategoryColorLine = ({ category, thickness=4 }) => {
const style = {
height: thickness,
alignSelf: "stretch",
backgroundColor: Sefaria.palette.categoryColor(category)
};
return (<View style={style} />);
}
const CategoryAttribution = ({ categories, context, linked=true, openUri }) => {
const { themeStr, textLanguage, interfaceLanguage } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
// language settings in TextColumn should be governed by textLanguage. Everything else should be governed by textLanguage
if (!categories) { return null; }
var attribution = Sefaria.categoryAttribution(categories);
if (!attribution) { return null; }
var openLink = () => {openUri(attribution.link)};
var boxStyles = [styles.categoryAttribution, styles[context + "CategoryAttribution" ]];
var content = Sefaria.util.get_menu_language(interfaceLanguage, textLanguage) == "hebrew" ?
<Text style={[styles[context + "CategoryAttributionTextHe"], theme.tertiaryText]}>{attribution.hebrew}</Text> :
<Text style={[styles[context + "CategoryAttributionTextEn"], theme.tertiaryText]}>{attribution.english}</Text>;
return linked ?
(<TouchableOpacity style={boxStyles} onPress={openLink}>
{content}
</TouchableOpacity>) :
(<View style={boxStyles}>
{content}
</View>);
}
CategoryAttribution.propTypes = {
categories: PropTypes.array,
context: PropTypes.string.isRequired,
linked: PropTypes.bool,
openUri: PropTypes.func,
};
const LibraryNavButton = ({
catColor,
onPress,
onPressCheckBox,
checkBoxSelected,
enText,
heText,
count,
hasEn,
withArrow,
buttonStyle,
isMainMenu
}) => {
const { themeStr, textLanguage, interfaceLanguage } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
let borderTopWidth = isMainMenu ? null : 1;
let colorStyle = catColor && !isMainMenu ? [{"borderColor": catColor}] : [theme.searchResultSummary, {"borderTopWidth": borderTopWidth}];
let height = isMainMenu ? {height: 36} : null;
let textStyle = [catColor ? styles.spacedText : null];
const isHeb = Sefaria.util.get_menu_language(interfaceLanguage, textLanguage) == "hebrew";
let flexDir = isHeb ? "row-reverse" : "row";
let textMargin = !onPressCheckBox && !isMainMenu && styles.readerSideMargin;
if (count === 0) { textStyle.push(theme.secondaryText); } else if (isMainMenu) { textStyle.push(theme.primaryText);}
return (
<TouchableOpacity
onPress={onPress}
style={[styles.searchFilterCat, {flexDirection: flexDir}, buttonStyle, height].concat(colorStyle)}
delayPressIn={200}
>
<View style={[{flexDirection: flexDir, alignItems: "center", justifyContent: "space-between", flex: 1}, textMargin]}>
<View style={{flexDirection: flexDir, alignItems: "center"}}>
{isMainMenu && <ColoredBook flexDir={flexDir} color={catColor} />}
{!!onPressCheckBox && <CheckBox themeStr={themeStr} state={checkBoxSelected} onPress={onPressCheckBox} />}
<LibraryNavButtonText enText={enText} heText={heText} count={count} isHeb={isHeb} textStyle={textStyle} />
</View>
{(hasEn && !isHeb) &&
<Text style={[styles.englishSystemFont, styles.enConnectionMarker, theme.enConnectionMarker, theme.secondaryText, Platform.OS === 'android' && {paddingLeft: 5, paddingTop: 2}]}>
{"EN"}
</Text>
}
</View>
</TouchableOpacity>
);
}
LibraryNavButton.propTypes = {
catColor: PropTypes.string,
onPress: PropTypes.func.isRequired,
onPressCheckBox: PropTypes.func,
checkBoxSelected:PropTypes.number,
enText: PropTypes.string.isRequired,
heText: PropTypes.string.isRequired,
count: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
buttonStyle: PropTypes.oneOfType([ViewPropTypes.style, PropTypes.array]),
isMainMenu: PropTypes.bool,
};
const ColoredBook = ({flexDir, color}) => {
return (
<View style={[styles.toolsButtonIcon, {flexDirection: flexDir}]}>
<BookSVG style={styles.menuButton} resizeMode={'contain'} color={color}/>
</View>
);
}
ColoredBook.proptypes = {
flexDir: PropTypes.string.isRequired,
color: PropTypes.string.isRequired,
};
const CheckBox = ({themeStr, state, onPress}) => {
return (
<TouchableOpacity style={{paddingHorizontal: 10, paddingVertical: 15}} onPress={onPress} >
<IndeterminateCheckBox themeStr={themeStr} state={state} onPress={onPress} />
</TouchableOpacity>
);
}
CheckBox.proptypes = {
themeStr: PropTypes.string.isRequired,
state: PropTypes.number.isRequired,
onPress: PropTypes.func.isRequired,
};
const LibraryNavButtonText = ({isHeb, enText, heText, count, textStyle}) => {
const langStyle = (isHeb) ? styles.hebrewText : styles.englishText;
const paddingTop = (isHeb) ? 13 : 3;
const text = (isHeb) ? heText : enText;
const { themeStr } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
return (
<Text style={[langStyle].concat([theme.tertiaryText, textStyle, {paddingTop:paddingTop}])}>
{text}
{ !!count && <Text style={[langStyle].concat([theme.secondaryText, textStyle])}>{` (${count})`}</Text> }
</Text>
);
}
LibraryNavButtonText.proptypes = {
isHeb: PropTypes.bool.isRequired,
enText: PropTypes.string.isRequired,
heText: PropTypes.string.isRequired,
count: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
textStyle: PropTypes.array.isRequired
};
const LanguageToggleButton = () => {
// button for toggling b/w he and en for menu and text lang (both controlled by `textLanguage`)
const { theme, textLanguage, interfaceLanguage } = useGlobalState();
const dispatch = useContext(DispatchContext);
const isHeb = textLanguage === 'hebrew';
const iconName = isHeb ? "a_icon" : "aleph";
const enabled = interfaceLanguage !== 'hebrew';
const toggle = () => {
const language = !isHeb ? "hebrew" : 'english';
dispatch({
type: STATE_ACTIONS.setTextLanguage,
value: language,
});
};
const style = [styles.languageToggle, theme.languageToggle, enabled ? null : {opacity:0}];
return (
<TouchableOpacity style={style} onPress={toggle} disabled={!enabled} accessibilityLabel={`Change language to ${isHeb ? "English" : "Hebrew"}`}>
<Icon name={iconName} length={13.5} />
</TouchableOpacity>
);
}
const CollapseIcon = ({ showHebrew, isVisible }) => {
const { themeStr } = useContext(GlobalStateContext);
let src;
if (isVisible) {
src = iconData.get('down', themeStr);
} else {
if (showHebrew) {
src = iconData.get('back', themeStr);
} else {
src = iconData.get('forward', themeStr);
}
}
return (
<Image
source={src}
style={[(showHebrew ? styles.collapseArrowHe : styles.collapseArrowEn), Platform.OS === 'android' ? {marginTop: 3} : null]}
resizeMode={'contain'}
/>
);
}
CollapseIcon.propTypes = {
showHebrew: PropTypes.bool,
isVisible: PropTypes.bool
};
class DirectedButton extends React.Component {
//simple button with onPress() and a forward/back arrow. NOTE: arrow should change direction depending on interfaceLang
static propTypes = {
text: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
language: PropTypes.oneOf(["hebrew", "english"]).isRequired,
textStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
imageStyle: PropTypes.oneOfType([ViewPropTypes.style, PropTypes.array]),
onPress: PropTypes.func.isRequired,
direction: PropTypes.oneOf(["forward", "back"]).isRequired,
placeholder:PropTypes.bool,
accessibilityText: PropTypes.string,
};
render() {
//the actual dir the arrow will face
var actualDirBack = (this.props.language === "hebrew" && this.props.direction === "forward") || (this.props.language === "english" && this.props.direction === "back")
return (
<TouchableOpacity onPress={this.props.onPress}
style={{ flexDirection: actualDirBack ? "row-reverse" : "row", alignItems: "center", opacity: this.props.placeholder ? 0 : 1 }}
hitSlop={{top: 20, bottom: 20, left: 10, right: 10}}
accessibilityLabel={ this.props.accessibilityText || this.props.text || this.props.direction }
>
{ this.props.text ?
<SText lang={this.props.language} style={this.props.textStyle}>
{this.props.text}
</SText> :
null
}
<DirectedArrow
imageStyle={this.props.imageStyle}
language={this.props.language}
direction={this.props.direction} />
</TouchableOpacity>
);
}
}
const DirectedArrow = ({ imageStyle, language, direction }) => {
const { themeStr } = useContext(GlobalStateContext);
const isheb = language === 'hebrew';
const actualDirBack = (isheb && direction === "forward") || (!isheb && direction === "back");
const iconName = actualDirBack ? 'back' : 'forward';
const src = iconData.get(iconName, themeStr);
return (
<Image source={src} style={imageStyle} resizeMode={'contain'}/>
);
}
DirectedArrow.propTypes = {
imageStyle: PropTypes.oneOfType([ViewPropTypes.style, PropTypes.array]),
language: PropTypes.oneOf(["hebrew", "bilingual", "english"]).isRequired,
direction: PropTypes.oneOf(["forward", "back"]).isRequired,
};
const BackButton = ({ onPress }) => {
const { interfaceLanguage } = useGlobalState();
const iconName = interfaceLanguage === "english" ? "back" : "forward";
return (
<SefariaPressable onPress={onPress} hitSlop={20}>
<Icon name={iconName} length={18} />
</SefariaPressable>
);
};
const BackButtonRow = ({ onPress }) => {
return (
<View style={{paddingVertical: 18}}>
<FlexFrame dir={"row"} justifyContent={"flex-start"} alignItems={"center"}>
<BackButton onPress={onPress} />
</FlexFrame>
</View>
);
};
const SearchButton = ({ onPress, extraStyles, disabled }) => {
const { themeStr } = useContext(GlobalStateContext);
return (
<TouchableOpacity style={[styles.headerButton, styles.headerButtonSearch, extraStyles]} onPress={onPress} disabled >
<Image
source={iconData.get('search', themeStr)}
style={styles.searchButton}
resizeMode={'contain'}
/>
</TouchableOpacity>
);
}
const MenuButton = ({ onPress, placeholder }) => {
const { themeStr } = useGlobalState();
return (
<TouchableOpacity style={[styles.headerButton, styles.leftHeaderButton, {opacity: placeholder ? 0 : 1}]} onPress={onPress} accessibilityLabel="Open Menu">
<Image
source={iconData.get('menu', themeStr)}
style={styles.menuButton}
resizeMode={'contain'}
/>
</TouchableOpacity>
);
}
const CloseButton = ({ onPress }) => {
const { themeStr } = useContext(GlobalStateContext);
return (
<TouchableOpacity style={[styles.headerButton, styles.leftHeaderButton]} onPress={onPress} accessibilityLabel="Close">
<Image
source={iconData.get('close', themeStr)}
style={styles.closeButton}
resizeMode={'contain'}
/>
</TouchableOpacity>
);
}
const CircleCloseButton = ({ onPress }) => {
const { themeStr } = useContext(GlobalStateContext);
return (
<TouchableOpacity style={styles.headerButton} onPress={onPress} accessibilityLabel="Close">
<Image
source={iconData.get('circle-close', themeStr)}
style={styles.circleCloseButton}
resizeMode={'contain'}
/>
</TouchableOpacity>
);
}
const TripleDots = ({ onPress }) => {
const { themeStr } = useContext(GlobalStateContext);
return (
<TouchableOpacity
style={styles.tripleDotsContainer}
onPress={onPress}
>
<Image
style={styles.tripleDots}
source={iconData.get('dots', themeStr)}
/>
</TouchableOpacity>
);
}
const DisplaySettingsButton = ({ onPress }) => {
const { themeStr } = useContext(GlobalStateContext);
const { interfaceLanguage } = useGlobalState();
const iconName = interfaceLanguage === 'hebrew' ? "aleph" : "a_icon";
return (
<TouchableOpacity
style={[styles.headerButton, styles.rightHeaderButton]}
onPress={onPress}
accessibilityLabel="Open display settings"
>
<Image
source={iconData.get(iconName, themeStr)}
style={styles.displaySettingsButton}
resizeMode={'contain'}
/>
</TouchableOpacity>
);
}
const ToggleSet = ({ options, active }) => {
const { themeStr, textLanguage, interfaceLanguage } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
const isHeb = Sefaria.util.get_menu_language(interfaceLanguage, textLanguage) == 'hebrew';
options = options.map((option, i) => {
var style = [styles.navToggle, theme.navToggle].concat(active === option.name ? [styles.navToggleActive, theme.navToggleActive] : []);
return (
<TouchableOpacity onPress={option.onPress} key={i} >
{isHeb ?
<Text style={[style, styles.heInt]}>{option.heText}</Text> :
<Text style={[style, styles.enInt]}>{option.text}</Text> }
</TouchableOpacity>
);
});
var dividedOptions = [];
for (var i = 0; i < options.length; i++) {
dividedOptions.push(options[i])
dividedOptions.push(<Text style={[styles.navTogglesDivider,theme.navTogglesDivider]} key={i+"d"}>|</Text>);
}
dividedOptions = dividedOptions.slice(0,-1);
return (
<View style={styles.navToggles}>
{dividedOptions}
</View>
);
}
ToggleSet.propTypes = {
options: PropTypes.array.isRequired, // array of object with `name`. `text`, `heText`, `onPress`
active: PropTypes.string.isRequired
};
const ButtonToggleSet= ({ options, active }) => {
/* based on new styles guide */
const { themeStr, interfaceLanguage } = useContext(GlobalStateContext);
const theme = getTheme(themeStr);
const isHeb = interfaceLanguage === 'hebrew';
return (
<View style={[styles.readerDisplayOptionsMenuRow, styles.boxShadow, styles.buttonToggleSet, theme.mainTextPanel]}>
{
options.map(option => {
const isActive = active === (typeof option.value == 'undefined' ? option.name : option.value);
return (
<TouchableOpacity key={option.name} onPress={option.onPress} style={[styles.buttonToggle, isActive ? styles.buttonToggleActive : null]}>
<Text style={[theme.text, isActive ? styles.buttonToggleActiveText : null, isHeb? styles.heInt : styles.enInt]}>
{ option.text }
</Text>
</TouchableOpacity>
);
})
}
</View>
);
}
const LoadingView = ({ style, category, size, height, color=Sefaria.palette.colors.system }) => (
<View style={[styles.loadingViewBox, style]}>
<ActivityIndicator
animating={true}
style={[styles.loadingView, !!height ? { height } : null]}
color={Platform.OS === 'android' ? (category ? Sefaria.palette.categoryColor(category) : color) : undefined}
size={size || 'large'}
/>
</View>
);
const useCheckboxIconName = (state) => {
const iconNameSuffixMap = ['unchecked', 'checked', 'partially'];
return `checkbox-${iconNameSuffixMap[state]}`;
}
const IndeterminateCheckBox = ({ state, onPress }) => {
const iconName = useCheckboxIconName(state);
return (
<TouchableOpacity onPress={onPress}>
<Icon name={iconName} length={18} />
</TouchableOpacity>
);
}
IndeterminateCheckBox.propTypes = {
state: PropTypes.oneOf([0,1,2]),
onPress: PropTypes.func.isRequired,
};
/**
* Icon component to be used wherever an icon from `IconData` is needed
* @param name - name of the icon
* @param length - assumption is the icon has the same width and height
* @param isSelected
* @param extraStyles - list of extra styles for icon
* @returns {JSX.Element}
* @constructor
*/
const Icon = ({ name, length, isSelected, extraStyles=[] }) => {
const { themeStr } = useGlobalState();
const icon = iconData.get(name, themeStr, isSelected);
return (
<Image
source={icon}
resizeMode={'contain'}
style={[{width: length, height: length}].concat(extraStyles)}
/>
);