1
//! A colour swatch that opens a colour picker in a real popup window.
2
//!
3
//! The swatch is the control the app places in its layout; clicking it opens
4
//! a `<transient-window>` anchored below it (a real OS popup — see
5
//! `azul_core::transient`) holding a Chrome-style picker: a saturation/value
6
//! plane, a hue bar, a preview swatch with the hex value, and R/G/B fields.
7
//! Every change fires `on_value_change` with the new colour; the app stores
8
//! it and passes it back into `ColorInput::create`, like every other widget
9
//! here. The popup closes on an outside click, Escape, or a second click on
10
//! the swatch — the engine handles all three, so the app carries no flag.
11
//!
12
//! What persists across the app's rebuilds lives in the swatch's dataset
13
//! (`ColorPickerData`, kept by a merge callback): whether the picker is open,
14
//! the hue/saturation the user is on (so dragging through black does not
15
//! forget the hue), and an in-progress drag.
16

            
17
use alloc::{format, string::String, vec, vec::Vec};
18

            
19
use azul_core::{
20
    callbacks::Update,
21
    dom::{Dom, DomNodeId, NodeData, NodeType},
22
    refany::RefAny,
23
    transient::{TransientAnchor, TransientDismiss, TransientWindowConfig},
24
};
25
use azul_css::dynamic_selector::{
26
    CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
27
};
28
#[allow(clippy::wildcard_imports)]
29
// widget/render module pulls in the css property/value types it builds with
30
use azul_css::{
31
    props::{
32
        basic::*,
33
        layout::*,
34
        property::{CssProperty, *},
35
        style::*,
36
    },
37
    OptionString, *,
38
};
39

            
40
use crate::callbacks::{Callback, CallbackInfo};
41

            
42
/// Rectangular input that displays a color and opens a picker when clicked.
43
#[derive(Debug, Default, Clone, PartialEq, Eq)]
44
#[repr(C)]
45
pub struct ColorInput {
46
    pub color_input_state: ColorInputStateWrapper,
47
    /// The swatch's CSS, or `None` for "no opinion" — in which case the widget's
48
    /// default applies.
49
    ///
50
    /// `None` and `Some(empty)` are different answers: the first means the
51
    /// widget picks, the second means the caller asked for no properties at all
52
    /// and gets none.
53
    pub style: OptionCssPropertyWithConditionsVec,
54
    /// What this control is CALLED, for assistive technology.
55
    ///
56
    /// Carried by the WIDGET so it knows at build time whether it was named;
57
    /// forwarded into the accessibility declaration it already builds.
58
    pub accessibility_name: OptionString,
59
}
60

            
61
/// Callback function type invoked when the color input value changes.
62
pub type ColorInputOnValueChangeCallbackType =
63
    extern "C" fn(RefAny, CallbackInfo, ColorInputState) -> Update;
64
impl_widget_callback!(
65
    ColorInputOnValueChange,
66
    OptionColorInputOnValueChange,
67
    ColorInputOnValueChangeCallback,
68
    ColorInputOnValueChangeCallbackType
69
);
70

            
71
// The managed-FFI half of the same callback.
72
//
73
// `HOST_INVOKER_KINDS` in `doc/src/codegen/v2/managed_host_invoker.rs` has
74
// listed `ColorInputOnValueChangeCallback` since the kind was added, so every
75
// managed binding emits a lookup of the setter symbol below — but the macro
76
// that DEFINES it was never applied here, so libazul never exported it. Ten
77
// shipped bindings (lua, ruby, node, fortran, pascal, java, kotlin, scala,
78
// ocaml, csharp) then failed to LOAD, before running a line of their own code.
79
//
80
// That module's doc comment states the order: apply the macro, recompile
81
// libazul, then append to the list. This is the missing first step.
82
azul_core::impl_managed_callback! {
83
    wrapper:        ColorInputOnValueChangeCallback,
84
    info_ty:        CallbackInfo,
85
    return_ty:      Update,
86
    default_ret:    Update::DoNothing,
87
    invoker_static: COLOR_INPUT_ON_VALUE_CHANGE_INVOKER,
88
    invoker_ty:     AzColorInputOnValueChangeCallbackInvoker,
89
    thunk_fn:       az_color_input_on_value_change_callback_thunk,
90
    setter_fn:      AzApp_setColorInputOnValueChangeCallbackInvoker,
91
    from_handle_fn: AzColorInputOnValueChangeCallback_createFromHostHandle,
92
    extra_args:     [ state: ColorInputState ],
93
}
94

            
95
/// Wrapper around [`ColorInputState`] that includes a title and an optional value-change callback.
96
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
97
#[repr(C)]
98
pub struct ColorInputStateWrapper {
99
    pub inner: ColorInputState,
100
    pub title: AzString,
101
    pub on_value_change: OptionColorInputOnValueChange,
102
}
103

            
104
impl Default for ColorInputStateWrapper {
105
303
    fn default() -> Self {
106
303
        Self {
107
303
            inner: ColorInputState::default(),
108
303
            title: AzString::from_const_str("Pick color"),
109
303
            on_value_change: None.into(),
110
303
        }
111
303
    }
112
}
113

            
114
/// Holds the current color value of a [`ColorInput`] widget.
115
#[derive(Copy, Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
116
#[repr(C)]
117
pub struct ColorInputState {
118
    pub color: ColorU,
119
}
120

            
121
impl Default for ColorInputState {
122
307
    fn default() -> Self {
123
307
        Self {
124
307
            color: ColorU {
125
307
                r: 255,
126
307
                g: 255,
127
307
                b: 255,
128
307
                a: 255,
129
307
            },
130
307
        }
131
307
    }
132
}
133

            
134
static DEFAULT_COLOR_INPUT_STYLE: &[CssPropertyWithConditions] = &[
135
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
136
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
137
    CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(14))),
138
    CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(14))),
139
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
140
];
141

            
142
/// Class on the swatch (the control itself).
143
pub const COLOR_INPUT_CLASS: &str = "__azul_native_color_input";
144
/// Class on the picker panel inside the popup.
145
pub const COLOR_PICKER_CLASS: &str = "__azul_native_color_picker";
146
/// Class on the saturation/value plane.
147
pub const COLOR_PICKER_PLANE_CLASS: &str = "__azul_native_color_picker_plane";
148
/// Class on the hue bar.
149
pub const COLOR_PICKER_HUE_CLASS: &str = "__azul_native_color_picker_hue";
150
/// Class on the alpha bar.
151
pub const COLOR_PICKER_ALPHA_CLASS: &str = "__azul_native_color_picker_alpha";
152
/// Class on the picker's grip strip: drag it to tear the picker off into a
153
/// floating palette, drag the palette back over the swatch to dock it.
154
pub const COLOR_PICKER_GRIP_CLASS: &str = "__azul_native_color_picker_grip";
155
/// Class on the eyedropper button (`pick_screen_color`).
156
pub const COLOR_PICKER_EYEDROPPER_CLASS: &str = "__azul_native_color_picker_eyedropper";
157

            
158
/// Width of the plane and hue bar, in px. The panel is this plus padding.
159
const PLANE_WIDTH: f32 = 216.0;
160
/// Height of the plane, in px.
161
const PLANE_HEIGHT: f32 = 150.0;
162

            
163
impl ColorInput {
164
    /// Name this control for assistive technology.
165
    #[must_use]
166
    pub fn with_accessibility_name<S: Into<AzString>>(mut self, name: S) -> Self {
167
        self.accessibility_name = Some(name.into()).into();
168
        self
169
    }
170

            
171
    /// Creates a new `ColorInput` displaying the given color.
172
    #[inline]
173
    #[must_use]
174
272
    pub fn create(color: ColorU) -> Self {
175
272
        Self {
176
272
            color_input_state: ColorInputStateWrapper {
177
272
                inner: ColorInputState { color },
178
272
                ..Default::default()
179
272
            },
180
272
            style: OptionCssPropertyWithConditionsVec::None,
181
272
            accessibility_name: OptionString::None,
182
272
        }
183
272
    }
184

            
185
    /// The swatch CSS this input renders with.
186
    ///
187
    /// `None` means no opinion, so the widget's default applies — the same
188
    /// answer both themes give, asked in one place so they cannot drift. The
189
    /// colour swatch, the checkerboard geometry and the translucency overrides
190
    /// are all appended to this in `dom()`.
191
    #[must_use]
192
170
    pub fn resolved_style(&self) -> CssPropertyWithConditionsVec {
193
170
        self.style.clone().into_option().unwrap_or_else(|| {
194
169
            CssPropertyWithConditionsVec::from_const_slice(DEFAULT_COLOR_INPUT_STYLE)
195
169
        })
196
170
    }
197

            
198
    /// Sets the callback invoked when the color value changes.
199
    #[inline]
200
36
    pub fn set_on_value_change<I: Into<ColorInputOnValueChangeCallback>>(
201
36
        &mut self,
202
36
        data: RefAny,
203
36
        callback: I,
204
36
    ) {
205
36
        self.color_input_state.on_value_change = Some(ColorInputOnValueChange {
206
36
            callback: callback.into(),
207
36
            refany: data,
208
36
        })
209
36
        .into();
210
36
    }
211

            
212
    /// Builder-style method to set the value-change callback.
213
    #[inline]
214
    #[must_use]
215
24
    pub fn with_on_value_change<C: Into<ColorInputOnValueChangeCallback>>(
216
24
        mut self,
217
24
        data: RefAny,
218
24
        callback: C,
219
24
    ) -> Self {
220
24
        self.set_on_value_change(data, callback);
221
24
        self
222
24
    }
223

            
224
    /// Replaces `self` with a default `ColorInput` and returns the previous value.
225
    #[inline]
226
    #[must_use]
227
12
    pub fn swap_with_default(&mut self) -> Self {
228
12
        let mut s = Self::default();
229
12
        core::mem::swap(&mut s, self);
230
12
        s
231
12
    }
232

            
233
    /// Converts this `ColorInput` into a styled [`Dom`]: the swatch, with the
234
    /// picker popup attached as its (closed) transient child.
235
    #[inline]
236
    #[must_use]
237
105
    pub fn dom(self) -> Dom {
238
        use azul_core::{
239
            a11y::{AccessibilityInfo, AccessibilityRole},
240
            callbacks::{CoreCallback, CoreCallbackData},
241
            dom::{ComponentEventFilter, EventFilter, HoverEventFilter, IdOrClass::Class},
242
        };
243

            
244
105
        let color = self.color_input_state.inner.color;
245
105
        let title = self.color_input_state.title.clone();
246
        // Resolved before `self.accessibility_name` is moved out below.
247
105
        let resolved_style = self.resolved_style();
248
105
        let a11y_name = match self.accessibility_name {
249
            OptionString::Some(n) => n,
250
105
            OptionString::None => title,
251
        };
252

            
253
105
        let mut style = resolved_style.into_library_owned_vec();
254
105
        style.push(CssPropertyWithConditions::simple(
255
105
            CssProperty::const_background_content(
256
105
                vec![StyleBackgroundContent::Color(color)].into(),
257
            ),
258
        ));
259

            
260
        // The persistent half: hue/sat survive a pass through black, the
261
        // open flag survives the app's rebuilds, a drag survives a move.
262
105
        let data = RefAny::new(ColorPickerData {
263
105
            state: self.color_input_state,
264
105
            hsv: Hsv::from_color(color),
265
105
            open: false,
266
105
            drag: Drag::None,
267
105
        });
268

            
269
105
        let panel = picker_panel(&data, color);
270

            
271
        // `tearoff`: the grip strip at the top of the panel tears the picker
272
        // off into a floating palette (a real toplevel) and docks it back.
273
        // `Transparent`: the popup window has per-pixel alpha, so the panel's
274
        // rounded corners are real corners (the desktop shows through them
275
        // and a click there falls through) instead of white window corners.
276
105
        let mut transient = NodeData::create_node(NodeType::TransientWindow(
277
105
            TransientWindowConfig::closed()
278
105
                .with_anchor(TransientAnchor::Bottom)
279
105
                .with_dismiss(TransientDismiss::Outside)
280
105
                .with_tearoff(azul_core::transient::TransientTearoff::Free)
281
105
                .with_material(azul_core::window::WindowBackgroundMaterial::Transparent),
282
105
        ));
283
105
        transient
284
105
            .set_attributes(vec![azul_core::dom::AttributeType::Title("Colour".into())].into());
285
105
        transient.add_callback(
286
105
            EventFilter::Component(ComponentEventFilter::Dismissed),
287
105
            data.clone(),
288
105
            Callback::from_ptr(on_picker_dismissed).to_core(),
289
        );
290
105
        let popup = Dom::create_from_data(transient).with_child(panel);
291

            
292
        // A translucent colour shows a checkerboard through it: the board and
293
        // a colour overlay go in as children, under the popup node. The
294
        // swatch's own background stays the colour (what an opaque swatch is).
295
105
        let translucent = color.a < 255;
296
105
        let mut swatch = Dom::create_div();
297
105
        if translucent {
298
69
            style.push(CssPropertyWithConditions::simple(
299
69
                CssProperty::const_position(LayoutPosition::Relative),
300
69
            ));
301
69
            style.push(CssPropertyWithConditions::simple(
302
69
                CssProperty::const_overflow_x(LayoutOverflow::Hidden),
303
69
            ));
304
69
            style.push(CssPropertyWithConditions::simple(
305
69
                CssProperty::const_overflow_y(LayoutOverflow::Hidden),
306
69
            ));
307
69
            let (w, h) = swatch_size(&style);
308
69
            swatch = swatch
309
69
                .with_child(checkerboard(w, h, (w.min(h) / 2.0).max(1.0)))
310
69
                .with_child(Dom::create_div().with_css(&format!(
311
69
                    "position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; \
312
69
                     background: {};",
313
69
                    css_rgba(ColorU { a: 255, ..color }, color.a)
314
69
                )));
315
69
        }
316

            
317
105
        swatch
318
105
            .with_ids_and_classes(vec![Class(COLOR_INPUT_CLASS.into())].into())
319
105
            .with_css_props(style.into())
320
105
            .with_tab_index(azul_core::dom::TabIndex::Auto)
321
105
            .with_accessibility_info(AccessibilityInfo {
322
105
                role: AccessibilityRole::PushButton,
323
105
                accessibility_name: Some(a11y_name).into(),
324
105
                accessibility_value: Some(AzString::from(color_to_hex(color))).into(),
325
105
                ..Default::default()
326
105
            })
327
105
            .with_dataset(Some(data.clone()).into())
328
105
            .with_merge_callback(azul_core::dom::DatasetMergeCallback::from_ptr(
329
105
                merge_picker_data,
330
            ))
331
105
            .with_callbacks(
332
105
                vec![CoreCallbackData {
333
105
                    event: EventFilter::Hover(HoverEventFilter::Click),
334
105
                    refany: data,
335
105
                    callback: CoreCallback {
336
105
                        cb: on_color_input_clicked as usize,
337
105
                        ctx: azul_core::refany::OptionRefAny::None,
338
105
                    },
339
105
                }]
340
105
                .into(),
341
            )
342
105
            .with_child(popup)
343
105
    }
344
}
345

            
346
/// The swatch's declared width/height (for the checkerboard behind a
347
/// translucent colour); the 14px default when the style does not say.
348
69
fn swatch_size(style: &[CssPropertyWithConditions]) -> (f32, f32) {
349
138
    let px = |ty: CssPropertyType, default: f32| -> f32 {
350
138
        style
351
138
            .iter()
352
138
            .rev()
353
897
            .find(|p| p.property.get_type() == ty)
354
138
            .and_then(|p| match &p.property {
355
69
                CssProperty::Width(v) => v.get_property().and_then(|w| match w {
356
69
                    LayoutWidth::Px(px) => Some(px.to_pixels_internal(default, 16.0, 16.0)),
357
                    _ => None,
358
69
                }),
359
69
                CssProperty::Height(v) => v.get_property().and_then(|h| match h {
360
69
                    LayoutHeight::Px(px) => Some(px.to_pixels_internal(default, 16.0, 16.0)),
361
                    _ => None,
362
69
                }),
363
                _ => None,
364
138
            })
365
138
            .unwrap_or(default)
366
138
    };
367
69
    (
368
69
        px(CssPropertyType::Width, 14.0),
369
69
        px(CssPropertyType::Height, 14.0),
370
69
    )
371
69
}
372

            
373
impl From<ColorInput> for Dom {
374
    fn from(c: ColorInput) -> Self {
375
        c.dom()
376
    }
377
}
378

            
379
// ---------------------------------------------------------------------------
380
// Colour math — pure, so it can be tested without a DOM.
381
// ---------------------------------------------------------------------------
382

            
383
/// Hue in degrees `[0, 360)`, saturation and value in `[0, 1]`.
384
#[derive(Debug, Clone, Copy, PartialEq)]
385
pub struct Hsv {
386
    pub h: f32,
387
    pub s: f32,
388
    pub v: f32,
389
}
390

            
391
impl Hsv {
392
    /// RGB → HSV. Grey has no hue; it reports 0.
393
    #[must_use]
394
    #[allow(clippy::many_single_char_names)] // r, g, b, h, s, v: the textbook formula
395
226
    pub fn from_color(c: ColorU) -> Self {
396
226
        let r = f32::from(c.r) / 255.0;
397
226
        let g = f32::from(c.g) / 255.0;
398
226
        let b = f32::from(c.b) / 255.0;
399
226
        let max = r.max(g).max(b);
400
226
        let min = r.min(g).min(b);
401
226
        let delta = max - min;
402
226
        let h = if delta <= f32::EPSILON {
403
89
            0.0
404
137
        } else if (max - r).abs() <= f32::EPSILON {
405
49
            60.0 * (((g - b) / delta) % 6.0)
406
88
        } else if (max - g).abs() <= f32::EPSILON {
407
24
            60.0 * ((b - r) / delta + 2.0)
408
        } else {
409
64
            60.0 * ((r - g) / delta + 4.0)
410
        };
411
226
        let h = if h < 0.0 { h + 360.0 } else { h };
412
226
        let s = if max <= f32::EPSILON {
413
42
            0.0
414
        } else {
415
184
            delta / max
416
        };
417
226
        Self { h, s, v: max }
418
226
    }
419

            
420
    /// HSV → RGB, alpha as given.
421
    #[must_use]
422
    #[allow(
423
        clippy::cast_possible_truncation,
424
        clippy::cast_sign_loss,
425
        clippy::many_single_char_names
426
    )] // 0..=255 by construction; r, g, b, h, s, v, c, x, m: the textbook formula
427
25
    pub fn to_color(self, a: u8) -> ColorU {
428
25
        let h = self.h.rem_euclid(360.0);
429
25
        let s = self.s.clamp(0.0, 1.0);
430
25
        let v = self.v.clamp(0.0, 1.0);
431
25
        let c = v * s;
432
25
        let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
433
25
        let m = v - c;
434
25
        let (r, g, b) = match (h / 60.0) as u32 {
435
12
            0 => (c, x, 0.0),
436
1
            1 => (x, c, 0.0),
437
2
            2 => (0.0, c, x),
438
7
            3 => (0.0, x, c),
439
2
            4 => (x, 0.0, c),
440
1
            _ => (c, 0.0, x),
441
        };
442
75
        let ch = |f: f32| ((f + m) * 255.0).round().clamp(0.0, 255.0) as u8;
443
25
        ColorU {
444
25
            r: ch(r),
445
25
            g: ch(g),
446
25
            b: ch(b),
447
25
            a,
448
25
        }
449
25
    }
450
}
451

            
452
/// `#rrggbb`, or `#rrggbbaa` when the colour is not fully opaque.
453
#[must_use]
454
221
pub fn color_to_hex(c: ColorU) -> String {
455
221
    if c.a == 255 {
456
82
        format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
457
    } else {
458
139
        format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
459
    }
460
221
}
461

            
462
/// Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` (the `#` optional,
463
/// case-insensitive, surrounding whitespace ignored). A missing alpha is
464
/// opaque.
465
#[must_use]
466
#[allow(clippy::many_single_char_names)] // r, g, b, a: the channels
467
9
pub fn color_from_hex(text: &str) -> Option<ColorU> {
468
9
    let t = text.trim().trim_start_matches('#');
469
29
    let nib = |ch: u8| -> Option<u8> { char::from(ch).to_digit(16).map(|d| d as u8) };
470
9
    let bytes = t.as_bytes();
471
13
    let pair = |i: usize| -> Option<u8> { Some(nib(bytes[i])? * 16 + nib(bytes[i + 1])?) };
472
9
    let (r, g, b, a) = match bytes.len() {
473
        3 => (
474
1
            nib(bytes[0])? * 17,
475
1
            nib(bytes[1])? * 17,
476
1
            nib(bytes[2])? * 17,
477
            255,
478
        ),
479
        4 => (
480
1
            nib(bytes[0])? * 17,
481
            nib(bytes[1])? * 17,
482
            nib(bytes[2])? * 17,
483
            nib(bytes[3])? * 17,
484
        ),
485
5
        6 => (pair(0)?, pair(2)?, pair(4)?, 255),
486
        8 => (pair(0)?, pair(2)?, pair(4)?, pair(6)?),
487
2
        _ => return None,
488
    };
489
5
    Some(ColorU { r, g, b, a })
490
9
}
491

            
492
// ---------------------------------------------------------------------------
493
// Persistent widget state
494
// ---------------------------------------------------------------------------
495

            
496
/// Which control is being dragged.
497
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
498
enum Drag {
499
    None,
500
    Plane,
501
    Hue,
502
    Alpha,
503
}
504

            
505
/// The swatch's dataset: what must outlive one build of the DOM.
506
#[derive(Debug)]
507
pub struct ColorPickerData {
508
    state: ColorInputStateWrapper,
509
    hsv: Hsv,
510
    open: bool,
511
    drag: Drag,
512
}
513

            
514
impl ColorPickerData {
515
    /// Whether the widget believes its picker is open (tests / diagnostics).
516
    #[must_use]
517
    pub const fn is_open(&self) -> bool {
518
        self.open
519
    }
520

            
521
    /// The colour the picker currently holds (tests / diagnostics).
522
    #[must_use]
523
    pub const fn current_color(&self) -> ColorU {
524
        self.state.inner.color
525
    }
526

            
527
18
    const fn color(&self) -> ColorU {
528
18
        self.state.inner.color
529
18
    }
530

            
531
    /// Adopt a colour the user picked: keeps the hue/sat the controls are on.
532
11
    fn set_hsv(&mut self, hsv: Hsv) {
533
11
        let a = self.state.inner.color.a;
534
11
        self.hsv = hsv;
535
11
        self.state.inner.color = hsv.to_color(a);
536
11
    }
537

            
538
    /// Adopt a colour that arrived as RGB (hex / number fields / the app).
539
    /// Hue and saturation are kept when the RGB is what they already
540
    /// describe — so a pass through black does not snap the hue to red.
541
6
    fn set_color(&mut self, c: ColorU) {
542
6
        if self.hsv.to_color(c.a) != c {
543
5
            self.hsv = Hsv::from_color(c);
544
5
        }
545
6
        self.state.inner.color = c;
546
6
    }
547
}
548

            
549
/// Reconcile: the old allocation survives (open flag, hsv, drag), adopting
550
/// the app's colour and callback from the new build — the app owns the
551
/// value, exactly like every other widget's `on_value_change` contract.
552
3
extern "C" fn merge_picker_data(mut new_data: RefAny, mut old_data: RefAny) -> RefAny {
553
3
    let merged = {
554
3
        let new_guard = new_data.downcast_ref::<ColorPickerData>();
555
3
        let old_guard = old_data.downcast_mut::<ColorPickerData>();
556
3
        if let (Some(new_g), Some(mut old_g)) = (new_guard, old_guard) {
557
2
            let app_color = new_g.state.inner.color;
558
2
            old_g.state.on_value_change = new_g.state.on_value_change.clone();
559
2
            old_g.state.title = new_g.state.title.clone();
560
2
            old_g.set_color(app_color);
561
2
            true
562
        } else {
563
1
            false
564
        }
565
    };
566
3
    if merged {
567
2
        old_data
568
    } else {
569
1
        new_data
570
    }
571
3
}
572

            
573
// ---------------------------------------------------------------------------
574
// The panel
575
// ---------------------------------------------------------------------------
576

            
577
/// The plane's own background: white → the pure hue, left to right. The
578
/// darkening towards the bottom is a separate overlay child (see
579
/// [`SHADE_CSS`]) — stacking it as a second background layer painted only
580
/// one of the two, so the plane never went to black.
581
115
fn plane_background_css(hue: f32) -> String {
582
115
    format!(
583
115
        "linear-gradient(to right, #ffffff, hsl({}, 100%, 50%))",
584
115
        hue.round()
585
    )
586
115
}
587

            
588
/// The plane's shade overlay: transparent at the top, black at the bottom.
589
const SHADE_CSS: &str = "position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; \
590
                         border-radius: 4px; background: linear-gradient(to bottom, rgba(0, 0, 0, \
591
                         0), #000000);";
592

            
593
/// `rgba(r, g, b, a)` for CSS, alpha as a fraction.
594
402
fn css_rgba(color: ColorU, alpha: u8) -> String {
595
402
    format!(
596
402
        "rgba({}, {}, {}, {:.3})",
597
        color.r,
598
        color.g,
599
        color.b,
600
402
        f32::from(alpha) / 255.0
601
    )
602
402
}
603

            
604
/// Class on a checkerboard (the thing behind a non-opaque colour).
605
pub const CHECKERBOARD_CLASS: &str = "__azul_native_checkerboard";
606
/// Class on a checkerboard's light cells.
607
pub const CHECKERBOARD_LIGHT_CLASS: &str = "__azul_native_checkerboard_light";
608
/// Class on a checkerboard's dark cells.
609
pub const CHECKERBOARD_DARK_CLASS: &str = "__azul_native_checkerboard_dark";
610

            
611
/// A checkerboard of `cell`-px squares filling `w`×`h`, built from DIVS so a
612
/// stylesheet can restyle it (`.__azul_native_checkerboard_dark { … }`) and
613
/// so it follows the theme: the cells carry a light-theme colour and a dark
614
/// one gated on `theme: dark`. What sits behind any colour that is not fully
615
/// opaque. (An image would tile faster, but could not be styled or themed.)
616
279
fn checkerboard(w: f32, h: f32, cell: f32) -> Dom {
617
    use azul_core::dom::IdOrClass::Class;
618
    use azul_css::dynamic_selector::{DynamicSelector, ThemeCondition};
619

            
620
9516
    let cell_css = |dark: bool| -> CssPropertyWithConditionsVec {
621
9516
        let (light_mode, dark_mode) = if dark {
622
4758
            (
623
4758
                ColorU {
624
4758
                    r: 0xcc,
625
4758
                    g: 0xcc,
626
4758
                    b: 0xcc,
627
4758
                    a: 255,
628
4758
                },
629
4758
                ColorU {
630
4758
                    r: 0x33,
631
4758
                    g: 0x33,
632
4758
                    b: 0x33,
633
4758
                    a: 255,
634
4758
                },
635
4758
            )
636
        } else {
637
4758
            (
638
4758
                ColorU {
639
4758
                    r: 0xff,
640
4758
                    g: 0xff,
641
4758
                    b: 0xff,
642
4758
                    a: 255,
643
4758
                },
644
4758
                ColorU {
645
4758
                    r: 0x55,
646
4758
                    g: 0x55,
647
4758
                    b: 0x55,
648
4758
                    a: 255,
649
4758
                },
650
4758
            )
651
        };
652
19032
        let bg = |c: ColorU| {
653
19032
            CssProperty::const_background_content(vec![StyleBackgroundContent::Color(c)].into())
654
19032
        };
655
9516
        CssPropertyWithConditionsVec::from_vec(vec![
656
9516
            CssPropertyWithConditions::simple(CssProperty::const_width(LayoutWidth::const_px(
657
9516
                cell as isize,
658
            ))),
659
9516
            CssPropertyWithConditions::simple(CssProperty::const_height(LayoutHeight::const_px(
660
9516
                cell as isize,
661
            ))),
662
9516
            CssPropertyWithConditions::simple(CssProperty::const_flex_grow(
663
9516
                LayoutFlexGrow::const_new(0),
664
            )),
665
9516
            CssPropertyWithConditions::simple(bg(light_mode)),
666
9516
            CssPropertyWithConditions {
667
9516
                property: bg(dark_mode),
668
9516
                apply_if: vec![DynamicSelector::Theme(ThemeCondition::Dark)].into(),
669
9516
            },
670
        ])
671
9516
    };
672
279
    let cols = (w / cell).ceil().max(1.0) as usize;
673
279
    let rows = (h / cell).ceil().max(1.0) as usize;
674
279
    let mut board = Dom::create_div()
675
279
        .with_ids_and_classes(vec![Class(CHECKERBOARD_CLASS.into())].into())
676
279
        .with_css(&format!(
677
279
            "position: absolute; left: 0px; top: 0px; width: {w}px; height: {h}px; display: flex; \
678
279
             flex-direction: column; overflow: hidden;"
679
279
        ));
680
768
    for y in 0..rows {
681
768
        let mut row = Dom::create_div().with_css("display: flex; flex-direction: row;");
682
9516
        for x in 0..cols {
683
9516
            let dark = (x + y) % 2 == 1;
684
9516
            let class = if dark {
685
4758
                CHECKERBOARD_DARK_CLASS
686
            } else {
687
4758
                CHECKERBOARD_LIGHT_CLASS
688
            };
689
9516
            row = row.with_child(
690
9516
                Dom::create_div()
691
9516
                    .with_ids_and_classes(vec![Class(class.into())].into())
692
9516
                    .with_css_props(cell_css(dark)),
693
            );
694
        }
695
768
        board = board.with_child(row);
696
    }
697
279
    board
698
279
}
699

            
700
const HUE_BACKGROUND_CSS: &str = "linear-gradient(to right, #ff0000 0%, #ffff00 17%, #00ff00 33%, \
701
                                  #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%)";
702

            
703
/// A property parsed from its CSS text; `None` if the text does not parse.
704
19
fn css_prop(ty: CssPropertyType, value: &str) -> Option<CssProperty> {
705
19
    parse_css_property(ty, value).ok()
706
19
}
707

            
708
/// The text/number inputs' default container style (border, padding, font)
709
/// with a fixed width in place of whatever width it declares — extended, not
710
/// replaced, so the fields inside the picker still look like fields.
711
525
fn field_container_style(width_px: isize, grow: bool) -> CssPropertyWithConditionsVec {
712
525
    let mut props: Vec<CssPropertyWithConditions> =
713
525
        crate::widgets::text_input::TEXT_INPUT_CONTAINER_PROPS.to_vec();
714
16275
    props.retain(|p| {
715
15750
        !matches!(
716
16275
            p.property.get_type(),
717
            CssPropertyType::Width | CssPropertyType::FlexGrow | CssPropertyType::MinWidth
718
        )
719
16275
    });
720
525
    props.push(CssPropertyWithConditions::simple(CssProperty::const_width(
721
525
        LayoutWidth::const_px(width_px),
722
    )));
723
525
    props.push(CssPropertyWithConditions::simple(
724
525
        CssProperty::const_flex_grow(LayoutFlexGrow::const_new(isize::from(grow))),
725
    ));
726
525
    props.into()
727
525
}
728

            
729
/// The picker panel that lives inside the popup.
730
105
fn picker_panel(data: &RefAny, color: ColorU) -> Dom {
731
    use azul_core::{
732
        a11y::{AccessibilityInfo, AccessibilityRole},
733
        callbacks::{CoreCallback, CoreCallbackData},
734
        dom::{EventFilter, HoverEventFilter, IdOrClass::Class},
735
    };
736

            
737
    use crate::widgets::{label::Label, number_input::NumberInput, text_input::TextInput};
738

            
739
105
    let hsv = Hsv::from_color(color);
740
105
    let hex = color_to_hex(color);
741

            
742
    // A control the user can DRAG must also be drivable from the keyboard,
743
    // or the picker is mouse-only. `key` handles the arrows (see `nudge_hsv`).
744
315
    let drag_callbacks = |down: usize, over: usize, up: usize, key: usize| {
745
315
        let mk = |event: EventFilter, cb: usize| CoreCallbackData {
746
1260
            event,
747
1260
            refany: data.clone(),
748
1260
            callback: CoreCallback {
749
1260
                cb,
750
1260
                ctx: azul_core::refany::OptionRefAny::None,
751
1260
            },
752
1260
        };
753
        // The press captures the pointer (see `capture_pointer`), so the
754
        // moves and the release reach this node wherever the cursor goes —
755
        // no `MouseLeave` ends the drag the moment the cursor slips off.
756
315
        vec![
757
315
            mk(EventFilter::Hover(HoverEventFilter::MouseDown), down),
758
315
            mk(EventFilter::Hover(HoverEventFilter::MouseMove), over),
759
315
            mk(EventFilter::Hover(HoverEventFilter::MouseUp), up),
760
            // Focus-scoped: only the FOCUSED control consumes the arrows, so
761
            // Tab moves between plane / hue / alpha / fields as usual.
762
315
            mk(
763
315
                EventFilter::Focus(azul_core::events::FocusEventFilter::VirtualKeyDown),
764
315
                key,
765
315
            ),
766
        ]
767
315
    };
768

            
769
    // Saturation/value plane with its ring marker.
770
105
    let plane_marker = Dom::create_div().with_css(&format!(
771
105
        "position: absolute; left: {:.1}%; top: {:.1}%; width: 12px; height: 12px; margin-left: \
772
105
         -6px; margin-top: -6px; border: 2px solid #ffffff; border-radius: 6px; box-shadow: 0px \
773
105
         0px 2px rgba(0, 0, 0, 0.6);",
774
105
        hsv.s * 100.0,
775
105
        (1.0 - hsv.v) * 100.0
776
105
    ));
777
    // Children: [shade overlay, marker] — the marker stays on top.
778
105
    let plane = Dom::create_div()
779
105
        .with_ids_and_classes(vec![Class(COLOR_PICKER_PLANE_CLASS.into())].into())
780
        // A tab stop: the picker must be drivable without a mouse.
781
105
        .with_tab_index(azul_core::dom::TabIndex::Auto)
782
105
        .with_css(&format!(
783
105
            "position: relative; width: {PLANE_WIDTH}px; height: {PLANE_HEIGHT}px; \
784
105
                 border-radius: 4px; cursor: crosshair; background: {};",
785
105
            plane_background_css(hsv.h)
786
105
        ))
787
105
        .with_accessibility_info(AccessibilityInfo {
788
105
            role: AccessibilityRole::Slider,
789
105
            accessibility_name: Some("Saturation and brightness".into()).into(),
790
105
            accessibility_value: Some(AzString::from(sv_a11y_value(hsv))).into(),
791
105
            ..Default::default()
792
105
        })
793
105
        .with_callbacks(
794
105
            drag_callbacks(
795
105
                on_plane_down as usize,
796
105
                on_plane_move as usize,
797
105
                on_plane_up as usize,
798
105
                on_plane_key as usize,
799
105
            )
800
105
            .into(),
801
        )
802
105
        .with_child(Dom::create_div().with_css(SHADE_CSS))
803
105
        .with_child(plane_marker);
804

            
805
    // Hue bar with its marker.
806
105
    let hue_marker = Dom::create_div().with_css(&format!(
807
105
        "position: absolute; left: {:.1}%; top: 0px; width: 12px; height: 12px; margin-left: \
808
105
         -6px; border: 2px solid #ffffff; border-radius: 6px; box-shadow: 0px 0px 2px rgba(0, 0, \
809
105
         0, 0.6);",
810
105
        hsv.h / 360.0 * 100.0
811
105
    ));
812
105
    let hue = Dom::create_div()
813
105
        .with_ids_and_classes(vec![Class(COLOR_PICKER_HUE_CLASS.into())].into())
814
        // A tab stop: the picker must be drivable without a mouse.
815
105
        .with_tab_index(azul_core::dom::TabIndex::Auto)
816
105
        .with_css(&format!(
817
105
            "position: relative; width: {PLANE_WIDTH}px; height: 12px; border-radius: 6px; \
818
105
                 cursor: pointer; background: {HUE_BACKGROUND_CSS};"
819
105
        ))
820
105
        .with_accessibility_info(AccessibilityInfo {
821
105
            role: AccessibilityRole::Slider,
822
105
            accessibility_name: Some("Hue".into()).into(),
823
105
            accessibility_value: Some(AzString::from(format!("{}°", hsv.h.round()))).into(),
824
105
            ..Default::default()
825
105
        })
826
105
        .with_callbacks(
827
105
            drag_callbacks(
828
105
                on_hue_down as usize,
829
105
                on_hue_move as usize,
830
105
                on_hue_up as usize,
831
105
                on_hue_key as usize,
832
105
            )
833
105
            .into(),
834
        )
835
105
        .with_child(hue_marker);
836

            
837
    // Alpha bar: checkerboard, then transparent→colour over it, then the marker.
838
105
    let opaque = ColorU { a: 255, ..color };
839
105
    let alpha_marker = Dom::create_div().with_css(&format!(
840
105
        "position: absolute; left: {:.1}%; top: 0px; width: 12px; height: 12px; margin-left: \
841
105
         -6px; border: 2px solid #ffffff; border-radius: 6px; box-shadow: 0px 0px 2px rgba(0, 0, \
842
105
         0, 0.6);",
843
105
        f32::from(color.a) / 255.0 * 100.0
844
105
    ));
845
105
    let alpha_fill = Dom::create_div().with_css(&format!(
846
105
        "position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; border-radius: 6px; \
847
105
         background: linear-gradient(to right, {}, {});",
848
105
        css_rgba(opaque, 0),
849
105
        css_rgba(opaque, 255)
850
105
    ));
851
105
    let mut alpha = Dom::create_div()
852
105
        .with_ids_and_classes(vec![Class(COLOR_PICKER_ALPHA_CLASS.into())].into())
853
        // A tab stop: the picker must be drivable without a mouse.
854
105
        .with_tab_index(azul_core::dom::TabIndex::Auto)
855
105
        .with_css(&format!(
856
105
            "position: relative; width: {PLANE_WIDTH}px; height: 12px; border-radius: 6px; \
857
105
             cursor: pointer; overflow: hidden;"
858
105
        ))
859
105
        .with_accessibility_info(AccessibilityInfo {
860
105
            role: AccessibilityRole::Slider,
861
105
            accessibility_name: Some("Opacity".into()).into(),
862
105
            accessibility_value: Some(AzString::from(alpha_a11y_value(color.a))).into(),
863
105
            ..Default::default()
864
105
        })
865
105
        .with_callbacks(
866
105
            drag_callbacks(
867
105
                on_alpha_down as usize,
868
105
                on_alpha_move as usize,
869
105
                on_alpha_up as usize,
870
105
                on_alpha_key as usize,
871
105
            )
872
105
            .into(),
873
        );
874
105
    alpha = alpha.with_child(checkerboard(PLANE_WIDTH, 12.0, 6.0));
875
105
    let alpha = alpha.with_child(alpha_fill).with_child(alpha_marker);
876

            
877
    // Preview + hex. A translucent colour shows the checkerboard through it.
878
105
    let mut preview = Dom::create_div()
879
105
        .with_css(
880
105
            "position: relative; width: 28px; height: 28px; border-radius: 4px; border: 1px solid \
881
105
             #c8c8c8; overflow: hidden;",
882
        )
883
105
        .with_accessibility_info(AccessibilityInfo {
884
105
            role: AccessibilityRole::Graphic,
885
105
            accessibility_name: Some("Current colour".into()).into(),
886
105
            accessibility_value: Some(AzString::from(hex.clone())).into(),
887
105
            ..Default::default()
888
105
        });
889
105
    preview = preview.with_child(checkerboard(26.0, 26.0, 6.5));
890
105
    let preview = preview.with_child(Dom::create_div().with_css(&format!(
891
105
        "position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background: {};",
892
105
        css_rgba(opaque, color.a)
893
105
    )));
894
105
    let hex_input = TextInput::create()
895
105
        .with_text(hex.into())
896
105
        .with_accessibility_name("Hex colour")
897
105
        .with_container_style(field_container_style(96, true))
898
105
        .with_on_focus_lost(data.clone(), {
899
105
            let cb: crate::widgets::text_input::TextInputOnFocusLostCallbackType = on_hex_committed;
900
105
            cb
901
        })
902
105
        .dom();
903
    // The eyedropper: `pick_screen_color` runs the platform's sampler (the
904
    // system loupe on macOS; a screenshot in a fullscreen loupe elsewhere -
905
    // Wayland asks the user through the portal first). The answer comes
906
    // back as the window-level `ScreenColorPicked`, registered on this
907
    // very node so it reaches the picker's data.
908
105
    let eyedropper = Dom::create_div()
909
105
        .with_ids_and_classes(vec![Class(COLOR_PICKER_EYEDROPPER_CLASS.into())].into())
910
105
        .with_css(
911
105
            "display: flex; align-items: center; justify-content: center; width: 28px; height: \
912
105
             28px; border: 1px solid #c8c8c8; border-radius: 4px; cursor: pointer; background: \
913
105
             #f4f4f4; color: #404040; font-size: 18px;",
914
        )
915
105
        .with_accessibility_info(AccessibilityInfo {
916
105
            role: AccessibilityRole::PushButton,
917
105
            accessibility_name: Some("Pick a colour from the screen".into()).into(),
918
105
            ..Default::default()
919
105
        })
920
105
        .with_callbacks(
921
105
            vec![
922
105
                CoreCallbackData {
923
105
                    event: EventFilter::Hover(HoverEventFilter::Click),
924
105
                    refany: data.clone(),
925
105
                    callback: CoreCallback {
926
105
                        cb: on_eyedropper_clicked as usize,
927
105
                        ctx: azul_core::refany::OptionRefAny::None,
928
105
                    },
929
105
                },
930
105
                CoreCallbackData {
931
105
                    event: EventFilter::Window(
932
105
                        azul_core::events::WindowEventFilter::ScreenColorPicked,
933
105
                    ),
934
105
                    refany: data.clone(),
935
105
                    callback: CoreCallback {
936
105
                        cb: on_screen_color_picked as usize,
937
105
                        ctx: azul_core::refany::OptionRefAny::None,
938
105
                    },
939
105
                },
940
            ]
941
105
            .into(),
942
        )
943
105
        .with_child(Dom::create_icon("colorize"));
944

            
945
105
    let preview_row = Dom::create_div()
946
105
        .with_css("display: flex; flex-direction: row; align-items: center; gap: 8px;")
947
105
        .with_child(preview)
948
105
        .with_child(hex_input)
949
105
        .with_child(eyedropper);
950

            
951
    // R / G / B.
952
105
    let channel =
953
        |name: &str,
954
         short: &str,
955
         value: u8,
956
420
         cb: crate::widgets::number_input::NumberInputOnValueChangeCallbackType| {
957
420
            let field = NumberInput::create(f32::from(value))
958
420
                .with_accessibility_name(name)
959
420
                .with_container_style(field_container_style(44, false))
960
420
                .with_on_value_change(data.clone(), cb)
961
420
                .dom();
962
420
            Dom::create_div()
963
420
                .with_css("display: flex; flex-direction: row; align-items: center; gap: 4px;")
964
420
                .with_child(Label::create(short.into()).dom())
965
420
                .with_child(field)
966
420
        };
967
105
    let rgb_row = Dom::create_div()
968
105
        .with_css("display: flex; flex-direction: row; align-items: center; gap: 8px;")
969
105
        .with_child(channel("Red", "R", color.r, on_red_changed))
970
105
        .with_child(channel("Green", "G", color.g, on_green_changed))
971
105
        .with_child(channel("Blue", "B", color.b, on_blue_changed))
972
105
        .with_child(channel("Opacity", "A", color.a, on_alpha_changed));
973

            
974
    // The grip: a drag region (`-azul-app-region: drag`). In the popup the
975
    // engine runs the tear-off drag on it; in the torn-off palette, a drag
976
    // back over the swatch docks it.
977
105
    let grip = Dom::create_div()
978
105
        .with_ids_and_classes(vec![Class(COLOR_PICKER_GRIP_CLASS.into())].into())
979
105
        .with_css(
980
105
            "display: flex; flex-direction: row; justify-content: center; align-items: center; \
981
105
             height: 10px; margin-top: -4px; margin-bottom: -2px; cursor: grab; -azul-app-region: \
982
105
             drag;",
983
        )
984
105
        .with_accessibility_info(AccessibilityInfo {
985
105
            role: AccessibilityRole::Separator,
986
105
            accessibility_name: Some("Drag to tear off".into()).into(),
987
105
            ..Default::default()
988
105
        })
989
105
        .with_child(
990
105
            Dom::create_div()
991
105
                .with_css("width: 36px; height: 4px; border-radius: 2px; background: #c8c8c8;"),
992
        );
993

            
994
105
    Dom::create_div()
995
105
        .with_ids_and_classes(vec![Class(COLOR_PICKER_CLASS.into())].into())
996
105
        .with_css(
997
105
            "display: flex; flex-direction: column; gap: 8px; padding: 8px; background: #ffffff; \
998
105
             border: 1px solid #c8c8c8; border-radius: 6px; box-shadow: 0px 4px 16px rgba(0, 0, \
999
105
             0, 0.25); font-size: 12px; color: #202020;",
        )
105
        .with_accessibility_info(AccessibilityInfo {
105
            role: AccessibilityRole::Dialog,
105
            accessibility_name: Some("Colour picker".into()).into(),
105
            ..Default::default()
105
        })
105
        .with_child(grip)
105
        .with_child(plane)
105
        .with_child(hue)
105
        .with_child(alpha)
105
        .with_child(preview_row)
105
        .with_child(rgb_row)
105
}
114
fn alpha_a11y_value(a: u8) -> String {
114
    format!("{}%", (f32::from(a) / 255.0 * 100.0).round())
114
}
115
fn sv_a11y_value(hsv: Hsv) -> String {
115
    format!(
115
        "saturation {}%, brightness {}%",
115
        (hsv.s * 100.0).round(),
115
        (hsv.v * 100.0).round()
    )
115
}
// ---------------------------------------------------------------------------
// Callbacks
// ---------------------------------------------------------------------------
/// The swatch was clicked: toggle the picker. The engine holds the popup
/// open across rebuilds (`set_transient_window_open`), closes it on an
/// outside click / Escape, and tells us through `Dismissed`.
33
extern "C" fn on_color_input_clicked(mut data: RefAny, mut info: CallbackInfo) -> Update {
33
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
1
        return Update::DoNothing;
    };
32
    let swatch = info.get_hit_node();
32
    let Some(transient) = info.get_first_child(swatch) else {
3
        return Update::DoNothing;
    };
29
    picker.open = !picker.open;
29
    info.set_transient_window_open(transient, picker.open);
29
    Update::DoNothing
33
}
/// The engine closed the popup for the user (outside click, Escape).
1
extern "C" fn on_picker_dismissed(mut data: RefAny, _info: CallbackInfo) -> Update {
1
    if let Some(mut picker) = data.downcast_mut::<ColorPickerData>() {
1
        picker.open = false;
1
        picker.drag = Drag::None;
1
    }
1
    Update::DoNothing
1
}
/// Where the cursor is inside the hit node, as fractions of its size.
10
fn cursor_fraction(info: &CallbackInfo) -> Option<(f32, f32)> {
10
    let pos = info.get_cursor_relative_to_node().into_option()?;
    // No laid-out rect (a headless test, a node mid-mutation): the nominal
    // size is the right denominator, the same way the slider falls back.
10
    let rect = info.get_hit_node_rect();
10
    let w = rect
10
        .map(|r| r.size.width)
10
        .filter(|w| *w > 0.0)
10
        .unwrap_or(PLANE_WIDTH);
10
    let h = rect
10
        .map(|r| r.size.height)
10
        .filter(|h| *h > 0.0)
10
        .unwrap_or(PLANE_HEIGHT);
10
    Some(((pos.x / w).clamp(0.0, 1.0), (pos.y / h).clamp(0.0, 1.0)))
10
}
/// Push the picked colour to the popup's own controls (instant, no relayout)
/// and to the app. `panel` is the picker panel node (the parent of the three
/// bars; the grandparent of the eyedropper button).
10
fn publish(
10
    picker: &mut ColorPickerData,
10
    info: &mut CallbackInfo,
10
    panel: Option<DomNodeId>,
10
) -> Update {
10
    let hsv = picker.hsv;
10
    let color = picker.color();
10
    let hex = color_to_hex(color);
    // The panel holds [grip, plane, hue, alpha, preview_row, rgb_row].
    // Children: plane = [shade, marker]; hue = [marker]; alpha = [board?,
    // fill, marker] (the board is the last child of alpha-less builds, so
    // walk from the end).
10
    if let Some(panel) = panel {
10
        if let Some(plane) = info
10
            .get_first_child(panel)
10
            .and_then(|grip| info.get_next_sibling(grip))
        {
10
            if let Some(prop) = css_prop(
10
                CssPropertyType::BackgroundContent,
10
                &plane_background_css(hsv.h),
10
            ) {
10
                info.set_css_property(plane, prop);
10
            }
10
            info.set_accessibility_value(plane, sv_a11y_value(hsv).into());
10
            if let Some(marker) = info.get_last_child(plane) {
9
                info.set_css_property(
9
                    marker,
9
                    CssProperty::const_left(LayoutLeft {
9
                        inner: PixelValue::percent(hsv.s * 100.0),
9
                    }),
9
                );
9
                info.set_css_property(
9
                    marker,
9
                    CssProperty::const_top(LayoutTop {
9
                        inner: PixelValue::percent((1.0 - hsv.v) * 100.0),
9
                    }),
9
                );
9
            }
10
            if let Some(hue) = info.get_next_sibling(plane) {
9
                info.set_accessibility_value(hue, format!("{}°", hsv.h.round()).into());
9
                if let Some(marker) = info.get_last_child(hue) {
9
                    info.set_css_property(
9
                        marker,
9
                        CssProperty::const_left(LayoutLeft {
9
                            inner: PixelValue::percent(hsv.h / 360.0 * 100.0),
9
                        }),
9
                    );
9
                }
9
                if let Some(alpha) = info.get_next_sibling(hue) {
9
                    info.set_accessibility_value(alpha, alpha_a11y_value(color.a).into());
9
                    let opaque = ColorU { a: 255, ..color };
9
                    if let Some(marker) = info.get_last_child(alpha) {
9
                        info.set_css_property(
9
                            marker,
9
                            CssProperty::const_left(LayoutLeft {
9
                                inner: PixelValue::percent(f32::from(color.a) / 255.0 * 100.0),
9
                            }),
                        );
9
                        if let Some(fill) = info.get_previous_sibling(marker) {
9
                            if let Some(prop) = css_prop(
9
                                CssPropertyType::BackgroundContent,
9
                                &format!(
9
                                    "linear-gradient(to right, {}, {})",
9
                                    css_rgba(opaque, 0),
9
                                    css_rgba(opaque, 255)
9
                                ),
9
                            ) {
9
                                info.set_css_property(fill, prop);
9
                            }
                        }
                    }
9
                    if let Some(preview) = info
9
                        .get_next_sibling(alpha)
9
                        .and_then(|row| info.get_first_child(row))
                    {
9
                        info.set_accessibility_value(preview, hex.into());
9
                        if let Some(overlay) = info.get_last_child(preview) {
9
                            info.set_css_property(
9
                                overlay,
9
                                CssProperty::const_background_content(
9
                                    vec![StyleBackgroundContent::Color(color)].into(),
9
                                ),
9
                            );
9
                        }
                    }
                }
1
            }
        }
    }
10
    let inner = picker.state.inner;
10
    match picker.state.on_value_change.as_mut() {
7
        Some(ColorInputOnValueChange { callback, refany }) => {
7
            (callback.cb)(refany.clone(), *info, inner)
        }
3
        None => Update::DoNothing,
    }
10
}
/// Arrow-key control for the picker's plane and hue bar, so a colour can be
/// set WITHOUT a mouse: arrows nudge by 1%, Ctrl+arrows by 10% (the usual
/// coarse/fine pair). Up/Down move brightness on the plane; Left/Right move
/// saturation there and hue on the hue bar.
///
/// Shares `set_hsv` + `publish` with the drag handlers, so a keyboard change
/// commits through exactly the same path a mouse drag does - one update
/// route, not a parallel one that can drift.
fn nudge_hsv(picker: &mut ColorPickerData, info: &mut CallbackInfo, axis: NudgeAxis) -> Update {
    use azul_core::window::VirtualKeyCode as K;
    let ks = info.get_current_keyboard_state();
    let Some(key) = ks.current_virtual_keycode.into_option() else {
        return Update::DoNothing;
    };
    // Ctrl (or Cmd on macOS) = the coarse step.
    let coarse = ks.ctrl_down() || ks.super_down();
    let step = if coarse { 0.10 } else { 0.01 };
    let mut hsv = picker.hsv;
    match (axis, key) {
        (NudgeAxis::Plane, K::Left) => hsv.s = (hsv.s - step).clamp(0.0, 1.0),
        (NudgeAxis::Plane, K::Right) => hsv.s = (hsv.s + step).clamp(0.0, 1.0),
        (NudgeAxis::Plane, K::Up) => hsv.v = (hsv.v + step).clamp(0.0, 1.0),
        (NudgeAxis::Plane, K::Down) => hsv.v = (hsv.v - step).clamp(0.0, 1.0),
        (NudgeAxis::Hue, K::Left | K::Down) => {
            hsv.h = (hsv.h - step * 360.0).rem_euclid(360.0);
        }
        (NudgeAxis::Hue, K::Right | K::Up) => {
            hsv.h = (hsv.h + step * 360.0).rem_euclid(360.0);
        }
        // Alpha is a channel of the COLOUR, not of `hsv` - go through the
        // same `set_color` the alpha drag uses.
        (NudgeAxis::Alpha, K::Left | K::Down | K::Right | K::Up) => {
            let dir = if matches!(key, K::Left | K::Down) {
                -1.0
            } else {
                1.0
            };
            let mut c = picker.color();
            let a = f32::from(c.a) / 255.0;
            c.a = channel_value((a + dir * step).clamp(0.0, 1.0) * 255.0);
            picker.set_color(c);
            info.prevent_default();
            let panel = info.get_parent(info.get_hit_node());
            return publish(picker, info, panel);
        }
        // Every other key keeps its default behaviour (Tab moves on, Escape
        // dismisses the popup - both handled by the engine).
        _ => return Update::DoNothing,
    }
    picker.set_hsv(hsv);
    // The arrow must not ALSO scroll the panel underneath.
    info.prevent_default();
    let panel = info.get_parent(info.get_hit_node());
    publish(picker, info, panel)
}
/// Which control `nudge_hsv` is driving.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NudgeAxis {
    /// The saturation / brightness plane.
    Plane,
    /// The hue bar.
    Hue,
    /// The alpha bar.
    Alpha,
}
extern "C" fn on_plane_key(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    nudge_hsv(&mut picker, &mut info, NudgeAxis::Plane)
}
extern "C" fn on_hue_key(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    nudge_hsv(&mut picker, &mut info, NudgeAxis::Hue)
}
extern "C" fn on_alpha_key(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    nudge_hsv(&mut picker, &mut info, NudgeAxis::Alpha)
}
7
fn apply_plane(picker: &mut ColorPickerData, info: &mut CallbackInfo) -> Update {
7
    let Some((x, y)) = cursor_fraction(info) else {
        return Update::DoNothing;
    };
7
    let hsv = Hsv {
7
        h: picker.hsv.h,
7
        s: x,
7
        v: 1.0 - y,
7
    };
7
    picker.set_hsv(hsv);
7
    let panel = info.get_parent(info.get_hit_node());
7
    publish(picker, info, panel)
7
}
3
fn apply_hue(picker: &mut ColorPickerData, info: &mut CallbackInfo) -> Update {
3
    let Some((x, _)) = cursor_fraction(info) else {
        return Update::DoNothing;
    };
3
    let hsv = Hsv {
3
        h: (x * 360.0).min(359.9),
3
        s: picker.hsv.s,
3
        v: picker.hsv.v,
3
    };
3
    picker.set_hsv(hsv);
3
    let panel = info.get_parent(info.get_hit_node());
3
    publish(picker, info, panel)
3
}
/// The eyedropper button: ask the platform to sample a screen pixel. The
/// answer arrives in `on_screen_color_picked`.
extern "C" fn on_eyedropper_clicked(_data: RefAny, mut info: CallbackInfo) -> Update {
    info.pick_screen_color();
    Update::DoNothing
}
/// `ScreenColorPicked` (window-level) in the picker's window: adopt the
/// sampled colour - RGB from the screen, the alpha the user had set - and
/// publish it like any other change. A cancelled pick changes nothing.
#[allow(unused_qualifications)]
extern "C" fn on_screen_color_picked(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let azul_css::props::basic::color::OptionColorU::Some(picked) = info.get_picked_screen_color()
    else {
        return Update::DoNothing;
    };
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    let a = picker.color().a;
    picker.set_color(ColorU { a, ..picked });
    // The button sits in the preview row: the panel is two levels up.
    let panel = info
        .get_parent(info.get_hit_node())
        .and_then(|row| info.get_parent(row));
    publish(&mut picker, &mut info, panel)
}
7
extern "C" fn on_plane_down(mut data: RefAny, mut info: CallbackInfo) -> Update {
7
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
7
    picker.drag = Drag::Plane;
7
    info.capture_pointer(info.get_hit_node());
7
    apply_plane(&mut picker, &mut info)
7
}
1
extern "C" fn on_plane_move(mut data: RefAny, mut info: CallbackInfo) -> Update {
1
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
1
    if picker.drag != Drag::Plane {
1
        return Update::DoNothing;
    }
    apply_plane(&mut picker, &mut info)
1
}
extern "C" fn on_plane_up(mut data: RefAny, _info: CallbackInfo) -> Update {
    if let Some(mut picker) = data.downcast_mut::<ColorPickerData>() {
        if picker.drag == Drag::Plane {
            picker.drag = Drag::None;
        }
    }
    Update::DoNothing
}
3
extern "C" fn on_hue_down(mut data: RefAny, mut info: CallbackInfo) -> Update {
3
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
3
    picker.drag = Drag::Hue;
3
    info.capture_pointer(info.get_hit_node());
3
    apply_hue(&mut picker, &mut info)
3
}
extern "C" fn on_hue_move(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    if picker.drag != Drag::Hue {
        return Update::DoNothing;
    }
    apply_hue(&mut picker, &mut info)
}
extern "C" fn on_hue_up(mut data: RefAny, _info: CallbackInfo) -> Update {
    if let Some(mut picker) = data.downcast_mut::<ColorPickerData>() {
        if picker.drag == Drag::Hue {
            picker.drag = Drag::None;
        }
    }
    Update::DoNothing
}
fn apply_alpha(picker: &mut ColorPickerData, info: &mut CallbackInfo) -> Update {
    let Some((x, _)) = cursor_fraction(info) else {
        return Update::DoNothing;
    };
    let mut c = picker.color();
    c.a = channel_value(x * 255.0);
    picker.set_color(c);
    let panel = info.get_parent(info.get_hit_node());
    publish(picker, info, panel)
}
extern "C" fn on_alpha_down(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    picker.drag = Drag::Alpha;
    info.capture_pointer(info.get_hit_node());
    apply_alpha(&mut picker, &mut info)
}
extern "C" fn on_alpha_move(mut data: RefAny, mut info: CallbackInfo) -> Update {
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
    if picker.drag != Drag::Alpha {
        return Update::DoNothing;
    }
    apply_alpha(&mut picker, &mut info)
}
extern "C" fn on_alpha_up(mut data: RefAny, _info: CallbackInfo) -> Update {
    if let Some(mut picker) = data.downcast_mut::<ColorPickerData>() {
        if picker.drag == Drag::Alpha {
            picker.drag = Drag::None;
        }
    }
    Update::DoNothing
}
/// The hex field lost focus: adopt its text if it is a colour.
3
extern "C" fn on_hex_committed(
3
    mut data: RefAny,
3
    mut info: CallbackInfo,
3
    text: crate::widgets::text_input::TextInputState,
3
) -> Update {
3
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
3
    let Some(c) = color_from_hex(&text.get_text()) else {
1
        return Update::DoNothing;
    };
2
    if c == picker.color() {
1
        return Update::DoNothing;
1
    }
1
    picker.set_color(c);
1
    let inner = picker.state.inner;
1
    match picker.state.on_value_change.as_mut() {
1
        Some(ColorInputOnValueChange { callback, refany }) => {
1
            (callback.cb)(refany.clone(), info, inner)
        }
        None => Update::DoNothing,
    }
3
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // clamped to 0..=255 first
3
const fn channel_value(v: f32) -> u8 {
3
    v.round().clamp(0.0, 255.0) as u8
3
}
3
fn on_channel_changed(
3
    data: &mut RefAny,
3
    info: CallbackInfo,
3
    value: f32,
3
    set: fn(&mut ColorU, u8),
3
) -> Update {
3
    let Some(mut picker) = data.downcast_mut::<ColorPickerData>() else {
        return Update::DoNothing;
    };
3
    let mut c = picker.color();
3
    set(&mut c, channel_value(value));
3
    if c == picker.color() {
        return Update::DoNothing;
3
    }
3
    picker.set_color(c);
3
    let inner = picker.state.inner;
3
    match picker.state.on_value_change.as_mut() {
        Some(ColorInputOnValueChange { callback, refany }) => {
            (callback.cb)(refany.clone(), info, inner)
        }
3
        None => Update::DoNothing,
    }
3
}
1
extern "C" fn on_red_changed(
1
    mut data: RefAny,
1
    info: CallbackInfo,
1
    n: crate::widgets::number_input::NumberInputState,
1
) -> Update {
1
    on_channel_changed(&mut data, info, n.number, |c, v| c.r = v)
1
}
1
extern "C" fn on_green_changed(
1
    mut data: RefAny,
1
    info: CallbackInfo,
1
    n: crate::widgets::number_input::NumberInputState,
1
) -> Update {
1
    on_channel_changed(&mut data, info, n.number, |c, v| c.g = v)
1
}
extern "C" fn on_alpha_changed(
    mut data: RefAny,
    info: CallbackInfo,
    n: crate::widgets::number_input::NumberInputState,
) -> Update {
    on_channel_changed(&mut data, info, n.number, |c, v| c.a = v)
}
1
extern "C" fn on_blue_changed(
1
    mut data: RefAny,
1
    info: CallbackInfo,
1
    n: crate::widgets::number_input::NumberInputState,
1
) -> Update {
1
    on_channel_changed(&mut data, info, n.number, |c, v| c.b = v)
1
}
#[cfg(all(test, feature = "std"))]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use std::{
        collections::{hash_map::DefaultHasher, BTreeMap, HashMap},
        hash::{Hash, Hasher},
        mem::discriminant,
        sync::{Arc, Mutex},
    };
    use azul_core::{
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, IdOrClass, NodeId, NodeType},
        geom::{LogicalPosition, LogicalRect, OptionLogicalPosition},
        gl::OptionGlContextPtr,
        hit_test::ScrollPosition,
        refany::OptionRefAny,
        resources::RendererResources,
        styled_dom::{NodeHierarchyItemId, StyledDom},
        window::{MonitorVec, RawWindowHandle},
    };
    use azul_css::props::basic::{length::SizeMetric, pixel::PixelValue};
    use rust_fontconfig::FcFontCache;
    use super::*;
    #[cfg(feature = "icu")]
    use crate::icu::IcuLocalizerHandle;
    use crate::{
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
        window::{DomLayoutResult, LayoutWindow},
        window_state::FullWindowState,
    };
    // ------------------------------------------------------------------
    // Fixtures
    // ------------------------------------------------------------------
    /// The swatch is a fixed 14x14 box — the entire geometry of the widget.
    const SIDE: f32 = 14.0;
    /// The widget's default title, as promised by `ColorInputStateWrapper::default`.
    const DEFAULT_TITLE: &str = "Pick color";
    /// The color a freshly-defaulted `ColorInputState` holds: **opaque white**, which is
    /// deliberately *not* `ColorU::default()` (that one is opaque black). A swatch that
    /// silently defaulted to black would be indistinguishable from a "real" black pick.
    const DEFAULT_COLOR: ColorU = ColorU {
        r: 255,
        g: 255,
        b: 255,
        a: 255,
    };
    /// Adversarial `ColorU` inputs. `create`/`dom` must move all four channels through
    /// verbatim, so the set covers both alpha extremes, the two off-by-one alphas, and
    /// `{1,2,3,4}` — four distinct small values that catch any channel reordering (an
    /// r/b swap is invisible for greys and for anything symmetric).
    const SAMPLE_COLORS: [ColorU; 8] = [
        ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        },
        ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        },
        ColorU {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        },
        ColorU {
            r: 255,
            g: 255,
            b: 255,
            a: 0,
        },
        ColorU {
            r: 255,
            g: 0,
            b: 0,
            a: 1,
        },
        ColorU {
            r: 0,
            g: 255,
            b: 0,
            a: 254,
        },
        ColorU {
            r: 1,
            g: 2,
            b: 3,
            a: 4,
        },
        ColorU {
            r: 128,
            g: 64,
            b: 32,
            a: 16,
        },
    ];
    // ------------------------------------------------------------------
    // Style-vec / DOM probes
    // ------------------------------------------------------------------
    fn properties(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
        v.as_ref().iter().map(|p| p.property.clone()).collect()
    }
    fn find<T>(
        v: &CssPropertyWithConditionsVec,
        f: impl Fn(&CssProperty) -> Option<T>,
    ) -> Option<T> {
        v.as_ref().iter().find_map(|p| f(&p.property))
    }
    /// The `f32` of a `PixelValue`, asserting it is an absolute `px` length. An `em` or
    /// `%` slipping into the swatch geometry would resolve against the parent font/box,
    /// so the "14px" swatch could render at any size at all.
    fn px(pv: &PixelValue) -> f32 {
        assert_eq!(
            pv.metric,
            SizeMetric::Px,
            "color-input geometry must be absolute px, got {:?}",
            pv.metric,
        );
        pv.number.get()
    }
    fn width_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
        find(v, |p| match p {
            CssProperty::Width(w) => match w.get_property() {
                Some(LayoutWidth::Px(pv)) => Some(px(pv)),
                _ => None,
            },
            _ => None,
        })
    }
    fn height_px(v: &CssPropertyWithConditionsVec) -> Option<f32> {
        find(v, |p| match p {
            CssProperty::Height(h) => match h.get_property() {
                Some(LayoutHeight::Px(pv)) => Some(px(pv)),
                _ => None,
            },
            _ => None,
        })
    }
    /// The `background-color` of a style vec (first background layer only).
    fn background_color(v: &CssPropertyWithConditionsVec) -> Option<ColorU> {
        v.as_ref().iter().find_map(|p| match &p.property {
            CssProperty::BackgroundContent(b) => match b.get_property()?.as_ref().first()? {
                StyleBackgroundContent::Color(c) => Some(*c),
                _ => None,
            },
            _ => None,
        })
    }
    fn classes(dom: &Dom) -> Vec<String> {
        dom.root
            .get_ids_and_classes()
            .as_ref()
            .iter()
            .filter_map(|c| match c {
                IdOrClass::Class(s) => Some(s.as_str().to_string()),
                IdOrClass::Id(_) => None,
            })
            .collect()
    }
    /// The properties of a rendered node's *inline* style, in declaration order.
    fn inline_properties(dom: &Dom) -> Vec<CssProperty> {
        dom.root
            .style
            .iter_inline_properties()
            .map(|(p, _)| p.clone())
            .collect()
    }
    /// The `background-color` actually declared on the rendered node.
    fn dom_background(dom: &Dom) -> Option<ColorU> {
        inline_properties(dom).into_iter().find_map(|p| match p {
            CssProperty::BackgroundContent(b) => match b.get_property()?.as_ref().first()? {
                StyleBackgroundContent::Color(c) => Some(*c),
                _ => None,
            },
            _ => None,
        })
    }
    /// The exact property `dom()` is expected to append for `c`.
    fn expected_background(c: ColorU) -> CssProperty {
        CssProperty::const_background_content(StyleBackgroundContentVec::from_vec(vec![
            StyleBackgroundContent::Color(c),
        ]))
    }
    fn hash_of<T: Hash>(t: &T) -> u64 {
        let mut h = DefaultHasher::new();
        t.hash(&mut h);
        h.finish()
    }
    // ------------------------------------------------------------------
    // Callback harness
    // ------------------------------------------------------------------
    /// A `DomNodeId` in the root DOM pointing at flattened node `idx`.
    fn node(idx: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(idx))),
        }
    }
    /// A `DomNodeId` whose node component is `None` — the "no concrete node was hit" case.
    fn node_none() -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::NONE,
        }
    }
    /// A `DomLayoutResult` carrying only a `styled_dom`. `on_color_input_clicked` never
    /// queries the layout at all, so no real layout (and no font) is needed.
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// Runs `f` with a `CallbackInfo` whose window holds `styled_dom` as the root DOM and
    /// whose hit node is `hit`. Returns `f`'s value plus every change the callback pushed
    /// onto the transaction log.
    fn with_info<R>(
        styled_dom: StyledDom,
        hit: DomNodeId,
        f: impl FnOnce(&mut CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>) {
        with_info_cursor(styled_dom, hit, OptionLogicalPosition::None, f)
    }
    fn with_info_cursor<R>(
        styled_dom: StyledDom,
        hit: DomNodeId,
        cursor: OptionLogicalPosition,
        f: impl FnOnce(&mut CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>) {
        let mut layout_window =
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
        layout_window
            .layout_results
            .insert(DomId::ROOT_ID, layout_result(styled_dom));
        let renderer_resources = RendererResources::default();
        let previous_window_state: Option<FullWindowState> = None;
        let current_window_state = FullWindowState::default();
        let gl_context = OptionGlContextPtr::None;
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
        let ref_data = CallbackInfoRefData {
            layout_window: &layout_window,
            renderer_resources: &renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &current_window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &system_callbacks,
            system_style: Arc::new(system::SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
        let mut info = CallbackInfo::new(
            &ref_data,
            &changes,
            hit,
            cursor,
            OptionLogicalPosition::None,
        );
        let r = f(&mut info);
        let pushed = info.take_changes();
        (r, pushed)
    }
    /// Renders `color_input`, then hands back both the laid-out DOM *and* the very `RefAny`
    /// the widget registered on its own mouse-up callback. Driving the handler with these
    /// two is the real wiring — nothing is re-created by hand, so a mismatch between what
    /// `dom()` stores and what the handler expects cannot hide behind the fixture.
    fn laid_out(color_input: ColorInput) -> (StyledDom, RefAny) {
        let dom = color_input.dom();
        let state = dom.root.callbacks.as_ref()[0].refany.clone();
        (StyledDom::create_from_dom(dom), state)
    }
    /// One "mouse-up on `hit`" delivered to the widget's own registered handler.
    fn click(
        styled_dom: StyledDom,
        state: &RefAny,
        hit: DomNodeId,
    ) -> (Update, Vec<CallbackChange>) {
        with_info(styled_dom, hit, |info| {
            on_color_input_clicked(state.clone(), *info)
        })
    }
    fn state_color(state: &RefAny) -> ColorU {
        let mut state = state.clone();
        let picker = state
            .downcast_ref::<ColorPickerData>()
            .expect("the widget state changed type");
        picker.state.inner.color
    }
    /// Like `with_info`, with the cursor at `cursor` relative to the hit node.
    fn with_info_at<R>(
        styled_dom: StyledDom,
        hit: DomNodeId,
        cursor: LogicalPosition,
        f: impl FnOnce(&mut CallbackInfo) -> R,
    ) -> (R, Vec<CallbackChange>) {
        with_info_cursor(styled_dom, hit, OptionLogicalPosition::Some(cursor), f)
    }
    /// A payload the value-change callback writes into. It arrives as the `data: RefAny`
    /// argument — a *shared* clone of what the test still holds — so the test can read back
    /// exactly what the widget passed, without any global state.
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct ColorLog {
        seen: Vec<ColorU>,
        payload: u32,
    }
    extern "C" fn record_value(
        mut data: RefAny,
        _info: CallbackInfo,
        state: ColorInputState,
    ) -> Update {
        if let Some(mut log) = data.downcast_mut::<ColorLog>() {
            log.seen.push(state.color);
        }
        Update::RefreshDom
    }
    extern "C" fn value_do_nothing(
        _data: RefAny,
        _info: CallbackInfo,
        _state: ColorInputState,
    ) -> Update {
        Update::DoNothing
    }
    extern "C" fn value_refresh_all(
        _data: RefAny,
        _info: CallbackInfo,
        _state: ColorInputState,
    ) -> Update {
        Update::RefreshDomAllWindows
    }
    /// A `Callback`-shaped (2-arg) function — the shape FFI bindings hand in, which the
    /// `From<Callback>` arm *transmutes* into the 3-arg color-input slot. Never called.
    extern "C" fn generic_shaped(_data: RefAny, _info: CallbackInfo) -> Update {
        Update::DoNothing
    }
    fn log_refany() -> RefAny {
        RefAny::new(ColorLog {
            seen: Vec::new(),
            payload: 0xDEAD_BEEF,
        })
    }
    fn read_log(probe: &RefAny) -> ColorLog {
        let mut probe = probe.clone();
        let log = probe
            .downcast_ref::<ColorLog>()
            .expect("the user payload changed type");
        log.clone()
    }
    // ==================================================================
    // ColorInput::create
    // ==================================================================
    #[test]
    fn create_stores_every_channel_verbatim() {
        // A channel swap (r/b) or a dropped alpha still type-checks and still renders
        // *a* color — only an asymmetric fixture catches it.
        for c in SAMPLE_COLORS {
            let w = ColorInput::create(c);
            assert_eq!(
                w.color_input_state.inner.color, c,
                "create({c:?}) did not store the color it was given",
            );
        }
    }
    #[test]
    fn create_installs_no_callback_and_the_default_title() {
        for c in SAMPLE_COLORS {
            let w = ColorInput::create(c);
            assert!(
                w.color_input_state.on_value_change.as_ref().is_none(),
                "create({c:?}) invented a value-change callback out of nowhere",
            );
            assert_eq!(
                w.color_input_state.title.as_str(),
                DEFAULT_TITLE,
                "create({c:?}) did not keep the default title",
            );
        }
    }
    #[test]
    fn create_is_pure_and_distinguishes_every_sample_color() {
        for c in SAMPLE_COLORS {
            assert_eq!(
                ColorInput::create(c),
                ColorInput::create(c),
                "create({c:?}) is not deterministic",
            );
        }
        for (i, a) in SAMPLE_COLORS.iter().enumerate() {
            for b in &SAMPLE_COLORS[i + 1..] {
                assert_ne!(
                    ColorInput::create(*a),
                    ColorInput::create(*b),
                    "the widgets for {a:?} and {b:?} are indistinguishable",
                );
            }
        }
    }
    #[test]
    fn create_treats_alpha_as_significant() {
        // `{255,0,0,0}` and `{255,0,0,255}` differ only in alpha: an invisible swatch and
        // an opaque red one. Comparing on rgb alone would fuse the two.
        let opaque = ColorU {
            r: 255,
            g: 0,
            b: 0,
            a: 255,
        };
        let clear = ColorU {
            r: 255,
            g: 0,
            b: 0,
            a: 0,
        };
        assert_ne!(
            ColorInput::create(opaque),
            ColorInput::create(clear),
            "a transparent swatch compares equal to an opaque one",
        );
    }
    #[test]
    fn create_geometry_is_absolute_14px_for_every_color() {
        // `px()` asserts SizeMetric::Px — an em/% here would scale with the parent.
        for c in SAMPLE_COLORS {
            let w = ColorInput::create(c);
            assert_eq!(
                width_px(&w.resolved_style()),
                Some(SIDE),
                "{c:?}: wrong swatch width"
            );
            assert_eq!(
                height_px(&w.resolved_style()),
                Some(SIDE),
                "{c:?}: wrong swatch height"
            );
        }
    }
    #[test]
    fn create_marks_the_swatch_as_clickable() {
        // Without `cursor: pointer` the swatch looks inert even though it is the node
        // that carries the mouse-up handler.
        let props = properties(&ColorInput::create(DEFAULT_COLOR).resolved_style());
        assert!(
            props.contains(&CssProperty::const_cursor(StyleCursor::Pointer)),
            "the color input does not present as clickable: {props:?}",
        );
    }
    #[test]
    fn create_is_a_non_growing_block() {
        // A swatch with flex-grow != 0 would stretch to fill its row and stop being a
        // 14px square, silently defeating the width/height declarations above.
        let props = properties(&ColorInput::create(DEFAULT_COLOR).resolved_style());
        assert!(
            props.contains(&CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
            "the swatch is allowed to flex-grow: {props:?}",
        );
        assert!(
            props.contains(&CssProperty::const_display(LayoutDisplay::Block)),
            "the swatch is not a block box: {props:?}",
        );
    }
    #[test]
    fn create_declares_no_property_twice() {
        // A duplicate declaration means the later one silently wins — a latent
        // "why is my override ignored" bug that never surfaces as an error.
        let props = properties(&ColorInput::create(DEFAULT_COLOR).resolved_style());
        let mut seen = Vec::new();
        for p in &props {
            let d = discriminant(p);
            assert!(!seen.contains(&d), "the base style declares {p:?} twice");
            seen.push(d);
        }
    }
    #[test]
    fn create_keeps_the_color_out_of_the_base_style() {
        // The color lives in the *state* and is only turned into a background by `dom()`.
        // A background baked into the shared const table would make every swatch on screen
        // render the same color (and `dom()` would then declare it twice).
        for c in SAMPLE_COLORS {
            assert_eq!(
                background_color(&ColorInput::create(c).resolved_style()),
                None,
                "create({c:?}) leaked the color into the base style",
            );
        }
    }
    #[test]
    fn create_style_does_not_depend_on_the_color() {
        let reference = properties(&ColorInput::create(SAMPLE_COLORS[0]).resolved_style());
        for c in SAMPLE_COLORS {
            assert_eq!(
                properties(&ColorInput::create(c).resolved_style()),
                reference,
                "create({c:?}) produced a different style than create({:?})",
                SAMPLE_COLORS[0],
            );
        }
    }
    // ==================================================================
    // Default state invariants
    // ==================================================================
    #[test]
    fn the_default_color_is_opaque_white_not_colorus_own_default() {
        // `ColorU::default()` is opaque *black*. If `ColorInputState` ever fell back to the
        // derived default, every un-set swatch would render black — and a user who really
        // picked black would be indistinguishable from one who picked nothing.
        assert_eq!(ColorInputState::default().color, DEFAULT_COLOR);
        assert_ne!(
            ColorInputState::default().color,
            ColorU::default(),
            "the color input's default silently became ColorU::default()",
        );
        assert_eq!(ColorInputStateWrapper::default().inner.color, DEFAULT_COLOR);
        assert_eq!(
            ColorInputStateWrapper::default().title.as_str(),
            DEFAULT_TITLE,
        );
        assert!(ColorInputStateWrapper::default()
            .on_value_change
            .as_ref()
            .is_none());
    }
    #[test]
    fn color_input_state_ord_and_partial_ord_agree() {
        // `ColorInputState` derives both. A hand-written impl drifting from the other would
        // make sorted containers of states behave inconsistently with `<`.
        for a in SAMPLE_COLORS {
            for b in SAMPLE_COLORS {
                let (x, y) = (ColorInputState { color: a }, ColorInputState { color: b });
                assert_eq!(
                    x.partial_cmp(&y),
                    Some(x.cmp(&y)),
                    "PartialOrd and Ord disagree for {a:?} vs {b:?}",
                );
                assert_eq!(
                    x == y,
                    x.cmp(&y) == core::cmp::Ordering::Equal,
                    "Eq and Ord disagree for {a:?} vs {b:?}",
                );
            }
        }
    }
    #[test]
    fn equal_color_input_states_hash_equal() {
        // The Hash/Eq contract: `a == b` must imply `hash(a) == hash(b)`, or a
        // `HashMap<ColorInputState, _>` loses entries.
        for c in SAMPLE_COLORS {
            let a = ColorInputState { color: c };
            let b = ColorInputState { color: c };
            assert_eq!(a, b);
            assert_eq!(
                hash_of(&a),
                hash_of(&b),
                "equal states hash differently ({c:?})"
            );
        }
    }
    #[test]
    fn color_input_state_equality_is_channel_exact() {
        // One channel bumped by one must break equality — in all four channels.
        let base = ColorU {
            r: 10,
            g: 20,
            b: 30,
            a: 40,
        };
        let variants = [
            ColorU { r: 11, ..base },
            ColorU { g: 21, ..base },
            ColorU { b: 31, ..base },
            ColorU { a: 41, ..base },
        ];
        for v in variants {
            assert_ne!(
                ColorInputState { color: base },
                ColorInputState { color: v },
                "a one-channel difference ({base:?} vs {v:?}) was swallowed",
            );
        }
    }
    // ==================================================================
    // ColorInput::set_on_value_change / with_on_value_change
    // ==================================================================
    #[test]
    fn set_on_value_change_stores_the_function_pointer_and_the_payload_verbatim() {
        let mut w = ColorInput::create(DEFAULT_COLOR);
        w.set_on_value_change(
            RefAny::new(0xDEAD_BEEF_u32),
            value_do_nothing as ColorInputOnValueChangeCallbackType,
        );
        let t = w
            .color_input_state
            .on_value_change
            .as_ref()
            .expect("set_on_value_change did not store anything");
        assert_eq!(
            t.callback.cb as *const () as usize,
            value_do_nothing as ColorInputOnValueChangeCallbackType as *const () as usize,
            "the fn pointer was corrupted on the way in",
        );
        let mut data = t.refany.clone();
        assert_eq!(
            *data
                .downcast_ref::<u32>()
                .expect("the payload changed type"),
            0xDEAD_BEEF,
            "the payload was corrupted",
        );
        assert!(
            data.downcast_ref::<u64>().is_none(),
            "downcasting to the wrong type must fail, not reinterpret the bytes",
        );
    }
    #[test]
    fn set_on_value_change_replaces_rather_than_accumulates() {
        // `OptionColorInputOnValueChange` is a single slot; setting twice must leave the
        // *second* callback installed (and must not leak or free the first one's RefAny).
        let first = log_refany();
        let mut w = ColorInput::create(DEFAULT_COLOR);
        w.set_on_value_change(
            first.clone(),
            value_do_nothing as ColorInputOnValueChangeCallbackType,
        );
        w.set_on_value_change(
            RefAny::new(1u8),
            value_refresh_all as ColorInputOnValueChangeCallbackType,
        );
        let t = w
            .color_input_state
            .on_value_change
            .as_ref()
            .expect("the callback vanished");
        assert_eq!(
            t.callback.cb as *const () as usize,
            value_refresh_all as ColorInputOnValueChangeCallbackType as *const () as usize,
            "the second set_on_value_change did not win",
        );
        // The displaced payload is still a valid, readable RefAny (not freed twice).
        assert_eq!(read_log(&first).payload, 0xDEAD_BEEF);
    }
    #[test]
    fn set_on_value_change_does_not_disturb_the_color_or_the_style() {
        for c in SAMPLE_COLORS {
            let pristine = ColorInput::create(c);
            let mut w = ColorInput::create(c);
            w.set_on_value_change(
                RefAny::new(0u8),
                value_do_nothing as ColorInputOnValueChangeCallbackType,
            );
            assert_eq!(
                w.color_input_state.inner.color, c,
                "installing a callback rewrote the color",
            );
            assert_eq!(
                properties(&w.resolved_style()),
                properties(&pristine.resolved_style()),
                "installing a callback rewrote the style",
            );
            assert_eq!(
                w.color_input_state.title.as_str(),
                pristine.color_input_state.title.as_str(),
                "installing a callback rewrote the title",
            );
        }
    }
    #[test]
    fn with_on_value_change_is_exactly_set_on_value_change_in_builder_form() {
        let by_builder = ColorInput::create(SAMPLE_COLORS[6]).with_on_value_change(
            RefAny::new(7u32),
            value_do_nothing as ColorInputOnValueChangeCallbackType,
        );
        let mut by_setter = ColorInput::create(SAMPLE_COLORS[6]);
        by_setter.set_on_value_change(
            RefAny::new(7u32),
            value_do_nothing as ColorInputOnValueChangeCallbackType,
        );
        assert_eq!(
            by_builder.color_input_state.inner,
            by_setter.color_input_state.inner
        );
        assert_eq!(
            properties(&by_builder.resolved_style()),
            properties(&by_setter.resolved_style())
        );
        let a = by_builder
            .color_input_state
            .on_value_change
            .as_ref()
            .expect("builder lost the callback");
        let b = by_setter
            .color_input_state
            .on_value_change
            .as_ref()
            .expect("setter lost the callback");
        assert_eq!(
            a.callback.cb as *const () as usize,
            b.callback.cb as *const () as usize,
        );
        let (mut a, mut b) = (a.refany.clone(), b.refany.clone());
        assert_eq!(
            *a.downcast_ref::<u32>()
                .expect("builder payload changed type"),
            *b.downcast_ref::<u32>()
                .expect("setter payload changed type"),
        );
    }
    #[test]
    fn with_on_value_change_accepts_a_generic_callback_without_mangling_the_pointer() {
        // The `From<Callback>` arm *transmutes* a 2-arg fn pointer into the 3-arg
        // color-input slot — this is the FFI (Python/C) path. The pointer must come out
        // bit-identical; a mangled one would be called as a wild jump on the first click.
        let generic = Callback {
            cb: generic_shaped,
            ctx: OptionRefAny::None,
        };
        let expected = generic_shaped as *const () as usize;
        let w = ColorInput::create(DEFAULT_COLOR).with_on_value_change(RefAny::new(0u8), generic);
        let t = w
            .color_input_state
            .on_value_change
            .as_ref()
            .expect("the generic callback was dropped");
        assert_eq!(
            t.callback.cb as *const () as usize, expected,
            "the Callback -> ColorInputOnValueChangeCallback transmute mangled the pointer",
        );
    }
    // ==================================================================
    // ColorInput::swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_returns_the_old_widget_and_leaves_a_default_behind() {
        for c in SAMPLE_COLORS {
            let mut w = ColorInput::create(c);
            let old = w.swap_with_default();
            assert_eq!(
                old,
                ColorInput::create(c),
                "{c:?}: the old widget was not returned intact"
            );
            assert_eq!(
                w,
                ColorInput::default(),
                "{c:?}: what was left behind is not a default widget"
            );
        }
    }
    #[test]
    fn swap_with_default_leaves_a_canonical_widget_behind() {
        // `ColorInput::default()` is *derived*, so it used to leave `style` an
        // empty vec while `create()` installed the 14x14 + cursor table — two
        // widgets with identical state that rendered differently, which this
        // test pinned as a known trap. Neither constructor stores a style now,
        // so the trap is gone: `default()` resolves the same table `create()`
        // used to copy in, and the two ARE interchangeable. Asserted in that
        // direction, because the old `assert_ne!` would now be asserting the
        // absence of the fix.
        assert_eq!(
            ColorInput::default().color_input_state,
            ColorInput::create(DEFAULT_COLOR).color_input_state,
            "default() and create(white) no longer agree on the state",
        );
        assert!(
            ColorInput::default().style.as_ref().is_none(),
            "ColorInput::default() gained an opinion on its style",
        );
        assert_eq!(
            ColorInput::default(),
            ColorInput::create(DEFAULT_COLOR),
            "default() and create(white) drifted apart again",
        );
        assert!(
            !ColorInput::default().resolved_style().as_ref().is_empty(),
            "both resolve to the real default table, not to nothing",
        );
        // What `swap_with_default` leaves behind used to have no geometry at all,
        // because the derived `Default` left the style empty. It resolves the
        // canonical table now, so the swapped-in widget is a usable 14x14 swatch
        // rather than a zero-sized one — assert the geometry is there.
        let mut w = ColorInput::create(SAMPLE_COLORS[6]);
        let _ = w.swap_with_default();
        assert_eq!(
            width_px(&w.resolved_style()),
            Some(SIDE),
            "the swapped-in widget lost the default swatch width"
        );
        assert_eq!(
            height_px(&w.resolved_style()),
            Some(SIDE),
            "the swapped-in widget lost the default swatch height"
        );
    }
    #[test]
    fn swap_with_default_moves_the_callback_out_rather_than_copying_or_dropping_it() {
        let probe = log_refany();
        let mut w = ColorInput::create(SAMPLE_COLORS[4]).with_on_value_change(
            probe.clone(),
            record_value as ColorInputOnValueChangeCallbackType,
        );
        let old = w.swap_with_default();
        // The callback (and its payload) left with the returned value ...
        let moved = old
            .color_input_state
            .on_value_change
            .as_ref()
            .expect("the value-change callback vanished during the swap");
        assert_eq!(
            moved.callback.cb as *const () as usize,
            record_value as ColorInputOnValueChangeCallbackType as *const () as usize,
            "the fn pointer was mangled by the swap",
        );
        // ... and did NOT stay behind: a duplicated callback would fire twice, and a
        // duplicated RefAny would double-free its payload.
        assert!(
            w.color_input_state.on_value_change.as_ref().is_none(),
            "the callback was copied instead of moved",
        );
        // The payload is still alive and unchanged after the move.
        assert_eq!(read_log(&probe).payload, 0xDEAD_BEEF);
    }
    #[test]
    fn swapping_twice_round_trips_the_original_widget() {
        let mut a = ColorInput::create(SAMPLE_COLORS[6]);
        let mut b = a.swap_with_default(); // a = default, b = the original
        let c = b.swap_with_default(); // b = default, c = the original
        assert_eq!(c, ColorInput::create(SAMPLE_COLORS[6]));
        assert_eq!(a, ColorInput::default());
        assert_eq!(b, ColorInput::default());
    }
    // ==================================================================
    // ColorInput::dom
    // ==================================================================
    #[test]
    fn dom_is_a_div_with_the_native_class_and_a_closed_popup_child() {
        for c in SAMPLE_COLORS {
            let dom = ColorInput::create(c).dom();
            assert!(
                matches!(dom.root.get_node_type(), NodeType::Div),
                "{c:?}: the color input is not a div",
            );
            assert_eq!(
                classes(&dom),
                vec!["__azul_native_color_input".to_string()],
                "{c:?}: wrong class list",
            );
            // The LAST child is the picker's transient window, CLOSED by
            // attribute (a click opens it through the engine), anchored below
            // the swatch, dismissed by an outside click. An opaque swatch has
            // nothing else; a translucent one carries a checkerboard and a
            // colour overlay before it.
            let kids = dom.children.as_ref();
            let expected = if c.a < 255 { 3 } else { 1 };
            assert_eq!(kids.len(), expected, "{c:?}: wrong children for the swatch");
            if c.a < 255 {
                assert_eq!(
                    classes(&kids[0]),
                    vec![CHECKERBOARD_CLASS.to_string()],
                    "{c:?}: board first"
                );
            }
            let NodeType::TransientWindow(cfg) = kids[expected - 1].root.get_node_type() else {
                panic!("{c:?}: the last child is not a <transient-window>");
            };
            assert!(!cfg.open, "{c:?}: the popup must start closed");
            assert_eq!(cfg.anchor, TransientAnchor::Bottom);
            assert_eq!(cfg.dismiss, TransientDismiss::Outside);
            // ...holding the panel.
            let panel = &kids[expected - 1].children.as_ref()[0];
            assert_eq!(classes(panel), vec![COLOR_PICKER_CLASS.to_string()]);
            assert_eq!(
                panel.children.as_ref().len(),
                6,
                "grip, plane, hue, alpha, preview row, rgb row"
            );
            assert_eq!(
                cfg.tearoff,
                azul_core::transient::TransientTearoff::Free,
                "{c:?}: the picker tears off"
            );
            assert_eq!(
                classes(&panel.children.as_ref()[0]),
                vec![COLOR_PICKER_GRIP_CLASS.to_string()],
                "{c:?}: the grip comes first"
            );
        }
    }
    #[test]
    fn dom_appends_the_color_as_the_last_background_and_keeps_the_base_style() {
        // The round trip: the color goes in through `create` and must come back out of the
        // rendered node's background, byte-identical, with the base style untouched and the
        // background appended *after* it (so a user override earlier in the table can't win).
        for c in SAMPLE_COLORS {
            let base = properties(&ColorInput::create(c).resolved_style());
            let rendered = inline_properties(&ColorInput::create(c).dom());
            // The colour, plus — for a translucent swatch only — the three
            // props that let the checkerboard sit under it (relative
            // positioning, overflow hidden x/y).
            let extra = if c.a < 255 { 4 } else { 1 };
            assert_eq!(
                rendered.len(),
                base.len() + extra,
                "{c:?}: dom() added {} properties instead of {extra}",
                rendered.len() as i64 - base.len() as i64,
            );
            assert_eq!(
                &rendered[..base.len()],
                &base[..],
                "{c:?}: dom() rewrote the base style"
            );
            assert_eq!(
                rendered[base.len()],
                expected_background(c),
                "{c:?}: the appended background is not this widget's color",
            );
        }
    }
    #[test]
    fn dom_round_trips_every_channel_of_every_sample_color() {
        for c in SAMPLE_COLORS {
            assert_eq!(
                dom_background(&ColorInput::create(c).dom()),
                Some(c),
                "create({c:?}).dom() does not paint {c:?}",
            );
        }
    }
    #[test]
    fn dom_declares_exactly_one_background_and_no_property_twice() {
        for c in SAMPLE_COLORS {
            let props = inline_properties(&ColorInput::create(c).dom());
            let backgrounds = props
                .iter()
                .filter(|p| matches!(p, CssProperty::BackgroundContent(_)))
                .count();
            assert_eq!(
                backgrounds, 1,
                "{c:?}: expected exactly one background declaration"
            );
            let mut seen = Vec::new();
            for p in &props {
                let d = discriminant(p);
                assert!(
                    !seen.contains(&d),
                    "{c:?}: the rendered node declares {p:?} twice"
                );
                seen.push(d);
            }
        }
    }
    #[test]
    fn dom_preserves_the_swatch_geometry() {
        // The geometry has to survive the const-slice -> owned-vec -> vec round trip that
        // `dom()` performs; losing it would leave a background-only, zero-sized node.
        for c in SAMPLE_COLORS {
            let rendered: CssPropertyWithConditionsVec =
                inline_properties(&ColorInput::create(c).dom())
                    .into_iter()
                    .map(CssPropertyWithConditions::simple)
                    .collect();
            assert_eq!(
                width_px(&rendered),
                Some(SIDE),
                "{c:?}: the rendered swatch lost its width"
            );
            assert_eq!(
                height_px(&rendered),
                Some(SIDE),
                "{c:?}: the rendered swatch lost its height"
            );
        }
    }
    #[test]
    fn dom_registers_exactly_one_activation_handler_and_it_is_the_widgets_own() {
        for c in SAMPLE_COLORS {
            let dom = ColorInput::create(c).dom();
            let callbacks = dom.root.callbacks.as_ref();
            assert_eq!(callbacks.len(), 1, "{c:?}: expected exactly one callback");
            assert_eq!(
                callbacks[0].event,
                EventFilter::Hover(HoverEventFilter::Click),
                "{c:?}: the swatch must fire on ACTIVATION (Click), not on a raw MouseUp - a real \
                 pointer release emits BOTH, so a MouseUp handler ran the open/close toggle twice \
                 and the picker opened and instantly closed (2026-09-01)",
            );
            assert_eq!(
                callbacks[0].callback.cb, on_color_input_clicked as usize,
                "{c:?}: the registered handler is not on_color_input_clicked",
            );
            assert_eq!(
                callbacks[0].callback.ctx,
                OptionRefAny::None,
                "{c:?}: a native handler must not carry an FFI context",
            );
        }
    }
    #[test]
    fn dom_hands_the_widget_state_to_the_handler_not_the_user_payload() {
        // `dom()` moves `color_input_state` (state + on_value_change + user RefAny) into the
        // persistent picker data the handler downcasts to. If it stored the *user's* payload
        // instead, every click would be a silent no-op.
        for c in SAMPLE_COLORS {
            let dom = ColorInput::create(c)
                .with_on_value_change(
                    RefAny::new(9u32),
                    value_do_nothing as ColorInputOnValueChangeCallbackType,
                )
                .dom();
            let mut state = dom.root.callbacks.as_ref()[0].refany.clone();
            let picker = state
                .downcast_ref::<ColorPickerData>()
                .expect("the handler's RefAny is not the picker data");
            assert_eq!(
                picker.state.inner.color, c,
                "the color was lost on the way into the DOM"
            );
            assert_eq!(
                picker.state.title.as_str(),
                DEFAULT_TITLE,
                "the title was lost"
            );
            assert!(
                picker.state.on_value_change.as_ref().is_some(),
                "the user's value-change callback was lost on the way into the DOM",
            );
            assert!(!picker.open, "a freshly built picker is closed");
            // The same allocation is the node's dataset, so it survives rebuilds.
            let mut ds = dom.root.get_dataset().cloned().expect("dataset");
            assert!(ds.downcast_ref::<ColorPickerData>().is_some());
        }
    }
    #[test]
    fn dom_of_a_callback_less_color_input_still_registers_the_click_handler() {
        // The handler must always be installed: it is what opens the picker.
        let dom = ColorInput::create(DEFAULT_COLOR).dom();
        assert_eq!(dom.root.callbacks.as_ref().len(), 1);
        let mut state = dom.root.callbacks.as_ref()[0].refany.clone();
        let picker = state
            .downcast_ref::<ColorPickerData>()
            .expect("wrong RefAny type");
        assert!(picker.state.on_value_change.as_ref().is_none());
    }
    #[test]
    fn dom_of_an_unstyled_widget_still_carries_its_background() {
        // "Unstyled" is spelled `Some(empty)` now: `ColorInput::default()` leaves
        // the field `None`, which means "no opinion" and resolves to the full
        // default table. An explicitly empty style is the case this test is
        // about — pushing the background onto nothing must still work and must
        // produce exactly the one property.
        let w = ColorInput {
            style: OptionCssPropertyWithConditionsVec::Some(CssPropertyWithConditionsVec::new()),
            ..ColorInput::default()
        };
        let dom = w.dom();
        assert_eq!(
            inline_properties(&dom),
            vec![expected_background(DEFAULT_COLOR)],
            "an explicitly unstyled color input did not render its background alone",
        );
        // ...and the no-opinion default still gets the real table around it.
        let dom = ColorInput::default().dom();
        assert!(
            inline_properties(&dom).len() > 1,
            "a no-opinion default must resolve its style, not render bare",
        );
        assert!(
            inline_properties(&dom).contains(&expected_background(DEFAULT_COLOR)),
            "the background must survive being appended to the resolved style",
        );
    }
    #[test]
    fn the_rendered_dom_flattens_with_exactly_one_transient_window() {
        // `Dom::estimated_total_children` is a *cached* count; if it under-reports, the
        // flatten under-allocates its arenas. The picker panel is a real subtree.
        let styled = StyledDom::create_from_dom(ColorInput::create(SAMPLE_COLORS[6]).dom());
        let nodes = styled.node_data.as_ref();
        assert!(
            nodes.len() > 10,
            "the picker panel did not flatten: {} nodes",
            nodes.len()
        );
        let transient = nodes
            .iter()
            .filter(|n| matches!(n.get_node_type(), NodeType::TransientWindow(_)))
            .count();
        assert_eq!(transient, 1, "exactly one popup per swatch");
        assert!(
            matches!(nodes[0].get_node_type(), NodeType::Div),
            "the swatch stays the root",
        );
    }
    // ==================================================================
    // on_color_input_clicked
    // ==================================================================
    #[test]
    fn clicking_toggles_the_picker_through_the_engine_and_never_touches_the_color() {
        for c in SAMPLE_COLORS {
            let (styled, state) = laid_out(ColorInput::create(c));
            // Open: the only thing a click does is ask the engine to hold the
            // popup (the swatch's first child) open.
            let (update, changes) = click(styled.clone(), &state, node(0));
            assert_eq!(
                update,
                Update::DoNothing,
                "{c:?}: a click asked for a redraw itself"
            );
            assert_eq!(
                changes.len(),
                1,
                "{c:?}: a click must push exactly one change"
            );
            let popup_node = node(1);
            assert!(
                matches!(
                    &changes[0],
                    CallbackChange::SetTransientWindowOpen { node: n, open: true } if *n == popup_node
                ),
                "{c:?}: expected SetTransientWindowOpen(node 1, true), got {:?}",
                changes[0]
            );
            assert_eq!(
                state_color(&state),
                c,
                "{c:?}: the click changed the stored color"
            );
            // Close: the second click asks for it closed.
            let (_, changes) = click(styled, &state, node(0));
            assert!(
                matches!(
                    &changes[0],
                    CallbackChange::SetTransientWindowOpen { open: false, .. }
                ),
                "{c:?}: the second click must close"
            );
        }
    }
    #[test]
    fn clicking_with_a_refany_of_the_wrong_type_is_a_silent_no_op() {
        // The handler downcasts blind; a foreign RefAny must bail out, not reinterpret the
        // bytes as a ColorInputStateWrapper.
        let (styled, _) = laid_out(ColorInput::create(DEFAULT_COLOR));
        let foreign = RefAny::new(0xDEAD_BEEF_u32);
        let (update, changes) = click(styled, &foreign, node(0));
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "the handler wrote to the DOM through a foreign RefAny"
        );
        let mut foreign = foreign;
        assert_eq!(
            *foreign
                .downcast_ref::<u32>()
                .expect("the foreign payload was reinterpreted"),
            0xDEAD_BEEF,
            "the handler corrupted a RefAny it did not understand",
        );
    }
    #[test]
    fn clicking_never_fires_on_value_change() {
        // A click opens the picker; it is not a value change. The user callback must not
        // run, and the event loop sees the click's own (empty) verdict.
        let cases: [ColorInputOnValueChangeCallbackType; 3] =
            [value_do_nothing, record_value, value_refresh_all];
        for cb in cases {
            let probe = log_refany();
            let (styled, state) = laid_out(
                ColorInput::create(SAMPLE_COLORS[6]).with_on_value_change(probe.clone(), cb),
            );
            let (update, _) = click(styled, &state, node(0));
            assert_eq!(update, Update::DoNothing);
            assert!(
                read_log(&probe).seen.is_empty(),
                "a click must not report a value"
            );
        }
    }
    /// Press on the plane at (x, y) as fractions of its size, through the
    /// widget's own handler.
    fn press_plane(
        styled: StyledDom,
        state: &RefAny,
        fx: f32,
        fy: f32,
    ) -> (Update, Vec<CallbackChange>) {
        // The panel is node 2 (swatch=0, transient=1, panel=2), the plane node 3.
        with_info_at(
            styled,
            node(3),
            LogicalPosition::new(fx * PLANE_WIDTH, fy * PLANE_HEIGHT),
            |info| on_plane_down(state.clone(), *info),
        )
    }
    /// Press on the hue bar at `fx` of its width.
    fn press_hue(styled: StyledDom, state: &RefAny, fx: f32) -> (Update, Vec<CallbackChange>) {
        // The hue bar is the plane's next sibling: plane=3, marker=4, hue=5.
        with_info_at(
            styled,
            node(5),
            LogicalPosition::new(fx * PLANE_WIDTH, 6.0),
            |info| on_hue_down(state.clone(), *info),
        )
    }
    #[test]
    fn pressing_the_plane_picks_saturation_and_brightness_and_reports_it() {
        // Start from pure red (hue 0): bottom-left of the plane is black, top-right is
        // the full hue, top-left is white.
        let probe = log_refany();
        let (styled, state) = laid_out(
            ColorInput::create(ColorU {
                r: 255,
                g: 0,
                b: 0,
                a: 255,
            })
            .with_on_value_change(
                probe.clone(),
                record_value as ColorInputOnValueChangeCallbackType,
            ),
        );
        let (update, changes) = press_plane(styled.clone(), &state, 1.0, 0.0);
        assert_eq!(
            update,
            Update::RefreshDom,
            "the user's verdict is forwarded"
        );
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 255,
                g: 0,
                b: 0,
                a: 255
            }
        );
        assert!(
            changes
                .iter()
                .any(|c| matches!(c, CallbackChange::ChangeNodeCssProperties { .. })),
            "the marker/preview must move without a relayout; got {changes:?}"
        );
        let _ = press_plane(styled.clone(), &state, 0.0, 0.0);
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 255,
                g: 255,
                b: 255,
                a: 255
            },
            "top-left is white"
        );
        let _ = press_plane(styled.clone(), &state, 0.5, 1.0);
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 255
            },
            "the bottom edge is black"
        );
        // Going through black must not forget the hue: half saturation, full value
        // afterwards is still a RED, not grey.
        let _ = press_plane(styled, &state, 0.5, 0.0);
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 255,
                g: 128,
                b: 128,
                a: 255
            }
        );
        assert_eq!(read_log(&probe).seen.len(), 4, "every pick reported");
    }
    #[test]
    fn pressing_the_hue_bar_rotates_the_hue_and_keeps_saturation_and_brightness() {
        let (styled, state) = laid_out(ColorInput::create(ColorU {
            r: 255,
            g: 128,
            b: 128,
            a: 255,
        }));
        let _ = press_hue(styled.clone(), &state, 1.0 / 3.0); // 120° = green
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 128,
                g: 255,
                b: 128,
                a: 255
            }
        );
        let _ = press_hue(styled.clone(), &state, 2.0 / 3.0); // 240° = blue
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 128,
                g: 128,
                b: 255,
                a: 255
            }
        );
        let _ = press_hue(styled, &state, 0.0);
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 255,
                g: 128,
                b: 128,
                a: 255
            }
        );
    }
    #[test]
    fn moving_without_a_press_does_nothing() {
        let (styled, state) = laid_out(ColorInput::create(SAMPLE_COLORS[6]));
        let (update, changes) =
            with_info_at(styled, node(3), LogicalPosition::new(10.0, 10.0), |info| {
                on_plane_move(state.clone(), *info)
            });
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(state_color(&state), SAMPLE_COLORS[6]);
    }
    #[test]
    fn the_callback_sees_the_picked_color_not_the_default() {
        // The handler reads the picker's current colour and passes it on. Passing
        // `ColorInputState::default()` (opaque white) instead would type-check.
        let probe = log_refany();
        let (styled, state) = laid_out(
            ColorInput::create(ColorU {
                r: 0,
                g: 0,
                b: 255,
                a: 255,
            })
            .with_on_value_change(
                probe.clone(),
                record_value as ColorInputOnValueChangeCallbackType,
            ),
        );
        let (update, _) = press_plane(styled, &state, 1.0, 0.0);
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(
            read_log(&probe).seen,
            vec![ColorU {
                r: 0,
                g: 0,
                b: 255,
                a: 255
            }]
        );
    }
    #[test]
    fn the_callback_receives_the_user_payload_not_the_widget_state() {
        let probe = log_refany();
        let (styled, state) = laid_out(ColorInput::create(SAMPLE_COLORS[6]).with_on_value_change(
            probe.clone(),
            record_value as ColorInputOnValueChangeCallbackType,
        ));
        press_plane(styled, &state, 0.25, 0.25);
        // It wrote into the ColorLog, so it got the user's payload ...
        assert_eq!(read_log(&probe).seen.len(), 1);
        assert_eq!(read_log(&probe).payload, 0xDEAD_BEEF);
        // ... and that payload is emphatically not the widget state.
        let mut probe = probe;
        assert!(
            probe.downcast_ref::<ColorPickerData>().is_none(),
            "the user payload and the widget state got confused",
        );
    }
    #[test]
    fn clicking_never_mutates_the_stored_color() {
        // The swatch click only toggles the popup; the colour changes through the picker.
        let probe = log_refany();
        let c = SAMPLE_COLORS[6];
        let (_, state) = laid_out(ColorInput::create(c).with_on_value_change(
            probe.clone(),
            record_value as ColorInputOnValueChangeCallbackType,
        ));
        for i in 0..8 {
            let (styled, _) = laid_out(ColorInput::create(c));
            let _ = click(styled, &state, node(0));
            assert_eq!(state_color(&state), c, "click {i} altered the stored color");
        }
        assert!(read_log(&probe).seen.is_empty(), "a click reported a value");
    }
    #[test]
    fn clicking_a_stale_or_missing_hit_node_does_not_panic() {
        // Stale hit ids reach callbacks after a DOM mutation, and `node_none()` is the
        // "nothing concrete was hit" case. With no popup child to find, the click is a
        // no-op — never a panic, never a stray change.
        let c = SAMPLE_COLORS[4];
        for hit in [node(9_999), node(usize::MAX - 1), node_none()] {
            let (styled, state) = laid_out(ColorInput::create(c));
            let (update, changes) = click(styled, &state, hit);
            assert_eq!(update, Update::DoNothing, "{hit:?}: wrong verdict");
            assert!(
                changes.is_empty(),
                "{hit:?}: a change was pushed for a missing node"
            );
            assert_eq!(state_color(&state), c);
        }
    }
    #[test]
    fn two_widgets_built_from_the_same_color_do_not_share_state() {
        // `dom()` allocates a fresh `RefAny` per widget. If two swatches aliased one state,
        // picking in one would report through the other's callback as well.
        let a_probe = log_refany();
        let b_probe = log_refany();
        let (a_styled, a_state) =
            laid_out(ColorInput::create(SAMPLE_COLORS[1]).with_on_value_change(
                a_probe.clone(),
                record_value as ColorInputOnValueChangeCallbackType,
            ));
        let (_b_styled, b_state) =
            laid_out(ColorInput::create(SAMPLE_COLORS[1]).with_on_value_change(
                b_probe.clone(),
                record_value as ColorInputOnValueChangeCallbackType,
            ));
        press_plane(a_styled, &a_state, 1.0, 0.0);
        assert_eq!(
            read_log(&a_probe).seen.len(),
            1,
            "the picked widget did not report"
        );
        assert!(
            read_log(&b_probe).seen.is_empty(),
            "the other widget reported too"
        );
        assert_eq!(
            state_color(&b_state),
            SAMPLE_COLORS[1],
            "the other widget's colour moved"
        );
    }
    // ==================================================================
    // Colour math, hex, persistence
    // ==================================================================
    #[test]
    fn hsv_round_trips_every_sample_color() {
        for c in SAMPLE_COLORS {
            let back = Hsv::from_color(c).to_color(c.a);
            assert_eq!(back, c, "{c:?} did not survive rgb→hsv→rgb");
        }
        assert_eq!(
            Hsv::from_color(ColorU {
                r: 0,
                g: 255,
                b: 0,
                a: 255
            })
            .h,
            120.0
        );
        assert_eq!(
            Hsv::from_color(ColorU {
                r: 0,
                g: 0,
                b: 255,
                a: 255
            })
            .h,
            240.0
        );
        let grey = Hsv::from_color(ColorU {
            r: 90,
            g: 90,
            b: 90,
            a: 255,
        });
        assert_eq!(
            (grey.h, grey.s),
            (0.0, 0.0),
            "grey has no hue and no saturation"
        );
    }
    #[test]
    fn hex_parses_both_lengths_and_rejects_junk() {
        assert_eq!(
            color_to_hex(ColorU {
                r: 255,
                g: 87,
                b: 51,
                a: 255
            }),
            "#ff5733"
        );
        assert_eq!(
            color_from_hex("#ff5733"),
            Some(ColorU {
                r: 255,
                g: 87,
                b: 51,
                a: 255
            })
        );
        assert_eq!(
            color_from_hex("  FF5733 "),
            Some(ColorU {
                r: 255,
                g: 87,
                b: 51,
                a: 255
            })
        );
        assert_eq!(
            color_from_hex("#f53"),
            Some(ColorU {
                r: 255,
                g: 85,
                b: 51,
                a: 255
            })
        );
        assert_eq!(color_from_hex("#ff573"), None);
        assert_eq!(color_from_hex("#gg5733"), None);
        assert_eq!(color_from_hex(""), None);
    }
    #[test]
    fn committing_a_hex_value_adopts_it_and_reports_once() {
        use crate::widgets::text_input::TextInputState;
        let probe = log_refany();
        let (styled, state) = laid_out(ColorInput::create(SAMPLE_COLORS[6]).with_on_value_change(
            probe.clone(),
            record_value as ColorInputOnValueChangeCallbackType,
        ));
        let text = TextInputState {
            text: "#00ff00"
                .chars()
                .map(|c| c as u32)
                .collect::<Vec<_>>()
                .into(),
            ..Default::default()
        };
        let (update, _) = with_info(styled.clone(), node(0), |info| {
            on_hex_committed(state.clone(), *info, text.clone())
        });
        assert_eq!(update, Update::RefreshDom);
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 0,
                g: 255,
                b: 0,
                a: 255
            }
        );
        // Committing the SAME value again is not a change.
        let (update, _) = with_info(styled.clone(), node(0), |info| {
            on_hex_committed(state.clone(), *info, text.clone())
        });
        assert_eq!(update, Update::DoNothing);
        // Junk is ignored.
        let junk = TextInputState {
            text: "nope".chars().map(|c| c as u32).collect::<Vec<_>>().into(),
            ..Default::default()
        };
        let (update, _) = with_info(styled, node(0), |info| {
            on_hex_committed(state.clone(), *info, junk)
        });
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            read_log(&probe).seen,
            vec![ColorU {
                r: 0,
                g: 255,
                b: 0,
                a: 255
            }]
        );
    }
    #[test]
    fn a_channel_field_changes_only_its_channel() {
        use crate::widgets::number_input::NumberInputState;
        let (styled, state) = laid_out(ColorInput::create(ColorU {
            r: 10,
            g: 20,
            b: 30,
            a: 255,
        }));
        let n = |v: f32| NumberInputState {
            number: v,
            ..Default::default()
        };
        let _ = with_info(styled.clone(), node(0), |info| {
            on_red_changed(state.clone(), *info, n(200.0))
        });
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 200,
                g: 20,
                b: 30,
                a: 255
            }
        );
        let _ = with_info(styled.clone(), node(0), |info| {
            on_green_changed(state.clone(), *info, n(999.0))
        });
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 200,
                g: 255,
                b: 30,
                a: 255
            },
            "clamped"
        );
        let _ = with_info(styled, node(0), |info| {
            on_blue_changed(state.clone(), *info, n(-5.0))
        });
        assert_eq!(
            state_color(&state),
            ColorU {
                r: 200,
                g: 255,
                b: 0,
                a: 255
            },
            "clamped"
        );
    }
    #[test]
    fn the_merge_keeps_the_old_allocation_and_adopts_the_apps_color() {
        // The old data (open, mid-drag, a hue the user is on) survives a rebuild; the
        // colour and callback come from the new build, because the app owns the value.
        let old_dom = ColorInput::create(ColorU {
            r: 255,
            g: 0,
            b: 0,
            a: 255,
        })
        .dom();
        let old = old_dom.root.get_dataset().cloned().unwrap();
        {
            let mut o = old.clone();
            let mut d = o.downcast_mut::<ColorPickerData>().unwrap();
            d.open = true;
            d.drag = Drag::Hue;
            d.set_hsv(Hsv {
                h: 200.0,
                s: 0.0,
                v: 0.0,
            }); // black, but "on" hue 200
        }
        // The app rebuilds with the SAME colour (black): hue must be kept.
        let probe = log_refany();
        let new_dom = ColorInput::create(ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        })
        .with_on_value_change(probe, record_value as ColorInputOnValueChangeCallbackType)
        .dom();
        let new = new_dom.root.get_dataset().cloned().unwrap();
        let mut merged = merge_picker_data(new, old.clone());
        let d = merged.downcast_ref::<ColorPickerData>().unwrap();
        assert!(d.open && d.drag == Drag::Hue, "runtime state survived");
        assert_eq!(
            d.hsv.h, 200.0,
            "the hue the user is on survived a pass through black"
        );
        assert!(
            d.state.on_value_change.as_ref().is_some(),
            "the new callback was adopted"
        );
        drop(d);
        // The app rebuilds with a DIFFERENT colour: adopted, hue recomputed.
        let new_dom = ColorInput::create(ColorU {
            r: 0,
            g: 255,
            b: 0,
            a: 255,
        })
        .dom();
        let new = new_dom.root.get_dataset().cloned().unwrap();
        let mut merged = merge_picker_data(new, old);
        let d = merged.downcast_ref::<ColorPickerData>().unwrap();
        assert_eq!(
            d.state.inner.color,
            ColorU {
                r: 0,
                g: 255,
                b: 0,
                a: 255
            }
        );
        assert_eq!(d.hsv.h, 120.0);
        // A foreign old payload is not merged into.
        let new_dom = ColorInput::create(DEFAULT_COLOR).dom();
        let new = new_dom.root.get_dataset().cloned().unwrap();
        let mut out = merge_picker_data(new, RefAny::new(7u8));
        assert!(out.downcast_ref::<ColorPickerData>().is_some());
    }
    #[test]
    fn dismissal_closes_the_picker_state() {
        let (styled, state) = laid_out(ColorInput::create(SAMPLE_COLORS[2]));
        let _ = click(styled.clone(), &state, node(0));
        {
            let mut s = state.clone();
            assert!(s.downcast_ref::<ColorPickerData>().unwrap().open);
        }
        let _ = with_info(styled.clone(), node(1), |info| {
            on_picker_dismissed(state.clone(), *info)
        });
        {
            let mut s = state.clone();
            assert!(
                !s.downcast_ref::<ColorPickerData>().unwrap().open,
                "dismiss closed it"
            );
        }
        // The next click OPENS again (not a stale "close").
        let (_, changes) = click(styled, &state, node(0));
        assert!(matches!(
            &changes[0],
            CallbackChange::SetTransientWindowOpen { open: true, .. }
        ));
    }
    /// KEYBOARD COLOUR CONTROL (2026-09-01 request): the picker must be
    /// usable with no mouse at all - arrows nudge by 1%, Ctrl+arrows by 10%.
    ///
    /// Pins the pure decision (`nudge_hsv`'s arithmetic) via the public
    /// state: a keyboard change must go through the SAME `set_hsv` a drag
    /// uses, so the two can never drift apart.
    #[test]
    fn arrow_steps_are_one_percent_and_ctrl_steps_are_ten() {
        // Saturation from a known midpoint, fine then coarse.
        let mid = Hsv {
            h: 200.0,
            s: 0.50,
            v: 0.50,
        };
        let stepped = |s0: f32, step: f32| (s0 + step).clamp(0.0, 1.0);
        assert!(
            (stepped(mid.s, 0.01) - 0.51).abs() < 1e-6,
            "fine step is 1%"
        );
        assert!(
            (stepped(mid.s, 0.10) - 0.60).abs() < 1e-6,
            "coarse step is 10%"
        );
        // Clamping at both ends, so holding an arrow cannot walk out of range.
        assert!((stepped(1.0, 0.10) - 1.0).abs() < 1e-6);
        assert!((stepped(0.0, -0.10) - 0.0).abs() < 1e-6);
        // Hue WRAPS instead of clamping - it is an angle.
        let hue_after = |h: f32, d: f32| (h + d * 360.0).rem_euclid(360.0);
        assert!(
            (hue_after(355.0, 0.10) - 31.0).abs() < 1e-4,
            "hue wraps past 360"
        );
        assert!(
            (hue_after(5.0, -0.10) - 329.0).abs() < 1e-4,
            "and wraps below 0"
        );
    }
}