-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpopup.js
More file actions
311 lines (275 loc) · 9.43 KB
/
popup.js
File metadata and controls
311 lines (275 loc) · 9.43 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
/* ─────────────────────────────────────────
Text Case Converter — popup.js
No permissions required. Pure JS.
───────────────────────────────────────── */
// ── DOM refs ──────────────────────────────
const inputEl = document.getElementById('inputText');
const clearBtn = document.getElementById('clearBtn');
const outputGrid = document.getElementById('outputGrid');
const placeholder = document.getElementById('placeholder');
const themeToggle = document.getElementById('themeToggle');
const iconSun = document.getElementById('iconSun');
const iconMoon = document.getElementById('iconMoon');
// ── Conversion definitions ────────────────
// Each entry: { id, label, fn }
// `fn` receives the normalised word array and returns a formatted string.
const CONVERSIONS = [
{
id: 'camel',
label: 'camelCase',
fn: words => words.map((w, i) =>
i === 0 ? w.toLowerCase() : capitalize(w)
).join('')
},
{
id: 'pascal',
label: 'PascalCase',
fn: words => words.map(capitalize).join('')
},
{
id: 'snake',
label: 'snake_case',
fn: words => words.map(w => w.toLowerCase()).join('_')
},
{
id: 'screaming',
label: 'SCREAMING_SNAKE',
fn: words => words.map(w => w.toUpperCase()).join('_')
},
{
id: 'kebab',
label: 'kebab-case',
fn: words => words.map(w => w.toLowerCase()).join('-')
},
{
id: 'cobol',
label: 'COBOL-CASE',
fn: words => words.map(w => w.toUpperCase()).join('-')
},
{
id: 'dot',
label: 'dot.case',
fn: words => words.map(w => w.toLowerCase()).join('.')
},
{
id: 'path',
label: 'path/case',
fn: words => words.map(w => w.toLowerCase()).join('/')
},
{
id: 'title',
label: 'Title Case',
fn: words => words.map(capitalize).join(' ')
},
{
id: 'sentence',
label: 'Sentence case',
fn: words => {
const joined = words.map(w => w.toLowerCase()).join(' ');
return joined.charAt(0).toUpperCase() + joined.slice(1);
}
},
{
id: 'lower',
label: 'lowercase',
fn: words => words.join(' ').toLowerCase()
},
{
id: 'upper',
label: 'UPPERCASE',
fn: words => words.join(' ').toUpperCase()
},
{
id: 'toggle',
label: 'tOGGLE cASE',
fn: words => words.join(' ').split('').map(
(ch, i) => i % 2 === 0 ? ch.toLowerCase() : ch.toUpperCase()
).join('')
},
];
// ── Helpers ───────────────────────────────
/**
* capitalize — uppercase first letter, lowercase rest.
* @param {string} w
* @returns {string}
*/
const capitalize = w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();
/**
* tokenize — splits any input string into an array of clean words.
*
* Steps:
* 1. Split camelCase / PascalCase boundaries: insert a space before
* each uppercase letter that follows a lowercase letter.
* e.g. "helloWorld" → "hello World"
* 2. Split on any run of non-alphanumeric characters (spaces, -, _, ., /, etc.)
* 3. Filter out empty strings produced by leading/trailing separators.
*
* @param {string} str — raw input
* @returns {string[]} — array of lowercase-normalised words
*/
function tokenize(str) {
return str
// Step 1: camelCase / PascalCase split
.replace(/([a-z])([A-Z])/g, '$1 $2')
// Also handle sequences like "XMLParser" → "XML Parser"
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
// Step 2: split on non-word characters
.split(/[^a-zA-Z0-9]+/)
// Step 3: remove empties and normalise to lowercase
.filter(Boolean)
.map(w => w.toLowerCase());
}
// ── Copy to clipboard ─────────────────────
/**
* copyToClipboard — writes text to clipboard and briefly marks the button.
* Uses the modern async Clipboard API (available in extension popups).
*
* @param {string} text
* @param {HTMLButtonElement} btn
*/
async function copyToClipboard(text, btn) {
try {
await navigator.clipboard.writeText(text);
btn.textContent = '✓ Copied';
btn.classList.add('copied');
setTimeout(() => {
btn.textContent = 'Copy';
btn.classList.remove('copied');
}, 1500);
} catch {
// Fallback for edge cases (shouldn't happen in an extension popup)
btn.textContent = 'Error';
}
}
// ── Render ────────────────────────────────
/**
* renderCards — builds or updates one output card per conversion.
* Called on every input event; uses a keyed update strategy to avoid
* tearing down and rebuilding the entire DOM on each keystroke.
*
* @param {string[]} words — tokenised word array (may be empty)
*/
function renderCards(words) {
const hasInput = words.length > 0;
// Show/hide the placeholder
if (placeholder) placeholder.style.display = hasInput ? 'none' : '';
CONVERSIONS.forEach(({ id, label, fn }) => {
const value = hasInput ? fn(words) : '';
// Try to find an existing card for this conversion (keyed by data-id)
let card = outputGrid.querySelector(`[data-id="${id}"]`);
if (!card) {
// ── First render: create the card DOM ──
card = document.createElement('div');
card.className = 'output-card';
card.dataset.id = id;
card.setAttribute('role', 'group');
card.setAttribute('aria-label', label);
const labelEl = document.createElement('div');
labelEl.className = 'output-card__label';
labelEl.textContent = label;
const row = document.createElement('div');
row.className = 'output-card__row';
const valueEl = document.createElement('span');
valueEl.className = 'output-card__value';
valueEl.title = value; // full value in tooltip (important for long strings)
const copyBtn = document.createElement('button');
copyBtn.className = 'btn-copy';
copyBtn.textContent = 'Copy';
copyBtn.setAttribute('aria-label', `Copy ${label}`);
copyBtn.addEventListener('click', () => {
if (valueEl.dataset.value) copyToClipboard(valueEl.dataset.value, copyBtn);
});
row.append(valueEl, copyBtn);
card.append(labelEl, row);
outputGrid.appendChild(card);
}
// ── Update card state (both first render and subsequent updates) ──
const valueEl = card.querySelector('.output-card__value');
const copyBtn = card.querySelector('.btn-copy');
if (hasInput) {
valueEl.textContent = value;
valueEl.title = value;
valueEl.dataset.value = value;
valueEl.classList.remove('output-card__value--empty');
copyBtn.disabled = false;
} else {
valueEl.textContent = '—';
valueEl.title = '';
valueEl.dataset.value = '';
valueEl.classList.add('output-card__value--empty');
copyBtn.disabled = true;
}
});
}
// ── Input handler ─────────────────────────
/**
* handleInput — debounced listener for textarea changes.
* Tokenises the current value and triggers a re-render.
*/
function handleInput() {
const raw = inputEl.value;
const words = tokenize(raw);
// Show/hide clear button
clearBtn.classList.toggle('visible', raw.length > 0);
renderCards(words);
}
// ── Theme ─────────────────────────────────
/**
* applyTheme — sets the data-theme attribute on <html> and flips the icons.
* @param {'light'|'dark'} theme
*/
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
iconSun.classList.toggle('hidden', theme === 'dark');
iconMoon.classList.toggle('hidden', theme === 'light');
}
/**
* loadTheme — reads persisted preference from chrome.storage.local.
* Falls back to the OS preference via prefers-color-scheme if no saved value.
*/
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');
}
});
}
/**
* toggleTheme — flips between light and dark, persists the choice.
*/
function toggleTheme() {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
const next = isDark ? 'light' : 'dark';
applyTheme(next);
chrome.storage.local.set({ theme: next });
}
// ── Keyboard shortcuts ────────────────────
document.addEventListener('keydown', e => {
// Escape: clear input
if (e.key === 'Escape') {
inputEl.value = '';
handleInput();
inputEl.focus();
}
});
// ── Init ──────────────────────────────────
function init() {
// Wire up events FIRST — so a theme storage error can never block input
inputEl.addEventListener('input', handleInput);
clearBtn.addEventListener('click', () => {
inputEl.value = '';
handleInput();
inputEl.focus();
});
themeToggle.addEventListener('click', toggleTheme);
// Initial render (empty state)
renderCards([]);
// Auto-focus the textarea
inputEl.focus();
// Restore theme last — non-critical, failure won't affect functionality
loadTheme();
}
init();