-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
547 lines (475 loc) · 19.8 KB
/
popup.js
File metadata and controls
547 lines (475 loc) · 19.8 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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/* ─────────────────────────────────────────────────────────────────
Base64 Encoder / Decoder — popup.js
──────────────────────────────────────────────────────────────── */
// ── DOM refs ──────────────────────────────────────────────────────
const inputEl = document.getElementById('inputEl');
const outputEl = document.getElementById('outputEl');
const charCountEl = document.getElementById('charCount');
const statusBar = document.getElementById('statusBar');
const encodeBtn = document.getElementById('encodeBtn');
const decodeBtn = document.getElementById('decodeBtn');
const swapBtn = document.getElementById('swapBtn');
const clearInputBtn = document.getElementById('clearInputBtn');
const pasteBtn = document.getElementById('pasteBtn');
const copyOutputBtn = document.getElementById('copyOutputBtn');
const downloadTxtBtn = document.getElementById('downloadTxtBtn');
const urlSafeToggle = document.getElementById('urlSafeToggle');
const wrapToggle = document.getElementById('wrapToggle');
const autoToggle = document.getElementById('autoToggle');
const tabText = document.getElementById('tabText');
const tabFile = document.getElementById('tabFile');
const panelText = document.getElementById('panelText');
const panelFile = document.getElementById('panelFile');
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const fileInfo = document.getElementById('fileInfo');
const fileNameEl = document.getElementById('fileName');
const fileSizeEl = document.getElementById('fileSize');
const encodeFileBtn = document.getElementById('encodeFileBtn');
const fileOutputEl = document.getElementById('fileOutputEl');
const fileStatusBar = document.getElementById('fileStatusBar');
const copyFileOutputBtn = document.getElementById('copyFileOutputBtn');
const downloadFileTxtBtn = document.getElementById('downloadFileTxtBtn');
const themeToggle = document.getElementById('themeToggle');
// ── Base64 core functions ─────────────────────────────────────────
/**
* Encodes a Unicode string to Base64.
*
* The Problem:
* btoa() only accepts "binary strings" — characters with code points
* 0–255. Any character above U+00FF (e.g. emoji, CJK, accented letters
* like é in some encodings) throws a "character out of range" DOMException.
*
* The Solution — UTF-8 round-trip via encodeURIComponent:
* 1. encodeURIComponent(str) converts the string to a percent-encoded
* ASCII string (e.g. "café" → "caf%C3%A9"). Each byte of the UTF-8
* representation becomes a %XX escape.
* 2. .replace(/%([0-9A-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
* converts each %XX back into a single-byte character — but now as a
* true byte value (0–255), not a Unicode code point.
* parseInt(hex, 16) parses the two-digit hex string as a base-16 number.
* String.fromCharCode() converts that number to a character.
* 3. btoa() can now safely encode this binary string.
*
* The result is the standard UTF-8 Base64 encoding that matches what most
* server-side implementations (Python's base64, Node's Buffer.from) produce.
*
* @param {string} str - Any Unicode string
* @returns {string} Standard Base64 string
*/
function encodeBase64(str) {
const binaryStr = encodeURIComponent(str).replace(
/%([0-9A-F]{2})/gi,
(_, hex) => String.fromCharCode(parseInt(hex, 16))
);
return btoa(binaryStr);
}
/**
* Decodes a Base64 string back to a Unicode string.
*
* Reverses encodeBase64:
* 1. atob() converts Base64 → binary string (each char is 0–255).
* 2. Each byte is converted back to a %XX percent-escape with
* .charCodeAt(0).toString(16).padStart(2,'0').
* charCodeAt(0) returns the numeric value of the character.
* toString(16) converts it to hex.
* padStart(2,'0') ensures it's always two digits (e.g. 9 → "09").
* 3. decodeURIComponent() converts the percent-encoded UTF-8 bytes back
* into the original Unicode string.
*
* @param {string} b64 - Standard or URL-safe Base64 string
* @returns {string} Decoded Unicode string
* @throws {Error} If the input is not valid Base64
*/
function decodeBase64(b64) {
// Normalise URL-safe chars before decoding (handles either mode)
const standard = b64.replace(/-/g, '+').replace(/_/g, '/');
const binaryStr = atob(standard);
const pctEncoded = binaryStr
.split('')
.map(ch => '%' + ch.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');
return decodeURIComponent(pctEncoded);
}
/**
* Converts a standard Base64 string to URL-safe Base64.
* RFC 4648 §5 replaces + → - and / → _ and strips trailing = padding.
*
* URL-safe Base64 is used in JWT tokens, URL parameters, and filenames
* because + and / have special meaning in URLs and must otherwise be
* percent-encoded, which inflates size and reduces readability.
*
* @param {string} b64 - Standard Base64 string
* @returns {string} URL-safe Base64 string (no padding)
*/
function toUrlSafe(b64) {
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
/**
* Restores URL-safe Base64 to standard Base64 with padding.
* Required before passing to atob(), which expects standard alphabet + padding.
*
* Padding rule: Base64 output length must be a multiple of 4.
* The number of missing padding characters is (4 - length % 4) % 4.
* The outer % 4 handles the case where length is already a multiple of 4
* (which would otherwise add 4 unnecessary padding chars).
*
* @param {string} b64url - URL-safe Base64 string
* @returns {string} Standard Base64 string with padding restored
*/
function fromUrlSafe(b64url) {
const s = b64url.replace(/-/g, '+').replace(/_/g, '/');
return s + '='.repeat((4 - s.length % 4) % 4);
}
/**
* Wraps a Base64 string at 76 characters per line (MIME standard).
* RFC 2045 specifies 76 characters as the max line length for MIME-encoded
* content (used in email, multipart forms, etc.).
* The regex /.{1,76}/g matches up to 76 characters at a time, greedily.
*
* @param {string} b64 - Base64 string to wrap
* @returns {string} Line-wrapped Base64
*/
function wrapAt76(b64) {
return b64.match(/.{1,76}/g).join('\n');
}
/**
* Heuristically detects whether a string looks like Base64.
* Used for auto-detect mode to decide encode vs decode direction.
*
* Detection logic:
* 1. Strip whitespace — wrapped/multiline Base64 has newlines.
* 2. Test against a loose Base64 character set: A-Z, a-z, 0-9, +, /, -, _, =
* The - and _ cover URL-safe variant; = covers padding.
* 3. Check that length (after stripping padding) is divisible by 4 when
* re-padded — valid Base64 output always has length % 4 === 0.
* 4. If all characters are printable ASCII (no extended Unicode), it could
* be Base64, but we confirm with the length check.
*
* Not a 100% guarantee — short alphanumeric strings are ambiguous — but
* reliable enough for a UX hint.
*
* @param {string} str
* @returns {boolean}
*/
function looksLikeBase64(str) {
const stripped = str.replace(/\s/g, '');
if (!stripped) return false;
if (!/^[A-Za-z0-9+/\-_=]+$/.test(stripped)) return false;
const normalised = stripped.replace(/-/g, '+').replace(/_/g, '/');
const padded = normalised + '='.repeat((4 - normalised.length % 4) % 4);
return padded.length % 4 === 0;
}
// ── Text panel logic ──────────────────────────────────────────────
/** Shows a status message with a severity class. */
function setStatus(el, msg, type = 'info') {
el.textContent = msg;
el.className = `status-bar is-${type}`;
}
/** Clears the status bar. */
function clearStatus(el) {
el.textContent = '';
el.className = 'status-bar';
}
/** Applies post-encode options (URL-safe conversion, line wrapping). */
function applyOutputOptions(b64) {
let result = b64;
if (urlSafeToggle.checked) result = toUrlSafe(result);
if (wrapToggle.checked) result = wrapAt76(result);
return result;
}
function handleEncode() {
const raw = inputEl.value;
if (!raw.trim()) { setStatus(statusBar, 'Nothing to encode.', 'info'); return; }
try {
const encoded = encodeBase64(raw);
outputEl.value = applyOutputOptions(encoded);
clearStatus(statusBar);
setStatus(statusBar,
`Encoded — ${raw.length} chars → ${outputEl.value.replace(/\s/g,'').length} Base64 chars`,
'success'
);
} catch (err) {
outputEl.value = '';
setStatus(statusBar, `Encode error: ${err.message}`, 'error');
}
}
function handleDecode() {
const raw = inputEl.value.trim();
if (!raw) { setStatus(statusBar, 'Nothing to decode.', 'info'); return; }
// Strip all whitespace (handles wrapped/multiline Base64)
const clean = raw.replace(/\s/g, '');
// Restore URL-safe characters and padding before atob
const normalised = fromUrlSafe(clean);
try {
const decoded = decodeBase64(normalised);
outputEl.value = decoded;
clearStatus(statusBar);
setStatus(statusBar,
`Decoded — ${clean.length} Base64 chars → ${decoded.length} chars`,
'success'
);
inputEl.classList.remove('is-error');
} catch (err) {
outputEl.value = '';
inputEl.classList.add('is-error');
setStatus(statusBar, 'Invalid Base64 — check your input.', 'error');
}
}
/** Auto-detect: inspect input and route to encode or decode. */
function handleAuto() {
const raw = inputEl.value;
if (!raw.trim()) return;
if (looksLikeBase64(raw)) {
handleDecode();
setStatus(statusBar, `Auto-detected Base64 → decoded. ${statusBar.textContent.split('—')[1] || ''}`.trim(), 'success');
} else {
handleEncode();
setStatus(statusBar, `Auto-detected text → encoded. ${statusBar.textContent.split('—')[1] || ''}`.trim(), 'success');
}
}
// ── File panel logic ──────────────────────────────────────────────
let selectedFile = null;
/**
* Converts a file to a Base64 data URI using FileReader.readAsDataURL(),
* then strips the "data:<mime>;base64," prefix to yield raw Base64.
*
* FileReader.readAsDataURL() is the only browser-native way to read a
* binary file as Base64 without Node.js Buffers or manual byte manipulation.
* It encodes all bytes of the file — not just printable characters — so it
* correctly handles images, PDFs, ZIPs, etc.
*
* The prefix format is: data:<mediatype>[;charset=<charset>];base64,<data>
* We split on the first comma to isolate the Base64 payload.
*
* @param {File} file
* @returns {Promise<string>} Raw Base64 string (without data URI prefix)
*/
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => resolve(e.target.result.split(',')[1]);
reader.onerror = () => reject(new Error('File could not be read'));
reader.readAsDataURL(file);
});
}
/** Formats a byte count as a human-readable size string. */
function formatBytes(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}
function handleFileSelected(file) {
if (!file) return;
selectedFile = file;
fileInfo.hidden = false;
fileNameEl.textContent = file.name;
fileSizeEl.textContent = formatBytes(file.size);
encodeFileBtn.disabled = false;
fileOutputEl.value = '';
clearStatus(fileStatusBar);
}
async function handleFileEncode() {
if (!selectedFile) return;
encodeFileBtn.disabled = true;
encodeFileBtn.textContent = 'Encoding…';
try {
const raw = await fileToBase64(selectedFile);
let result = raw;
if (urlSafeToggle.checked) result = toUrlSafe(result);
if (wrapToggle.checked) result = wrapAt76(result);
fileOutputEl.value = result;
const ratio = ((result.replace(/\s/g,'').length / selectedFile.size) * 0.75).toFixed(2);
setStatus(fileStatusBar,
`Encoded ${formatBytes(selectedFile.size)} → ${formatBytes(result.replace(/\s/g,'').length)} Base64 chars`,
'success'
);
} catch (err) {
setStatus(fileStatusBar, `Error: ${err.message}`, 'error');
} finally {
encodeFileBtn.disabled = false;
encodeFileBtn.textContent = 'Encode File → Base64';
}
}
// ── Clipboard helpers ─────────────────────────────────────────────
/**
* Writes text to the clipboard and gives visual feedback on the button.
* navigator.clipboard.writeText() is async and returns a Promise.
* Extension popups run in a secure context, so no user gesture is required.
*/
async function copyToClipboard(text, btn) {
if (!text.trim()) return;
try {
await navigator.clipboard.writeText(text);
btn.textContent = '✓ Copied';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = 'Copy';
btn.classList.remove('copied');
}, 1500);
} catch {
btn.textContent = 'Error';
setTimeout(() => { btn.textContent = 'Copy'; }, 1500);
}
}
/**
* Creates an invisible <a> with a Blob URL and clicks it programmatically
* to trigger a browser download. Revokes the object URL afterward to free
* memory — failing to revoke causes a memory leak for the tab's lifetime.
*/
function downloadText(text, filename) {
if (!text.trim()) return;
const blob = new Blob([text], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// ── Theme persistence ─────────────────────────────────────────────
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
themeToggle.textContent = theme === 'dark' ? '☀️' : '🌙';
themeToggle.setAttribute('aria-label', theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
}
function loadTheme() {
chrome.storage.local.get('theme', ({ theme }) => {
if (theme) {
applyTheme(theme);
} else {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
applyTheme(prefersDark ? 'dark' : 'light');
}
});
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const next = current === 'dark' ? 'light' : 'dark';
applyTheme(next);
chrome.storage.local.set({ theme: next });
}
// ── Tab switching ─────────────────────────────────────────────────
function switchTab(activeTab) {
const isText = activeTab === tabText;
tabText.classList.toggle('tab--active', isText);
tabFile.classList.toggle('tab--active', !isText);
tabText.setAttribute('aria-selected', isText);
tabFile.setAttribute('aria-selected', !isText);
panelText.classList.toggle('panel--hidden', !isText);
panelFile.classList.toggle('panel--hidden', isText);
}
// ── Input character counter ───────────────────────────────────────
function updateCharCount() {
const len = inputEl.value.length;
charCountEl.textContent = len > 0 ? `${len.toLocaleString()} chars` : '';
// Remove red border on new input
if (len === 0 || !looksLikeBase64(inputEl.value) === false) {
inputEl.classList.remove('is-error');
}
}
// ── init ──────────────────────────────────────────────────────────
function init() {
loadTheme();
// Theme toggle
themeToggle.addEventListener('click', toggleTheme);
// Tab switching
tabText.addEventListener('click', () => switchTab(tabText));
tabFile.addEventListener('click', () => switchTab(tabFile));
// Encode / Decode buttons
encodeBtn.addEventListener('click', handleEncode);
decodeBtn.addEventListener('click', handleDecode);
// Swap: move output → input and re-process
swapBtn.addEventListener('click', () => {
const out = outputEl.value;
if (!out) return;
inputEl.value = out;
outputEl.value = '';
updateCharCount();
clearStatus(statusBar);
inputEl.focus();
});
// Clear input
clearInputBtn.addEventListener('click', () => {
inputEl.value = '';
outputEl.value = '';
charCountEl.textContent = '';
inputEl.classList.remove('is-error');
clearStatus(statusBar);
inputEl.focus();
});
// Paste from clipboard
pasteBtn.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText();
inputEl.value = text;
updateCharCount();
clearStatus(statusBar);
// Auto-detect on paste if toggle is on
if (autoToggle.checked && text.trim()) handleAuto();
} catch {
setStatus(statusBar, 'Could not access clipboard.', 'error');
}
});
// Copy / download text output
copyOutputBtn.addEventListener('click', () => copyToClipboard(outputEl.value, copyOutputBtn));
downloadTxtBtn.addEventListener('click', () => downloadText(outputEl.value, 'base64-output.txt'));
// Auto-detect on input change
inputEl.addEventListener('input', () => {
updateCharCount();
clearStatus(statusBar);
inputEl.classList.remove('is-error');
// Soft auto-detect while typing (only after user pauses — debounced)
clearTimeout(inputEl._autoTimer);
if (autoToggle.checked) {
inputEl._autoTimer = setTimeout(() => {
if (inputEl.value.trim()) handleAuto();
}, 600); // 600ms debounce so it doesn't fire on every keystroke
}
});
// Keyboard shortcuts in text panel
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
inputEl.value = '';
outputEl.value = '';
charCountEl.textContent = '';
inputEl.classList.remove('is-error');
clearStatus(statusBar);
}
// Ctrl/Cmd+Enter → encode or auto-detect
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
autoToggle.checked ? handleAuto() : handleEncode();
}
});
// File panel — drop zone click opens file picker
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') fileInput.click();
});
// File input change (via picker)
fileInput.addEventListener('change', () => {
if (fileInput.files[0]) handleFileSelected(fileInput.files[0]);
});
// Drag-and-drop onto the drop zone
dropZone.addEventListener('dragover', e => {
e.preventDefault(); // Required to allow drop
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const file = e.dataTransfer.files[0];
if (file) handleFileSelected(file);
});
// Encode file button
encodeFileBtn.addEventListener('click', handleFileEncode);
// Copy / download file output
copyFileOutputBtn.addEventListener('click', () => copyToClipboard(fileOutputEl.value, copyFileOutputBtn));
downloadFileTxtBtn.addEventListener('click', () => downloadText(fileOutputEl.value, 'base64-file.txt'));
// Focus input on open
inputEl.focus();
}
init();