-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
389 lines (345 loc) · 12 KB
/
script.js
File metadata and controls
389 lines (345 loc) · 12 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
/**
* Text Case Converter - Core Application Logic
* A lightweight, vanilla JavaScript case converter with real-time updates
*/
// Utility functions for text processing
const utils = {
/**
* Split text into words, handling mixed case formats intelligently
* @param {string} text - Input text to split
* @returns {string[]} Array of words
*/
splitWords(text) {
if (!text || typeof text !== 'string') return [];
return text
// Handle camelCase and PascalCase
.replace(/([a-z])([A-Z])/g, '$1 $2')
// Handle numbers adjacent to letters
.replace(/([a-zA-Z])(\d)/g, '$1 $2')
.replace(/(\d)([a-zA-Z])/g, '$1 $2')
// Split on common delimiters
.split(/[\s\-_]+/)
// Filter out empty strings
.filter(word => word.length > 0);
},
/**
* Sanitize input text by removing excessive whitespace
* @param {string} text - Input text to sanitize
* @returns {string} Sanitized text
*/
sanitizeInput(text) {
if (!text || typeof text !== 'string') return '';
return text.trim().replace(/\s+/g, ' ');
},
/**
* Capitalize first letter of a word
* @param {string} word - Word to capitalize
* @returns {string} Capitalized word
*/
capitalize(word) {
if (!word) return '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
},
/**
* Debounce function to limit frequent calls
* @param {Function} func - Function to debounce
* @param {number} wait - Wait time in milliseconds
* @returns {Function} Debounced function
*/
debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
};
// Case conversion functions - pure functions with no side effects
const converters = {
/**
* Convert to camelCase (firstName)
* @param {string} text - Input text
* @returns {string} camelCase formatted text
*/
toCamelCase(text) {
const words = utils.splitWords(text);
if (words.length === 0) return '';
return words[0].toLowerCase() +
words.slice(1).map(word => utils.capitalize(word)).join('');
},
/**
* Convert to PascalCase (FirstName)
* @param {string} text - Input text
* @returns {string} PascalCase formatted text
*/
toPascalCase(text) {
const words = utils.splitWords(text);
return words.map(word => utils.capitalize(word)).join('');
},
/**
* Convert to snake_case (first_name)
* @param {string} text - Input text
* @returns {string} snake_case formatted text
*/
toSnakeCase(text) {
const words = utils.splitWords(text);
return words.map(word => word.toLowerCase()).join('_');
},
/**
* Convert to kebab-case (first-name)
* @param {string} text - Input text
* @returns {string} kebab-case formatted text
*/
toKebabCase(text) {
const words = utils.splitWords(text);
return words.map(word => word.toLowerCase()).join('-');
},
/**
* Convert to SCREAMING_SNAKE_CASE (FIRST_NAME)
* @param {string} text - Input text
* @returns {string} SCREAMING_SNAKE_CASE formatted text
*/
toScreamingSnakeCase(text) {
const words = utils.splitWords(text);
return words.map(word => word.toUpperCase()).join('_');
},
/**
* Convert to lowercase (firstname)
* @param {string} text - Input text
* @returns {string} lowercase formatted text
*/
toLowercase(text) {
return utils.sanitizeInput(text).toLowerCase();
},
/**
* Convert to UPPERCASE (FIRSTNAME)
* @param {string} text - Input text
* @returns {string} UPPERCASE formatted text
*/
toUppercase(text) {
return utils.sanitizeInput(text).toUpperCase();
},
/**
* Convert to Title Case (First Name)
* @param {string} text - Input text
* @returns {string} Title Case formatted text
*/
toTitleCase(text) {
const words = utils.splitWords(text);
return words.map(word => utils.capitalize(word)).join(' ');
},
/**
* Convert to Sentence case (First name)
* @param {string} text - Input text
* @returns {string} Sentence case formatted text
*/
toSentenceCase(text) {
const words = utils.splitWords(text);
if (words.length === 0) return '';
return utils.capitalize(words[0]) +
(words.length > 1 ? ' ' + words.slice(1).map(word => word.toLowerCase()).join(' ') : '');
}
};
// UI Controller - handles DOM manipulation and user interactions
const ui = {
// Cache DOM elements for better performance
elements: {
inputText: null,
clearBtn: null,
charCount: null,
outputFields: null,
copyBtns: null,
notification: null
},
/**
* Initialize UI elements and event listeners
*/
init() {
this.cacheElements();
this.setupEventListeners();
this.updateCharCount('');
},
/**
* Cache frequently used DOM elements
*/
cacheElements() {
this.elements.inputText = document.getElementById('input-text');
this.elements.clearBtn = document.getElementById('clear-btn');
this.elements.charCount = document.getElementById('char-count');
this.elements.outputFields = document.querySelectorAll('.output-field');
this.elements.copyBtns = document.querySelectorAll('.copy-btn');
this.elements.notification = document.getElementById('copy-notification');
},
/**
* Set up all event listeners
*/
setupEventListeners() {
// Debounced input handler for performance
const debouncedUpdate = utils.debounce((text) => {
this.updateOutputs(text);
}, 150);
this.elements.inputText.addEventListener('input', (e) => {
const text = e.target.value;
this.updateCharCount(text);
debouncedUpdate(text);
});
this.elements.clearBtn.addEventListener('click', () => {
this.clearInput();
});
// Copy button handlers
this.elements.copyBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
const caseType = e.currentTarget.dataset.case;
this.copyToClipboard(caseType, e.currentTarget);
});
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
if (e.key === 'k') {
e.preventDefault();
this.elements.inputText.focus();
}
}
});
},
/**
* Update character count display
* @param {string} text - Current input text
*/
updateCharCount(text) {
const count = text.length;
const words = text.trim() ? utils.splitWords(text).length : 0;
this.elements.charCount.textContent = `${count} characters, ${words} words`;
},
/**
* Update all output fields with converted text
* @param {string} inputText - Input text to convert
*/
updateOutputs(inputText) {
const sanitizedText = utils.sanitizeInput(inputText);
// Mapping of case types to converter functions
const caseMap = {
'camelCase': converters.toCamelCase,
'PascalCase': converters.toPascalCase,
'snake_case': converters.toSnakeCase,
'kebab-case': converters.toKebabCase,
'SCREAMING_SNAKE_CASE': converters.toScreamingSnakeCase,
'lowercase': converters.toLowercase,
'UPPERCASE': converters.toUppercase,
'Title Case': converters.toTitleCase,
'Sentence case': converters.toSentenceCase
};
// Update each output field
this.elements.outputFields.forEach(field => {
const caseType = field.closest('.converter-item').dataset.case;
const converter = caseMap[caseType];
if (converter) {
field.value = converter(sanitizedText);
}
});
},
/**
* Clear input and all outputs
*/
clearInput() {
this.elements.inputText.value = '';
this.elements.inputText.focus();
this.updateCharCount('');
this.updateOutputs('');
},
/**
* Copy text to clipboard with visual feedback
* @param {string} caseType - Type of case being copied
* @param {HTMLElement} button - Copy button element
*/
async copyToClipboard(caseType, button) {
const outputField = button.parentElement.querySelector('.output-field');
const textToCopy = outputField.value;
if (!textToCopy) {
this.showNotification('Nothing to copy!', 'error');
return;
}
try {
// Modern Clipboard API
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(textToCopy);
} else {
// Fallback for older browsers
this.fallbackCopyToClipboard(textToCopy);
}
this.showCopySuccess(button, caseType);
this.showNotification(`${caseType} copied to clipboard!`);
} catch (err) {
console.error('Copy failed:', err);
this.showNotification('Copy failed. Please try again.', 'error');
}
},
/**
* Fallback copy method for older browsers
* @param {string} text - Text to copy
*/
fallbackCopyToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} finally {
document.body.removeChild(textArea);
}
},
/**
* Show visual feedback for successful copy
* @param {HTMLElement} button - Copy button element
* @param {string} caseType - Type of case copied
*/
showCopySuccess(button, caseType) {
const originalText = button.querySelector('.copy-text').textContent;
const copyText = button.querySelector('.copy-text');
button.classList.add('copied');
copyText.textContent = 'Copied!';
setTimeout(() => {
button.classList.remove('copied');
copyText.textContent = originalText;
}, 2000);
},
/**
* Show notification message
* @param {string} message - Message to display
* @param {string} type - Type of notification ('success' or 'error')
*/
showNotification(message, type = 'success') {
this.elements.notification.textContent = message;
this.elements.notification.className = `copy-notification ${type}`;
this.elements.notification.classList.add('show');
setTimeout(() => {
this.elements.notification.classList.remove('show');
}, 3000);
}
};
// Application initialization
document.addEventListener('DOMContentLoaded', () => {
ui.init();
// Add some example text if the URL has a parameter
const urlParams = new URLSearchParams(window.location.search);
const exampleText = urlParams.get('text');
if (exampleText) {
ui.elements.inputText.value = decodeURIComponent(exampleText);
ui.updateCharCount(ui.elements.inputText.value);
ui.updateOutputs(ui.elements.inputText.value);
}
});
// Export for testing purposes (if running in Node.js environment)
if (typeof module !== 'undefined' && module.exports) {
module.exports = { utils, converters, ui };
}