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

CopyTextButton.tsx

87 lines2.8 KB

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 Dialog.alert("Could not copy", "Try again.");
47 return;
48 }
49 } catch {
50 Dialog.alert("Could not copy", "Try again.");
51 return;
52 }
53 setCopied(true);
54 if (resetTimeoutRef.current) {
55 clearTimeout(resetTimeoutRef.current);
56 }
57 resetTimeoutRef.current = setTimeout(() => {
58 setCopied(false);
59 resetTimeoutRef.current = null;
60 }, COPY_FEEDBACK_DURATION_MS);
61 }}
62 style={({ pressed }) => ({
63 width: props.buttonSize ?? 30,
64 height: props.buttonSize ?? 30,
65 alignItems: "center",
66 justifyContent: "center",
67 borderRadius: 9,
68 borderWidth: props.borderColor ? 1 : 0,
69 borderColor: props.borderColor,
70 backgroundColor: props.backgroundColor,
71 opacity: pressed ? 0.52 : 1,
72 })}
73 >
74 <SymbolView
75 name={
76 copied
77 ? { ios: "checkmark", android: "check" }
78 : { ios: "doc.on.doc", android: "content_copy" }
79 }
80 size={props.iconSize ?? 13}
81 tintColor={copied ? (props.copiedTintColor ?? props.tintColor) : props.tintColor}
82 tintColorClassName={props.tintColor ? undefined : "accent-foreground"}
83 type="monochrome"
84 />
85 </Pressable>
86 );
87});