Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CopyTextButton.tsx

73 lines2.2 KB

1import { SymbolView } from "expo-symbols";
2import * as Clipboard from "expo-clipboard";
3import * as Haptics from "expo-haptics";
4import { memo, useEffect, useRef, useState } from "react";
5import { Pressable, type ColorValue } from "react-native";
6​
7const COPY_FEEDBACK_DURATION_MS = 1200;
8​
9function copyTextWithHaptic(value: string): void {
10 void Clipboard.setStringAsync(value);
11 void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
13​
14export const CopyTextButton = memo(function CopyTextButton(props: {
15 readonly accessibilityLabel: string;
16 readonly text: string;
17 readonly tintColor: ColorValue;
18 readonly copiedTintColor?: ColorValue;
19 readonly backgroundColor?: ColorValue;
20 readonly borderColor?: ColorValue;
21 readonly iconSize?: number;
22 readonly buttonSize?: number;
23}) {
24 const [copied, setCopied] = useState(false);
25 const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
26​
27 useEffect(
28 () => () => {
29 if (resetTimeoutRef.current) {
30 clearTimeout(resetTimeoutRef.current);
31 }
32 },
33 [],
34 );
35​
36 return (
37 <Pressable
38 accessibilityRole="button"
39 accessibilityLabel={copied ? "Copied" : props.accessibilityLabel}
40 disabled={props.text.length === 0}
41 hitSlop={8}
42 onPress={() => {
43 copyTextWithHaptic(props.text);
44 setCopied(true);
45 if (resetTimeoutRef.current) {
46 clearTimeout(resetTimeoutRef.current);
47 }
48 resetTimeoutRef.current = setTimeout(() => {
49 setCopied(false);
50 resetTimeoutRef.current = null;
51 }, COPY_FEEDBACK_DURATION_MS);
52 }}
53 style={({ pressed }) => ({
54 width: props.buttonSize ?? 30,
55 height: props.buttonSize ?? 30,
56 alignItems: "center",
57 justifyContent: "center",
58 borderRadius: 9,
59 borderWidth: props.borderColor ? 1 : 0,
60 borderColor: props.borderColor,
61 backgroundColor: props.backgroundColor,
62 opacity: pressed ? 0.52 : 1,
63 })}
64 >
65 <SymbolView
66 name={copied ? "checkmark" : "doc.on.doc"}
67 size={props.iconSize ?? 13}
68 tintColor={copied ? (props.copiedTintColor ?? props.tintColor) : props.tintColor}
69 type="monochrome"
70 />
71 </Pressable>
72 );
73});