Massive/Alarm.tsx

79 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-07-03 01:50:01 +00:00
import AsyncStorage from '@react-native-async-storage/async-storage';
import React, {useEffect, useState} from 'react';
2022-07-05 00:43:23 +00:00
import {NativeModules, StyleSheet, Text, View} from 'react-native';
2022-07-04 04:03:48 +00:00
import {Button, Modal, Portal} from 'react-native-paper';
2022-07-03 01:50:01 +00:00
2022-07-04 04:03:48 +00:00
export default function Alarm() {
const [show, setShow] = useState(false);
2022-07-03 01:50:01 +00:00
const [seconds, setSeconds] = useState(0);
const [minutes, setMinutes] = useState(0);
2022-07-05 00:43:23 +00:00
let intervalId: number;
2022-07-03 01:50:01 +00:00
useEffect(() => {
if (!show) return;
(async () => {
2022-07-04 04:03:48 +00:00
const next = await AsyncStorage.getItem('nextAlarm');
2022-07-03 01:50:01 +00:00
if (!next) return;
2022-07-05 00:43:23 +00:00
const milliseconds = new Date(next).getTime() - new Date().getTime();
if (milliseconds <= 0) return;
let secondsLeft = milliseconds / 1000;
2022-07-03 06:25:21 +00:00
setSeconds(Math.floor(secondsLeft % 60));
2022-07-03 01:50:01 +00:00
setMinutes(Math.floor(secondsLeft / 60));
intervalId = setInterval(() => {
secondsLeft--;
if (secondsLeft <= 0) return clearInterval(intervalId);
setSeconds(Math.floor(secondsLeft % 60));
setMinutes(Math.floor(secondsLeft / 60));
}, 1000);
})();
2022-07-03 01:50:01 +00:00
return () => clearInterval(intervalId);
}, [show]);
2022-07-03 01:50:01 +00:00
2022-07-05 00:43:23 +00:00
const stop = async () => {
NativeModules.AlarmModule.stop();
clearInterval(intervalId);
setSeconds(0);
setMinutes(0);
await AsyncStorage.setItem('nextAlarm', '');
};
2022-07-03 01:50:01 +00:00
return (
2022-07-04 04:03:48 +00:00
<>
<Portal>
<Modal
visible={show}
style={styles.center}
onDismiss={() => setShow(false)}>
<Text style={[styles.center, styles.title]}>Resting</Text>
<Text style={styles.center}>
{minutes}:{seconds}
</Text>
2022-07-05 00:43:23 +00:00
<View style={{flexDirection: 'row'}}>
<Button icon="close" onPress={() => setShow(false)}>
Close
</Button>
<Button mode="contained" icon="stop" onPress={stop}>
Stop
</Button>
</View>
2022-07-04 04:03:48 +00:00
</Modal>
</Portal>
<Button icon="time" onPress={() => setShow(true)}>
Time left
</Button>
</>
2022-07-03 01:50:01 +00:00
);
}
const styles = StyleSheet.create({
2022-07-04 04:03:48 +00:00
center: {
2022-07-03 01:50:01 +00:00
alignItems: 'center',
2022-07-04 04:03:48 +00:00
alignSelf: 'center',
marginBottom: 10,
2022-07-03 01:50:01 +00:00
},
2022-07-04 04:03:48 +00:00
title: {
fontSize: 18,
2022-07-03 01:50:01 +00:00
},
});