boltz-ui 0.2.9

High-level reusable GPUI UI components (Label, Button, Input, etc.).
Documentation
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
use gpui::Hsla;

/// APCA (Accessible Perceptual Contrast Algorithm) constants
/// Based on APCA 0.0.98G-4g W3 compatible constants
/// https://github.com/Myndex/apca-w3
struct APCAConstants {
    // Main TRC exponent for monitor perception
    main_trc: f32,

    // sRGB coefficients
    s_rco: f32,
    s_gco: f32,
    s_bco: f32,

    // G-4g constants for use with 2.4 exponent
    norm_bg: f32,
    norm_txt: f32,
    rev_txt: f32,
    rev_bg: f32,

    // G-4g Clamps and Scalers
    blk_thrs: f32,
    blk_clmp: f32,
    scale_bow: f32,
    scale_wob: f32,
    lo_bow_offset: f32,
    lo_wob_offset: f32,
    delta_y_min: f32,
    lo_clip: f32,
}

impl Default for APCAConstants {
    fn default() -> Self {
        Self {
            main_trc: 2.4,
            s_rco: 0.2126729,
            s_gco: 0.7151522,
            s_bco: 0.0721750,
            norm_bg: 0.56,
            norm_txt: 0.57,
            rev_txt: 0.62,
            rev_bg: 0.65,
            blk_thrs: 0.022,
            blk_clmp: 1.414,
            scale_bow: 1.14,
            scale_wob: 1.14,
            lo_bow_offset: 0.027,
            lo_wob_offset: 0.027,
            delta_y_min: 0.0005,
            lo_clip: 0.1,
        }
    }
}

/// Calculates the perceptual lightness contrast using APCA.
/// Returns a value between approximately -108 and 106.
/// Negative values indicate light text on dark background.
/// Positive values indicate dark text on light background.
///
/// The APCA algorithm is more perceptually accurate than WCAG 2.x,
/// especially for dark mode interfaces. Key improvements include:
/// - Better accuracy for dark backgrounds
/// - Polarity-aware (direction matters)
/// - Perceptually uniform across the range
///
/// Common APCA Lc thresholds per ARC Bronze Simple Mode:
/// https://readtech.org/ARC/tests/bronze-simple-mode/
/// - Lc 45: Minimum for large fluent text (36px+)
/// - Lc 60: Minimum for other content text
/// - Lc 75: Minimum for body text
/// - Lc 90: Preferred for body text
///
/// Most terminal themes use colors with APCA values of 40-70.
///
/// https://github.com/Myndex/apca-w3
pub fn apca_contrast(text_color: Hsla, background_color: Hsla) -> f32 {
    let constants = APCAConstants::default();

    let text_y = srgb_to_y(text_color, &constants);
    let bg_y = srgb_to_y(background_color, &constants);

    // Apply soft clamp to near-black colors
    let text_y_clamped = if text_y > constants.blk_thrs {
        text_y
    } else {
        text_y + (constants.blk_thrs - text_y).powf(constants.blk_clmp)
    };

    let bg_y_clamped = if bg_y > constants.blk_thrs {
        bg_y
    } else {
        bg_y + (constants.blk_thrs - bg_y).powf(constants.blk_clmp)
    };

    // Return 0 for extremely low delta Y
    if (bg_y_clamped - text_y_clamped).abs() < constants.delta_y_min {
        return 0.0;
    }

    let sapc;
    let output_contrast;

    if bg_y_clamped > text_y_clamped {
        // Normal polarity: dark text on light background
        sapc = (bg_y_clamped.powf(constants.norm_bg) - text_y_clamped.powf(constants.norm_txt))
            * constants.scale_bow;

        // Low contrast smooth rollout to prevent polarity reversal
        output_contrast = if sapc < constants.lo_clip {
            0.0
        } else {
            sapc - constants.lo_bow_offset
        };
    } else {
        // Reverse polarity: light text on dark background
        sapc = (bg_y_clamped.powf(constants.rev_bg) - text_y_clamped.powf(constants.rev_txt))
            * constants.scale_wob;

        output_contrast = if sapc > -constants.lo_clip {
            0.0
        } else {
            sapc + constants.lo_wob_offset
        };
    }

    // Return Lc (lightness contrast) scaled to percentage
    output_contrast * 100.0
}

/// Converts sRGB color to Y (luminance) for APCA calculation
fn srgb_to_y(color: Hsla, constants: &APCAConstants) -> f32 {
    let rgba = color.to_rgb();

    // Linearize and apply coefficients
    let r_linear = (rgba.r).powf(constants.main_trc);
    let g_linear = (rgba.g).powf(constants.main_trc);
    let b_linear = (rgba.b).powf(constants.main_trc);

    constants.s_rco * r_linear + constants.s_gco * g_linear + constants.s_bco * b_linear
}

/// Adjusts the foreground color to meet the minimum APCA contrast against the background.
/// The minimum_apca_contrast should be an absolute value (e.g., 75 for Lc 75).
///
/// This implementation gradually adjusts the lightness while preserving the hue and
/// saturation as much as possible, only falling back to black/white when necessary.
pub fn ensure_minimum_contrast(
    foreground: Hsla,
    background: Hsla,
    minimum_apca_contrast: f32,
) -> Hsla {
    if minimum_apca_contrast <= 0.0 {
        return foreground;
    }

    let current_contrast = apca_contrast(foreground, background).abs();

    if current_contrast >= minimum_apca_contrast {
        return foreground;
    }

    // First, try to adjust lightness while preserving hue and saturation
    let adjusted = adjust_lightness_for_contrast(foreground, background, minimum_apca_contrast);

    let adjusted_contrast = apca_contrast(adjusted, background).abs();
    if adjusted_contrast >= minimum_apca_contrast {
        return adjusted;
    }

    // If that's not enough, gradually reduce saturation while adjusting lightness
    let desaturated =
        adjust_lightness_and_saturation_for_contrast(foreground, background, minimum_apca_contrast);

    let desaturated_contrast = apca_contrast(desaturated, background).abs();
    if desaturated_contrast >= minimum_apca_contrast {
        return desaturated;
    }

    // Last resort: use black or white
    let black = Hsla {
        h: 0.0,
        s: 0.0,
        l: 0.0,
        a: foreground.a,
    };

    let white = Hsla {
        h: 0.0,
        s: 0.0,
        l: 1.0,
        a: foreground.a,
    };

    let black_contrast = apca_contrast(black, background).abs();
    let white_contrast = apca_contrast(white, background).abs();

    if white_contrast > black_contrast {
        white
    } else {
        black
    }
}

/// Adjusts only the lightness to meet the minimum contrast, preserving hue and saturation
fn adjust_lightness_for_contrast(
    foreground: Hsla,
    background: Hsla,
    minimum_apca_contrast: f32,
) -> Hsla {
    // Determine if we need to go lighter or darker
    let bg_luminance = srgb_to_y(background, &APCAConstants::default());
    let should_go_darker = bg_luminance > 0.5;

    // Binary search for the optimal lightness
    let mut low = if should_go_darker { 0.0 } else { foreground.l };
    let mut high = if should_go_darker { foreground.l } else { 1.0 };
    let mut best_l = foreground.l;

    for _ in 0..20 {
        let mid = (low + high) / 2.0;
        let test_color = Hsla {
            h: foreground.h,
            s: foreground.s,
            l: mid,
            a: foreground.a,
        };

        let contrast = apca_contrast(test_color, background).abs();

        if contrast >= minimum_apca_contrast {
            best_l = mid;
            // Try to get closer to the minimum
            if should_go_darker {
                low = mid;
            } else {
                high = mid;
            }
        } else if should_go_darker {
            high = mid;
        } else {
            low = mid;
        }

        // If we're close enough to the target, stop
        if (contrast - minimum_apca_contrast).abs() < 1.0 {
            best_l = mid;
            break;
        }
    }

    Hsla {
        h: foreground.h,
        s: foreground.s,
        l: best_l,
        a: foreground.a,
    }
}

/// Adjusts both lightness and saturation to meet the minimum contrast
fn adjust_lightness_and_saturation_for_contrast(
    foreground: Hsla,
    background: Hsla,
    minimum_apca_contrast: f32,
) -> Hsla {
    // Try different saturation levels
    let saturation_steps = [1.0, 0.8, 0.6, 0.4, 0.2, 0.0];

    for &sat_multiplier in &saturation_steps {
        let test_color = Hsla {
            h: foreground.h,
            s: foreground.s * sat_multiplier,
            l: foreground.l,
            a: foreground.a,
        };

        let adjusted = adjust_lightness_for_contrast(test_color, background, minimum_apca_contrast);
        let contrast = apca_contrast(adjusted, background).abs();

        if contrast >= minimum_apca_contrast {
            return adjusted;
        }
    }

    // If we get here, even grayscale didn't work, so return the grayscale attempt
    Hsla {
        h: foreground.h,
        s: 0.0,
        l: foreground.l,
        a: foreground.a,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
        Hsla { h, s, l, a }
    }

    fn hsla_from_hex(hex: u32) -> Hsla {
        let r = ((hex >> 16) & 0xFF) as f32 / 255.0;
        let g = ((hex >> 8) & 0xFF) as f32 / 255.0;
        let b = (hex & 0xFF) as f32 / 255.0;

        let max = r.max(g).max(b);
        let min = r.min(g).min(b);
        let l = (max + min) / 2.0;

        if max == min {
            // Achromatic
            Hsla {
                h: 0.0,
                s: 0.0,
                l,
                a: 1.0,
            }
        } else {
            let d = max - min;
            let s = if l > 0.5 {
                d / (2.0 - max - min)
            } else {
                d / (max + min)
            };

            let h = if max == r {
                (g - b) / d + if g < b { 6.0 } else { 0.0 }
            } else if max == g {
                (b - r) / d + 2.0
            } else {
                (r - g) / d + 4.0
            } / 6.0;

            Hsla { h, s, l, a: 1.0 }
        }
    }

    #[test]
    fn test_apca_contrast() {
        // Test black text on white background (should be positive)
        let black = hsla(0.0, 0.0, 0.0, 1.0);
        let white = hsla(0.0, 0.0, 1.0, 1.0);
        let contrast = apca_contrast(black, white);
        assert!(
            contrast > 100.0,
            "Black on white should have high positive contrast, got {}",
            contrast
        );

        // Test white text on black background (should be negative)
        let contrast_reversed = apca_contrast(white, black);
        assert!(
            contrast_reversed < -100.0,
            "White on black should have high negative contrast, got {}",
            contrast_reversed
        );

        // Same color should have zero contrast
        let gray = hsla(0.0, 0.0, 0.5, 1.0);
        let contrast_same = apca_contrast(gray, gray);
        assert!(
            contrast_same.abs() < 1.0,
            "Same color should have near-zero contrast, got {}",
            contrast_same
        );

        // APCA is NOT commutative - polarity matters
        assert!(
            (contrast + contrast_reversed).abs() > 1.0,
            "APCA should not be commutative"
        );
    }

    #[test]
    fn test_srgb_to_y() {
        let constants = APCAConstants::default();

        // Test known Y values
        let black = hsla(0.0, 0.0, 0.0, 1.0);
        let y_black = srgb_to_y(black, &constants);
        assert!(
            y_black.abs() < 0.001,
            "Black should have Y near 0, got {}",
            y_black
        );

        let white = hsla(0.0, 0.0, 1.0, 1.0);
        let y_white = srgb_to_y(white, &constants);
        assert!(
            (y_white - 1.0).abs() < 0.001,
            "White should have Y near 1, got {}",
            y_white
        );
    }

    #[test]
    fn test_srgb_to_y_nan_issue() {
        let dark_red = hsla_from_hex(0x5f0000);
        let y_dark_red = srgb_to_y(dark_red, &APCAConstants::default());
        assert!(!y_dark_red.is_nan());
    }

    #[test]
    fn test_ensure_minimum_contrast() {
        let white_bg = hsla(0.0, 0.0, 1.0, 1.0);
        let light_gray = hsla(0.0, 0.0, 0.9, 1.0);

        // Light gray on white has poor contrast
        let initial_contrast = apca_contrast(light_gray, white_bg).abs();
        assert!(
            initial_contrast < 15.0,
            "Initial contrast should be low, got {}",
            initial_contrast
        );

        // Should be adjusted to black for better contrast (using APCA Lc 45 as minimum)
        let adjusted = ensure_minimum_contrast(light_gray, white_bg, 45.0);
        assert_eq!(adjusted.l, 0.0); // Should be black
        assert_eq!(adjusted.a, light_gray.a); // Alpha preserved

        // Test with dark background
        let black_bg = hsla(0.0, 0.0, 0.0, 1.0);
        let dark_gray = hsla(0.0, 0.0, 0.1, 1.0);

        // Dark gray on black has poor contrast
        let initial_contrast = apca_contrast(dark_gray, black_bg).abs();
        assert!(
            initial_contrast < 15.0,
            "Initial contrast should be low, got {}",
            initial_contrast
        );

        // Should be adjusted to white for better contrast
        let adjusted = ensure_minimum_contrast(dark_gray, black_bg, 45.0);
        assert_eq!(adjusted.l, 1.0); // Should be white

        // Test when contrast is already sufficient
        let black = hsla(0.0, 0.0, 0.0, 1.0);
        let adjusted = ensure_minimum_contrast(black, white_bg, 45.0);
        assert_eq!(adjusted, black); // Should remain unchanged
    }

    #[test]
    fn test_one_light_theme_exact_colors() {
        // Test with exact colors from One Light theme
        // terminal.background and terminal.ansi.white are both #fafafaff
        let fafafa = hsla_from_hex(0xfafafa);

        // They should be identical
        let bg = fafafa;
        let fg = fafafa;

        // Contrast should be 0 (no contrast)
        let contrast = apca_contrast(fg, bg);
        assert!(
            contrast.abs() < 1.0,
            "Same color should have near-zero APCA contrast, got {}",
            contrast
        );

        // With minimum APCA contrast of 15 (very low, but detectable), it should adjust
        let adjusted = ensure_minimum_contrast(fg, bg, 15.0);
        // The new algorithm preserves colors, so we just need to check contrast
        let new_contrast = apca_contrast(adjusted, bg).abs();
        assert!(
            new_contrast >= 15.0,
            "Adjusted contrast {} should be >= 15.0",
            new_contrast
        );

        // The adjusted color should have sufficient contrast
        let new_contrast = apca_contrast(adjusted, bg).abs();
        assert!(
            new_contrast >= 15.0,
            "Adjusted APCA contrast {} should be >= 15.0",
            new_contrast
        );
    }
}