File size: 16,073 Bytes
ba8f733 ec258d5 ba8f733 1065ace ba8f733 ec258d5 ba8f733 54dda09 ba8f733 54dda09 ba8f733 ec258d5 ba8f733 |
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 |
// QR Code Generator Application
class QRGenerator {
constructor() {
this.currentType = 'url';
this.currentQRUrl = null;
this.init();
}
init() {
this.bindEvents();
this.updateSizeDisplay();
this.setActiveTab('url');
}
bindEvents() {
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const type = e.currentTarget.dataset.type;
this.setActiveTab(type);
});
});
// Size slider
const sizeSlider = document.getElementById('qr-size');
sizeSlider.addEventListener('input', () => {
this.updateSizeDisplay();
});
// Generate button
document.getElementById('generate-btn').addEventListener('click', () => {
this.generateQRCode();
});
// Download button
document.getElementById('download-btn').addEventListener('click', () => {
this.downloadQRCode();
});
// Real-time input changes
this.bindInputEvents();
// Color changes - removed auto-generation
// Users need to click "Generate QR Code" to apply color changes
}
bindInputEvents() {
// Clear QR code when input changes, but don't auto-generate
// URL input
document.getElementById('url-input').addEventListener('input', () => {
this.clearPreview();
});
// Text input
document.getElementById('text-input').addEventListener('input', () => {
this.clearPreview();
});
// Email inputs
document.getElementById('email-input').addEventListener('input', () => {
this.clearPreview();
});
document.getElementById('email-subject').addEventListener('input', () => {
this.clearPreview();
});
document.getElementById('email-body').addEventListener('input', () => {
this.clearPreview();
});
// Phone input
document.getElementById('phone-input').addEventListener('input', () => {
this.clearPreview();
});
// WiFi inputs
document.getElementById('wifi-ssid').addEventListener('input', () => {
this.clearPreview();
});
document.getElementById('wifi-password').addEventListener('input', () => {
this.clearPreview();
});
document.getElementById('wifi-security').addEventListener('change', () => {
this.clearPreview();
});
document.getElementById('wifi-hidden').addEventListener('change', () => {
this.clearPreview();
});
// SMS inputs
document.getElementById('sms-number').addEventListener('input', () => {
this.clearPreview();
});
document.getElementById('sms-message').addEventListener('input', () => {
this.clearPreview();
});
}
setActiveTab(type) {
this.currentType = type;
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`[data-type="${type}"]`).classList.add('active');
// Update content forms
document.querySelectorAll('.content-form').forEach(form => {
form.classList.remove('active');
});
document.getElementById(`${type}-form`).classList.add('active');
// Clear current QR code
this.clearPreview();
}
updateSizeDisplay() {
const size = document.getElementById('qr-size').value;
document.querySelector('.size-value').textContent = `${size}px`;
}
autoGenerate() {
const content = this.getContentData();
if (content && content.trim()) {
this.generateQRCode();
} else {
this.clearPreview();
}
}
getContentData() {
switch (this.currentType) {
case 'url':
return document.getElementById('url-input').value;
case 'text':
return document.getElementById('text-input').value;
case 'email':
const email = document.getElementById('email-input').value;
const subject = document.getElementById('email-subject').value;
const body = document.getElementById('email-body').value;
if (!email) return '';
let mailto = `mailto:${email}`;
const params = [];
if (subject) params.push(`subject=${encodeURIComponent(subject)}`);
if (body) params.push(`body=${encodeURIComponent(body)}`);
if (params.length > 0) mailto += `?${params.join('&')}`;
return mailto;
case 'phone':
const phone = document.getElementById('phone-input').value;
return phone ? `tel:${phone}` : '';
case 'wifi':
const ssid = document.getElementById('wifi-ssid').value;
const password = document.getElementById('wifi-password').value;
const security = document.getElementById('wifi-security').value;
const hidden = document.getElementById('wifi-hidden').checked;
if (!ssid) return '';
return `WIFI:T:${security};S:${ssid};P:${password};H:${hidden ? 'true' : 'false'};;`;
case 'sms':
const smsNumber = document.getElementById('sms-number').value;
const smsMessage = document.getElementById('sms-message').value;
if (!smsNumber) return '';
let sms = `sms:${smsNumber}`;
if (smsMessage) sms += `?body=${encodeURIComponent(smsMessage)}`;
return sms;
default:
return '';
}
}
async generateQRCode() {
const content = this.getContentData();
if (!content || !content.trim()) {
this.showToast('Please enter content to generate QR code', 'error');
return;
}
this.showLoading(true);
try {
const qrUrl = this.buildQRUrl(content);
await this.displayQRCode(qrUrl);
this.currentQRUrl = qrUrl;
// Enable download button
document.getElementById('download-btn').disabled = false;
this.showToast('QR code generated successfully!', 'success');
} catch (error) {
console.error('Error generating QR code:', error);
this.showToast('Failed to generate QR code. Please try again.', 'error');
} finally {
this.showLoading(false);
}
}
buildQRUrl(content) {
const size = document.getElementById('qr-size').value;
const fgColor = document.getElementById('fg-color').value.replace('#', '');
const bgColor = document.getElementById('bg-color').value.replace('#', '');
const errorCorrection = document.getElementById('error-correction').value;
const format = document.getElementById('output-format').value;
const params = new URLSearchParams({
cht: 'qr',
chs: `${size}x${size}`,
chl: content,
choe: 'UTF-8',
chld: `${errorCorrection}|2`,
icqrf: fgColor,
icqrb: bgColor
});
if (format === 'svg') {
params.append('chof', '.svg');
}
return `https://image-charts.com/chart?${params.toString()}`;
}
async displayQRCode(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const preview = document.getElementById('qr-preview');
preview.innerHTML = '';
preview.appendChild(img);
preview.classList.add('has-qr');
resolve();
};
img.onerror = () => {
reject(new Error('Failed to load QR code image'));
};
img.src = url;
img.alt = 'Generated QR Code';
img.style.maxWidth = '100%';
img.style.height = 'auto';
});
}
clearPreview() {
const preview = document.getElementById('qr-preview');
preview.innerHTML = `
<div class="placeholder">
<i class="fas fa-qrcode"></i>
<p>Enter content to generate QR code</p>
</div>
`;
preview.classList.remove('has-qr');
// Disable download button
document.getElementById('download-btn').disabled = true;
this.currentQRUrl = null;
}
async downloadQRCode() {
if (!this.currentQRUrl) {
this.showToast('No QR code to download', 'error');
return;
}
try {
const format = document.getElementById('output-format').value;
const response = await fetch(this.currentQRUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `qrcode.${format}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
this.showToast('QR code downloaded successfully!', 'success');
} catch (error) {
console.error('Error downloading QR code:', error);
this.showToast('Failed to download QR code', 'error');
}
}
showLoading(show) {
const overlay = document.getElementById('loading-overlay');
if (show) {
overlay.classList.add('show');
} else {
overlay.classList.remove('show');
}
}
showToast(message, type = 'info') {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `toast ${type}`;
const icon = type === 'success' ? 'fas fa-check-circle' :
type === 'error' ? 'fas fa-exclamation-circle' :
'fas fa-info-circle';
toast.innerHTML = `
<i class="${icon}"></i>
<span>${message}</span>
`;
container.appendChild(toast);
// Auto remove after 3 seconds
setTimeout(() => {
if (toast.parentNode) {
toast.parentNode.removeChild(toast);
}
}, 3000);
}
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Validation methods
isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
isValidPhone(phone) {
const phoneRegex = /^[\+]?[1-9][\d]{0,15}$/;
return phoneRegex.test(phone.replace(/[\s\-\(\)]/g, ''));
}
// Enhanced validation for different content types
validateContent() {
const content = this.getContentData();
switch (this.currentType) {
case 'url':
if (content && !this.isValidUrl(content)) {
this.showToast('Please enter a valid URL', 'error');
return false;
}
break;
case 'email':
const email = document.getElementById('email-input').value;
if (email && !this.isValidEmail(email)) {
this.showToast('Please enter a valid email address', 'error');
return false;
}
break;
case 'phone':
const phone = document.getElementById('phone-input').value;
if (phone && !this.isValidPhone(phone)) {
this.showToast('Please enter a valid phone number', 'error');
return false;
}
break;
case 'sms':
const smsPhone = document.getElementById('sms-number').value;
if (smsPhone && !this.isValidPhone(smsPhone)) {
this.showToast('Please enter a valid phone number', 'error');
return false;
}
break;
}
return true;
}
}
// Utility functions
function formatPhoneNumber(phone) {
// Remove all non-digit characters except +
const cleaned = phone.replace(/[^\d\+]/g, '');
return cleaned;
}
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, m => map[m]);
}
// Initialize the application when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
const qrGenerator = new QRGenerator();
// Add some sample data for demonstration
const urlInput = document.getElementById('url-input');
if (urlInput) {
urlInput.placeholder = 'https://example.com';
}
// Add keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Ctrl/Cmd + Enter to generate
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
qrGenerator.generateQRCode();
}
// Ctrl/Cmd + D to download
if ((e.ctrlKey || e.metaKey) && e.key === 'd') {
e.preventDefault();
if (!document.getElementById('download-btn').disabled) {
qrGenerator.downloadQRCode();
}
}
});
// Add focus management for better accessibility
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
btn.click();
}
});
});
// Add form validation on submit
document.querySelectorAll('.form-input, .form-textarea').forEach(input => {
input.addEventListener('blur', () => {
qrGenerator.validateContent();
});
});
// Add drag and drop functionality for future logo upload feature
const previewArea = document.getElementById('qr-preview');
previewArea.addEventListener('dragover', (e) => {
e.preventDefault();
previewArea.style.borderColor = 'var(--primary-color)';
});
previewArea.addEventListener('dragleave', (e) => {
e.preventDefault();
previewArea.style.borderColor = '';
});
// Add print functionality
window.addEventListener('beforeprint', () => {
document.body.classList.add('printing');
});
window.addEventListener('afterprint', () => {
document.body.classList.remove('printing');
});
// Add service worker for offline functionality (future enhancement)
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch(err => {
console.log('Service worker registration failed:', err);
});
}
console.log('QR Generator initialized successfully!');
});
|