summaryrefslogtreecommitdiff
path: root/src/components/SmartClipboardButton.tsx
blob: 229560d355238f42bb6573000a1e7b0204049759 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import { useState } from "react";
import { PanelSectionRow, ButtonItem } from "@decky/ui";
import { FaClipboard, FaRocket } from "react-icons/fa";
import { toaster } from "@decky/api";
import { getLaunchOption, copyToSystemClipboard } from "../api/lsfgApi";

export function SmartClipboardButton() {
  const [isLoading, setIsLoading] = useState(false);

  const getLaunchOptionText = async (): Promise<string> => {
    try {
      const result = await getLaunchOption();
      return result.launch_option || "~/lsfg %command%";
    } catch (error) {
      return "~/lsfg %command%";
    }
  };

  const copyToClipboard = async () => {
    if (isLoading) return;
    
    setIsLoading(true);
    try {
      const text = await getLaunchOptionText();
      
      // Strategy 1: Try direct navigator.clipboard first (fastest)
      let directSuccess = false;
      try {
        await navigator.clipboard.writeText(text);
        // Verify it worked
        const readBack = await navigator.clipboard.readText();
        directSuccess = readBack === text;
      } catch (e) {
        // Direct clipboard failed, will try alternatives
      }

      if (directSuccess) {
        toaster.toast({
          title: "Copied to Clipboard!",
          body: "Launch option ready to paste"
        });
        return;
      }

      // Strategy 2: Try backend system clipboard
      try {
        const result = await copyToSystemClipboard(text);
        if (result.success) {
          toaster.toast({
            title: "Copied to Clipboard!",
            body: `Using ${result.method || "system clipboard"}`
          });
          return;
        }
      } catch (e) {
        // Backend failed, fall back to browser
      }

      // Strategy 3: Fall back to optimized browser window
      const htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <title>Quick Copy - Steam Deck Clipboard Helper</title>
          <style>
            body { 
              font-family: 'Motiva Sans', system-ui, sans-serif; 
              background: linear-gradient(135deg, #1e2328 0%, #2a475e 100%); 
              color: white; 
              padding: 20px; 
              margin: 0;
              display: flex;
              align-items: center;
              justify-content: center;
              min-height: 100vh;
            }
            .container { 
              background: rgba(42, 71, 94, 0.9);
              padding: 30px; 
              border-radius: 12px; 
              text-align: center; 
              box-shadow: 0 8px 32px rgba(0,0,0,0.3);
              border: 1px solid rgba(255,255,255,0.1);
              max-width: 500px;
              width: 100%;
            }
            h2 { 
              margin-top: 0; 
              color: #66c0f4; 
              font-size: 24px;
            }
            .launch-option {
              background: rgba(0,0,0,0.3);
              padding: 15px;
              border-radius: 8px;
              font-family: 'Fira Code', 'Courier New', monospace;
              font-size: 16px;
              margin: 20px 0;
              word-break: break-all;
              border: 1px solid rgba(102, 192, 244, 0.3);
            }
            .status { 
              margin: 20px 0; 
              font-size: 16px; 
              min-height: 24px;
            }
            .success { color: #66bb6a; }
            .error { color: #f44336; }
            button { 
              background: linear-gradient(135deg, #417a9b 0%, #67c1f5 100%);
              color: white;
              border: none;
              padding: 12px 24px; 
              font-size: 16px; 
              border-radius: 6px;
              cursor: pointer;
              margin: 8px;
              transition: all 0.2s;
              font-family: inherit;
            }
            button:hover { 
              background: linear-gradient(135deg, #4e8bb8 0%, #7bc8f7 100%);
              transform: translateY(-1px);
            }
            button:active {
              transform: translateY(0px);
            }
            .close-timer {
              font-size: 14px;
              opacity: 0.7;
              margin-top: 15px;
            }
          </style>
        </head>
        <body>
          <div class="container">
            <h2>🚀 Steam Deck Clipboard Helper</h2>
            <div>Copy this launch option for your Steam games:</div>
            <div class="launch-option">${text}</div>
            <div id="status" class="status">⏳ Copying to clipboard...</div>
            <div>
              <button onclick="copyAndClose()" id="copyBtn">Copy & Close</button>
              <button onclick="window.close()">Close</button>
            </div>
            <div class="close-timer" id="timer"></div>
          </div>
          <script>
            const textToCopy = ${JSON.stringify(text)};
            let copied = false;
            let autoCloseTimer = null;
            
            async function autoCopy() {
              try {
                await navigator.clipboard.writeText(textToCopy);
                // Verify it worked
                const readBack = await navigator.clipboard.readText();
                if (readBack === textToCopy) {
                  document.getElementById('status').innerHTML = '<span class="success">✅ Successfully copied to clipboard!</span>';
                  copied = true;
                  startAutoClose();
                } else {
                  document.getElementById('status').innerHTML = '<span class="error">⚠️ Copy may have failed - use button below</span>';
                }
              } catch (e) {
                document.getElementById('status').innerHTML = '<span class="error">❌ Auto-copy failed - click "Copy & Close" below</span>';
              }
            }
            
            async function copyAndClose() {
              try {
                await navigator.clipboard.writeText(textToCopy);
                const readBack = await navigator.clipboard.readText();
                if (readBack === textToCopy) {
                  window.close();
                } else {
                  alert('Copy verification failed. Please try again or copy manually.');
                }
              } catch (e) {
                alert('Copy failed: ' + e.message);
              }
            }
            
            function startAutoClose() {
              let seconds = 3;
              const timerEl = document.getElementById('timer');
              timerEl.textContent = \`Window will close in \${seconds} seconds...\`;
              
              autoCloseTimer = setInterval(() => {
                seconds--;
                if (seconds <= 0) {
                  clearInterval(autoCloseTimer);
                  window.close();
                } else {
                  timerEl.textContent = \`Window will close in \${seconds} seconds...\`;
                }
              }, 1000);
            }
            
            // Auto-copy on load
            window.addEventListener('load', autoCopy);
          </script>
        </body>
        </html>
      `;

      const dataUrl = 'data:text/html;charset=utf-8,' + encodeURIComponent(htmlContent);
      window.open(dataUrl, '_blank', 'width=600,height=400,scrollbars=no,resizable=yes');
      
      toaster.toast({
        title: "Browser Helper Opened",
        body: "Clipboard helper window opened with auto-copy"
      });

    } catch (error) {
      toaster.toast({
        title: "Copy Failed",
        body: `Error: ${String(error)}`
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <PanelSectionRow>
      <ButtonItem
        layout="below"
        onClick={copyToClipboard}
        disabled={isLoading}
      >
        <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
          {isLoading ? <FaRocket style={{ animation: "spin 1s linear infinite" }} /> : <FaClipboard />}
          <div>{isLoading ? "Copying..." : "Smart Clipboard Copy"}</div>
        </div>
      </ButtonItem>
      <style>{`
        @keyframes spin {
          from { transform: rotate(0deg); }
          to { transform: rotate(360deg); }
        }
      `}</style>
    </PanelSectionRow>
  );
}