-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathresponsive-toolbar.tsx
432 lines (392 loc) · 13.1 KB
/
responsive-toolbar.tsx
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
'use client';
import { useEffect, useRef, useState, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import {
Code as CodeIcon,
Copy,
Download,
Eye,
GitFork,
Github,
Share2,
Terminal,
Loader,
} from 'lucide-react';
import { useAuthContext } from '@/providers/AuthProvider';
import { logger } from '@/app/log/logger';
import { useMutation, useQuery, gql } from '@apollo/client';
import { toast } from 'sonner';
import { SYNC_PROJECT_TO_GITHUB, GET_PROJECT } from '../../../graphql/request';
import { authenticatedFetch } from '@/lib/authenticatedFetch';
interface ResponsiveToolbarProps {
isLoading: boolean;
activeTab: 'preview' | 'code' | 'console';
setActiveTab: (tab: 'preview' | 'code' | 'console') => void;
projectId?: string;
}
const ResponsiveToolbar = ({
isLoading,
activeTab,
setActiveTab,
projectId,
}: ResponsiveToolbarProps) => {
const containerRef = useRef(null);
const [containerWidth, setContainerWidth] = useState(700);
const [visibleTabs, setVisibleTabs] = useState(3);
const [compactIcons, setCompactIcons] = useState(false);
const [isDownloading, setIsDownloading] = useState(false);
const { token, user, refreshUserInfo } = useAuthContext();
// Poll for GitHub installation status when needed
const [isPollingGitHub, setIsPollingGitHub] = useState(false);
// Apollo mutations and queries
const [syncProject, { loading: isPublishingToGitHub }] = useMutation(
SYNC_PROJECT_TO_GITHUB,
{
onCompleted: (data) => {
const syncResult = data.syncProjectToGitHub;
toast.success('Successfully published to GitHub!');
// Offer to open the repo in a new tab
const repoUrl = syncResult.githubRepoUrl;
console.log('GitHub repo URL:', repoUrl);
if (repoUrl) {
const shouldOpen = window.confirm(
'Would you like to open the GitHub repository?'
);
if (shouldOpen) {
window.open(repoUrl, '_blank');
}
}
},
onError: (error) => {
logger.error('Error publishing to GitHub:', error);
toast.error(`Error publishing to GitHub: ${error.message}`);
},
}
);
// Query to check if the project is already synced
const { data: projectData } = useQuery(GET_PROJECT, {
variables: { projectId },
skip: !projectId,
fetchPolicy: 'cache-and-network',
});
// Determine if GitHub sync is complete based on query data
const isGithubSyncComplete =
projectData?.getProject?.isSyncedWithGitHub || false;
const githubRepoUrl = projectData?.getProject?.githubRepoUrl || '';
// Observe container width changes
useEffect(() => {
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
setContainerWidth(entry.contentRect.width);
}
});
if (containerRef.current) {
observer.observe(containerRef.current);
}
return () => observer.disconnect();
}, []);
// Adjust visible tabs and icon style based on container width
useEffect(() => {
if (containerWidth > 650) {
setVisibleTabs(3);
setCompactIcons(false);
} else if (containerWidth > 550) {
setVisibleTabs(2);
setCompactIcons(false);
} else if (containerWidth > 450) {
setVisibleTabs(1);
setCompactIcons(true);
} else {
setVisibleTabs(0);
setCompactIcons(true);
}
}, [containerWidth]);
// Poll for GitHub installation completion
useEffect(() => {
let pollInterval: NodeJS.Timeout;
if (isPollingGitHub) {
pollInterval = setInterval(async () => {
console.log('Polling backend for GitHub installation status...');
try {
// Call to refresh user info (from backend)
await refreshUserInfo();
// Check if user now has installation ID
if (user?.githubInstallationId) {
console.log('GitHub installation complete!');
setIsPollingGitHub(false);
clearInterval(pollInterval);
}
} catch (error) {
logger.error('Polling error:', error);
setIsPollingGitHub(false);
}
}, 3000); // Poll every 3s
}
return () => {
if (pollInterval) clearInterval(pollInterval);
};
}, [isPollingGitHub, user?.githubInstallationId, refreshUserInfo]);
const handlePublishToGitHub = async () => {
// If already publishing, do nothing
if (isPublishingToGitHub) return;
// If the user hasn't installed the GitHub App yet
if (!user?.githubInstallationId) {
try {
// Prompt the user to install the GitHub App
const shouldInstall = window.confirm(
'You need to install the GitHub App to publish your project. Would you like to do this now?'
);
if (shouldInstall) {
// Start polling for installation completion
setIsPollingGitHub(true);
// This format ensures GitHub will prompt the user to choose where to install
const installUrl = `https://github.com/apps/codefox-project-fork/installations/new`;
window.open(installUrl, '_blank');
}
return;
} catch (error) {
logger.error('Error opening GitHub installation:', error);
setIsPollingGitHub(false);
toast.error(
'Error opening GitHub installation page. Please try again.'
);
return;
}
}
// Ensure we have a project ID
if (!projectId) {
toast.error('Cannot publish: No project ID available');
return;
}
// If already synced and we have the URL, offer to open it
if (isGithubSyncComplete && githubRepoUrl) {
const shouldOpen = window.confirm(
'This project is already published to GitHub. Would you like to open the repository?'
);
if (shouldOpen) {
window.open(projectData.getProject.githubRepoUrl, '_blank');
}
return;
}
// Execute the mutation
try {
await syncProject({
variables: {
projectId,
},
});
} catch (error) {
// Error is handled by the mutation's onError callback
logger.error('Error in handlePublishToGitHub:', error);
}
};
const handleDownload = async () => {
// If projectId is available, initiate download
if (projectId && !isDownloading) {
setIsDownloading(true);
try {
// Create a hidden anchor element for download
const a = document.createElement('a');
const backendUrl =
process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8080';
// Set the download URL with credentials included
const downloadUrl = `${backendUrl}/download/project/${projectId}`;
const headers = new Headers();
if (token) {
headers.append('Authorization', `Bearer ${token}`);
}
// Fetch with credentials to ensure auth is included
// const response = await fetch(downloadUrl, {
// method: 'GET',
// headers: headers,
// });
// Use authenticatedFetch which handles token refresh
const response = await authenticatedFetch(downloadUrl, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`Download failed: ${response.status}`);
}
// Get the blob from the response
const blob = await response.blob();
// Create a URL for the blob
const url = window.URL.createObjectURL(blob);
// Set the anchor's href to the blob URL
a.href = url;
// Set download attribute with filename from Content-Disposition header or default
const contentDisposition = response.headers.get('Content-Disposition');
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(contentDisposition || '');
const filename =
matches && matches[1]
? matches[1].replace(/['"]/g, '')
: `project-${projectId}.zip`;
a.download = filename;
// Append to the document
document.body.appendChild(a);
// Click the anchor to start download
a.click();
// Clean up
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error('Error downloading project:', error);
// Could add a toast notification here
} finally {
setIsDownloading(false);
}
}
};
return (
<div
ref={containerRef}
className="flex items-center justify-between p-4 border-b w-full bg-background/60 backdrop-blur supports-[backdrop-filter]:bg-background/60"
>
<div className="flex items-center space-x-2">
<Button
variant={activeTab === 'preview' ? 'default' : 'outline'}
size="sm"
className="text-sm"
onClick={() => setActiveTab('preview')}
disabled={isLoading}
>
<Eye className="w-3 h-3 mr-1" />
Preview
</Button>
{visibleTabs >= 2 && (
<Button
variant={activeTab === 'code' ? 'default' : 'outline'}
size="sm"
className="text-sm"
onClick={() => setActiveTab('code')}
disabled={isLoading}
>
<CodeIcon className="w-3 h-3 mr-1" />
Code
</Button>
)}
{visibleTabs >= 3 && (
<Button
variant={activeTab === 'console' ? 'default' : 'outline'}
size="sm"
className="text-sm"
onClick={() => setActiveTab('console')}
disabled={isLoading}
>
<Terminal className="w-3 h-3 mr-1" />
Console
</Button>
)}
</div>
<div className="flex items-center space-x-2">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
className={`p-0 ${compactIcons ? 'hidden' : 'block'}`}
disabled={isLoading}
>
<Copy className="w-3 h-3" />
</Button>
</div>
<div className="flex items-center space-x-2">
{!compactIcons && (
<>
{/*
//TODO: FIX ME (ALLEN)
<Button
variant="outline"
size="sm"
className="text-sm"
disabled={isLoading}
>
Supabase
</Button>
<Button
variant="outline"
size="sm"
className="text-sm"
disabled={isLoading}
>
Publish
</Button> */}
<Button
variant="outline"
size="sm"
className="text-sm"
disabled={isLoading || !projectId || isDownloading}
onClick={handleDownload}
>
{isDownloading ? (
<Loader className="w-3 h-3 mr-1 animate-spin" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Download
</Button>
<Button
variant={isGithubSyncComplete ? 'secondary' : 'outline'}
size="sm"
className="text-sm"
disabled={
isLoading ||
!projectId ||
isPublishingToGitHub ||
isPollingGitHub
}
onClick={handlePublishToGitHub}
>
{isPublishingToGitHub ? (
<Loader className="w-3 h-3 mr-1 animate-spin" />
) : (
<Github className="w-3 h-3 mr-1" />
)}
{isGithubSyncComplete ? 'View on GitHub' : 'GitHub'}
</Button>
</>
)}
{compactIcons && (
<>
{/*
//TODO: FIX ME (ALLEN)
<Button variant="outline" className="p-2" disabled={isLoading}>
<Share2 className="w-4 h-4" />
</Button> */}
<Button
variant="outline"
size="icon"
className="h-8 w-8"
disabled={isLoading || !projectId || isDownloading}
onClick={handleDownload}
>
{isDownloading ? (
<Loader className="w-3 h-3 animate-spin" />
) : (
<Download className="w-3 h-3" />
)}
</Button>
<Button
variant={isGithubSyncComplete ? 'secondary' : 'outline'}
className="p-2"
disabled={
isLoading ||
!projectId ||
isPublishingToGitHub ||
isPollingGitHub
}
onClick={handlePublishToGitHub}
>
{isPublishingToGitHub ? (
<Loader className="w-3 h-3 animate-spin" />
) : (
<Github className="w-3 h-3" />
)}
</Button>
</>
)}
</div>
</div>
</div>
);
};
export default ResponsiveToolbar;