1
//! Built-in widgets for the Azul GUI system
2

            
3
/// Implements `Display, Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Hash`
4
/// for a Callback with a `.cb` field.
5
///
6
/// This is necessary to work around for <https://github.com/rust-lang/rust/issues/54508>
7
///
8
/// # Host-invoker plumbing for managed-FFI bindings
9
///
10
/// Widget callbacks have varying shapes — some are
11
/// `(RefAny, CallbackInfo) -> Update` (Button), others add a state
12
/// struct (CheckBox/Tab/etc.), a few have two extras (`ListView`). The
13
/// macro therefore does **not** auto-emit an `impl_managed_callback!`
14
/// invocation; per-widget files apply it themselves with the right
15
/// extras list. The base invocation still produces the standard
16
/// `Display`/`Debug`/`Clone`/`From<CallbackType>`/`From<Callback>` impls
17
/// that all widget callbacks share.
18
#[macro_export]
19
macro_rules! impl_widget_callback {
20
    (
21
        $callback_wrapper:ident,
22
        $option_callback_wrapper:ident,
23
        $callback_value:ident,
24
        $callback_ty:ident
25
    ) => {
26
        #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
27
        #[repr(C)]
28
        pub struct $callback_wrapper {
29
            pub refany: RefAny,
30
            pub callback: $callback_value,
31
        }
32

            
33
        #[repr(C)]
34
        pub struct $callback_value {
35
            pub cb: $callback_ty,
36
            /// For FFI: stores the foreign callable (e.g., `PyFunction`)
37
            /// Native Rust code sets this to None
38
            pub ctx: azul_core::refany::OptionRefAny,
39
        }
40

            
41
        azul_css::impl_option!(
42
            $callback_wrapper,
43
            $option_callback_wrapper,
44
            copy = false,
45
            [Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash]
46
        );
47

            
48
        impl $callback_value {
49
            /// Create a new callback with just a function pointer (for native Rust code)
50
            pub fn create<I: Into<$callback_value>>(cb: I) -> $callback_value {
51
                cb.into()
52
            }
53
        }
54

            
55
        impl ::core::fmt::Display for $callback_value {
56
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
57
                write!(f, "{:?}", self)
58
            }
59
        }
60

            
61
        impl ::core::fmt::Debug for $callback_value {
62
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
63
                let callback = stringify!($callback_value);
64
                write!(f, "{} @ 0x{:x}", callback, self.cb as *const () as usize)
65
            }
66
        }
67

            
68
        impl Clone for $callback_value {
69
5949
            fn clone(&self) -> Self {
70
5949
                $callback_value {
71
5949
                    cb: self.cb.clone(),
72
5949
                    ctx: self.ctx.clone(),
73
5949
                }
74
5949
            }
75
        }
76

            
77
        impl core::hash::Hash for $callback_value {
78
            fn hash<H>(&self, state: &mut H)
79
            where
80
                H: ::core::hash::Hasher,
81
            {
82
                state.write_usize(self.cb as *const () as usize);
83
            }
84
        }
85

            
86
        impl PartialEq for $callback_value {
87
44
            fn eq(&self, rhs: &Self) -> bool {
88
44
                self.cb as *const () as usize == rhs.cb as usize
89
44
            }
90
        }
91

            
92
        impl PartialOrd for $callback_value {
93
            fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
94
                // Defer to Ord below: the two bodies were identical, and one
95
                // copy per widget callback type is 55 chances to diverge.
96
                Some(self.cmp(other))
97
            }
98
        }
99

            
100
        impl Ord for $callback_value {
101
            fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
102
                (self.cb as *const () as usize).cmp(&(other.cb as usize))
103
            }
104
        }
105

            
106
        impl Eq for $callback_value {}
107

            
108
        /// Allow creating callback from a raw function pointer
109
        /// Sets callable to None (for native Rust/C usage)
110
        impl From<$callback_ty> for $callback_value {
111
2197
            fn from(cb: $callback_ty) -> $callback_value {
112
2197
                $callback_value {
113
2197
                    cb,
114
2197
                    ctx: azul_core::refany::OptionRefAny::None,
115
2197
                }
116
2197
            }
117
        }
118

            
119
        /// Allow creating widget callback from a generic Callback
120
        /// This enables Python/FFI code to pass generic callbacks to widget methods
121
        impl From<$crate::callbacks::Callback> for $callback_value {
122
            // transmute target ($callback_value's cb fn-ptr type) varies per macro
123
            // instantiation, so an explicit annotation can't be written generically here.
124
            #[allow(clippy::missing_transmute_annotations, clippy::useless_transmute)]
125
13
            fn from(cb: $crate::callbacks::Callback) -> $callback_value {
126
13
                $callback_value {
127
13
                    cb: unsafe { core::mem::transmute(cb.cb) },
128
13
                    ctx: cb.ctx,
129
13
                }
130
13
            }
131
        }
132
    };
133
}
134

            
135
/// Accordion / expander widget.
136
///
137
/// One or more collapsible titled sections; see `accordion.rs`.
138
pub mod accordion;
139
/// Alert / banner widget.
140
///
141
/// A coloured inline message box with an optional dismissible close button; see `alert.rs`.
142
pub mod alert;
143
/// Avatar widget.
144
///
145
/// A circular image/initials badge (stateless); see `avatar.rs`.
146
pub mod avatar;
147
/// Office-style backstage view (the full-window "FILE" screen): accent nav
148
/// column + back ring + app-provided pane content. the Office-2013-era look look by default;
149
/// pairs with the ribbon's `RibbonAppButton`. See `backstage.rs`.
150
pub mod backstage;
151
/// Badge widget.
152
///
153
/// A small rounded count/status pill (stateless); see `badge.rs`.
154
pub mod badge;
155
/// Breadcrumb widget.
156
///
157
/// A horizontal trail of clickable crumb links separated by "/", ending in the current
158
/// (non-clickable) page; see `breadcrumb.rs`.
159
pub mod breadcrumb;
160
/// Button widget
161
pub mod button;
162
/// Camera-preview widget (P6) — a "dumb widget" owning a background capture
163
/// thread + a GL-texture ImageRef; no camera logic in core.
164
///
165
/// Same RefAny-
166
/// dataset + merge-callback design as the map widget. See `camera.rs`.
167
pub mod camera;
168
/// Shared core for the video-ish widgets (camera/screencap/video): the
169
/// `VideoFrame` type + the GL-texture `present_frame` writeback.
170
///
171
/// See
172
/// `capture_common.rs`.
173
pub mod capture_common;
174
/// Card container widget.
175
///
176
/// Elevated/bordered content box (no title); see `card.rs`.
177
pub mod card;
178
/// Checkbox widget
179
pub mod check_box;
180
/// Chip / tag widget.
181
///
182
/// A compact rounded pill with a label + optional removable "x" (stateful when removable, mirrors
183
/// alert's dismiss); see `chip.rs`.
184
pub mod chip;
185
/// Box displaying a color with a callback for value changes
186
pub mod color_input;
187
/// Combobox widget.
188
///
189
/// An editable text field with a click-toggled drop-down list of options (drop_down's select +
190
/// text_input's editable field); see `combobox.rs`.
191
pub mod combobox;
192
/// Calendar date picker widget.
193
///
194
/// A month header (‹ / `Month YYYY` / ›) above a weekday-labelled 7-column day grid computed from
195
/// real calendar math; clicking a day selects + restyles it (segmented-style), and the per-cell day
196
/// number is carried drop_down-style. Month nav fires on_change but cannot rebuild the grid
197
/// in-widget (prominent module TODO2); see `date_picker.rs`.
198
pub mod date_picker;
199
/// Divider / separator rule widget (horizontal or vertical).
200
///
201
/// See `divider.rs`.
202
pub mod divider;
203
/// Drop-down select widget
204
pub mod drop_down;
205
/// File input widget
206
pub mod file_input;
207
/// Frame container widget
208
pub mod frame;
209
/// Label widget (centered text)
210
pub mod label;
211
/// List view widget
212
pub mod list_view;
213
/// Map widget — MVT tile + MapCSS → SVG → DOM (AzulMaps goal app, P3).
214
///
215
/// Cache lives in a dataset RefAny owned by a merge callback so it
216
/// survives relayout. See `layout/src/widgets/map.rs` for the design.
217
pub mod map;
218
/// Built-in map themes (vendored `MapCSS` palettes, see the file header for licences).
219
pub mod map_themes;
220
/// Software menu-bar widget (Linux fallback when there is no native global menu).
221
///
222
/// Renders a window's `Menu` as a horizontal bar; items open dropdowns via the
223
/// unified `WindowPosition::RelativeToParentWindow` popup path.
224
pub mod menubar;
225
/// Microphone-capture widget (P7) — same "dumb widget" architecture as the
226
/// capture widgets, audio instead of video (no GL): a background thread feeds
227
/// each `AudioFrame` to the user's `on_frame` hook.
228
///
229
/// See `microphone.rs`.
230
pub mod microphone;
231
/// Modal / dialog widget.
232
///
233
/// An in-app overlay dialog (backdrop + centred panel + arbitrary content), shown/hidden via state
234
/// toggle; see `modal.rs`.
235
pub mod modal;
236
/// Node graph widget
237
pub mod node_graph;
238
/// Same as text input, but only allows numeric input
239
pub mod number_input;
240
/// Pagination widget.
241
///
242
/// A `Prev` / page-numbers / `Next` page navigator with an active-page restyle (segmented-style);
243
/// see `pagination.rs`.
244
pub mod pagination;
245
/// Popover widget.
246
///
247
/// A click-triggered floating panel holding arbitrary content, anchored to a `Dom` (the
248
/// click-toggled sibling of tooltip); see `popover.rs`.
249
pub mod popover;
250
/// Progress bar widget
251
pub mod progressbar;
252
/// Office-style title band with a Quick Access Toolbar (save/undo/redo),
253
/// centered title and window buttons, drawn as DOM. the Office-2013-era look look by
254
/// default; use `titlebar` instead for native-caption windows. See
255
/// `quick_access.rs`.
256
pub mod quick_access;
257
/// Radio-group widget.
258
///
259
/// Vertical/horizontal group of mutually-exclusive options (exactly one selected) with a circular
260
/// indicator; see `radio_group.rs`.
261
pub mod radio_group;
262
/// Ribbon widget
263
pub mod ribbon;
264
/// Screen-capture widget (P6) — identical "dumb widget" architecture to the
265
/// camera widget, capturing a display/window instead.
266
///
267
/// See `screencap.rs`.
268
pub mod screencap;
269
/// Segmented control widget.
270
///
271
/// Joined row of mutually-exclusive buttons; see `segmented.rs`.
272
pub mod segmented;
273
/// Slider / range widget.
274
///
275
/// Draggable thumb on a track → numeric value; see `slider.rs`.
276
pub mod slider;
277
/// Spinner / activity widget.
278
///
279
/// A static indeterminate busy ring (stateless; no animation — see the file's PARTIAL/TODO2 note);
280
/// see `spinner.rs`.
281
pub mod spinner;
282
/// Split-pane / splitter widget.
283
///
284
/// A two-pane (horizontal/vertical) container with a draggable divider that live-resizes the panes
285
/// via `set_css_property` (the frame two-box layout + the map/slider pointer-drag state machine);
286
/// see `split_pane.rs`.
287
pub mod split_pane;
288
/// Office-style status bar: left text segments, view switcher, zoom cluster
289
/// (embeds the `slider` widget). the Office-2013-era look look by default. See `statusbar.rs`.
290
pub mod statusbar;
291
/// Stepper / wizard widget.
292
///
293
/// A horizontal numbered-step progress indicator with connector lines and an accent/muted restyle
294
/// on step change (segmented-style + progressbar-style filled connector); see `stepper.rs`.
295
pub mod stepper;
296
/// Switch / toggle widget.
297
///
298
/// Boolean on/off with a sliding knob; see `switch.rs`.
299
pub mod switch;
300
/// Tab container widgets
301
pub mod tabs;
302
/// Multi-line text input (text area) widget.
303
///
304
/// See `text_area.rs`.
305
pub mod text_area;
306
/// Single line text input widget
307
pub mod text_input;
308
/// Time picker widget.
309
///
310
/// Two clamped numeric up/down spinners (hour + minute) side by side with an optional AM/PM toggle
311
/// for 12-hour mode (the number_input clamp/retext path + segmented's clickable-cell navigation);
312
/// see `time_picker.rs`.
313
pub mod time_picker;
314
/// Titlebar widget for custom window chrome
315
pub mod titlebar;
316
/// Toast / snackbar widget.
317
///
318
/// A transient floating notification banner pinned to a corner, manually dismissed via "x"
319
/// (auto-timeout needs a host timer — see the file's TODO2); a near-clone of `alert.rs` positioned
320
/// as an overlay; see `toast.rs`.
321
pub mod toast;
322
/// Tooltip widget.
323
///
324
/// Shows a small text popup near an anchor on hover; see `tooltip.rs`.
325
pub mod tooltip;
326
/// Tree view widget
327
pub mod tree_view;
328
/// Video-playback widget (P6) — same "dumb widget" architecture, decoding a
329
/// video source (vk-video) into a GL texture.
330
///
331
/// See `video.rs`.
332
pub mod video;
333
// /// Spreadsheet (virtualized view) widget
334
// pub mod spreadsheet;
335

            
336
/// Every shipped widget's `dom()` with reasonable defaults, for lints that
337
/// must hold across the whole widget set (the label-convention test below and
338
/// `dom_lint`'s runtime-warning twin). Test-only.
339
#[cfg(test)]
340
1
pub(crate) fn all_widget_doms_for_lint() -> Vec<(&'static str, azul_core::dom::Dom)> {
341
1
    label_convention::every_widget_dom()
342
1
}
343

            
344
/// Reading a rendered node's inline style apart from the theme's contribution.
345
///
346
/// A widget resolves its own style; the theme module then appends the
347
/// declarations only it can write — the dark twin of a colour, the hover and
348
/// pressed faces — on top of that. So a test that compares a rendered node
349
/// against the widget's own style cannot use raw equality: it has to say which
350
/// half it is looking at. These two helpers are that distinction, shared so
351
/// each widget's suite does not grow its own copy of the predicate.
352
#[cfg(test)]
353
pub(crate) mod theme_probe {
354
    use azul_core::dom::Dom;
355
    use azul_css::{
356
        dynamic_selector::{DynamicSelector, DynamicSelectorVec, ThemeCondition},
357
        props::property::CssProperty,
358
    };
359

            
360
    /// True if a declaration is gated on a theme, i.e. it is one half of a
361
    /// light/dark pair rather than something that applies in every mode.
362
88
    fn is_theme_gated(conditions: &DynamicSelectorVec) -> bool {
363
88
        conditions
364
88
            .as_ref()
365
88
            .iter()
366
88
            .any(|c| matches!(c, DynamicSelector::Theme(_)))
367
88
    }
368

            
369
    /// The node's inline declarations that apply in EVERY theme, in declaration
370
    /// order — what the widget itself resolved, with the theme's mode-specific
371
    /// additions left out. Pair it with [`dark`] so skipping them here cannot
372
    /// hide a theme that forgot its dark half.
373
7
    pub(crate) fn unthemed(dom: &Dom) -> Vec<CssProperty> {
374
7
        dom.root
375
7
            .style
376
7
            .iter_inline_properties()
377
88
            .filter(|(_, c)| !is_theme_gated(c))
378
82
            .map(|(p, _)| p.clone())
379
7
            .collect()
380
7
    }
381

            
382
    /// The node's inline declarations that apply in EVERY state and theme, in
383
    /// declaration order — the widget's resting style.
384
    ///
385
    /// Distinct from [`unthemed`], which keeps `:hover`-style rules and drops only
386
    /// the theme-gated ones. Phase 2 of the widget theme migration moves hover,
387
    /// pressed and focus rules into the theme modules, so a rendered node now
388
    /// carries conditional declarations the widget itself never declared; a test
389
    /// comparing "what landed on this node" against a widget's style wants this.
390
20
    pub(crate) fn unconditional(dom: &Dom) -> Vec<CssProperty> {
391
20
        dom.root
392
20
            .style
393
20
            .iter_inline_properties()
394
481
            .filter(|(_, c)| c.as_ref().is_empty())
395
340
            .map(|(p, _)| p.clone())
396
20
            .collect()
397
20
    }
398

            
399
    /// The node's inline declarations that apply only in dark mode.
400
25
    pub(crate) fn dark(dom: &Dom) -> Vec<CssProperty> {
401
25
        dom.root
402
25
            .style
403
25
            .iter_inline_properties()
404
666
            .filter(|(_, c)| {
405
666
                c.as_ref()
406
666
                    .iter()
407
666
                    .any(|s| matches!(s, DynamicSelector::Theme(ThemeCondition::Dark)))
408
666
            })
409
159
            .map(|(p, _)| p.clone())
410
25
            .collect()
411
25
    }
412
}
413

            
414
// ---------------------------------------------------------------------------
415
// Widget-owned text carriers
416
// ---------------------------------------------------------------------------
417
//
418
// The label convention (see `label_convention` below) puts every widget's own
419
// text — a label, a value, a placeholder, a `×` glyph — inside a `<p>`, because
420
// a bare text node is box-less. But the UA stylesheet gives every `<p>`
421
// `margin: 1em 0`, which is right for a paragraph of prose and wrong for a
422
// control's text: it is what made a NumberInput holding "42" 39 px tall
423
// against a 26 px empty TextInput, pushed the TextArea placeholder 13 px down,
424
// and grew hello-world's counter by two font-sizes (demo test, 2026-08-21).
425
//
426
// The reset cannot live in the per-site inline props: `with_css_props`
427
// REPLACES a node's inline style, and half the call sites apply their style
428
// after constructing the `<p>`. It lives on the `<p>`'s own component sheet
429
// instead (`Dom::css`), which `with_css_props` never touches, at AUTHOR
430
// priority — above the UA default, below an explicit inline margin, so a
431
// widget that deliberately sets one still wins. It is scoped to the `<p>`
432
// itself (`*` over a `<p>` whose only child is text), NOT to the widget's
433
// subtree: a container widget's user content must keep its paragraph margins.
434
//
435
// `widget_text_carriers_do_not_inherit_the_ua_paragraph_margin` below fails
436
// for any widget `<p>` built without these helpers.
437

            
438
/// The component sheet [`widget_p`] attaches: `margin-top: 0; margin-bottom: 0`
439
/// at AUTHOR priority on a `*` path.
440
91902
pub(crate) fn widget_p_margin_reset() -> azul_css::css::Css {
441
    use azul_css::{
442
        css::{rule_priority, Css, CssDeclaration, CssPath, CssPathSelector, CssRuleBlock},
443
        props::{
444
            layout::{LayoutMarginBottom, LayoutMarginTop},
445
            property::CssProperty,
446
        },
447
    };
448
91902
    Css {
449
91902
        rules: vec![CssRuleBlock {
450
91902
            path: CssPath {
451
91902
                selectors: vec![CssPathSelector::Global].into(),
452
91902
            },
453
91902
            declarations: vec![
454
91902
                CssDeclaration::Static(CssProperty::const_margin_top(LayoutMarginTop::const_px(0))),
455
91902
                CssDeclaration::Static(CssProperty::const_margin_bottom(
456
91902
                    LayoutMarginBottom::const_px(0),
457
91902
                )),
458
91902
            ]
459
91902
            .into(),
460
91902
            conditions: Vec::new().into(),
461
91902
            priority: rule_priority::AUTHOR,
462
91902
        }]
463
91902
        .into(),
464
91902
        ..Css::default()
465
91902
    }
466
91902
}
467

            
468
/// A `<p>` that carries a widget's OWN text (not a paragraph of the app's
469
/// prose): `Dom::create_p()` with the UA paragraph margin reset attached as
470
/// the node's component sheet. Set the rest of the style as usual —
471
/// `with_css_props` replaces the inline style and leaves the sheet alone.
472
#[must_use]
473
91902
pub(crate) fn widget_p() -> azul_core::dom::Dom {
474
91902
    azul_core::dom::Dom::create_p().with_component_css(widget_p_margin_reset())
475
91902
}
476

            
477
/// [`widget_p`] with a text child — the widget-owned twin of
478
/// `Dom::create_p_with_text`.
479
#[must_use]
480
60978
pub(crate) fn widget_p_with_text<S: Into<azul_css::AzString>>(text: S) -> azul_core::dom::Dom {
481
60978
    widget_p()
482
60978
        .with_child(azul_core::dom::Dom::create_text_do_not_use_without_block_level_wrapper(text))
483
60978
}
484

            
485
/// A widget telling its caller that only THEY can supply the missing piece.
486
///
487
/// Two warnings exist for accessibility and they are deliberately different:
488
///
489
/// * **This one, from the widget.** A widget knows its own type and its own builder API, so it can
490
///   name the exact call — "Slider has no accessible name; use `.with_accessibility_name(..)`". It
491
///   fires at BUILD time, from inside the widget, and it can be specific in a way nothing
492
///   downstream can.
493
/// * **`dom_lint::warn_a11y_shape`, from the framework.** That one sees only nodes, long after any
494
///   widget has finished, and speaks in terms of the DOM: "node 40 has role Slider and no value".
495
///   It catches hand-built DOMs and third-party widgets the engine has never heard of.
496
///
497
/// Neither subsumes the other. The widget's warning is actionable and narrow;
498
/// the framework's is universal and structural.
499
///
500
/// Silent when the widget got a name, and suppressible with
501
/// `AZ_SUPPRESS=a11y_widget` (or `AZ_SUPPRESS=all`).
502
#[cfg(feature = "std")]
503
652
pub fn warn_widget_needs_a_name(widget_type: &str, has_name: bool) {
504
652
    if has_name || crate::dom_lint::lint_suppressed("a11y_widget") {
505
        return;
506
652
    }
507
652
    azul_core::diagnostics::emit(alloc::format!(
508
652
        "[azul][a11y-widget] {widget_type} was built without an accessible name. It has no text \
509
652
         of its own to derive one from, so a screen reader announces its ROLE and nothing else. \
510
652
         Only the caller knows what this control is called — add it at the call site with \
511
652
         `.with_accessibility_name(\"…\")`, which MERGES and leaves the {widget_type}'s own role, \
512
652
         value and state intact, or point at an existing label with \
513
652
         `.with_accessibility_labelled_by(node)`. (suppress with AZ_SUPPRESS=a11y_widget)"
514
    ));
515
652
}
516

            
517
#[cfg(not(feature = "std"))]
518
pub fn warn_widget_needs_a_name(_widget_type: &str, _has_name: bool) {}
519

            
520
#[allow(clippy::too_many_lines)]
521
#[cfg(test)]
522
mod ua_paragraph_margin {
523
    //! Workspace-level guard for the bug class "a widget's text carrier inherits
524
    //! the UA paragraph margin" (demo test 2026-08-21: NumberInput 26 → 39 px,
525
    //! TextArea placeholder 13 px low, hello-world's counter two font-sizes
526
    //! tall). Every `<p>` a widget emits must either go through
527
    //! `widgets::widget_p` / `widget_p_with_text` (the reset rides on the
528
    //! node's own component sheet) or set both margins inline itself.
529
    //!
530
    //! Scoped to widget-OWNED `<p>`s by construction: `every_widget_dom` builds
531
    //! the widgets with their default content, so a `<p>` the walk finds is one
532
    //! the widget created. User prose placed inside a container widget keeps
533
    //! its margins — that is the reason the reset is per node, not per subtree.
534

            
535
    use azul_core::dom::{Dom, NodeType};
536
    use azul_css::{
537
        css::{CssDeclaration, CssPathSelector},
538
        props::property::CssPropertyType,
539
    };
540

            
541
263
    fn inline_sets(node: &Dom, ty: CssPropertyType) -> bool {
542
263
        node.root
543
263
            .style
544
263
            .iter_inline_properties()
545
2543
            .any(|(p, _)| p.get_type() == ty)
546
263
    }
547

            
548
    /// The node's OWN component sheet (attached to this `Dom`, `*` path)
549
    /// declares `ty`.
550
262
    fn own_sheet_sets(node: &Dom, ty: CssPropertyType) -> bool {
551
262
        node.css.as_ref().iter().any(|sheet| {
552
262
            sheet.rules.as_ref().iter().any(|rule| {
553
262
                let global = matches!(
554
262
                    rule.path.selectors.as_ref().first(),
555
                    None | Some(CssPathSelector::Global)
556
                );
557
262
                global
558
394
                    && rule.declarations.as_ref().iter().any(|d| match d {
559
394
                        CssDeclaration::Static(p) => p.get_type() == ty,
560
                        CssDeclaration::Dynamic(_) => false,
561
394
                    })
562
262
            })
563
262
        })
564
262
    }
565

            
566
584
    fn walk(node: &Dom, widget: &str, path: &str, bad: &mut Vec<String>) {
567
584
        if matches!(node.root.get_node_type(), NodeType::P) {
568
131
            let top = inline_sets(node, CssPropertyType::MarginTop)
569
129
                || own_sheet_sets(node, CssPropertyType::MarginTop);
570
131
            let bottom = inline_sets(node, CssPropertyType::MarginBottom)
571
131
                || own_sheet_sets(node, CssPropertyType::MarginBottom);
572
131
            if !(top && bottom) {
573
                let text = node
574
                    .children
575
                    .as_ref()
576
                    .first()
577
                    .and_then(|c| match c.root.get_node_type() {
578
                        NodeType::Text(t) => Some(t.as_ref().as_str().to_string()),
579
                        _ => None,
580
                    })
581
                    .unwrap_or_default();
582
                bad.push(format!(
583
                    "{widget}: <p> at {path} ({text:?}) inherits the UA `margin: 1em 0` — build \
584
                     it with widgets::widget_p_with_text / widget_p, or set margin-top AND \
585
                     margin-bottom inline"
586
                ));
587
131
            }
588
453
        }
589
584
        for (i, child) in node.children.as_ref().iter().enumerate() {
590
538
            walk(child, widget, &format!("{path}/{i}"), bad);
591
538
        }
592
584
    }
593

            
594
    #[test]
595
1
    fn widget_text_carriers_do_not_inherit_the_ua_paragraph_margin() {
596
1
        let mut bad = Vec::new();
597
46
        for (widget, dom) in super::label_convention::every_widget_dom() {
598
46
            walk(&dom, widget, "root", &mut bad);
599
46
        }
600
1
        assert!(
601
1
            bad.is_empty(),
602
            "{} widget <p> node(s) inherit the UA paragraph margin:\n  {}",
603
            bad.len(),
604
            bad.join("\n  ")
605
        );
606
1
    }
607

            
608
    /// The helper's own contract: the reset is on the node's sheet (so a later
609
    /// `with_css_props` cannot wipe it), at AUTHOR priority (so an explicit
610
    /// inline margin still wins), and the node is still a `<p>` with its text.
611
    #[test]
612
1
    fn widget_p_carries_the_reset_on_its_own_sheet_and_survives_with_css_props() {
613
        use azul_css::{
614
            css::rule_priority,
615
            dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
616
            props::{basic::StyleFontSize, property::CssProperty},
617
        };
618
1
        let p = super::widget_p_with_text("label").with_css_props(
619
1
            CssPropertyWithConditionsVec::from_vec(vec![CssPropertyWithConditions::simple(
620
1
                CssProperty::const_font_size(StyleFontSize::const_px(12)),
621
            )]),
622
        );
623
1
        assert!(matches!(p.root.get_node_type(), NodeType::P));
624
1
        assert_eq!(p.children.as_ref().len(), 1);
625
1
        assert!(own_sheet_sets(&p, CssPropertyType::MarginTop));
626
1
        assert!(own_sheet_sets(&p, CssPropertyType::MarginBottom));
627
1
        assert!(
628
1
            !inline_sets(&p, CssPropertyType::MarginTop),
629
            "the reset must not live in the inline style `with_css_props` replaces"
630
        );
631
1
        let sheet = &p.css.as_ref()[0];
632
1
        assert_eq!(sheet.rules.as_ref()[0].priority, rule_priority::AUTHOR);
633
1
    }
634

            
635
    // An explicit inline margin wins over the reset: checked at compile time.
636
    const _: () =
637
        assert!(azul_css::css::rule_priority::AUTHOR < azul_css::css::rule_priority::INLINE);
638
}
639

            
640
#[cfg(test)]
641
mod label_convention {
642
    //! Workspace-level enforcement of the widget label convention (USER ruling,
643
    //! 2026-08-12): a widget must never attach state to a raw text node.
644
    //!
645
    //! `NodeType::Text` is unconditionally inline-level
646
    //! (`solver3::layout_tree`): it is given no rect and no `UnifiedLayout` of
647
    //! its own — the wrapping block box carries those. Anything attached to a
648
    //! text node is therefore attached to a box-less node and is silently
649
    //! INERT: box-model properties never paint, callbacks and `tab_index` have
650
    //! no hit area, and a dataset has no node to be found on.
651
    //!
652
    //! The canonical shape is `Dom::create_p_with_text(label)` (or
653
    //! `create_p().with_children([create_text_do_not_use_without_block_level_wrapper(label)])`)
654
    //! with every property on the `<p>`, or — where a dedicated styled `<div>` already is the
655
    //! box — a bare `create_text` leaf with the properties on that `<div>`.
656
    //!
657
    //! This generalises `ribbon`'s per-widget invariant test to every widget in
658
    //! the crate. Widgets that emit no text at all are still instantiated, so
659
    //! the list doubles as a smoke test that every `dom()` builds.
660

            
661
    use azul_core::dom::{Dom, NodeType};
662
    use azul_css::{props::basic::color::ColorU, AzString, OptionString, StringVec};
663

            
664
    /// Everything a node can carry that only a real box can honour, in the
665
    /// order the failure message lists it.
666
142
    fn inert_state_on(node: &Dom) -> Vec<&'static str> {
667
142
        let mut found = Vec::new();
668
142
        if !node.root.style.rules.as_ref().is_empty() {
669
1
            found.push("css props");
670
141
        }
671
        // A subtree stylesheet on a childless text node can only target the text
672
        // node itself (`with_css("width: …")` parses to `* { … }`), so it is the
673
        // same violation wearing the other API.
674
142
        if !node.css.as_ref().is_empty() {
675
            found.push("subtree css");
676
142
        }
677
142
        if !node.root.get_callbacks().as_ref().is_empty() {
678
            found.push("callbacks");
679
142
        }
680
142
        if node.root.get_tab_index().is_some() {
681
1
            found.push("tab_index");
682
141
        }
683
142
        if node.root.get_dataset().is_some() {
684
            found.push("dataset");
685
142
        }
686
142
        if !node.children.as_ref().is_empty() {
687
            found.push("children");
688
142
        }
689
142
        found
690
142
    }
691

            
692
586
    fn walk(node: &Dom, widget: &str, bad: &mut Vec<String>) {
693
586
        if let NodeType::Text(text) = node.root.get_node_type() {
694
142
            let found = inert_state_on(node);
695
142
            if !found.is_empty() {
696
1
                bad.push(format!(
697
1
                    "{widget}: text node {:?} carries {} — move it onto a wrapping <p> (or onto \
698
1
                     the styled <div> that already boxes it)",
699
1
                    text.as_ref().as_str(),
700
1
                    found.join(" + "),
701
1
                ));
702
141
            }
703
444
        }
704
586
        for child in node.children.as_ref() {
705
539
            walk(child, widget, bad);
706
539
        }
707
586
    }
708

            
709
40
    fn labels(items: &[&str]) -> StringVec {
710
95
        StringVec::from_vec(items.iter().map(|s| AzString::from(*s)).collect::<Vec<_>>())
711
40
    }
712

            
713
    /// A user-content placeholder for the widgets that embed an arbitrary
714
    /// caller-supplied `Dom`. Deliberately property-free: this test governs
715
    /// what *widgets* emit, not what an application passes in.
716
55
    fn user_content() -> Dom {
717
55
        Dom::create_div()
718
55
    }
719

            
720
5
    fn node_graph_fixture() -> super::node_graph::NodeGraph {
721
        use super::node_graph::{
722
            InputConnectionVec, InputOutputInfo, InputOutputTypeId, InputOutputTypeIdInfoMap,
723
            InputOutputTypeIdInfoMapVec, InputOutputTypeIdVec, Node, NodeGraph, NodeGraphNodeId,
724
            NodeGraphNodePosition, NodeIdNodeMap, NodeIdNodeMapVec, NodeTypeField,
725
            NodeTypeFieldValue, NodeTypeFieldVec, NodeTypeId, NodeTypeIdInfoMap,
726
            NodeTypeIdInfoMapVec, NodeTypeInfo, OutputConnectionVec,
727
        };
728

            
729
        const TYPE_A: NodeTypeId = NodeTypeId { inner: 1 };
730
        const IO_A: InputOutputTypeId = InputOutputTypeId { inner: 1 };
731

            
732
5
        NodeGraph {
733
5
            node_types: NodeTypeIdInfoMapVec::from_vec(vec![NodeTypeIdInfoMap {
734
5
                node_type_id: TYPE_A,
735
5
                node_type_info: NodeTypeInfo {
736
5
                    is_root: true,
737
5
                    node_type_name: AzString::from("Add"),
738
5
                    inputs: InputOutputTypeIdVec::from_vec(vec![IO_A]),
739
5
                    outputs: InputOutputTypeIdVec::from_vec(vec![IO_A]),
740
5
                },
741
5
            }]),
742
5
            input_output_types: InputOutputTypeIdInfoMapVec::from_vec(vec![
743
5
                InputOutputTypeIdInfoMap {
744
5
                    io_type_id: IO_A,
745
5
                    io_info: InputOutputInfo {
746
5
                        data_type: AzString::from("number"),
747
5
                        color: ColorU {
748
5
                            r: 0,
749
5
                            g: 0,
750
5
                            b: 0,
751
5
                            a: 255,
752
5
                        },
753
5
                    },
754
5
                },
755
5
            ]),
756
5
            nodes: NodeIdNodeMapVec::from_vec(vec![NodeIdNodeMap {
757
5
                node_id: NodeGraphNodeId { inner: 1 },
758
5
                node: Node {
759
5
                    node_type: TYPE_A,
760
5
                    position: NodeGraphNodePosition { x: 0.0, y: 0.0 },
761
5
                    fields: NodeTypeFieldVec::from_vec(vec![NodeTypeField {
762
5
                        key: AzString::from("enabled"),
763
5
                        value: NodeTypeFieldValue::CheckBox(false),
764
5
                    }]),
765
5
                    connect_in: InputConnectionVec::from_const_slice(&[]),
766
5
                    connect_out: OutputConnectionVec::from_const_slice(&[]),
767
5
                },
768
5
            }]),
769
5
            add_node_str: AzString::from("Add node"),
770
5
            ..NodeGraph::default()
771
5
        }
772
5
    }
773

            
774
    /// Every widget in the crate, built with defaults that actually exercise
775
    /// its label paths (a widget with no labels proves nothing).
776
    ///
777
    /// NOT in this list, and why:
778
    /// * `camera` / `microphone` / `screencap` / `video` — each `dom()` emits a single replaced
779
    ///   `<img>` (or nothing) fed by a background worker and needs a device/GL config to construct;
780
    ///   they contain no text node at all, so there is nothing for this convention to govern.
781
    /// * `menubar` — a free function over a window `Menu`, not a `dom()` widget; its bar items are
782
    ///   already `div > bare text`.
783
    /// * `map`'s tile labels — emitted from the `VirtualView` render callback, not from `dom()`, so
784
    ///   the walk cannot reach them; they were converted by hand and are pinned by the map widget's
785
    ///   own tests.
786
5
    pub(super) fn every_widget_dom() -> Vec<(&'static str, Dom)> {
787
        use super::{
788
            accordion::{Accordion, AccordionSection, AccordionSectionVec},
789
            alert::Alert,
790
            avatar::Avatar,
791
            backstage::{Backstage, BackstageNavItem, BackstageNavItemVec},
792
            badge::Badge,
793
            breadcrumb::Breadcrumb,
794
            button::Button,
795
            card::Card,
796
            check_box::CheckBox,
797
            chip::Chip,
798
            color_input::ColorInput,
799
            combobox::ComboBox,
800
            date_picker::DatePicker,
801
            divider::Divider,
802
            drop_down::DropDown,
803
            file_input::FileInput,
804
            frame::Frame,
805
            label::Label,
806
            list_view::ListView,
807
            map::{MapTileLayer, MapWidget},
808
            menubar::build_menubar_dom,
809
            modal::Modal,
810
            number_input::NumberInput,
811
            pagination::Pagination,
812
            popover::Popover,
813
            progressbar::ProgressBar,
814
            quick_access::QuickAccessBar,
815
            radio_group::RadioGroup,
816
            ribbon::{
817
                Ribbon, RibbonAppButton, RibbonButton, RibbonGroup, RibbonItem, RibbonTab,
818
                RibbonTabVec,
819
            },
820
            segmented::Segmented,
821
            slider::Slider,
822
            spinner::Spinner,
823
            split_pane::{SplitDirection, SplitPane},
824
            statusbar::{StatusBar, StatusBarSegment, StatusBarSegmentVec},
825
            stepper::Stepper,
826
            switch::Switch,
827
            tabs::{TabContent, TabHeader},
828
            text_area::TextArea,
829
            text_input::TextInput,
830
            time_picker::TimePicker,
831
            titlebar::Titlebar,
832
            toast::Toast,
833
            tooltip::Tooltip,
834
            tree_view::{TreeView, TreeViewNode},
835
        };
836

            
837
5
        vec![
838
5
            (
839
5
                "accordion",
840
5
                Accordion::new(AccordionSectionVec::from_vec(vec![
841
5
                    AccordionSection::new("Open section", user_content()).with_open(true),
842
5
                    AccordionSection::new("Closed section", user_content()),
843
5
                ]))
844
5
                .dom(),
845
5
            ),
846
5
            (
847
5
                "alert",
848
5
                Alert::create(AzString::from("Something happened"))
849
5
                    .with_dismissible(true)
850
5
                    .dom(),
851
5
            ),
852
5
            ("avatar", Avatar::create(AzString::from("AB")).dom()),
853
5
            (
854
5
                "backstage",
855
5
                Backstage::new(BackstageNavItemVec::from_vec(vec![
856
5
                    BackstageNavItem::new(AzString::from("Info")),
857
5
                    BackstageNavItem::new(AzString::from("Save")),
858
5
                ]))
859
5
                .dom(),
860
5
            ),
861
5
            ("badge", Badge::create(AzString::from("99+")).dom()),
862
5
            (
863
5
                "breadcrumb",
864
5
                Breadcrumb::create(labels(&["Home", "Docs", "Page"])).dom(),
865
5
            ),
866
5
            ("button", Button::create(AzString::from("Click me")).dom()),
867
5
            ("card", Card::create(user_content()).dom()),
868
5
            ("check_box", CheckBox::create(true).dom()),
869
5
            (
870
5
                "chip",
871
5
                Chip::create(AzString::from("tag"))
872
5
                    .with_removable(true)
873
5
                    .dom(),
874
5
            ),
875
5
            (
876
5
                "color_input",
877
5
                ColorInput::create(ColorU {
878
5
                    r: 1,
879
5
                    g: 2,
880
5
                    b: 3,
881
5
                    a: 255,
882
5
                })
883
5
                .dom(),
884
5
            ),
885
5
            ("combobox", ComboBox::new(labels(&["one", "two"])).dom()),
886
5
            ("date_picker", DatePicker::create(2024, 2, 15).dom()),
887
5
            ("divider", Divider::create().dom()),
888
5
            ("drop_down", DropDown::new(labels(&["one", "two"])).dom()),
889
5
            ("file_input", FileInput::create(OptionString::None).dom()),
890
5
            (
891
5
                "frame",
892
5
                Frame::create(AzString::from("Frame title"), user_content()).dom(),
893
5
            ),
894
5
            ("label", Label::create(AzString::from("A label")).dom()),
895
5
            (
896
5
                "list_view",
897
5
                ListView::create(labels(&["Name", "Size"])).dom(),
898
5
            ),
899
5
            ("map", MapWidget::create(MapTileLayer::default()).dom()),
900
5
            (
901
5
                "menubar",
902
5
                build_menubar_dom(&azul_core::menu::Menu::create(
903
5
                    azul_core::menu::MenuItemVec::from_vec(vec![
904
5
                        azul_core::menu::MenuItem::String(azul_core::menu::StringMenuItem::create(
905
5
                            "File".into(),
906
5
                        )),
907
5
                        azul_core::menu::MenuItem::String(azul_core::menu::StringMenuItem::create(
908
5
                            "Edit".into(),
909
5
                        )),
910
5
                    ]),
911
5
                )),
912
5
            ),
913
5
            (
914
5
                "modal",
915
5
                Modal::create(user_content())
916
5
                    .with_title(AzString::from("Dialog"))
917
5
                    .with_open(true)
918
5
                    .dom(),
919
5
            ),
920
5
            ("node_graph", node_graph_fixture().dom()),
921
5
            ("number_input", NumberInput::create(4.0).dom()),
922
5
            ("pagination", Pagination::create(2, 5).dom()),
923
5
            (
924
5
                "popover",
925
5
                Popover::new(user_content(), user_content())
926
5
                    .with_open(true)
927
5
                    .dom(),
928
5
            ),
929
5
            ("progressbar", ProgressBar::create(40.0).dom()),
930
5
            (
931
5
                "quick_access",
932
5
                QuickAccessBar::new(AzString::from("Document1")).dom(),
933
5
            ),
934
5
            (
935
5
                "radio_group",
936
5
                RadioGroup::create(labels(&["First", "Second"])).dom(),
937
5
            ),
938
5
            (
939
5
                "ribbon",
940
5
                Ribbon::new(RibbonTabVec::from_vec(vec![
941
5
                    RibbonTab::new(AzString::from("HOME")).with_group(
942
5
                        RibbonGroup::new(AzString::from("Clipboard")).with_item(
943
5
                            RibbonItem::LargeButton(RibbonButton::new(
944
5
                                AzString::from("content_paste"),
945
5
                                AzString::from("Paste"),
946
5
                            )),
947
5
                        ),
948
5
                    ),
949
5
                    RibbonTab::new(AzString::from("PAGE LAYOUT")),
950
5
                ]))
951
5
                .with_app_button(RibbonAppButton::new(AzString::from("FILE")))
952
5
                .dom(),
953
5
            ),
954
5
            (
955
5
                "segmented",
956
5
                Segmented::create(labels(&["Day", "Week", "Month"])).dom(),
957
5
            ),
958
5
            ("slider", Slider::create(0.5, 0.0, 1.0).dom()),
959
5
            ("spinner", Spinner::create().dom()),
960
5
            (
961
5
                "split_pane",
962
5
                SplitPane::create(SplitDirection::Horizontal, user_content(), user_content()).dom(),
963
5
            ),
964
5
            (
965
5
                "statusbar",
966
5
                StatusBar::new(StatusBarSegmentVec::from_vec(vec![StatusBarSegment::new(
967
5
                    AzString::from("Page 1 of 3"),
968
5
                )]))
969
5
                .dom(),
970
5
            ),
971
5
            (
972
5
                "stepper",
973
5
                Stepper::create(labels(&["Start", "Details", "Done"])).dom(),
974
5
            ),
975
5
            ("switch", Switch::create(true).dom()),
976
5
            (
977
5
                "tabs (header)",
978
5
                TabHeader::create(labels(&["One", "Two"])).dom(),
979
5
            ),
980
5
            ("tabs (content)", TabContent::new(user_content()).dom()),
981
5
            ("text_area", TextArea::create().dom()),
982
5
            ("text_input", TextInput::create().dom()),
983
5
            (
984
5
                "time_picker",
985
5
                TimePicker::create(9, 30).with_24h(false).dom(),
986
5
            ),
987
5
            ("titlebar", Titlebar::create(AzString::from("Window")).dom()),
988
5
            ("toast", Toast::create(AzString::from("Saved")).dom()),
989
5
            (
990
5
                "tooltip",
991
5
                Tooltip::new(user_content(), AzString::from("Explains it")).dom(),
992
5
            ),
993
5
            (
994
5
                "tree_view",
995
5
                TreeView::new(
996
5
                    TreeViewNode::new("root")
997
5
                        .with_expanded(true)
998
5
                        .with_child(TreeViewNode::new("child")),
999
5
                )
5
                .dom(),
5
            ),
        ]
5
    }
    /// THE convention. A widget that trips this has attached box-model CSS, a
    /// callback, a `tab_index`, a dataset or children to a node that owns no
    /// rect — all of which the layout engine silently discards.
    #[test]
1
    fn no_widget_attaches_state_to_a_rect_less_text_node() {
1
        let mut bad = Vec::new();
46
        for (name, dom) in every_widget_dom() {
46
            walk(&dom, name, &mut bad);
46
        }
1
        assert!(
1
            bad.is_empty(),
            "widget label convention violated ({} site(s)):\n{}",
            bad.len(),
            bad.join("\n"),
        );
1
    }
    /// A guard on the guard: the walk must be able to SEE a violation, or the
    /// test above would pass vacuously the day someone breaks `inert_state_on`.
    #[test]
1
    fn the_walk_reports_a_deliberately_broken_text_node() {
        use azul_core::dom::TabIndex;
1
        let mut leaf =
1
            Dom::create_text_do_not_use_without_block_level_wrapper(AzString::from("bare"));
1
        leaf.root.set_css("width: 10px;");
1
        let broken = Dom::create_div().with_child(leaf.with_tab_index(TabIndex::Auto));
1
        let mut bad = Vec::new();
1
        walk(&broken, "fixture", &mut bad);
1
        assert_eq!(bad.len(), 1, "the walk missed a hand-broken text node");
1
        assert!(bad[0].contains("css props"), "{}", bad[0]);
1
        assert!(bad[0].contains("tab_index"), "{}", bad[0]);
1
    }
}
#[cfg(test)]
mod theme_pairs {
    //! Workspace-level guard for invariant I8 of the theme-chain analysis
    //! (2026-09-12): a dark twin never ships without its light half, and
    //! never BEFORE it.
    //!
    //! Inline declarations resolve last-match-wins (`prop_cache.rs`,
    //! `get_property_slow`), and the widgets rely on that ordering: the
    //! widget declares its light face, the theme module appends the
    //! `dark_theme(..)` twins after it. Two things can go wrong by hand and
    //! nothing else catches either: a twin whose light counterpart was
    //! never declared (the light window gets the UA default, the dark one a
    //! widget colour — the halves come from different files), and a twin
    //! pushed before its light value (dead under the dark theme: the later
    //! unconditional value wins there too). Build pairs with
    //! `CssPropertyWithConditions::themed*` and neither can happen; this
    //! walk catches whatever is still built by hand.
    //!
    //! Scope, mechanically: every node of every widget `dom()` in the lint
    //! manifest (`label_convention::every_widget_dom`), its inline
    //! declarations only (the theme module writes them there). For each
    //! declaration carrying a `Theme(Dark)` condition, there must be an
    //! EARLIER declaration of the same property type whose conditions are the
    //! same pseudo-states (in the same order) and no `Theme(Dark)` — the
    //! unconditional light value, the `light_theme(..)` value, or the
    //! `on_hover(..)` to a `dark_on_hover(..)`. The "vice versa" (a light
    //! colour with no twin) is NOT a violation: a surface that is its own
    //! colour keeps it in dark mode by design (see `hover_bg_both`).
    use azul_core::dom::Dom;
    use azul_css::dynamic_selector::CssPropertyWithConditions;
    /// Sites the walk flags that are KNOWN and being fixed elsewhere: one
    /// `(widget name, message prefix, reason)` per entry. Empty means every
    /// widget is clean; an entry masks every finding of that widget whose
    /// message contains the prefix (`the_known_list_masks_only_live_findings`
    /// rejects an entry that masks nothing).
    const KNOWN_HALF_PAIRS: &[(&str, &str, &str)] = &[
        // A dark text twin with NO light half is the migration's "no opinion"
        // shape: the light window takes the UA default on purpose (and since
        // the UA text colour is themed and cascaded, the twin is belt and
        // braces). Listed rather than paired, because inventing a light value
        // here would be exactly the "light value moved" the migration forbids.
        (
            "list_view",
            "node root declares a dark twin for color (states [])",
            "light text = the UA default by design; the dark twin predates the themed UA colour",
        ),
        (
            "tree_view",
            "node root/0/1 declares a dark twin for color (states [])",
            "light text = the UA default by design; the dark twin predates the themed UA colour",
        ),
        (
            "tree_view",
            "node root/1/0/1 declares a dark twin for color (states [])",
            "light text = the UA default by design; the dark twin predates the themed UA colour",
        ),
    ];
    /// Every half-pair in one node's inline declarations, as messages. The
    /// ONE message builder: the walk, the self-test and the known-list
    /// staleness check all read these, so a prefix that matched a reported
    /// finding matches here too.
1172
    fn findings(props: &[CssPropertyWithConditions], widget: &str, path: &str) -> Vec<String> {
1172
        let mut out = Vec::new();
7859
        for (i, twin) in props.iter().enumerate() {
7859
            if !twin.is_dark_twin() {
7151
                continue;
708
            }
708
            let ty = twin.property.get_type();
708
            let states = twin.pseudo_state_conditions();
13028
            let counterpart_at = props.iter().position(|p| {
13028
                p.property.get_type() == ty
1182
                    && p.is_light_half()
1048
                    && p.pseudo_state_conditions() == states
13028
            });
700
            match counterpart_at {
8
                None => out.push(format!(
8
                    "{widget}: node {path} declares a dark twin for {ty:?} (states {states:?}) \
8
                     with NO light counterpart — the light window gets the UA default here"
                )),
700
                Some(j) if j > i => out.push(format!(
1
                    "{widget}: node {path} pushes the dark twin for {ty:?} (states {states:?}) \
1
                     at #{i}, BEFORE its light value at #{j} — dead under the dark theme \
1
                     (last match wins)"
                )),
699
                Some(_) => {}
            }
        }
1172
        out
1172
    }
3
    fn is_known(widget: &str, msg: &str) -> bool {
3
        KNOWN_HALF_PAIRS
3
            .iter()
6
            .any(|(w, prefix, _)| *w == widget && msg.contains(prefix))
3
    }
1168
    fn inline_props(node: &Dom) -> Vec<CssPropertyWithConditions> {
1168
        node.root
1168
            .style
1168
            .iter_inline_properties()
1168
            .map(|(p, conds)| CssPropertyWithConditions {
7848
                property: p.clone(),
7848
                apply_if: conds.clone(),
7848
            })
1168
            .collect()
1168
    }
    /// Every finding in the widget's tree, known ones included.
1168
    fn walk_raw(node: &Dom, widget: &str, path: &str, out: &mut Vec<String>) {
1168
        out.extend(findings(&inline_props(node), widget, path));
1168
        for (i, child) in node.children.as_ref().iter().enumerate() {
1076
            walk_raw(child, widget, &format!("{path}/{i}"), out);
1076
        }
1168
    }
    /// The findings of every widget in the manifest, known ones included.
2
    fn all_raw_findings() -> Vec<(&'static str, String)> {
2
        let mut out = Vec::new();
92
        for (widget, dom) in super::label_convention::every_widget_dom() {
92
            let mut raw = Vec::new();
92
            walk_raw(&dom, widget, "root", &mut raw);
92
            out.extend(raw.into_iter().map(|m| (widget, m)));
        }
2
        out
2
    }
    #[test]
1
    fn every_widget_dark_twin_has_a_light_half_declared_before_it() {
1
        let bad: Vec<String> = all_raw_findings()
1
            .into_iter()
3
            .filter(|(widget, msg)| !is_known(widget, msg))
1
            .map(|(_, msg)| msg)
1
            .collect();
1
        assert!(
1
            bad.is_empty(),
            "{} half-pair(s) in the widget styles:\n  {}\n\nBuild the pair with \
             CssPropertyWithConditions::themed / themed_on_hover / themed_on_active (light \
             value first), or list the site in KNOWN_HALF_PAIRS with the reason.",
            bad.len(),
            bad.join("\n  ")
        );
1
    }
    /// A guard on the guard: the walk must SEE both failure shapes, and the
    /// builder's shape must be clean.
    #[test]
1
    fn the_walk_reports_a_missing_half_and_a_reversed_pair() {
        use azul_css::props::{basic::color::ColorU, property::CssProperty, style::StyleTextColor};
11
        let c = |v: u8| {
11
            CssProperty::const_text_color(StyleTextColor {
11
                inner: ColorU::rgb(v, v, v),
11
            })
11
        };
        // Missing half.
1
        let bad = findings(&[CssPropertyWithConditions::dark_theme(c(1))], "fixture", "root");
1
        assert_eq!(bad.len(), 1, "{bad:?}");
1
        assert!(bad[0].contains("NO light counterpart"), "{}", bad[0]);
        // Reversed pair.
1
        let bad = findings(
1
            &[
1
                CssPropertyWithConditions::dark_theme(c(1)),
1
                CssPropertyWithConditions::simple(c(2)),
1
            ],
1
            "fixture",
1
            "root",
        );
1
        assert_eq!(bad.len(), 1, "{bad:?}");
1
        assert!(bad[0].contains("BEFORE its light value"), "{}", bad[0]);
        // The builder's shape is clean, in every state.
1
        let mut props: Vec<_> = CssPropertyWithConditions::themed(c(1), c(2)).into();
1
        props.extend(CssPropertyWithConditions::themed_on_hover(c(3), c(4)));
1
        props.extend(CssPropertyWithConditions::themed_on_active(c(5), c(6)));
1
        let bad = findings(&props, "fixture", "root");
1
        assert!(bad.is_empty(), "{bad:?}");
        // A hover twin is NOT paired by a resting light value.
1
        let bad = findings(
1
            &[
1
                CssPropertyWithConditions::simple(c(1)),
1
                CssPropertyWithConditions::dark_on_hover(c(2)),
1
            ],
1
            "fixture",
1
            "root",
        );
1
        assert_eq!(bad.len(), 1, "{bad:?}");
1
    }
    /// An entry in `KNOWN_HALF_PAIRS` that masks nothing is stale and must
    /// go: the finding it parked was fixed, so the parking is now hiding
    /// whatever appears next under the same prefix.
    #[test]
1
    fn the_known_list_masks_only_live_findings() {
1
        let raw = all_raw_findings();
4
        for (w, prefix, reason) in KNOWN_HALF_PAIRS {
3
            assert!(
6
                raw.iter().any(|(widget, msg)| widget == w && msg.contains(prefix)),
                "KNOWN_HALF_PAIRS entry ({w}, {prefix:?}) masks nothing any more — delete it \
                 (reason on file: {reason})"
            );
        }
1
    }
}
pub mod themes;