-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
375 lines (325 loc) · 12.5 KB
/
Copy pathscript.js
File metadata and controls
375 lines (325 loc) · 12.5 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
let currentType = "url";
let exportSize = 512;
let bulkQRCodes = [];
let singleQR = null;
let bulkQRInstances = [];
let qrSettings = {
width: 250,
height: 250,
margin: 10,
dotsOptions: { color: "#4361ee", type: "rounded" },
backgroundOptions: { color: "#ffffff" },
image: "",
qrOptions: { errorCorrectionLevel: "M" },
imageOptions: { crossOrigin: "anonymous", imageSize: 0.4, margin: 4 }
};
const qrWrapper = document.getElementById("qr-code");
const input = document.getElementById("qr-input");
const bulkInput = document.getElementById("qr-bulk-input");
const generateBtn = document.getElementById("generate-btn");
const downloadPngBtn = document.getElementById("download-png");
const downloadSvgBtn = document.getElementById("download-svg");
const clearInputBtn = document.getElementById("clear-input");
const chipGroup = document.getElementById("input-type");
const exportSizeSelect = document.getElementById("export-size");
const logoInput = document.getElementById("logo-input");
const removeLogoBtn = document.getElementById("remove-logo");
const logoSettingsGroup = document.getElementById("logo-settings-group");
const logoSizeInput = document.getElementById("logo-size");
const logoMarginInput = document.getElementById("logo-margin");
const errorCorrectionSelect = document.getElementById("error-correction");
const cornerStyleBtns = document.querySelectorAll(".btn-option");
// ------------------- Theme Handling -------------------
const htmlElement = document.documentElement;
const themeToggleBtn = document.getElementById('theme-toggle');
function applySystemTheme() {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
htmlElement.setAttribute('data-theme', prefersDark ? 'dark' : 'light');
themeToggleBtn.innerHTML = prefersDark ? '<i class="fas fa-moon"></i>' : '<i class="fas fa-sun"></i>';
}
themeToggleBtn.addEventListener('click', () => {
const currentTheme = htmlElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
htmlElement.setAttribute('data-theme', newTheme);
themeToggleBtn.innerHTML = newTheme === 'dark' ? '<i class="fas fa-moon"></i>' : '<i class="fas fa-sun"></i>';
});
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applySystemTheme);
applySystemTheme();
// ------------------- Helpers -------------------
function formatData(data) {
if (!data) return "https://example.com";
switch (currentType) {
case "url":
return data.startsWith("http") ? data : `https://${data}`;
case "email":
return data.startsWith("mailto:") ? data : `mailto:${data}`;
case "phone":
const cleanPhone = data.replace(/[^0-9+]/g, '');
return `tel:${cleanPhone}`;
case "text":
return data;
default:
return data;
}
}
function createQRCodeInstance(data, size = qrSettings.width) {
return new QRCodeStyling({ ...qrSettings, data, width: size, height: size });
}
async function createQRCodeBlob(data, format = "png", size = 512) {
const tempQR = new QRCodeStyling({ ...qrSettings, data, width: size, height: size });
return await tempQR.getRawData(format);
}
function updateQRWrapperMode() {
const count = qrWrapper.querySelectorAll('.qr-item').length;
if (count > 1) {
qrWrapper.classList.add('qr-grid');
} else {
qrWrapper.classList.remove('qr-grid');
}
}
function animateUpdate(item, updateFn) {
item.classList.add('updating');
setTimeout(() => {
updateFn();
item.classList.remove('updating');
}, 200);
}
// ------------------- Parsing -------------------
function parseBulkInput(text) {
const lines = text.split(/\n/);
const urlRegex = /(https?:\/\/[^\s)]+)/;
const nameUrlRegex = /\[(.*?)\]\((https?:\/\/[^\s)]+)\)/;
const parsed = [];
lines.forEach(line => {
line = line.trim();
if (!line) return;
let match = nameUrlRegex.exec(line);
if (match) {
parsed.push({ name: match[1].trim(), url: match[2] });
} else {
let urlMatch = urlRegex.exec(line);
if (urlMatch) {
const url = urlMatch[0];
const domain = new URL(url).hostname.replace('www.', '');
parsed.push({ name: domain, url });
}
}
});
return parsed;
}
// ------------------- Rendering -------------------
function renderSingleQRCode() {
const text = formatData(input.value.trim());
if (!text) return input.focus();
if (!singleQR) {
qrWrapper.innerHTML = '';
const container = document.createElement('div');
container.classList.add('qr-item');
singleQR = createQRCodeInstance(text, 250);
singleQR.append(container);
qrWrapper.appendChild(container);
} else {
animateUpdate(qrWrapper.querySelector('.qr-item'), () => {
singleQR.update({ data: text, width: 250, height: 250, ...qrSettings });
});
}
updateQRWrapperMode();
}
async function renderBulkQRCodes() {
const entries = parseBulkInput(bulkInput.value.trim());
if (!entries.length) return alert("No valid URLs found!");
const currentCount = bulkQRInstances.length;
const newCount = entries.length;
if (newCount !== currentCount) {
qrWrapper.innerHTML = '';
bulkQRInstances = [];
for (let entry of entries) {
// Generate at slightly higher res for display
const qr = createQRCodeInstance(entry.url, 200);
const qrItem = document.createElement('div');
qrItem.classList.add('qr-item');
qr.append(qrItem);
const nameLabel = document.createElement('p');
nameLabel.textContent = entry.name;
nameLabel.title = entry.url; // Tooltip for full URL
const wrapper = document.createElement('div');
wrapper.classList.add('qr-item-wrapper');
wrapper.appendChild(qrItem);
wrapper.appendChild(nameLabel);
qrWrapper.appendChild(wrapper);
bulkQRInstances.push({ qr, url: entry.url, name: entry.name, container: qrItem });
}
} else {
// Update existing QR codes
requestAnimationFrame(() => {
entries.forEach((entry, i) => {
animateUpdate(qrWrapper.children[i], () => {
bulkQRInstances[i].qr.update({
data: entry.url,
width: 200,
height: 200,
...qrSettings
});
bulkQRInstances[i].url = entry.url;
bulkQRInstances[i].name = entry.name;
// Update label text if needed
qrWrapper.children[i].querySelector('p').textContent = entry.name;
});
});
});
}
updateQRWrapperMode();
}
function updateAllQRCodes() {
requestAnimationFrame(() => {
if (currentType === 'bulk') {
bulkQRInstances.forEach(instance => {
instance.qr.update({ width: 200, height: 200, ...qrSettings });
});
} else if (singleQR) {
singleQR.update({ width: 250, height: 250, ...qrSettings });
}
});
}
// ------------------- Generate -------------------
generateBtn.addEventListener("click", () => {
currentType === 'bulk' ? renderBulkQRCodes() : renderSingleQRCode();
});
// ------------------- Download -------------------
downloadPngBtn.addEventListener("click", async () => {
currentType === 'bulk' ? await downloadBulk('png') : downloadSingle('png');
});
downloadSvgBtn.addEventListener("click", async () => {
currentType === 'bulk' ? await downloadBulk('svg') : downloadSingle('svg');
});
async function downloadSingle(extension) {
const size = parseInt(exportSizeSelect.value, 10);
// Create a fresh instance for export to ensure high resolution logo
const tempQR = new QRCodeStyling({
...qrSettings,
width: size,
height: size,
data: formatData(input.value.trim()) // Ensure current data is used
});
await tempQR.download({ name: "qr-code", extension });
}
async function downloadBulk(format) {
if (!bulkQRInstances.length) return alert("No QR codes generated for bulk download.");
const zip = new JSZip();
for (let i = 0; i < bulkQRInstances.length; i++) {
const instance = bulkQRInstances[i];
const blob = await createQRCodeBlob(instance.url, format, parseInt(exportSizeSelect.value, 10));
// Use parsed name if available, fallback to domain, then generic
let safeName = (instance.name || instance.url.replace(/https?:\/\//, '').split('/')[0] || 'qr-code')
.replace(/[^a-z0-9\-_]/gi, '_'); // Sanitize filename
const filename = `${safeName}-${i + 1}.${format}`;
zip.file(filename, blob);
}
const content = await zip.generateAsync({ type: "blob" });
const a = document.createElement('a');
a.href = URL.createObjectURL(content);
a.download = "qr-codes.zip";
a.click();
}
// ------------------- Customization -------------------
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
const debouncedUpdate = debounce(() => updateAllQRCodes(), 200);
document.getElementById('color-foreground').addEventListener('input', (e) => {
qrSettings.dotsOptions.color = e.target.value;
debouncedUpdate();
});
document.getElementById('color-background').addEventListener('input', (e) => {
qrSettings.backgroundOptions.color = e.target.value;
debouncedUpdate();
});
cornerStyleBtns.forEach(btn => {
btn.addEventListener("click", () => {
cornerStyleBtns.forEach(b => b.classList.remove("active"));
btn.classList.add("active");
qrSettings.dotsOptions.type = btn.dataset.value;
updateAllQRCodes();
});
});
errorCorrectionSelect.addEventListener("change", () => {
qrSettings.qrOptions.errorCorrectionLevel = errorCorrectionSelect.value;
updateAllQRCodes();
});
// Logo Upload
logoInput.addEventListener("change", (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (event) {
qrSettings.image = event.target.result;
logoSettingsGroup.style.display = "block";
updateAllQRCodes();
};
reader.readAsDataURL(file);
});
// Remove Logo
removeLogoBtn.addEventListener("click", () => {
qrSettings.image = "";
logoInput.value = "";
logoSettingsGroup.style.display = "none";
updateAllQRCodes();
});
// Logo Size Slider
logoSizeInput.addEventListener("input", (e) => {
qrSettings.imageOptions.imageSize = parseFloat(e.target.value);
debouncedUpdate();
});
// Logo Margin Slider
logoMarginInput.addEventListener("input", (e) => {
qrSettings.imageOptions.margin = parseInt(e.target.value, 10);
debouncedUpdate();
});
// Clear input
clearInputBtn.addEventListener("click", () => {
if (currentType === 'bulk') bulkInput.value = "";
else input.value = "";
});
// Chip selection
chipGroup.addEventListener("click", (e) => {
if (e.target.closest(".chip")) {
const chip = e.target.closest(".chip");
document.querySelectorAll(".chip").forEach(c => c.classList.remove("active"));
chip.classList.add("active");
currentType = chip.dataset.type;
// Clear inputs on switch to prevent invalid format data
input.value = "";
bulkInput.value = "";
const placeholder = {
url: "https://example.com",
text: "Enter your text here",
email: "user@example.com",
phone: "+1234567890",
bulk: "Enter multiple URLs, one per line"
};
if (currentType === "bulk") {
input.style.display = "none";
bulkInput.style.display = "block";
bulkInput.placeholder = placeholder.bulk;
} else {
input.style.display = "block";
bulkInput.style.display = "none";
input.placeholder = placeholder[currentType];
}
}
});
// ------------------- Init -------------------
document.addEventListener("DOMContentLoaded", () => {
setTimeout(() => {
document.body.classList.add("loaded");
}, 300);
renderSingleQRCode();
});