-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2427 lines (2124 loc) · 89.9 KB
/
app.js
File metadata and controls
2427 lines (2124 loc) · 89.9 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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// app.js
// Client-side APCA + WCAG 2.x contrast checker with suggestion support.
let APCAcontrast = null;
let APCA_sRGBtoY = null;
// Try to dynamically import APCA. If it fails, we still run the rest.
(async function init() {
try {
const mod = await import("https://cdn.jsdelivr.net/npm/apca-w3@0.1.9/+esm");
APCAcontrast = mod.APCAcontrast;
// helper to convert sRGB (0-255) to the Y value expected by APCAcontrast
APCA_sRGBtoY = mod.sRGBtoY || null;
} catch (e) {
console.warn("APCA module could not be loaded. APCA results will be n/a.", e);
}
setupContrastTool();
})();
// Ensure random helpers are available globally for event handlers
// Simple HSL -> HEX converter (expects h in degrees 0-360, s and l in percent 0-100)
function hslToHex(h, s, l) {
s = s / 100;
l = l / 100;
const c = (1 - Math.abs(2 * l - 1)) * s;
const hh = (h % 360) / 60;
const x = c * (1 - Math.abs((hh % 2) - 1));
let r1 = 0, g1 = 0, b1 = 0;
if (0 <= hh && hh < 1) { r1 = c; g1 = x; b1 = 0; }
else if (1 <= hh && hh < 2) { r1 = x; g1 = c; b1 = 0; }
else if (2 <= hh && hh < 3) { r1 = 0; g1 = c; b1 = x; }
else if (3 <= hh && hh < 4) { r1 = 0; g1 = x; b1 = c; }
else if (4 <= hh && hh < 5) { r1 = x; g1 = 0; b1 = c; }
else { r1 = c; g1 = 0; b1 = x; }
const m = l - c / 2;
const r = Math.round((r1 + m) * 255);
const g = Math.round((g1 + m) * 255);
const b = Math.round((b1 + m) * 255);
const toHex = (n) => n.toString(16).padStart(2, '0').toUpperCase();
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function randomHex() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
const toHex = (n) => n.toString(16).padStart(2, '0').toUpperCase();
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function randomLightHex() {
const h = Math.floor(Math.random() * 360);
const s = Math.floor(Math.random() * 30) + 50; // 50-80%
const l = Math.floor(Math.random() * 15) + 70; // 70-85%
return hslToHex(h, s, l);
}
function randomDarkHex() {
const h = Math.floor(Math.random() * 360);
const s = Math.floor(Math.random() * 40) + 40; // 40-80%
const l = Math.floor(Math.random() * 20) + 8; // 8-28%
return hslToHex(h, s, l);
}
function hashCode(str) {
let h = 0;
for (let i = 0; i < str.length; i++) {
h = ((h << 5) - h) + str.charCodeAt(i);
h |= 0;
}
return h;
}
function setupContrastTool() {
// ---------- DOM references ----------
const page = document.getElementById("main");
const fgText = document.getElementById("fgText");
const fgPicker = document.getElementById("fgPicker");
const bgText = document.getElementById("bgText");
const bgPicker = document.getElementById("bgPicker");
const thirdText = document.getElementById("thirdText");
const thirdPicker = document.getElementById("thirdPicker");
const enableThird = document.getElementById("enableThird");
const thirdContainer = document.getElementById("thirdContainer");
const wcagThresholdSelect = document.getElementById("wcagThreshold");
const apcaThresholdSelect = document.getElementById("apcaThreshold");
const previewBase = document.getElementById("previewBase");
const previewThird = document.getElementById("previewThird");
const previewThirdCard = document.getElementById("previewThirdCard");
const demoHeadingBase = document.getElementById("demoHeadingBase");
const demoLinkBase = document.getElementById("demoLinkBase");
const demoButtonBase = document.querySelector("#demoButtonBase");
const demoHeadingThird = document.getElementById("demoHeadingThird");
const demoLinkThird = document.getElementById("demoLinkThird");
const demoButtonThird = document.querySelector("#demoButtonThird");
const simToggles = Array.from(document.querySelectorAll(".sim-toggle"));
// Initialize simulation toggle visual state from aria-pressed attributes
simToggles.forEach(b => {
const pressed = b.getAttribute('aria-pressed') === 'true';
if (pressed) {
b.classList.add('sim-toggle-active');
b.classList.remove('btn-secondary');
b.classList.add('btn-primary');
} else {
b.classList.remove('sim-toggle-active');
b.classList.remove('btn-primary');
b.classList.add('btn-secondary');
}
});
const errorBox = document.getElementById("errorBox");
const resultsBody = document.getElementById("resultsBody");
const focusSummary = document.getElementById("focusSummary");
const focusText = document.getElementById("focusText");
const suggestSection = document.getElementById("suggestSection");
const fgSuggestions = document.getElementById("fgSuggestions");
const bgSuggestions = document.getElementById("bgSuggestions");
const thirdSuggestionBlock = document.getElementById("thirdSuggestionBlock");
const thirdSuggestions = document.getElementById("thirdSuggestions");
const suggestionStatus = document.getElementById("suggestionStatus");
const liveRegion = document.getElementById("liveRegion");
const themeToggleBtn = document.getElementById("theme-toggle");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
let userHasThemeOverride = false;
// Read colors from URL params on load (e.g., ?fg=%23B53636&bg=%234e4c18&third=%23663399)
function readColorsFromURL() {
try {
const params = new URLSearchParams(window.location.search);
const fgParam = params.get('fg');
const bgParam = params.get('bg');
const thirdParam = params.get('third');
if (fgParam) {
try { const p = parseCssColor(fgParam); fgText.value = fgText.value || p.hex; fgPicker.value = p.hex; } catch {}
}
if (bgParam) {
try { const p = parseCssColor(bgParam); bgText.value = bgText.value || p.hex; bgPicker.value = p.hex; } catch {}
}
if (thirdParam) {
try { const p = parseCssColor(thirdParam); thirdText.value = thirdText.value || p.hex; thirdPicker.value = p.hex; enableThird.checked = true; thirdContainer.classList.remove('hidden'); } catch {}
}
} catch (e) {
// ignore
}
}
function updateURLWithColors(fgHex, bgHex, thirdHex) {
try {
const params = new URLSearchParams(window.location.search);
if (fgHex) params.set('fg', fgHex);
else params.delete('fg');
if (bgHex) params.set('bg', bgHex);
else params.delete('bg');
if (thirdHex) params.set('third', thirdHex);
else params.delete('third');
const newUrl = window.location.pathname + '?' + params.toString();
history.replaceState(null, '', newUrl);
} catch (e) {}
}
function applyTheme(theme) {
const root = document.documentElement;
if (theme === "light" || theme === "dark") {
root.dataset.theme = theme;
} else {
delete root.dataset.theme;
}
if (themeToggleBtn) {
if (theme === "dark" || (theme === "system" && prefersDarkScheme.matches)) {
themeToggleBtn.setAttribute("aria-label", "Switch to light mode");
} else {
themeToggleBtn.setAttribute("aria-label", "Switch to dark mode");
}
}
try {
if (theme === "light" || theme === "dark") {
localStorage.setItem("contrastToolTheme", theme);
} else {
localStorage.removeItem("contrastToolTheme");
}
} catch {}
}
// Hidden element used to let the browser parse CSS color strings.
const parserElement = document.createElement("span");
parserElement.style.display = "none";
document.body.appendChild(parserElement);
// Determine initial theme: use stored user preference, or fall back to system preference
const systemTheme = prefersDarkScheme.matches ? "dark" : "light";
let initialTheme = systemTheme;
try {
const stored = localStorage.getItem("contrastToolTheme");
if (stored === "light" || stored === "dark") {
initialTheme = stored;
userHasThemeOverride = true;
}
} catch {}
applyTheme(initialTheme);
// ---------- Helpers ----------
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
// Compute a nearby focus color meeting 3:1 with foreground and reasonable contrast with background
function computeClosestFocus(fgRgb, bgRgb) {
const fgHsl = rgbToHsl(fgRgb);
const bgHsl = rgbToHsl(bgRgb);
const baseCandidates = [ {h: fgHsl.h, s: fgHsl.s}, {h: bgHsl.h, s: bgHsl.s} ];
const results = [];
for (const base of baseCandidates) {
for (let d = 0; d <= 100; d += 2) {
const l = clamp(fgHsl.l + d / 100, 0.02, 0.98);
const candRgb = hslToRgb({ h: base.h, s: base.s, l });
const ratioToFg = wcagContrast(candRgb, fgRgb);
const ratioToBg = wcagContrast(candRgb, bgRgb);
if (ratioToFg >= 3.0 && (ratioToBg >= 3.0 || ratioToBg >= 2.5)) {
results.push({ hex: rgbToHex(candRgb), rgb: candRgb, delta: Math.abs(l - fgHsl.l) });
break;
}
}
for (let d = 2; d <= 100; d += 2) {
const l = clamp(fgHsl.l - d / 100, 0.02, 0.98);
const candRgb = hslToRgb({ h: base.h, s: base.s, l });
const ratioToFg = wcagContrast(candRgb, fgRgb);
const ratioToBg = wcagContrast(candRgb, bgRgb);
if (ratioToFg >= 3.0 && (ratioToBg >= 3.0 || ratioToBg >= 2.5)) {
results.push({ hex: rgbToHex(candRgb), rgb: candRgb, delta: Math.abs(l - fgHsl.l) });
break;
}
}
}
if (!results.length) return null;
results.sort((a, b) => a.delta - b.delta);
return results[0];
}
function toHex(n) {
return n.toString(16).padStart(2, "0").toUpperCase();
}
function rgbToHex({ r, g, b }) {
return "#" + toHex(r) + toHex(g) + toHex(b);
}
function parseCssColor(colorString) {
parserElement.style.color = "";
parserElement.style.color = colorString.trim();
const computed = getComputedStyle(parserElement).color;
const nums = computed.match(/[\d.]+/g);
if (!nums || nums.length < 3) {
throw new Error(`Could not parse color: "${colorString}"`);
}
const r = clamp(Math.round(Number(nums[0])), 0, 255);
const g = clamp(Math.round(Number(nums[1])), 0, 255);
const b = clamp(Math.round(Number(nums[2])), 0, 255);
return { r, g, b, hex: rgbToHex({ r, g, b }) };
}
function relativeLuminance({ r, g, b }) {
function channel(c) {
const cs = c / 255;
return cs <= 0.04045 ? cs / 12.92 : Math.pow((cs + 0.055) / 1.055, 2.4);
}
const R = channel(r);
const G = channel(g);
const B = channel(b);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
function wcagContrast(c1, c2) {
const L1 = relativeLuminance(c1);
const L2 = relativeLuminance(c2);
const lighter = Math.max(L1, L2);
const darker = Math.min(L1, L2);
return (lighter + 0.05) / (darker + 0.05);
}
function apcaLc(textRgb, backgroundRgb) {
if (!APCAcontrast || !APCA_sRGBtoY) return NaN;
try {
const tY = APCA_sRGBtoY([textRgb.r, textRgb.g, textRgb.b]);
const bY = APCA_sRGBtoY([backgroundRgb.r, backgroundRgb.g, backgroundRgb.b]);
return APCAcontrast(tY, bY);
} catch (e) {
return NaN;
}
}
function rgbToHsl({ r, g, b }) {
const R = r / 255;
const G = g / 255;
const B = b / 255;
const max = Math.max(R, G, B);
const min = Math.min(R, G, B);
let h, s;
const l = (max + min) / 2;
if (max === min) {
h = 0;
s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case R:
h = (G - B) / d + (G < B ? 6 : 0);
break;
case G:
h = (B - R) / d + 2;
break;
default:
h = (R - G) / d + 4;
break;
}
h /= 6;
}
return { h, s, l };
}
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslToRgb({ h, s, l }) {
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255),
};
}
function foregroundCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l) {
const wcagDiff = Math.abs(ratio - wcagThreshold);
let apcaDiff = 0;
if (!Number.isNaN(lc)) {
apcaDiff = Math.abs(Math.abs(lc) - apcaThreshold);
}
const deltaL = Math.abs(l - baseL);
return wcagDiff + apcaDiff + deltaL * 0.5;
}
function backgroundCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l, deltaH, deltaS) {
const wcagDiff = Math.abs(ratio - wcagThreshold);
let apcaDiff = 0;
if (!Number.isNaN(lc)) {
apcaDiff = Math.abs(Math.abs(lc) - apcaThreshold);
}
const deltaL = Math.abs(l - baseL);
return wcagDiff + apcaDiff + deltaL * 0.5 + deltaH + deltaS;
}
function focusCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l) {
const wcagDiff = Math.abs(ratio - wcagThreshold);
let apcaDiff = 0;
if (!Number.isNaN(lc)) {
apcaDiff = Math.abs(Math.abs(lc) - apcaThreshold);
}
const deltaL = Math.abs(l - baseL);
return wcagDiff + apcaDiff + deltaL * 0.5;
}
/**
* Foreground palette: keep hue/saturation, vary lightness.
* candidate is treated as TEXT against fixed background.
* Only returns candidates that pass BOTH WCAG and APCA thresholds.
*/
function findForegroundPalette(baseTextRgb, bgRgb, wcagThreshold, apcaThreshold, count) {
const baseHsl = rgbToHsl(baseTextRgb);
const { h, s, l: baseL } = baseHsl;
const candidates = [];
// Try keeping hue/sat constant, varying lightness
for (let l = 0.02; l <= 0.98 + 1e-9; l += 0.02) {
const candidateRgb = hslToRgb({ h, s, l });
const ratio = wcagContrast(candidateRgb, bgRgb);
const lc = apcaLc(candidateRgb, bgRgb); // text = candidate
const wcagPass = ratio >= wcagThreshold;
const apcaPass = !Number.isNaN(lc) && Math.abs(lc) >= apcaThreshold;
if (!wcagPass || !apcaPass) continue;
const score = foregroundCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l);
candidates.push({
rgb: candidateRgb,
hex: rgbToHex(candidateRgb),
ratio,
lc,
score,
});
}
// If we don't have enough candidates, try modest saturation adjustments
if (candidates.length < count) {
for (const sAdj of [0.9, 0.8, 1.1]) {
const adjustedS = clamp(s * sAdj, 0, 1);
for (let l = 0.02; l <= 0.98 + 1e-9; l += 0.02) {
const candidateRgb = hslToRgb({ h, s: adjustedS, l });
const ratio = wcagContrast(candidateRgb, bgRgb);
const lc = apcaLc(candidateRgb, bgRgb);
const wcagPass = ratio >= wcagThreshold;
const apcaPass = !Number.isNaN(lc) && Math.abs(lc) >= apcaThreshold;
if (!wcagPass || !apcaPass) continue;
const score = foregroundCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l);
candidates.push({ rgb: candidateRgb, hex: rgbToHex(candidateRgb), ratio, lc, score });
}
}
}
if (!candidates.length) return [];
candidates.sort((a, b) => a.score - b.score);
return candidates.slice(0, count);
}
/**
* Background palette: try multiple passes to stay close to base hue/sat,
* but relax saturation and hue slightly if needed. Score prefers
* combinations that are near thresholds for both WCAG and APCA.
* Strict mode: only WCAG+APCA combinations are accepted.
*/
function findBackgroundPalette(baseBgRgb, fgRgb, wcagThreshold, apcaThreshold, count) {
const baseHsl = rgbToHsl(baseBgRgb);
const { h: baseH, s: baseS, l: baseL } = baseHsl;
const candidates = [];
function tryPass(hueOffsets, satScales) {
for (const hOff of hueOffsets) {
const h = ((baseH + hOff) % 1 + 1) % 1;
for (const sScale of satScales) {
const s = clamp(baseS * sScale, 0, 1);
for (let l = 0.02; l <= 0.98 + 1e-9; l += 0.02) {
const candidateRgb = hslToRgb({ h, s, l });
const ratio = wcagContrast(fgRgb, candidateRgb);
const lc = apcaLc(fgRgb, candidateRgb); // text = fg, bg = candidate
const wcagPass = ratio >= wcagThreshold;
const apcaPass = !Number.isNaN(lc) && Math.abs(lc) >= apcaThreshold;
if (!wcagPass || !apcaPass) continue;
const deltaH = Math.abs(hOff);
const deltaS = Math.abs(s - baseS);
const score = backgroundCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l, deltaH, deltaS);
candidates.push({
rgb: candidateRgb,
hex: rgbToHex(candidateRgb),
ratio,
lc,
score,
});
if (candidates.length >= count * 10) return; // Early exit if we have enough
}
}
}
}
// Pass 1: Tight search around base color
tryPass([0], [1, 0.95, 0.9]);
// Pass 2: Same hue, broader saturation range
if (candidates.length < count) {
tryPass([0], [1, 0.9, 0.8, 0.7, 0.6]);
}
// Pass 3: Small hue shifts
if (candidates.length < count) {
tryPass([0.03, -0.03, 0.06, -0.06, 0.09, -0.09], [1, 0.9, 0.8]);
}
// Pass 4: Broader hue exploration
if (candidates.length < count) {
tryPass([0.12, -0.12, 0.15, -0.15], [1, 0.9, 0.8, 0.7]);
}
// Pass 5: Wide hue exploration with full saturation range
if (candidates.length < count) {
tryPass([0.2, -0.2, 0.25, -0.25], [1, 0.8, 0.6, 0.4]);
}
// Pass 6: Extreme hue shifts (almost opposite)
if (candidates.length < count) {
tryPass([0.35, -0.35, 0.4, -0.4], [1, 0.7, 0.5]);
}
// Pass 7: Very broad search across full range if still not enough
if (candidates.length < count) {
for (let h = 0; h <= 1; h += 0.1) {
for (let s of [1, 0.8, 0.6, 0.4]) {
for (let l = 0.02; l <= 0.98; l += 0.05) {
const candidateRgb = hslToRgb({ h, s, l });
const ratio = wcagContrast(fgRgb, candidateRgb);
const lc = apcaLc(fgRgb, candidateRgb);
const wcagPass = ratio >= wcagThreshold;
const apcaPass = !Number.isNaN(lc) && Math.abs(lc) >= apcaThreshold;
if (!wcagPass || !apcaPass) continue;
const score = backgroundCandidateScore(baseL, ratio, lc, wcagThreshold, apcaThreshold, l, Math.abs(h - baseH), Math.abs(s - baseS));
candidates.push({ rgb: candidateRgb, hex: rgbToHex(candidateRgb), ratio, lc, score });
}
}
}
}
if (!candidates.length) {
return [];
}
candidates.sort((a, b) => a.score - b.score);
// Enforce minimum lightness spacing so backgrounds are perceptibly different.
const picked = [];
const minDeltaL = 0.08;
for (const c of candidates) {
if (picked.length === 0) {
picked.push(c);
} else {
const tooClose = picked.some(p => {
const dl = Math.abs((rgbToHsl(p.rgb).l) - (rgbToHsl(c.rgb).l));
return dl < minDeltaL;
});
if (!tooClose) picked.push(c);
}
if (picked.length >= count) break;
}
return picked.slice(0, count);
}
/**
* Third/focus palette: treat candidate as FOCUS color, evaluated against background
* and extra constraints (e.g., 3:1 vs foreground). Score prefers near-threshold
* combinations that minimally change lightness.
* Strict mode: only WCAG+APCA combinations are accepted.
*/
function findFocusPalette(baseFocusRgb, bgRgb, wcagThreshold, apcaThreshold, count, extraCheck) {
const baseHsl = rgbToHsl(baseFocusRgb);
const { h, s, l: baseL } = baseHsl;
const candidates = [];
// First try: keep hue/saturation, vary lightness
for (let l = 0.02; l <= 0.98 + 1e-9; l += 0.02) {
const candidateRgb = hslToRgb({ h, s, l });
const ratioBg = wcagContrast(candidateRgb, bgRgb);
const lcBg = apcaLc(candidateRgb, bgRgb);
const wcagPass = ratioBg >= wcagThreshold;
const apcaPass = !Number.isNaN(lcBg) && Math.abs(lcBg) >= apcaThreshold;
if (!wcagPass || !apcaPass) continue;
if (extraCheck && !extraCheck(candidateRgb)) continue;
const score = focusCandidateScore(baseL, ratioBg, lcBg, wcagThreshold, apcaThreshold, l);
candidates.push({
rgb: candidateRgb,
hex: rgbToHex(candidateRgb),
ratio: ratioBg,
lc: lcBg,
score,
l,
});
}
// Second try: if not enough, also try saturation adjustments
if (candidates.length < count) {
for (const sAdj of [0.9, 0.8, 1.1]) {
const adjustedS = clamp(s * sAdj, 0, 1);
for (let l = 0.02; l <= 0.98 + 1e-9; l += 0.02) {
const candidateRgb = hslToRgb({ h, s: adjustedS, l });
const ratioBg = wcagContrast(candidateRgb, bgRgb);
const lcBg = apcaLc(candidateRgb, bgRgb);
const wcagPass = ratioBg >= wcagThreshold;
const apcaPass = !Number.isNaN(lcBg) && Math.abs(lcBg) >= apcaThreshold;
if (!wcagPass || !apcaPass) continue;
if (extraCheck && !extraCheck(candidateRgb)) continue;
const score = focusCandidateScore(baseL, ratioBg, lcBg, wcagThreshold, apcaThreshold, l);
candidates.push({ rgb: candidateRgb, hex: rgbToHex(candidateRgb), ratio: ratioBg, lc: lcBg, score, l });
}
}
}
if (!candidates.length) return [];
candidates.sort((a, b) => a.score - b.score);
// Similar spacing for focus colors so the focus ring options are distinct.
const picked = [];
const minDeltaL = 0.08;
for (const c of candidates) {
if (picked.length === 0) {
picked.push(c);
} else {
const tooClose = picked.some(p => Math.abs(p.l - c.l) < minDeltaL);
if (!tooClose) picked.push(c);
}
if (picked.length >= count) break;
}
return picked.slice(0, count);
}
function formatRatio(value) {
if (!isFinite(value)) return "n/a";
return value.toFixed(2) + ":1";
}
function formatLc(value) {
if (!isFinite(value)) return "n/a";
const sign = value > 0 ? "+" : "";
return sign + value.toFixed(1);
}
// label: string, ratio: number, wcagPass: bool, lc: number, apcaPass: bool
// leftColor/rightColor: optional { display: string, hex: string }
function addResultRow(label, ratio, wcagPass, lc, apcaPass, leftColor, rightColor) {
const tr = document.createElement("tr");
const tdLabel = document.createElement("td");
if (label instanceof Node) {
tdLabel.appendChild(label);
} else {
tdLabel.textContent = label;
}
tdLabel.setAttribute('data-label', 'Pair');
// color cell shows small swatches and the original CSS string values for quick copy
const tdColors = document.createElement('td');
tdColors.className = 'result-colors';
tdColors.setAttribute('data-label', 'Colors');
tdColors.className = 'result-colors';
function makeColorBlock(info, title) {
const wrap = document.createElement('div');
wrap.className = 'result-color-wrap';
if (!info) return wrap;
const sw = document.createElement('span');
sw.className = 'result-swatch';
sw.style.backgroundColor = info.hex || info.display;
sw.setAttribute('title', (title ? title + ': ' : '') + (info.display || info.hex));
const txt = document.createElement('code');
txt.className = 'result-color-text';
txt.textContent = info.display || info.hex || '';
wrap.appendChild(sw);
wrap.appendChild(txt);
return wrap;
}
// left (text) and right (background/focus) stacked
tdColors.appendChild(makeColorBlock(leftColor, 'Left'));
tdColors.appendChild(makeColorBlock(rightColor, 'Right'));
const tdRatio = document.createElement("td");
tdRatio.textContent = formatRatio(ratio);
tdRatio.setAttribute('data-label', 'WCAG ratio');
const tdWcag = document.createElement("td");
tdWcag.setAttribute('data-label', 'WCAG status');
const wcagSpan = document.createElement("span");
wcagSpan.className =
"status-badge " + (wcagPass ? "status-pass" : "status-fail");
wcagSpan.textContent = wcagPass ? "Pass" : "Fail";
tdWcag.appendChild(wcagSpan);
const tdLc = document.createElement("td");
tdLc.textContent = formatLc(lc);
tdLc.setAttribute('data-label', 'APCA Lc');
const tdApca = document.createElement("td");
tdApca.setAttribute('data-label', 'APCA status');
const apcaSpan = document.createElement("span");
apcaSpan.className =
"status-badge " + (apcaPass ? "status-pass" : "status-fail");
apcaSpan.textContent = apcaPass ? "Pass" : "Fail";
tdApca.appendChild(apcaSpan);
tr.appendChild(tdLabel);
tr.appendChild(tdColors);
tr.appendChild(tdRatio);
tr.appendChild(tdWcag);
tr.appendChild(tdLc);
tr.appendChild(tdApca);
resultsBody.appendChild(tr);
}
function applyPreviewColors(container, heading, link, button, fgHex, bgHex) {
if (!container) return;
container.style.color = fgHex;
container.style.backgroundColor = bgHex;
try {
container.style.setProperty('--preview-fg', fgHex);
container.style.setProperty('--preview-bg', bgHex);
} catch (e) {}
if (heading) heading.style.color = fgHex;
if (link) {
link.style.color = fgHex;
link.style.textDecorationColor = fgHex;
}
if (button) {
button.style.backgroundColor = fgHex;
button.style.color = bgHex;
button.style.borderColor = fgHex;
button.style.boxShadow = "none";
}
}
// --- Local persistence (localStorage fallback) ---
const PALETTE_KEY = 'contrastplus.savedPalette';
function loadSavedPalette() {
try {
const raw = localStorage.getItem(PALETTE_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) return parsed;
} catch (e) {
console.warn('Failed to read saved palette', e);
}
return [];
}
function savePaletteToStorage(paletteArray) {
try {
localStorage.setItem(PALETTE_KEY, JSON.stringify(paletteArray));
} catch (e) {
console.warn('Failed to save palette', e);
}
}
function addSavedColor(value) {
const palette = loadSavedPalette();
palette.unshift({ id: crypto.randomUUID(), value });
savePaletteToStorage(palette.slice(0, 50)); // keep last 50
renderSavedPalette();
}
function deleteSavedColor(id) {
let palette = loadSavedPalette();
palette = palette.filter(p => p.id !== id);
savePaletteToStorage(palette);
renderSavedPalette();
}
function renderSavedPalette() {
const container = document.getElementById('paletteContainer');
const count = document.getElementById('paletteCount');
container.innerHTML = '';
const palette = loadSavedPalette();
count.textContent = String(palette.length);
if (!palette.length) {
const p = document.createElement('p');
p.id = 'palettePlaceholder';
p.className = 'small italic';
p.textContent = 'No saved colors yet. Use the Save buttons near color inputs.';
container.appendChild(p);
return;
}
palette.forEach((item, idx) => {
const row = document.createElement('div');
row.className = 'palette-item';
// (no inline icon in the saved-palette list; preview icons render in the Preview section)
const sw = document.createElement('div');
sw.className = 'palette-swatch';
sw.style.width = '28px';
sw.style.height = '28px';
sw.style.borderRadius = '6px';
sw.style.backgroundColor = item.value;
sw.title = item.value;
const meta = document.createElement('div');
meta.className = 'palette-meta';
const val = document.createElement('div');
val.className = 'palette-value';
val.textContent = item.value;
const actions = document.createElement('div');
actions.className = 'palette-actions';
const loadBtn = document.createElement('button');
loadBtn.type = 'button';
loadBtn.textContent = 'Load as FG';
loadBtn.addEventListener('click', () => { fgText.value = item.value; fgPicker.value = parseCssColor(item.value).hex; updateAll(); });
const loadBgBtn = document.createElement('button');
loadBgBtn.type = 'button';
loadBgBtn.textContent = 'Load as BG';
loadBgBtn.addEventListener('click', () => { bgText.value = item.value; bgPicker.value = parseCssColor(item.value).hex; updateAll(); });
const loadFocusBtn = document.createElement('button');
loadFocusBtn.type = 'button';
loadFocusBtn.textContent = 'Load as focus';
loadFocusBtn.addEventListener('click', () => { thirdText.value = item.value; thirdPicker.value = parseCssColor(item.value).hex; enableThird.checked = true; thirdContainer.classList.remove('hidden'); updateAll(); });
const delBtn = document.createElement('button');
delBtn.type = 'button';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', () => { if (item.id) { deleteSavedColor(item.id); } renderSavedPalette(); try { updateBarChart([fgText.value || fgPicker.value, bgText.value || bgPicker.value, (document.getElementById('enableThird') && document.getElementById('enableThird').checked) ? (thirdText.value || thirdPicker.value) : null]); } catch(e){} });
actions.appendChild(loadBtn);
actions.appendChild(loadBgBtn);
actions.appendChild(loadFocusBtn);
actions.appendChild(delBtn);
meta.appendChild(val);
row.appendChild(sw);
row.appendChild(meta);
row.appendChild(actions);
container.appendChild(row);
});
// Render preview icons into both preview panels using sequential selection rules
try {
const baseIcons = document.getElementById('previewSavedIconsBase');
const thirdIcons = document.getElementById('previewSavedIconsThird');
if (baseIcons) baseIcons.innerHTML = '';
if (thirdIcons) thirdIcons.innerHTML = '';
// Helper: build a sequential list of colors from saved palette
const buildSequentialList = (savedArr, bgHex, focusHex, minCount = 4) => {
const seen = new Set();
const out = [];
const normalizedBg = bgHex ? String(bgHex).toLowerCase() : null;
// include focus first for third preview if provided
if (focusHex) {
const fh = String(focusHex);
if (fh && fh.toLowerCase() !== normalizedBg) {
out.push(fh);
seen.add(fh.toLowerCase());
}
}
// then include saved colors in their stored order, skipping any equal to BG
for (const s of savedArr) {
const val = String(s.value || '');
if (!val) continue;
const low = val.toLowerCase();
if (normalizedBg && low === normalizedBg) continue;
if (seen.has(low)) continue;
out.push(val);
seen.add(low);
}
// if fewer than minCount, add deterministic random-ish fillers (not random order)
let fillerIndex = 0;
while (out.length < minCount) {
// alternate dark and light to maintain variety
const hex = (fillerIndex % 2 === 0) ? randomDarkHex() : randomLightHex();
fillerIndex += 1;
const low = hex.toLowerCase();
if (normalizedBg && low === normalizedBg) continue;
if (seen.has(low)) continue;
out.push(hex);
seen.add(low);
}
return out;
};
// current bg and focus values from inputs (best-effort)
let bgHex = null;
let focusHex = null;
try { bgHex = document.getElementById('bgPicker').value; } catch (e) {}
try { if (document.getElementById('enableThird') && document.getElementById('enableThird').checked) focusHex = document.getElementById('thirdPicker').value; } catch (e) {}
const seqBase = buildSequentialList(palette, bgHex, null, 4);
const seqThird = buildSequentialList(palette, bgHex, focusHex, 4);
const makeBig = (color, containerEl) => {
const link = document.createElement('a');
link.href = '#';
link.className = 'saved-icon-link svg-link';
link.title = color + ' — click: FG, shift+click: BG, alt+click: Focus';
link.addEventListener('click', (e) => {
e.preventDefault();
const val = color;
try { updateSVG(val); } catch (err) {}
if (e.shiftKey) {
bgText.value = val; bgPicker.value = parseCssColor(val).hex; updateAll();
} else if (e.altKey) {
thirdText.value = val; thirdPicker.value = parseCssColor(val).hex; enableThird.checked = true; thirdContainer.classList.remove('hidden'); updateAll();
} else {
fgText.value = val; fgPicker.value = parseCssColor(val).hex; updateAll();
}
});
const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgEl.setAttribute('viewBox', '0 0 24 24');
svgEl.setAttribute('width', '56');
svgEl.setAttribute('height', '56');
svgEl.setAttribute('aria-hidden', 'true');
const pick = SVG_PATHS[Math.abs(hashCode(color)) % SVG_PATHS.length] || SVG_PATHS[0];
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('d', pick.path);
path.setAttribute('fill', color);
svgEl.appendChild(path);
link.appendChild(svgEl);
containerEl.appendChild(link);
};
if (baseIcons) seqBase.forEach(c => makeBig(c, baseIcons));
if (thirdIcons) seqThird.forEach(c => makeBig(c, thirdIcons));
} catch (e) {
// non-fatal
}
// ensure bar chart reflects the current colors after re-rendering palette
try { updateBarChart([fgText.value || fgPicker.value, bgText.value || bgPicker.value, (document.getElementById('enableThird') && document.getElementById('enableThird').checked) ? (thirdText.value || thirdPicker.value) : null]); } catch (e) {}
}
// --- Harmony generator (no LLM) ---
function generateHarmony(fgRgb) {
// Create 5 colors rotating hue and varying lightness
const hsl = rgbToHsl(fgRgb);
const baseH = hsl.h;
const baseS = Math.max(0.25, hsl.s);
const baseL = hsl.l;
const palette = [];
const offsets = [0, 0.08, -0.08, 0.16, -0.16];
const lightness = [baseL, clamp(baseL + 0.12, 0.05, 0.95), clamp(baseL - 0.12, 0.05, 0.95), clamp(baseL + 0.22, 0.05, 0.95), clamp(baseL - 0.22, 0.05, 0.95)];
for (let i = 0; i < 5; i++) {
const h = ((baseH + offsets[i]) % 1 + 1) % 1;
const s = clamp(baseS * (1 - i * 0.05), 0.15, 1);
const l = lightness[i];
const rgb = hslToRgb({ h, s, l });
palette.push({ hex: rgbToHex(rgb), name: `Harmonized ${i + 1}` });
}
return palette;
}
function renderHarmonyOutput(palette) {
const out = document.getElementById('harmonyOutput');
out.innerHTML = '';
palette.forEach(c => {
const card = document.createElement('div');
card.className = 'harmony-swatch';
const box = document.createElement('div');
box.className = 'harmony-box';
box.style.backgroundColor = c.hex;
box.title = `${c.name} — ${c.hex}`;
// clicking the swatch loads to foreground; small controls allow load to BG
box.addEventListener('click', () => {
fgText.value = c.hex;
fgPicker.value = c.hex;
updateAll();
});
const label = document.createElement('div');
label.className = 'harmony-label';
label.textContent = `${c.name} · ${c.hex}`;
const controls = document.createElement('div');
controls.className = 'harmony-controls-inline';