|
| 1 | +class URLShortener { |
| 2 | + constructor() { |
| 3 | + this.urlStorage = this.loadFromStorage(); |
| 4 | + this.baseUrl = window.location.origin + window.location.pathname; |
| 5 | + this.initializeElements(); |
| 6 | + this.bindEvents(); |
| 7 | + this.displayRecentUrls(); |
| 8 | + } |
| 9 | + |
| 10 | + initializeElements() { |
| 11 | + this.urlInput = document.getElementById('urlInput'); |
| 12 | + this.shortenBtn = document.getElementById('shortenBtn'); |
| 13 | + this.result = document.getElementById('result'); |
| 14 | + this.shortUrl = document.getElementById('shortUrl'); |
| 15 | + this.originalUrl = document.getElementById('originalUrl'); |
| 16 | + this.copyBtn = document.getElementById('copyBtn'); |
| 17 | + this.error = document.getElementById('error'); |
| 18 | + this.urlList = document.getElementById('urlList'); |
| 19 | + } |
| 20 | + |
| 21 | + bindEvents() { |
| 22 | + this.shortenBtn.addEventListener('click', () => this.shortenUrl()); |
| 23 | + this.urlInput.addEventListener('keypress', (e) => { |
| 24 | + if (e.key === 'Enter') this.shortenUrl(); |
| 25 | + }); |
| 26 | + this.copyBtn.addEventListener('click', () => this.copyToClipboard()); |
| 27 | + } |
| 28 | + |
| 29 | + isValidUrl(string) { |
| 30 | + try { |
| 31 | + new URL(string); |
| 32 | + return true; |
| 33 | + } catch (_) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + generateShortCode() { |
| 39 | + // Generate a random 6-character code |
| 40 | + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; |
| 41 | + let result = ''; |
| 42 | + for (let i = 0; i < 6; i++) { |
| 43 | + result += chars.charAt(Math.floor(Math.random() * chars.length)); |
| 44 | + } |
| 45 | + return result; |
| 46 | + } |
| 47 | + |
| 48 | + shortenUrl() { |
| 49 | + const longUrl = this.urlInput.value.trim(); |
| 50 | + |
| 51 | + // Hide previous results |
| 52 | + this.result.style.display = 'none'; |
| 53 | + this.error.style.display = 'none'; |
| 54 | + |
| 55 | + if (!longUrl) { |
| 56 | + this.showError('Please enter a URL'); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + if (!this.isValidUrl(longUrl)) { |
| 61 | + this.showError('Please enter a valid URL'); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + // Check if URL already exists |
| 66 | + const existingEntry = this.findExistingUrl(longUrl); |
| 67 | + if (existingEntry) { |
| 68 | + this.displayResult(existingEntry.shortCode, longUrl); |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + // Generate new short code |
| 73 | + let shortCode; |
| 74 | + do { |
| 75 | + shortCode = this.generateShortCode(); |
| 76 | + } while (this.urlStorage[shortCode]); // Ensure uniqueness |
| 77 | + |
| 78 | + // Store the URL |
| 79 | + this.urlStorage[shortCode] = { |
| 80 | + originalUrl: longUrl, |
| 81 | + createdAt: new Date().toISOString(), |
| 82 | + clickCount: 0 |
| 83 | + }; |
| 84 | + |
| 85 | + this.saveToStorage(); |
| 86 | + this.displayResult(shortCode, longUrl); |
| 87 | + this.displayRecentUrls(); |
| 88 | + } |
| 89 | + |
| 90 | + findExistingUrl(url) { |
| 91 | + for (const [code, data] of Object.entries(this.urlStorage)) { |
| 92 | + if (data.originalUrl === url) { |
| 93 | + return { shortCode: code, ...data }; |
| 94 | + } |
| 95 | + } |
| 96 | + return null; |
| 97 | + } |
| 98 | + |
| 99 | + displayResult(shortCode, originalUrl) { |
| 100 | + const shortUrl = `${this.baseUrl}#${shortCode}`; |
| 101 | + this.shortUrl.value = shortUrl; |
| 102 | + this.originalUrl.textContent = originalUrl; |
| 103 | + this.result.style.display = 'block'; |
| 104 | + this.urlInput.value = ''; |
| 105 | + } |
| 106 | + |
| 107 | + showError(message) { |
| 108 | + this.error.querySelector('p').textContent = message; |
| 109 | + this.error.style.display = 'block'; |
| 110 | + } |
| 111 | + |
| 112 | + copyToClipboard() { |
| 113 | + this.shortUrl.select(); |
| 114 | + this.shortUrl.setSelectionRange(0, 99999); // For mobile devices |
| 115 | + document.execCommand('copy'); |
| 116 | + |
| 117 | + // Visual feedback |
| 118 | + const originalText = this.copyBtn.textContent; |
| 119 | + this.copyBtn.textContent = 'Copied!'; |
| 120 | + this.copyBtn.style.backgroundColor = '#28a745'; |
| 121 | + |
| 122 | + setTimeout(() => { |
| 123 | + this.copyBtn.textContent = originalText; |
| 124 | + this.copyBtn.style.backgroundColor = ''; |
| 125 | + }, 2000); |
| 126 | + } |
| 127 | + |
| 128 | + displayRecentUrls() { |
| 129 | + const entries = Object.entries(this.urlStorage) |
| 130 | + .sort((a, b) => new Date(b[1].createdAt) - new Date(a[1].createdAt)) |
| 131 | + .slice(0, 10); // Show only last 10 |
| 132 | + |
| 133 | + if (entries.length === 0) { |
| 134 | + this.urlList.innerHTML = '<p class="no-urls">No URLs shortened yet</p>'; |
| 135 | + return; |
| 136 | + } |
| 137 | + |
| 138 | + this.urlList.innerHTML = entries.map(([code, data]) => ` |
| 139 | + <div class="url-item"> |
| 140 | + <div class="url-info"> |
| 141 | + <div class="short-url"> |
| 142 | + <a href="${this.baseUrl}#${code}" target="_blank">${this.baseUrl}#${code}</a> |
| 143 | + </div> |
| 144 | + <div class="original-url">${data.originalUrl}</div> |
| 145 | + <div class="url-meta"> |
| 146 | + Created: ${new Date(data.createdAt).toLocaleDateString()} | |
| 147 | + Clicks: ${data.clickCount} |
| 148 | + </div> |
| 149 | + </div> |
| 150 | + <button class="delete-btn" onclick="urlShortener.deleteUrl('${code}')">Delete</button> |
| 151 | + </div> |
| 152 | + `).join(''); |
| 153 | + } |
| 154 | + |
| 155 | + deleteUrl(shortCode) { |
| 156 | + if (confirm('Are you sure you want to delete this URL?')) { |
| 157 | + delete this.urlStorage[shortCode]; |
| 158 | + this.saveToStorage(); |
| 159 | + this.displayRecentUrls(); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + loadFromStorage() { |
| 164 | + try { |
| 165 | + const stored = localStorage.getItem('urlShortener'); |
| 166 | + return stored ? JSON.parse(stored) : {}; |
| 167 | + } catch (e) { |
| 168 | + console.error('Error loading from storage:', e); |
| 169 | + return {}; |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + saveToStorage() { |
| 174 | + try { |
| 175 | + localStorage.setItem('urlShortener', JSON.stringify(this.urlStorage)); |
| 176 | + } catch (e) { |
| 177 | + console.error('Error saving to storage:', e); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + // Handle URL redirection |
| 182 | + handleRedirect() { |
| 183 | + const hash = window.location.hash.substring(1); |
| 184 | + if (hash && this.urlStorage[hash]) { |
| 185 | + // Increment click count |
| 186 | + this.urlStorage[hash].clickCount++; |
| 187 | + this.saveToStorage(); |
| 188 | + |
| 189 | + // Redirect to original URL |
| 190 | + window.location.href = this.urlStorage[hash].originalUrl; |
| 191 | + } |
| 192 | + } |
| 193 | +} |
| 194 | + |
| 195 | +// Initialize the URL shortener |
| 196 | +const urlShortener = new URLShortener(); |
| 197 | + |
| 198 | +// Handle page load for redirects |
| 199 | +window.addEventListener('load', () => { |
| 200 | + urlShortener.handleRedirect(); |
| 201 | +}); |
| 202 | + |
| 203 | +// Handle hash changes |
| 204 | +window.addEventListener('hashchange', () => { |
| 205 | + urlShortener.handleRedirect(); |
| 206 | +}); |
0 commit comments