Open History to see the last commit
1import { SymbolView } from "../components/AppSymbol";
2import { memo, useEffect, useRef, useState } from "react";
3import { Alert, Pressable, type ColorValue } from "react-native";
4
5import { tryCopyTextWithHaptic } from "../lib/copyTextWithHaptic";
6
7const COPY_FEEDBACK_DURATION_MS = 1200;
8
9export const CopyTextButton = memo(function CopyTextButton(props: {
10 readonly accessibilityLabel: string;
11 readonly text: string;
12 readonly onCopy?: () => Promise<void>;
13 readonly tintColor?: ColorValue;
14 readonly copiedTintColor?: ColorValue;
15 readonly backgroundColor?: ColorValue;
16 readonly borderColor?: ColorValue;
17 readonly iconSize?: number;
18 readonly buttonSize?: number;
19}) {
20 const [copied, setCopied] = useState(false);
21 const resetTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
22
23 useEffect(
24 () => () => {
25 if (resetTimeoutRef.current) {
26 clearTimeout(resetTimeoutRef.current);
27 }
28 },
29 [],
30 );
31
32 return (
33 <Pressable
34 accessibilityRole="button"
35 accessibilityLabel={copied ? "Copied" : props.accessibilityLabel}
36 disabled={props.text.length === 0}
37 hitSlop={8}
38 onPress={async () => {
39 try {
40 if (props.onCopy) await props.onCopy();
41 else if (!(await tryCopyTextWithHaptic(props.text))) {
42 // A refused clipboard write is the common failure, and silence reads as success.
43 Alert.alert("Could not copy", "Try again.");
44 return;
45 }
46 } catch {
47 Alert.alert("Could not copy", "Try again.");
48 return;
49 }
50 setCopied(true);
51 if (resetTimeoutRef.current) {
52 clearTimeout(resetTimeoutRef.current);
53 }
54 resetTimeoutRef.current = setTimeout(() => {
55 setCopied(false);
56 resetTimeoutRef.current = null;
57 }, COPY_FEEDBACK_DURATION_MS);
58 }}
59 style={({ pressed }) => ({
60 width: props.buttonSize ?? 30,
61 height: props.buttonSize ?? 30,
62 alignItems: "center",
63 justifyContent: "center",
64 borderRadius: 9,
65 borderWidth: props.borderColor ? 1 : 0,
66 borderColor: props.borderColor,
67 backgroundColor: props.backgroundColor,
68 opacity: pressed ? 0.52 : 1,
69 })}
70 >
71 <SymbolView
72 name={
73 copied
74 ? { ios: "checkmark", android: "check" }
75 : { ios: "doc.on.doc", android: "content_copy" }
76 }
77 size={props.iconSize ?? 13}
78 tintColor={copied ? (props.copiedTintColor ?? props.tintColor) : props.tintColor}
79 tintColorClassName={props.tintColor ? undefined : "accent-foreground"}
80 type="monochrome"
81 />
82 </Pressable>
83 );
84});