-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl-shortener.tsx
More file actions
506 lines (475 loc) · 20.3 KB
/
Copy pathurl-shortener.tsx
File metadata and controls
506 lines (475 loc) · 20.3 KB
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import React, { useState, useEffect } from 'react';
import { Link2, BarChart3, Copy, Check, TrendingUp, Trash2, Edit2, Save, X, Calendar, Search, Download, QrCode } from 'lucide-react';
export default function URLShortener() {
const [urls, setUrls] = useState([]);
const [longUrl, setLongUrl] = useState('');
const [customAlias, setCustomAlias] = useState('');
const [urlTitle, setUrlTitle] = useState('');
const [copied, setCopied] = useState('');
const [view, setView] = useState('shorten');
const [editingId, setEditingId] = useState(null);
const [editTitle, setEditTitle] = useState('');
const [searchTerm, setSearchTerm] = useState('');
const [showQR, setShowQR] = useState(null);
const [dateFilter, setDateFilter] = useState('all');
useEffect(() => {
loadUrls();
}, []);
const loadUrls = async () => {
try {
const keys = await window.storage.list('url:');
if (keys && keys.keys) {
const loadedUrls = [];
for (const key of keys.keys) {
const result = await window.storage.get(key);
if (result) {
loadedUrls.push(JSON.parse(result.value));
}
}
setUrls(loadedUrls.sort((a, b) => b.created - a.created));
}
} catch (error) {
console.log('No URLs found yet');
}
};
const generateShortCode = () => {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
};
const generateQRCode = (text) => {
const size = 200;
return `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&data=${encodeURIComponent(text)}`;
};
const handleShorten = async () => {
if (!longUrl.trim()) return;
const shortCode = customAlias.trim() || generateShortCode();
// Check if custom alias already exists
if (customAlias.trim()) {
const existing = urls.find(u => u.id === shortCode);
if (existing) {
alert('This custom alias is already taken. Please choose another one.');
return;
}
}
const newUrl = {
id: shortCode,
longUrl: longUrl.trim(),
shortUrl: `short.ly/${shortCode}`,
title: urlTitle.trim() || 'Untitled',
clicks: 0,
clickHistory: [],
created: Date.now(),
lastClicked: null
};
try {
await window.storage.set(`url:${shortCode}`, JSON.stringify(newUrl));
setUrls([newUrl, ...urls]);
setLongUrl('');
setCustomAlias('');
setUrlTitle('');
} catch (error) {
console.error('Failed to save URL:', error);
}
};
const handleClick = async (id) => {
const updatedUrls = urls.map(url => {
if (url.id === id) {
const now = Date.now();
const updated = {
...url,
clicks: url.clicks + 1,
lastClicked: now,
clickHistory: [...(url.clickHistory || []), now]
};
window.storage.set(`url:${id}`, JSON.stringify(updated));
return updated;
}
return url;
});
setUrls(updatedUrls);
};
const handleDelete = async (id) => {
if (confirm('Are you sure you want to delete this URL?')) {
try {
await window.storage.delete(`url:${id}`);
setUrls(urls.filter(url => url.id !== id));
} catch (error) {
console.error('Failed to delete URL:', error);
}
}
};
const handleEdit = (url) => {
setEditingId(url.id);
setEditTitle(url.title);
};
const handleSaveEdit = async (id) => {
const updatedUrls = urls.map(url => {
if (url.id === id) {
const updated = { ...url, title: editTitle };
window.storage.set(`url:${id}`, JSON.stringify(updated));
return updated;
}
return url;
});
setUrls(updatedUrls);
setEditingId(null);
};
const copyToClipboard = (text) => {
navigator.clipboard.writeText(text);
setCopied(text);
setTimeout(() => setCopied(''), 2000);
};
const exportData = () => {
const data = JSON.stringify(urls, null, 2);
const blob = new Blob([data], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `url-shortener-data-${Date.now()}.json`;
a.click();
};
const getFilteredUrls = () => {
let filtered = urls;
// Search filter
if (searchTerm) {
filtered = filtered.filter(url =>
url.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
url.longUrl.toLowerCase().includes(searchTerm.toLowerCase()) ||
url.shortUrl.toLowerCase().includes(searchTerm.toLowerCase())
);
}
// Date filter
if (dateFilter !== 'all') {
const now = Date.now();
const day = 24 * 60 * 60 * 1000;
filtered = filtered.filter(url => {
switch(dateFilter) {
case 'today':
return now - url.created < day;
case 'week':
return now - url.created < 7 * day;
case 'month':
return now - url.created < 30 * day;
default:
return true;
}
});
}
return filtered;
};
const filteredUrls = getFilteredUrls();
const totalClicks = urls.reduce((sum, url) => sum + url.clicks, 0);
const avgClicks = urls.length > 0 ? (totalClicks / urls.length).toFixed(1) : 0;
const clicksToday = urls.reduce((sum, url) => {
const todayClicks = (url.clickHistory || []).filter(
time => Date.now() - time < 24 * 60 * 60 * 1000
).length;
return sum + todayClicks;
}, 0);
return (
<div className="min-h-screen bg-black text-gray-100 p-6">
<div className="max-w-6xl mx-auto">
{/* Header */}
<div className="text-center mb-8">
<div className="flex items-center justify-center gap-2 mb-2">
<Link2 className="w-8 h-8 text-gray-400" />
<h1 className="text-4xl font-bold">Short.ly</h1>
</div>
<p className="text-gray-400">Shorten URLs and track analytics</p>
</div>
{/* Navigation */}
<div className="flex gap-2 mb-6 bg-gray-900 p-1 rounded-lg max-w-md mx-auto">
<button
onClick={() => setView('shorten')}
className={`flex-1 py-2 px-4 rounded-md transition-colors ${
view === 'shorten' ? 'bg-gray-700 text-white' : 'text-gray-400 hover:text-white'
}`}
>
<Link2 className="w-4 h-4 inline mr-2" />
Shorten
</button>
<button
onClick={() => setView('analytics')}
className={`flex-1 py-2 px-4 rounded-md transition-colors ${
view === 'analytics' ? 'bg-gray-700 text-white' : 'text-gray-400 hover:text-white'
}`}
>
<BarChart3 className="w-4 h-4 inline mr-2" />
Analytics
</button>
</div>
{/* Shorten View */}
{view === 'shorten' && (
<div className="space-y-6">
{/* Input Section */}
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<h2 className="text-xl font-semibold mb-4">Create Short URL</h2>
<div className="space-y-3">
<input
type="text"
value={urlTitle}
onChange={(e) => setUrlTitle(e.target.value)}
placeholder="Title (optional)"
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-gray-600"
/>
<input
type="url"
value={longUrl}
onChange={(e) => setLongUrl(e.target.value)}
placeholder="Enter your long URL here..."
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-gray-600"
/>
<div className="flex gap-2">
<div className="flex-1 flex items-center bg-gray-800 border border-gray-700 rounded-lg px-4 py-3">
<span className="text-gray-500 mr-2">short.ly/</span>
<input
type="text"
value={customAlias}
onChange={(e) => setCustomAlias(e.target.value.replace(/[^a-zA-Z0-9]/g, ''))}
placeholder="custom-alias (optional)"
className="flex-1 bg-transparent text-white placeholder-gray-500 focus:outline-none"
/>
</div>
<button
onClick={handleShorten}
className="bg-gray-700 hover:bg-gray-600 text-white px-6 py-3 rounded-lg transition-colors font-medium"
>
Shorten
</button>
</div>
</div>
</div>
{/* Search and Filter */}
<div className="flex gap-3 flex-wrap">
<div className="flex-1 min-w-[200px] relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-500" />
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search URLs..."
className="w-full bg-gray-900 border border-gray-800 rounded-lg pl-10 pr-4 py-2 text-white placeholder-gray-500 focus:outline-none focus:border-gray-700"
/>
</div>
<select
value={dateFilter}
onChange={(e) => setDateFilter(e.target.value)}
className="bg-gray-900 border border-gray-800 rounded-lg px-4 py-2 text-white focus:outline-none focus:border-gray-700"
>
<option value="all">All Time</option>
<option value="today">Today</option>
<option value="week">This Week</option>
<option value="month">This Month</option>
</select>
<button
onClick={exportData}
className="bg-gray-900 border border-gray-800 hover:bg-gray-800 text-gray-300 px-4 py-2 rounded-lg transition-colors flex items-center gap-2"
>
<Download className="w-4 h-4" />
Export
</button>
</div>
{/* URLs List */}
<div className="space-y-3">
{filteredUrls.map((url) => (
<div
key={url.id}
className="bg-gray-900 p-5 rounded-lg border border-gray-800 hover:border-gray-700 transition-colors"
>
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
{editingId === url.id ? (
<div className="flex items-center gap-2 mb-2">
<input
type="text"
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
className="flex-1 bg-gray-800 border border-gray-700 rounded px-2 py-1 text-white focus:outline-none focus:border-gray-600"
/>
<button
onClick={() => handleSaveEdit(url.id)}
className="text-green-400 hover:text-green-300"
>
<Save className="w-4 h-4" />
</button>
<button
onClick={() => setEditingId(null)}
className="text-gray-400 hover:text-gray-300"
>
<X className="w-4 h-4" />
</button>
</div>
) : (
<div className="flex items-center gap-2 mb-2">
<span className="text-lg font-semibold text-gray-200">{url.title}</span>
<button
onClick={() => handleEdit(url)}
className="text-gray-500 hover:text-gray-300"
>
<Edit2 className="w-3 h-3" />
</button>
</div>
)}
<div className="flex items-center gap-2 mb-2">
<span className="font-mono text-gray-300">{url.shortUrl}</span>
<button
onClick={() => copyToClipboard(url.shortUrl)}
className="text-gray-400 hover:text-white transition-colors"
>
{copied === url.shortUrl ? (
<Check className="w-4 h-4 text-green-400" />
) : (
<Copy className="w-4 h-4" />
)}
</button>
<button
onClick={() => setShowQR(showQR === url.id ? null : url.id)}
className="text-gray-400 hover:text-white transition-colors"
>
<QrCode className="w-4 h-4" />
</button>
</div>
<p className="text-gray-400 text-sm truncate mb-2">{url.longUrl}</p>
<div className="flex items-center gap-4 text-sm text-gray-500">
<span>{url.clicks} clicks</span>
<span>•</span>
<span>Created {new Date(url.created).toLocaleDateString()}</span>
{url.lastClicked && (
<>
<span>•</span>
<span>Last clicked {new Date(url.lastClicked).toLocaleDateString()}</span>
</>
)}
</div>
{showQR === url.id && (
<div className="mt-3 p-3 bg-gray-800 rounded-lg inline-block">
<img src={generateQRCode(url.shortUrl)} alt="QR Code" className="w-32 h-32" />
</div>
)}
</div>
<div className="flex gap-2">
<button
onClick={() => handleClick(url.id)}
className="bg-gray-800 hover:bg-gray-700 text-gray-300 px-4 py-2 rounded-lg transition-colors text-sm whitespace-nowrap"
>
Simulate Click
</button>
<button
onClick={() => handleDelete(url.id)}
className="bg-gray-800 hover:bg-red-900 text-gray-400 hover:text-red-300 p-2 rounded-lg transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</div>
</div>
))}
{filteredUrls.length === 0 && urls.length > 0 && (
<div className="text-center py-12 text-gray-500">
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No URLs match your search or filter criteria.</p>
</div>
)}
{urls.length === 0 && (
<div className="text-center py-12 text-gray-500">
<Link2 className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No URLs shortened yet. Create your first one above!</p>
</div>
)}
</div>
</div>
)}
{/* Analytics View */}
{view === 'analytics' && (
<div className="space-y-6">
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<div className="flex items-center justify-between mb-2">
<span className="text-gray-400 text-sm">Total URLs</span>
<Link2 className="w-5 h-5 text-gray-600" />
</div>
<p className="text-3xl font-bold">{urls.length}</p>
</div>
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<div className="flex items-center justify-between mb-2">
<span className="text-gray-400 text-sm">Total Clicks</span>
<TrendingUp className="w-5 h-5 text-gray-600" />
</div>
<p className="text-3xl font-bold">{totalClicks}</p>
</div>
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<div className="flex items-center justify-between mb-2">
<span className="text-gray-400 text-sm">Clicks Today</span>
<Calendar className="w-5 h-5 text-gray-600" />
</div>
<p className="text-3xl font-bold">{clicksToday}</p>
</div>
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<div className="flex items-center justify-between mb-2">
<span className="text-gray-400 text-sm">Avg. Clicks</span>
<BarChart3 className="w-5 h-5 text-gray-600" />
</div>
<p className="text-3xl font-bold">{avgClicks}</p>
</div>
</div>
{/* Top URLs */}
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<h2 className="text-xl font-semibold mb-4">Top Performing URLs</h2>
{urls.length > 0 ? (
<div className="space-y-3">
{[...urls].sort((a, b) => b.clicks - a.clicks).slice(0, 10).map((url, index) => (
<div key={url.id} className="flex items-center gap-4">
<div className="w-8 h-8 bg-gray-800 rounded-full flex items-center justify-center text-gray-400 font-semibold">
{index + 1}
</div>
<div className="flex-1 min-w-0">
<p className="font-semibold text-gray-200">{url.title}</p>
<p className="text-sm font-mono text-gray-400 truncate">{url.shortUrl}</p>
</div>
<div className="text-right">
<p className="text-lg font-semibold">{url.clicks}</p>
<p className="text-xs text-gray-500">clicks</p>
</div>
</div>
))}
</div>
) : (
<p className="text-center text-gray-500 py-8">No data available yet</p>
)}
</div>
{/* Recent Activity */}
<div className="bg-gray-900 p-6 rounded-lg border border-gray-800">
<h2 className="text-xl font-semibold mb-4">Recent Activity</h2>
{urls.filter(u => u.lastClicked).length > 0 ? (
<div className="space-y-2">
{[...urls]
.filter(u => u.lastClicked)
.sort((a, b) => b.lastClicked - a.lastClicked)
.slice(0, 5)
.map((url) => (
<div key={url.id} className="flex items-center justify-between py-2 border-b border-gray-800 last:border-0">
<div className="flex-1 min-w-0">
<p className="font-semibold text-gray-200 truncate">{url.title}</p>
<p className="text-sm text-gray-500">{url.shortUrl}</p>
</div>
<div className="text-right text-sm text-gray-400">
{new Date(url.lastClicked).toLocaleString()}
</div>
</div>
))}
</div>
) : (
<p className="text-center text-gray-500 py-8">No click activity yet</p>
)}
</div>
</div>
)}
</div>
</div>
);
}