Chore/make function components 4

This commit is contained in:
Sofiya Tepikin
2022-09-11 14:01:23 +00:00
parent cec2c5bc2e
commit cd43271bbd
5 changed files with 185 additions and 239 deletions
@@ -1,4 +1,4 @@
import React, { Component } from 'react' import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
import { Alert, StyleSheet, View } from 'react-native' import { Alert, StyleSheet, View } from 'react-native'
import nodejs from 'nodejs-mobile-react-native' import nodejs from 'nodejs-mobile-react-native'
@@ -11,78 +11,65 @@ import { Containers } from '../../../styles'
import settings from '../../../i18n/en/settings' import settings from '../../../i18n/en/settings'
import { shared } from '../../../i18n/en/labels' import { shared } from '../../../i18n/en/labels'
export default class ConfirmWithPassword extends Component { const ConfirmWithPassword = ({ onSuccess, onCancel }) => {
constructor() { const [password, setPassword] = useState(null)
super()
this.state = { password: null } const checkPassword = async (hash) => {
nodejs.channel.addListener('password-check', this.checkPassword, this) try {
await openDb(hash)
onSuccess()
} catch (err) {
onIncorrectPassword()
}
} }
componentWillUnmount() { useEffect(() => {
nodejs.channel.removeListener('password-check', this.checkPassword) nodejs.channel.addListener('password-check', checkPassword, this)
} return () => {
nodejs.channel.removeListener('password-check', checkPassword)
}
}, [])
resetPasswordInput = () => { const onIncorrectPassword = () => {
this.setState({ password: null })
}
onIncorrectPassword = () => {
Alert.alert(shared.incorrectPassword, shared.incorrectPasswordMessage, [ Alert.alert(shared.incorrectPassword, shared.incorrectPasswordMessage, [
{ {
text: shared.cancel, text: shared.cancel,
onPress: this.props.onCancel, onPress: onCancel,
}, },
{ {
text: shared.tryAgain, text: shared.tryAgain,
onPress: this.resetPasswordInput, onPress: () => setPassword(null),
}, },
]) ])
} }
checkPassword = async (hash) => { const initPasswordCheck = () => {
try { requestHash('password-check', password)
await openDb(hash)
this.props.onSuccess()
} catch (err) {
this.onIncorrectPassword()
}
} }
handlePasswordInput = (password) => { const labels = settings.passwordSettings
this.setState({ password }) const isPassword = password !== null
}
initPasswordCheck = () => { return (
requestHash('password-check', this.state.password) <>
} <AppTextInput
onChangeText={setPassword}
render() { placeholder={labels.enterCurrent}
const { password } = this.state value={password}
const labels = settings.passwordSettings secureTextEntry
const isPassword = password !== null />
<View style={styles.container}>
return ( <Button onPress={onCancel}>{shared.cancel}</Button>
<React.Fragment> <Button
<AppTextInput disabled={!isPassword}
onChangeText={this.handlePasswordInput} isCTA={isPassword}
placeholder={labels.enterCurrent} onPress={initPasswordCheck}
value={password} >
secureTextEntry={true} {shared.confirmToProceed}
/> </Button>
<View style={styles.container}> </View>
<Button onPress={this.props.onCancel}>{shared.cancel}</Button> </>
<Button )
disabled={!isPassword}
isCTA={isPassword}
onPress={this.initPasswordCheck}
>
{shared.confirmToProceed}
</Button>
</View>
</React.Fragment>
)
}
} }
ConfirmWithPassword.propTypes = { ConfirmWithPassword.propTypes = {
@@ -95,3 +82,5 @@ const styles = StyleSheet.create({
...Containers.rowContainer, ...Containers.rowContainer,
}, },
}) })
export default ConfirmWithPassword
@@ -1,4 +1,4 @@
import React, { Component } from 'react' import React, { useState } from 'react'
import RNFS from 'react-native-fs' import RNFS from 'react-native-fs'
import { Alert } from 'react-native' import { Alert } from 'react-native'
import PropTypes from 'prop-types' import PropTypes from 'prop-types'
@@ -17,26 +17,21 @@ import { EXPORT_FILE_NAME } from './constants'
const exportedFilePath = `${RNFS.DocumentDirectoryPath}/${EXPORT_FILE_NAME}` const exportedFilePath = `${RNFS.DocumentDirectoryPath}/${EXPORT_FILE_NAME}`
export default class DeleteData extends Component { const DeleteData = ({ onStartDeletion, isDeletingData }) => {
constructor() { const isPasswordSet = hasEncryptionObservable.value
super() const [isConfirmingWithPassword, setIsConfirmingWithPassword] =
useState(false)
this.state = { const onAlertConfirmation = () => {
isPasswordSet: hasEncryptionObservable.value, onStartDeletion()
isConfirmingWithPassword: false, if (isPasswordSet) {
} setIsConfirmingWithPassword(true)
}
onAlertConfirmation = () => {
this.props.onStartDeletion()
if (this.state.isPasswordSet) {
this.setState({ isConfirmingWithPassword: true })
} else { } else {
this.deleteAppData() deleteAppData()
} }
} }
alertBeforeDeletion = async () => { const alertBeforeDeletion = async () => {
const { question, message, confirmation, errors } = settings.deleteSegment const { question, message, confirmation, errors } = settings.deleteSegment
if (isDbEmpty() && !(await RNFS.exists(exportedFilePath))) { if (isDbEmpty() && !(await RNFS.exists(exportedFilePath))) {
alertError(errors.noData) alertError(errors.noData)
@@ -44,64 +39,61 @@ export default class DeleteData extends Component {
Alert.alert(question, message, [ Alert.alert(question, message, [
{ {
text: confirmation, text: confirmation,
onPress: this.onAlertConfirmation, onPress: onAlertConfirmation,
}, },
{ {
text: sharedLabels.cancel, text: sharedLabels.cancel,
style: 'cancel', style: 'cancel',
onPress: this.cancelConfirmationWithPassword, onPress: cancelConfirmationWithPassword,
}, },
]) ])
} }
} }
deleteExportedFile = async () => { const deleteExportedFile = async () => {
if (await RNFS.exists(exportedFilePath)) { if (await RNFS.exists(exportedFilePath)) {
await RNFS.unlink(exportedFilePath) await RNFS.unlink(exportedFilePath)
} }
} }
deleteAppData = async () => { const deleteAppData = async () => {
const { errors, success } = settings.deleteSegment const { errors, success } = settings.deleteSegment
try { try {
if (!isDbEmpty()) { if (!isDbEmpty()) {
clearDb() clearDb()
} }
await this.deleteExportedFile() await deleteExportedFile()
showToast(success.message) showToast(success.message)
} catch (err) { } catch (err) {
alertError(errors.couldNotDeleteFile) alertError(errors.couldNotDeleteFile)
} }
this.cancelConfirmationWithPassword() cancelConfirmationWithPassword()
} }
cancelConfirmationWithPassword = () => { const cancelConfirmationWithPassword = () => {
this.setState({ isConfirmingWithPassword: false }) setIsConfirmingWithPassword(false)
} }
render() { if (isConfirmingWithPassword && isDeletingData) {
const { isConfirmingWithPassword } = this.state
const { isDeletingData } = this.props
if (isConfirmingWithPassword && isDeletingData) {
return (
<ConfirmWithPassword
onSuccess={this.deleteAppData}
onCancel={this.cancelConfirmationWithPassword}
/>
)
}
return ( return (
<Button isCTA onPress={this.alertBeforeDeletion}> <ConfirmWithPassword
{settings.deleteSegment.title} onSuccess={deleteAppData}
</Button> onCancel={cancelConfirmationWithPassword}
/>
) )
} }
return (
<Button isCTA onPress={alertBeforeDeletion}>
{settings.deleteSegment.title}
</Button>
)
} }
DeleteData.propTypes = { DeleteData.propTypes = {
isDeletingData: PropTypes.bool, isDeletingData: PropTypes.bool,
onStartDeletion: PropTypes.func.isRequired, onStartDeletion: PropTypes.func.isRequired,
} }
export default DeleteData
+39 -61
View File
@@ -1,4 +1,4 @@
import React, { Component } from 'react' import React, { useState } from 'react'
import AppLoadingView from '../../common/app-loading' import AppLoadingView from '../../common/app-loading'
import AppPage from '../../common/app-page' import AppPage from '../../common/app-page'
@@ -13,78 +13,56 @@ import DeleteData from './delete-data'
import labels from '../../../i18n/en/settings' import labels from '../../../i18n/en/settings'
import { ACTION_DELETE, ACTION_EXPORT, ACTION_IMPORT } from '../../../config' import { ACTION_DELETE, ACTION_EXPORT, ACTION_IMPORT } from '../../../config'
export default class DataManagement extends Component { const DataManagement = () => {
constructor(props) { const [isLoading, setIsLoading] = useState(false)
super(props) const [currentAction, setCurrentAction] = useState(null)
this.state = { const startImportFlow = async (shouldDeleteExistingData) => {
isLoading: false, setIsLoading(true)
currentAction: null,
}
}
startLoading = () => {
this.setState({ isLoading: true })
}
endLoading = () => {
this.setState({ isLoading: false })
}
startImportFlow = async (shouldDeleteExistingData) => {
this.startLoading()
const fileContent = await getFileContent() const fileContent = await getFileContent()
if (fileContent) { if (fileContent) {
await importData(shouldDeleteExistingData, fileContent) await importData(shouldDeleteExistingData, fileContent)
} }
this.endLoading() setIsLoading(false)
} }
startExport = () => { const startExport = () => {
this.setCurrentAction(ACTION_EXPORT) setCurrentAction(ACTION_EXPORT)
openShareDialogAndExport() openShareDialogAndExport()
} }
startImport = () => { const startImport = () => {
this.setCurrentAction(ACTION_IMPORT) setCurrentAction(ACTION_IMPORT)
openImportDialog(this.startImportFlow) openImportDialog(startImportFlow)
} }
setCurrentAction = (action) => { if (isLoading) return <AppLoadingView />
this.setState({ currentAction: action })
}
render() { const isDeletingData = currentAction === ACTION_DELETE
const { currentAction, isLoading } = this.state
const isDeletingData = currentAction === ACTION_DELETE
return ( return (
<React.Fragment> <AppPage>
{isLoading && <AppLoadingView />} <Segment title={labels.export.button}>
{!isLoading && ( <AppText>{labels.export.segmentExplainer}</AppText>
<AppPage> <Button isCTA onPress={startExport}>
<Segment title={labels.export.button}> {labels.export.button}
<AppText>{labels.export.segmentExplainer}</AppText> </Button>
<Button isCTA onPress={this.startExport}> </Segment>
{labels.export.button} <Segment title={labels.import.button}>
</Button> <AppText>{labels.import.segmentExplainer}</AppText>
</Segment> <Button isCTA onPress={startImport}>
<Segment title={labels.import.button}> {labels.import.button}
<AppText>{labels.import.segmentExplainer}</AppText> </Button>
<Button isCTA onPress={this.startImport}> </Segment>
{labels.import.button} <Segment title={labels.deleteSegment.title} last>
</Button> <AppText>{labels.deleteSegment.explainer}</AppText>
</Segment> <DeleteData
<Segment title={labels.deleteSegment.title} last> isDeletingData={isDeletingData}
<AppText>{labels.deleteSegment.explainer}</AppText> onStartDeletion={() => setCurrentAction(ACTION_DELETE)}
<DeleteData />
isDeletingData={isDeletingData} </Segment>
onStartDeletion={() => this.setCurrentAction(ACTION_DELETE)} </AppPage>
/> )
</Segment>
</AppPage>
)}
</React.Fragment>
)
}
} }
export default DataManagement
+40 -45
View File
@@ -1,4 +1,4 @@
import React, { Component } from 'react' import React, { useState } from 'react'
import { Platform, StyleSheet, View } from 'react-native' import { Platform, StyleSheet, View } from 'react-native'
import AppIcon from '../../common/app-icon' import AppIcon from '../../common/app-icon'
@@ -12,58 +12,53 @@ import { useCervixObservable, saveUseCervix } from '../../../local-storage'
import { Colors, Spacing, Typography } from '../../../styles' import { Colors, Spacing, Typography } from '../../../styles'
import labels from '../../../i18n/en/settings' import labels from '../../../i18n/en/settings'
export default class Settings extends Component { const Settings = () => {
constructor(props) { const [shouldUseCervix, setShouldUseCervix] = useState(
super(props) useCervixObservable.value
)
this.state = { const onCervixToggle = (value) => {
shouldUseCervix: useCervixObservable.value, setShouldUseCervix(value)
}
}
onCervixToggle = (value) => {
this.setState({ shouldUseCervix: value })
saveUseCervix(value) saveUseCervix(value)
} }
render() { const cervixText = shouldUseCervix
const { shouldUseCervix } = this.state ? labels.useCervix.cervixModeOn
const cervixText = shouldUseCervix : labels.useCervix.cervixModeOff
? labels.useCervix.cervixModeOn
: labels.useCervix.cervixModeOff
return ( return (
<AppPage> <AppPage>
<Segment title={labels.useCervix.title}> <Segment title={labels.useCervix.title}>
<AppSwitch <AppSwitch
onToggle={this.onCervixToggle} onToggle={onCervixToggle}
text={cervixText} text={cervixText}
value={shouldUseCervix} value={shouldUseCervix}
/>
</Segment>
{/* for iOS disabled temporarily, TODO https://gitlab.com/bloodyhealth/drip/-/issues/545 */}
{Platform.OS !== 'ios' && (
<Segment title={labels.tempScale.segmentTitle}>
<AppText>{labels.tempScale.segmentExplainer}</AppText>
<TemperatureSlider />
</Segment>
)}
<Segment last>
<View style={styles.line}>
<AppIcon
color={Colors.purple}
name="info-with-circle"
style={styles.icon}
/> />
</Segment> <AppText style={styles.title}>{labels.preOvu.title}</AppText>
{/* for iOS disabled temporarily, TODO https://gitlab.com/bloodyhealth/drip/-/issues/545 */} </View>
{Platform.OS !== 'ios' && ( <AppText>{labels.preOvu.note}</AppText>
<Segment title={labels.tempScale.segmentTitle}> </Segment>
<AppText>{labels.tempScale.segmentExplainer}</AppText> </AppPage>
<TemperatureSlider /> )
</Segment>
)}
<Segment last>
<View style={styles.line}>
<AppIcon
color={Colors.purple}
name="info-with-circle"
style={styles.icon}
/>
<AppText style={styles.title}>{labels.preOvu.title}</AppText>
</View>
<AppText>{labels.preOvu.note}</AppText>
</Segment>
</AppPage>
)
}
} }
export default Settings
const styles = StyleSheet.create({ const styles = StyleSheet.create({
icon: { icon: {
marginRight: Spacing.base, marginRight: Spacing.base,
@@ -1,4 +1,4 @@
import React, { Component } from 'react' import React, { useState } from 'react'
import { StyleSheet, View } from 'react-native' import { StyleSheet, View } from 'react-native'
import Slider from '@ptomasroos/react-native-multi-slider' import Slider from '@ptomasroos/react-native-multi-slider'
@@ -10,51 +10,43 @@ import { Colors, Sizes } from '../../../styles'
import labels from '../../../i18n/en/settings' import labels from '../../../i18n/en/settings'
import { TEMP_MIN, TEMP_MAX, TEMP_SLIDER_STEP } from '../../../config' import { TEMP_MIN, TEMP_MAX, TEMP_SLIDER_STEP } from '../../../config'
export default class TemperatureSlider extends Component { const TemperatureSlider = () => {
constructor(props) { const savedValue = scaleObservable.value
super(props) const [minTemperature, setMinTemperature] = useState(savedValue.min)
const [maxTemperature, setMaxTemperature] = useState(savedValue.max)
const { min, max } = scaleObservable.value
this.state = { minTemperature: min, maxTemperature: max }
}
onTemperatureSliderChange = (values) => {
this.setState({
minTemperature: values[0],
maxTemperature: values[1],
})
const onTemperatureSliderChange = ([min, max]) => {
setMinTemperature(min)
setMaxTemperature(max)
try { try {
saveTempScale({ min: values[0], max: values[1] }) saveTempScale({ min, max })
} catch (err) { } catch (err) {
alertError(labels.tempScale.saveError) alertError(labels.tempScale.saveError)
} }
} }
render() { return (
const { minTemperature, maxTemperature } = this.state <View style={styles.container}>
<Slider
return ( customLabel={SliderLabel}
<View style={styles.container}> enableLabel={true}
<Slider markerStyle={styles.marker}
customLabel={SliderLabel} markerOffsetY={Sizes.tiny}
enableLabel={true} max={TEMP_MAX}
markerStyle={styles.marker} min={TEMP_MIN}
markerOffsetY={Sizes.tiny} onValuesChange={onTemperatureSliderChange}
max={TEMP_MAX} selectedStyle={styles.sliderAccentBackground}
min={TEMP_MIN} step={TEMP_SLIDER_STEP}
onValuesChange={this.onTemperatureSliderChange} trackStyle={styles.slider}
selectedStyle={styles.sliderAccentBackground} unselectedStyle={styles.sliderBackground}
step={TEMP_SLIDER_STEP} values={[minTemperature, maxTemperature]}
trackStyle={styles.slider} />
unselectedStyle={styles.sliderBackground} </View>
values={[minTemperature, maxTemperature]} )
/>
</View>
)
}
} }
export default TemperatureSlider
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
alignItems: 'center', alignItems: 'center',