-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
254 lines (225 loc) · 8.85 KB
/
script.js
File metadata and controls
254 lines (225 loc) · 8.85 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
const urlInput = document.getElementById('urlInput');
const shortenBtn = document.getElementById('shortenBtn');
const resultContainer = document.getElementById('result');
const urlHistory = document.getElementById('urlHistory');
const notification = document.getElementById('notification');
const notificationText = document.getElementById('notificationText');
const themeToggle = document.querySelector('.theme-toggle');
const clearHistoryBtn = document.getElementById('clearHistory');
const customSlug = document.getElementById('customSlug');
let urlHistoryData = JSON.parse(localStorage.getItem('urlHistory')) || [];
let isDarkMode = localStorage.getItem('darkMode') === 'true';
updateUrlHistory();
updateTheme();
shortenBtn.addEventListener('click', handleShorten);
urlInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleShorten();
}
});
themeToggle.addEventListener('click', toggleTheme);
clearHistoryBtn.addEventListener('click', clearHistory);
customSlug.addEventListener('input', validateCustomSlug);
function toggleTheme() {
isDarkMode = !isDarkMode;
localStorage.setItem('darkMode', isDarkMode);
updateTheme();
}
function updateTheme() {
document.body.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');
themeToggle.innerHTML = isDarkMode ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
}
function clearHistory() {
if (urlHistoryData.length === 0) {
showNotification('History is already empty', 'error');
return;
}
if (confirm('Are you sure you want to clear all history?')) {
urlHistoryData = [];
localStorage.setItem('urlHistory', JSON.stringify(urlHistoryData));
updateUrlHistory();
showNotification('History cleared successfully', 'success');
}
}
function validateCustomSlug() {
const slug = customSlug.value.trim();
const isValid = /^[a-zA-Z0-9-_]+$/.test(slug);
customSlug.style.borderColor = isValid ? 'var(--border-color)' : 'var(--error-color)';
return isValid;
}
async function handleShorten() {
const url = urlInput.value.trim();
const customSlugValue = customSlug.value.trim();
if (!isValidUrl(url)) {
showNotification('Please enter a valid URL', 'error');
return;
}
if (customSlugValue && !validateCustomSlug()) {
showNotification('Custom alias can only contain letters, numbers, hyphens, and underscores', 'error');
return;
}
try {
shortenBtn.disabled = true;
shortenBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span>Shortening...</span>';
const response = await fetch('https://url-shortener-service.p.rapidapi.com/shorten', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'x-rapidapi-host': config.RAPIDAPI_HOST,
'x-rapidapi-key': config.RAPIDAPI_KEY
},
body: `url=${encodeURIComponent(url)}${customSlugValue ? `&custom=${customSlugValue}` : ''}`
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
if (data.result_url) {
showResult(url, data.result_url);
addToHistory(url, data.result_url);
showNotification('URL shortened successfully!', 'success');
urlInput.value = '';
customSlug.value = '';
} else {
throw new Error('Failed to get shortened URL');
}
} catch (error) {
showNotification(error.message || 'Failed to shorten URL', 'error');
} finally {
shortenBtn.disabled = false;
shortenBtn.innerHTML = '<i class="fas fa-magic"></i> <span>Shorten</span>';
}
}
function showResult(originalUrl, shortenedUrl) {
const qrCodeUrl = generateQRCodeUrl(shortenedUrl);
resultContainer.innerHTML = `
<div class="url-item">
<div class="url-info">
<div class="original-url">${originalUrl}</div>
<div class="shortened-url">${shortenedUrl}</div>
</div>
<div class="url-actions">
<button class="action-btn copy-btn" onclick="copyToClipboard('${shortenedUrl}')">
<i class="fas fa-copy"></i>
</button>
<a href="${shortenedUrl}" target="_blank" class="action-btn">
<i class="fas fa-external-link-alt"></i>
</a>
</div>
</div>
<div class="qr-code-container">
<img id="qr-img" src="${qrCodeUrl}" alt="QR Code" class="qr-code-image">
<div class="qr-code-actions">
<a href="${qrCodeUrl}" download="qr-code.png" class="action-btn" id="downloadQR">
<i class="fas fa-download"></i> Download QR
</a>
<button class="action-btn" id="copyQR">
<i class="fas fa-copy"></i> Copy QR
</button>
</div>
</div>
`;
resultContainer.classList.add('show');
// Copy QR code image to clipboard
document.getElementById('copyQR').onclick = async () => {
const img = document.getElementById('qr-img');
if (img) {
try {
const data = await fetch(img.src);
const blob = await data.blob();
await navigator.clipboard.write([
new ClipboardItem({ 'image/png': blob })
]);
showNotification('QR code copied to clipboard!', 'success');
} catch (err) {
showNotification('Failed to copy QR code', 'error');
}
}
};
}
function generateQRCodeUrl(url) {
const size = '200x200';
const foreground = isDarkMode ? 'ffffff' : '000000';
const background = isDarkMode ? '1f2937' : 'ffffff';
return `https://api.qrserver.com/v1/create-qr-code/?size=${size}&data=${encodeURIComponent(url)}&color=${foreground}&bgcolor=${background}`;
}
function addToHistory(originalUrl, shortenedUrl) {
urlHistoryData.unshift({
originalUrl,
shortenedUrl,
timestamp: new Date().toISOString()
});
if (urlHistoryData.length > 10) {
urlHistoryData.pop();
}
localStorage.setItem('urlHistory', JSON.stringify(urlHistoryData));
updateUrlHistory();
}
function updateUrlHistory() {
urlHistory.innerHTML = urlHistoryData.map((item, index) => `
<div class="url-item">
<div class="url-info">
<div class="original-url">${item.originalUrl}</div>
<div class="shortened-url">${item.shortenedUrl}</div>
</div>
<div class="url-actions">
<button class="action-btn copy-btn" onclick="copyToClipboard('${item.shortenedUrl}')">
<i class="fas fa-copy"></i>
</button>
<a href="${item.shortenedUrl}" target="_blank" class="action-btn">
<i class="fas fa-external-link-alt"></i>
</a>
<button class="action-btn" onclick="showQRCode('${item.shortenedUrl}')">
<i class="fas fa-qrcode"></i>
</button>
<button class="action-btn delete-btn" onclick="deleteFromHistory(${index})">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
`).join('');
}
function showQRCode(url) {
const qrCodeUrl = generateQRCodeUrl(url);
resultContainer.innerHTML = `
<div class="qr-code-container">
<img src="${qrCodeUrl}" alt="QR Code" class="qr-code-image">
<div class="qr-code-actions">
<a href="${qrCodeUrl}" download="qr-code.png" class="action-btn">
<i class="fas fa-download"></i> Download QR
</a>
<button class="action-btn" id="copyQR">
<i class="fas fa-copy"></i> Copy QR
</button>
</div>
</div>
`;
resultContainer.classList.add('show');
}
function deleteFromHistory(index) {
urlHistoryData.splice(index, 1);
localStorage.setItem('urlHistory', JSON.stringify(urlHistoryData));
updateUrlHistory();
showNotification('URL removed from history', 'success');
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
.then(() => showNotification('Copied to clipboard!', 'success'))
.catch(() => showNotification('Failed to copy to clipboard', 'error'));
}
function showNotification(message, type = 'success') {
notificationText.textContent = message;
notification.className = `notification ${type}`;
notification.classList.add('show');
setTimeout(() => {
notification.classList.remove('show');
}, 3000);
}
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}