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

copyTextWithHaptic.ts

80 lines2.0 KB

1import * as Schema from "effect/Schema";
2import * as Clipboard from "expo-clipboard";
3import * as Haptics from "expo-haptics";
4​
5export class CopyTextClipboardWriteError extends Schema.TaggedErrorClass<CopyTextClipboardWriteError>()(
6 "CopyTextClipboardWriteError",
7 {
8 target: Schema.String,
9 cause: Schema.Defect(),
10 },
11) {
12 override get message(): string {
13 return `Failed to copy ${this.target} to the clipboard.`;
14 }
16​
17export class CopyTextHapticFeedbackError extends Schema.TaggedErrorClass<CopyTextHapticFeedbackError>()(
18 "CopyTextHapticFeedbackError",
19 {
20 target: Schema.String,
21 feedback: Schema.Literals(["light-impact", "selection"]),
22 cause: Schema.Defect(),
23 },
24) {
25 override get message(): string {
26 return `Failed to trigger ${this.feedback} haptic feedback after copying ${this.target}.`;
27 }
29​
30interface CopyTextWithHapticOptions {
31 readonly target?: string;
32 readonly feedback?: "light-impact" | "selection";
34​
35export async function tryCopyTextWithHaptic(
36 value: string,
37 options: CopyTextWithHapticOptions = {},
38): Promise<boolean> {
39 const target = options.target ?? "text";
40 const feedback = options.feedback ?? "light-impact";
41​
42 const clipboardWrite = (async () => {
43 try {
44 await Clipboard.setStringAsync(value);
45 return true;
46 } catch (cause) {
47 console.error(
48 new CopyTextClipboardWriteError({
49 target,
50 cause,
51 }),
52 );
53 return false;
54 }
55 })();
56​
57 void (async () => {
58 try {
59 if (feedback === "selection") {
60 await Haptics.selectionAsync();
61 } else {
62 await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
63 }
64 } catch (cause) {
65 console.error(
66 new CopyTextHapticFeedbackError({
67 target,
68 feedback,
69 cause,
70 }),
71 );
72 }
73 })();
74​
75 return await clipboardWrite;
77​
78export function copyTextWithHaptic(value: string, options: CopyTextWithHapticOptions = {}): void {
79 void tryCopyTextWithHaptic(value, options);