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

copyTextWithHaptic.ts

70 lines1.7 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​
30export function copyTextWithHaptic(
31 value: string,
32 options: {
33 readonly target?: string;
34 readonly feedback?: "light-impact" | "selection";
35 } = {},
36): void {
37 const target = options.target ?? "text";
38 const feedback = options.feedback ?? "light-impact";
39​
40 void (async () => {
41 try {
42 await Clipboard.setStringAsync(value);
43 } catch (cause) {
44 console.error(
45 new CopyTextClipboardWriteError({
46 target,
47 cause,
48 }),
49 );
50 }
51 })();
52​
53 void (async () => {
54 try {
55 if (feedback === "selection") {
56 await Haptics.selectionAsync();
57 } else {
58 await Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
59 }
60 } catch (cause) {
61 console.error(
62 new CopyTextHapticFeedbackError({
63 target,
64 feedback,
65 cause,
66 }),
67 );
68 }
69 })();