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