-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch-hex-code-viewer.html
More file actions
589 lines (510 loc) · 19.7 KB
/
Copy pathbatch-hex-code-viewer.html
File metadata and controls
589 lines (510 loc) · 19.7 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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hex Color Viewer</title>
<style>
/* CSS Reset - Remove default browser styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Base body styles with neobrutalist gray background */
body {
font-family: 'Courier New', monospace;
background: #979797;
padding: 40px 20px;
min-height: 100vh;
}
/* Main container with max-width for responsive design */
.container {
max-width: 900px;
margin: 0 auto;
}
h1 {
font-size: 48px;
font-weight: 900;
text-transform: uppercase;
color: #000;
border: 6px solid #000;
padding: 20px 30px;
background-color: #FFD700;
box-shadow: 12px 12px 0 #000;
margin-bottom: 20px;
text-align: center;
}
.subtitle {
background-color: #fff;
border: 4px solid #000;
padding: 15px 25px;
font-size: 16px;
font-weight: bold;
text-transform: uppercase;
box-shadow: 8px 8px 0 #000;
margin-bottom: 40px;
text-align: center;
}
/* Input section with thick borders and shadows */
.input-section {
background: #fff;
border: 6px solid #000;
box-shadow: 12px 12px 0px #000;
padding: 30px;
margin-bottom: 40px;
}
/* Form label styling with uppercase text */
label {
display: block;
font-size: 1.2rem;
font-weight: bold;
color: #000;
margin-bottom: 15px;
text-transform: uppercase;
}
/* Textarea with harsh borders */
textarea {
width: 100%;
min-height: 120px;
padding: 15px;
font-family: 'Courier New', monospace;
font-size: 1rem;
border: 4px solid #000;
background: #F5F5F5;
resize: vertical;
outline: none;
}
/* Textarea focus state with green outline */
textarea:focus {
background: #fff;
box-shadow: 0 0 0 4px #00E676;
}
/* Button with neobrutalism style */
button {
margin-top: 20px;
padding: 15px 40px;
font-family: 'Courier New', monospace;
font-size: 1.1rem;
font-weight: bold;
text-transform: uppercase;
background: #00E676;
color: #000;
border: 4px solid #000;
cursor: pointer;
box-shadow: 6px 6px 0px #000;
transition: all 0.1s;
}
/* Button hover effect - moves up and left */
button:hover {
transform: translate(2px, 2px);
box-shadow: 4px 4px 0px #000;
}
/* Button active effect - appears pressed down */
button:active {
transform: translate(6px, 6px);
box-shadow: 0px 0px 0px #000;
}
/* Hidden class for share button */
.hidden {
display: none;
}
/* Share button styling */
#shareColors {
background: #FFD700;
color: #000;
}
/* Grid container for color tiles */
.color-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 30px;
margin-top: 20px;
}
/* Individual color tile with thick borders */
.color-tile {
aspect-ratio: 1;
border: 6px solid #000;
box-shadow: 8px 8px 0px #000;
cursor: pointer;
transition: all 0.15s;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
/* Color tile hover effect - moves up and left */
.color-tile:hover {
transform: translate(3px, 3px);
box-shadow: 5px 5px 0px #000;
}
/* Color tile active effect - appears pressed down */
.color-tile:active {
transform: translate(8px, 8px);
box-shadow: 0px 0px 0px #000;
}
/* Label inside each tile - WCAG compliant colors */
.color-label {
font-family: 'Courier New', monospace;
font-size: 1rem;
font-weight: bold;
text-align: center;
padding: 10px;
word-break: break-all;
text-transform: uppercase;
}
/* Invalid hex code tile styling */
.invalid-tile {
background: repeating-linear-gradient(
45deg,
#FF1744,
#FF1744 10px,
#000 10px,
#000 20px
);
}
/* Invalid hex code label styling */
.invalid-label {
background: #fff;
color: #000;
padding: 15px;
border: 3px solid #000;
font-size: 0.85rem;
}
/* Copy notification toast */
.copy-notification {
position: fixed;
top: 30px;
right: 30px;
background: #00E676;
color: #000;
padding: 20px 30px;
border: 5px solid #000;
box-shadow: 8px 8px 0px #000;
font-weight: bold;
font-size: 1.1rem;
z-index: 1000;
animation: slideIn 0.3s, slideOut 0.3s 2.7s;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
/* Mobile responsive adjustments */
@media (max-width: 768px) {
h1 {
font-size: 2rem;
}
.color-grid {
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 20px;
}
}
</style>
</head>
<body>
<div class="container">
<h1>BATCH HEX CODE VIEWER</h1>
<p class="subtitle">Paste any text containing hex codes to extract and view them</p>
<!-- Input section -->
<div class="input-section">
<label for="hexInput">Hex Codes:</label>
<textarea
id="hexInput"
placeholder="e.g., $green: #113CA1; $purple: #5A3CA1; 1575EF"
aria-label="Paste any text containing hex color codes"
></textarea>
<button id="showColors" type="button">SHOW COLORS</button>
<button id="shareColors" type="button" class="hidden">SHARE THESE COLORS</button>
</div>
<!-- Grid container for color tiles -->
<div class="color-grid" id="colorGrid"></div>
</div>
<script>
// DOM element references for UI interaction
const hexInput = document.getElementById('hexInput');
const showColorsBtn = document.getElementById('showColors');
const shareColorsBtn = document.getElementById('shareColors');
const colorGrid = document.getElementById('colorGrid');
/**
* Validates if a string is a valid hex color code
* Accepts 3 or 6 character hex codes with or without #
* @param {string} hex - The hex string to validate
* @returns {boolean} - True if valid, false otherwise
*/
function isValidHex(hex) {
// Remove # if present
const cleanHex = hex.replace('#', '');
// Check if it's 3 or 6 characters and contains only valid hex characters
return /^[0-9A-Fa-f]{3}$|^[0-9A-Fa-f]{6}$/.test(cleanHex);
}
/**
* Normalizes hex code to full 6-character format with #
* Converts 3-char hex codes to 6-char by doubling each character
* @param {string} hex - The hex string to normalize
* @returns {string} - Normalized hex code with #
*/
function normalizeHex(hex) {
// Remove # if present
let cleanHex = hex.replace('#', '').toUpperCase();
// If 3 characters, expand to 6 (e.g., "F00" becomes "FF0000")
if (cleanHex.length === 3) {
cleanHex = cleanHex.split('').map(char => char + char).join('');
}
return '#' + cleanHex;
}
/**
* Calculates relative luminance of a color according to WCAG standards
* Formula from WCAG 2.1 specification
* @param {number} r - Red value (0-255)
* @param {number} g - Green value (0-255)
* @param {number} b - Blue value (0-255)
* @returns {number} - Relative luminance (0-1)
*/
function getRelativeLuminance(r, g, b) {
// Normalize RGB values to 0-1 range
const rsRGB = r / 255;
const gsRGB = g / 255;
const bsRGB = b / 255;
// Apply gamma correction as per WCAG formula
const rLinear = rsRGB <= 0.03928 ? rsRGB / 12.92 : Math.pow((rsRGB + 0.055) / 1.055, 2.4);
const gLinear = gsRGB <= 0.03928 ? gsRGB / 12.92 : Math.pow((gsRGB + 0.055) / 1.055, 2.4);
const bLinear = bsRGB <= 0.03928 ? bsRGB / 12.92 : Math.pow((bsRGB + 0.055) / 1.055, 2.4);
// Calculate relative luminance using WCAG coefficients
return 0.2126 * rLinear + 0.7152 * gLinear + 0.0722 * bLinear;
}
/**
* Determines if text should be black or white based on background color
* Uses WCAG contrast ratio guidelines for accessibility
* @param {string} hexColor - Background color in hex format
* @returns {string} - Either '#000000' (black) or '#FFFFFF' (white)
*/
function getContrastingTextColor(hexColor) {
// Remove # and convert hex to RGB
const hex = hexColor.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16);
const g = parseInt(hex.substr(2, 2), 16);
const b = parseInt(hex.substr(4, 2), 16);
// Calculate luminance
const luminance = getRelativeLuminance(r, g, b);
// Return black text for light backgrounds, white for dark
// Threshold of 0.5 provides good contrast in most cases
return luminance > 0.5 ? '#000000' : '#FFFFFF';
}
/**
* Copies text to clipboard and shows notification
* Uses modern Clipboard API with fallback
* @param {string} text - Text to copy to clipboard
* @param {string} notificationText - Optional custom notification text
*/
function copyToClipboard(text, notificationText = null) {
// Use modern Clipboard API
navigator.clipboard.writeText(text).then(() => {
showCopyNotification(notificationText || text);
}).catch(err => {
// Fallback for older browsers
console.error('Failed to copy:', err);
});
}
/**
* Creates a shareable URL with colors pre-populated
* @returns {string} - Shareable URL with color parameters
*/
function createShareableUrl() {
const input = hexInput.value.trim();
if (!input) return '';
// Parse hex codes from input
const hexCodes = parseHexCodes(input);
const validColors = hexCodes.filter(hexCode => isValidHex(hexCode));
if (validColors.length === 0) return '';
// Create URL with colors as query parameter
const baseUrl = window.location.origin + window.location.pathname;
const colorParam = validColors.join(',');
return `${baseUrl}?colors=${encodeURIComponent(colorParam)}`;
}
/**
* Handles sharing colors by copying URL to clipboard
*/
function shareColors() {
const shareUrl = createShareableUrl();
if (shareUrl) {
copyToClipboard(shareUrl, 'URL copied');
}
}
/**
* Shows a temporary notification when hex code is copied
* @param {string} hexCode - The hex code that was copied
*/
function showCopyNotification(hexCode) {
// Create notification element
const notification = document.createElement('div');
notification.className = 'copy-notification';
notification.textContent = `COPIED: ${hexCode}`;
notification.setAttribute('role', 'alert');
notification.setAttribute('aria-live', 'polite');
document.body.appendChild(notification);
// Remove notification after animation completes
setTimeout(() => {
notification.remove();
}, 3000);
}
/**
* Creates a color tile element for the grid
* @param {string} hexCode - The hex color code
* @param {boolean} isValid - Whether the hex code is valid
* @returns {HTMLElement} - The created tile element
*/
function createColorTile(hexCode, isValid) {
const tile = document.createElement('div');
tile.className = 'color-tile';
if (isValid) {
// Normalize the hex code
const normalizedHex = normalizeHex(hexCode);
// Set background color
tile.style.backgroundColor = normalizedHex;
// Create label with contrasting text color
const label = document.createElement('div');
label.className = 'color-label';
label.textContent = normalizedHex;
label.style.color = getContrastingTextColor(normalizedHex);
tile.appendChild(label);
// Add click handler to copy hex code
tile.addEventListener('click', () => {
copyToClipboard(normalizedHex);
});
// Add keyboard accessibility
tile.setAttribute('tabindex', '0');
tile.setAttribute('role', 'button');
tile.setAttribute('aria-label', `Copy color ${normalizedHex}`);
// Handle Enter/Space key press
tile.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
copyToClipboard(normalizedHex);
}
});
} else {
// Create invalid tile with striped background
tile.classList.add('invalid-tile');
const label = document.createElement('div');
label.className = 'color-label invalid-label';
label.textContent = `INVALID: ${hexCode}`;
tile.appendChild(label);
// Make non-interactive
tile.style.cursor = 'not-allowed';
tile.setAttribute('aria-label', `Invalid hex code: ${hexCode}`);
}
return tile;
}
/**
* Parses input string and extracts hex codes
* Uses regex to find hex patterns in any text content
* @param {string} input - Raw input string from textarea
* @returns {Array<string>} - Array of hex code strings
*/
function parseHexCodes(input) {
// Regex to match hex color codes (3 or 6 characters, with or without #)
const hexRegex = /#?[0-9A-Fa-f]{3}(?:[0-9A-Fa-f]{3})?/g;
// Find all matches and return them
const matches = input.match(hexRegex);
return matches ? matches : [];
}
/**
* Main function to process input and display color tiles
*/
function displayColors() {
// Clear existing tiles
colorGrid.innerHTML = '';
// Get input value
const input = hexInput.value.trim();
if (!input) {
// Hide share button if no input
shareColorsBtn.classList.add('hidden');
return;
}
// Parse hex codes from input
const hexCodes = parseHexCodes(input);
// Create a tile for each hex code
hexCodes.forEach(hexCode => {
const isValid = isValidHex(hexCode);
const tile = createColorTile(hexCode, isValid);
colorGrid.appendChild(tile);
});
// Show share button if we have valid colors
const validColors = hexCodes.filter(hexCode => isValidHex(hexCode));
if (validColors.length > 0) {
shareColorsBtn.classList.remove('hidden');
} else {
shareColorsBtn.classList.add('hidden');
}
}
/**
* Generates a random hex color code
* @returns {string} - Random hex color in format #RRGGBB
*/
function getRandomColor() {
// Generate random values for R, G, B (0-255)
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
// Convert to hex and pad with zeros if needed
const hex = '#' +
r.toString(16).padStart(2, '0') +
g.toString(16).padStart(2, '0') +
b.toString(16).padStart(2, '0');
return hex.toUpperCase();
}
/**
* Sets a random background color on page load
*/
function setRandomBackgroundColor() {
const randomColor = getRandomColor();
document.body.style.backgroundColor = randomColor;
console.log('Background color set to:', randomColor);
}
// Initialize page with random background color
setRandomBackgroundColor();
// Event listener for button click
showColorsBtn.addEventListener('click', displayColors);
// Event listener for share button
shareColorsBtn.addEventListener('click', shareColors);
// Keyboard shortcut: Ctrl+Enter or Cmd+Enter to display colors
hexInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
displayColors();
}
});
/**
* Load colors from URL parameters if present
*/
function loadColorsFromUrl() {
const urlParams = new URLSearchParams(window.location.search);
const colorsParam = urlParams.get('colors');
if (colorsParam) {
const colors = colorsParam.split(',').map(color => color.trim()).filter(color => color);
hexInput.value = colors.join(' ');
displayColors();
}
}
// Load colors from URL on page load
loadColorsFromUrl();
</script>
</body>
</html>