1import * as ScreenCapture from 'expo-screen-capture';
2import React from 'react';
3import { FlatList, StyleSheet, Text, View } from 'react-native';
4
5import HeadingText from '../components/HeadingText';
6import MonoText from '../components/MonoText';
7import TitleSwitch from '../components/TitledSwitch';
8
9function useScreenCapture(onCapture: () => void) {
10  React.useEffect(() => {
11    const listener = ScreenCapture.addScreenshotListener(onCapture);
12    return () => {
13      listener.remove();
14    };
15  }, []);
16}
17
18export default function ScreenCaptureScreen() {
19  const [isEnabled, setEnabled] = React.useState(true);
20  const [timestamps, setTimestamps] = React.useState<Date[]>([]);
21
22  React.useEffect(() => {
23    if (isEnabled) {
24      ScreenCapture.allowScreenCaptureAsync();
25    } else {
26      ScreenCapture.preventScreenCaptureAsync();
27    }
28  }, [isEnabled]);
29
30  useScreenCapture(() => setTimestamps((timestamps) => timestamps.concat([new Date()])));
31
32  return (
33    <View style={styles.container}>
34      <TitleSwitch title="Screen Capture Enabled" value={isEnabled} setValue={setEnabled} />
35      <Text style={{ padding: 8 }}>
36        Take a screenshot or attempt to record the screen to test that the image is/isn't obscured.
37      </Text>
38      <HeadingText>Capture Timestamps</HeadingText>
39      <Text>Take a screenshot to test if the listener works.</Text>
40      <FlatList
41        data={timestamps}
42        keyExtractor={(item) => item.getTime() + '-'}
43        renderItem={({ item }) => <MonoText>{item.toLocaleTimeString()}</MonoText>}
44      />
45    </View>
46  );
47}
48
49const styles = StyleSheet.create({
50  container: {
51    flex: 1,
52    alignItems: 'center',
53    justifyContent: 'center',
54  },
55});
56