File size: 2,280 Bytes
78d0e31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Safe clipboard utilities with fallback mechanisms
export class ClipboardManager {
  private static async checkClipboardPermission(): Promise<boolean> {
    if (typeof window === "undefined" || !navigator.clipboard) {
      return false
    }

    try {
      const permission = await navigator.permissions.query({ name: "clipboard-write" as PermissionName })
      return permission.state === "granted" || permission.state === "prompt"
    } catch {
      return false
    }
  }

  private static fallbackCopy(text: string): Promise<boolean> {
    return new Promise((resolve) => {
      try {
        const textArea = document.createElement("textarea")
        textArea.value = text
        textArea.style.position = "fixed"
        textArea.style.left = "-999999px"
        textArea.style.top = "-999999px"
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        const successful = document.execCommand("copy")
        document.body.removeChild(textArea)
        resolve(successful)
      } catch (error) {
        console.error("Fallback copy failed:", error)
        resolve(false)
      }
    })
  }

  static async copyToClipboard(text: string): Promise<{ success: boolean; method: string }> {
    // Only attempt clipboard operations after user gesture
    if (typeof window === "undefined") {
      return { success: false, method: "server-side" }
    }

    // Try modern clipboard API first
    if (navigator.clipboard && window.isSecureContext) {
      try {
        await navigator.clipboard.writeText(text)
        return { success: true, method: "clipboard-api" }
      } catch (error) {
        console.warn("Clipboard API failed, trying fallback:", error)
      }
    }

    // Fallback to execCommand
    const fallbackSuccess = await this.fallbackCopy(text)
    return {
      success: fallbackSuccess,
      method: fallbackSuccess ? "execCommand" : "failed",
    }
  }

  static async readFromClipboard(): Promise<string | null> {
    if (typeof window === "undefined" || !navigator.clipboard) {
      return null
    }

    try {
      const text = await navigator.clipboard.readText()
      return text
    } catch (error) {
      console.warn("Clipboard read failed:", error)
      return null
    }
  }
}