1
//! Native list view widget with column headers, row selection, and sorting indicators.
2

            
3
use alloc::vec::Vec;
4

            
5
use azul_core::{
6
    callbacks::{CoreCallback, CoreCallbackData, Update},
7
    dom::{
8
        Dom, DomVec, EventFilter, HoverEventFilter, IdOrClass, IdOrClass::Class, IdOrClassVec,
9
        TabIndex,
10
    },
11
    geom::{LogicalPosition, LogicalSize},
12
    menu::{Menu, OptionMenu},
13
    refany::{OptionRefAny, RefAny},
14
};
15
use azul_css::css::BoxOrStatic;
16
#[allow(clippy::wildcard_imports)]
17
// widget/render module pulls in the css property/value types it builds with
18
use azul_css::{
19
    corety::OptionUsize,
20
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
21
    props::{
22
        basic::*,
23
        layout::*,
24
        property::{CssProperty, *},
25
        style::*,
26
    },
27
    *,
28
};
29

            
30
use crate::{
31
    callbacks::{Callback, CallbackInfo},
32
    widgets::themes::flat,
33
};
34

            
35
const STRING_16146701490593874959: AzString = AzString::from_const_str("system:ui");
36
const STYLE_BACKGROUND_CONTENT_661302523448178568_ITEMS: &[StyleBackgroundContent] =
37
    &[StyleBackgroundContent::Color(ColorU {
38
        r: 209,
39
        g: 232,
40
        b: 255,
41
        a: 255,
42
    })];
43
const STYLE_BACKGROUND_CONTENT_2444935983575427872_ITEMS: &[StyleBackgroundContent] =
44
    &[StyleBackgroundContent::Color(ColorU {
45
        r: 252,
46
        g: 252,
47
        b: 252,
48
        a: 255,
49
    })];
50
const STYLE_BACKGROUND_CONTENT_7422581697888665934_ITEMS: &[StyleBackgroundContent] =
51
    &[StyleBackgroundContent::LinearGradient(LinearGradient {
52
        direction: Direction::FromTo(DirectionCorners {
53
            dir_from: DirectionCorner::Top,
54
            dir_to: DirectionCorner::Bottom,
55
        }),
56
        extend_mode: ExtendMode::Clamp,
57
        stops: NormalizedLinearColorStopVec::from_const_slice(
58
            LINEAR_COLOR_STOP_513857305091467054_ITEMS,
59
        ),
60
    })];
61
const STYLE_BACKGROUND_CONTENT_11062356617965867290_ITEMS: &[StyleBackgroundContent] =
62
    &[StyleBackgroundContent::Color(ColorU {
63
        r: 240,
64
        g: 240,
65
        b: 240,
66
        a: 255,
67
    })];
68
const STYLE_FONT_FAMILY_8122988506401935406_ITEMS: &[StyleFontFamily] =
69
    &[StyleFontFamily::System(STRING_16146701490593874959)];
70
const LINEAR_COLOR_STOP_513857305091467054_ITEMS: &[NormalizedLinearColorStop] = &[
71
    NormalizedLinearColorStop {
72
        offset: PercentageValue::const_new(0),
73
        color: ColorOrSystem::color(ColorU {
74
            r: 255,
75
            g: 255,
76
            b: 255,
77
            a: 255,
78
        }),
79
    },
80
    NormalizedLinearColorStop {
81
        offset: PercentageValue::const_new(50),
82
        color: ColorOrSystem::color(ColorU {
83
            r: 255,
84
            g: 255,
85
            b: 255,
86
            a: 255,
87
        }),
88
    },
89
    NormalizedLinearColorStop {
90
        offset: PercentageValue::const_new(51),
91
        color: ColorOrSystem::color(ColorU {
92
            r: 247,
93
            g: 248,
94
            b: 250,
95
            a: 255,
96
        }),
97
    },
98
    NormalizedLinearColorStop {
99
        offset: PercentageValue::const_new(100),
100
        color: ColorOrSystem::color(ColorU {
101
            r: 243,
102
            g: 244,
103
            b: 246,
104
            a: 255,
105
        }),
106
    },
107
];
108

            
109
const CSS_MATCH_12498280255863106397_PROPERTIES: &[CssPropertyWithConditions] = &[
110
    // A flex container: `flex-direction` / `justify-content` / `align-items`
111
    // below do nothing without it (this rule had none, so the box laid out as
112
    // a block and its children stacked vertically).
113
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
114
        LayoutDisplay::Flex,
115
    ))),
116
    // .__azul_native-list-header-item:hover and :active, light AND dark.
117
    // Declared in the theme module — see `themes::flat::LIST_HEADER_HOVER_BG`
118
    // — because the dark half of each pair needs a palette this file cannot
119
    // see; declared here they could only ever name the light-mode colour,
120
    // which is how a hovered header kept its light face on a dark surface.
121
    // Each light rule is followed by its dark twin so the twin wins in dark
122
    // mode (inline CSS is last-wins).
123
    flat::LIST_HOVER_BORDER_BOTTOM_WIDTH,
124
    flat::LIST_HOVER_BORDER_BOTTOM_WIDTH_DARK,
125
    flat::LIST_HOVER_BORDER_BOTTOM_STYLE,
126
    flat::LIST_HOVER_BORDER_BOTTOM_STYLE_DARK,
127
    flat::LIST_HEADER_HOVER_LINE_COLOR,
128
    flat::LIST_HEADER_HOVER_LINE_COLOR_DARK,
129
    flat::LIST_HEADER_HOVER_BG,
130
    flat::LIST_HEADER_HOVER_BG_DARK,
131
    // .__azul_native-list-header-item:active
132
    flat::LIST_HEADER_ACTIVE_SHADOW_BOTTOM,
133
    flat::LIST_HEADER_ACTIVE_SHADOW_BOTTOM_DARK,
134
    flat::LIST_HEADER_ACTIVE_SHADOW_TOP,
135
    flat::LIST_HEADER_ACTIVE_SHADOW_TOP_DARK,
136
    flat::LIST_HEADER_ACTIVE_SHADOW_RIGHT,
137
    flat::LIST_HEADER_ACTIVE_SHADOW_RIGHT_DARK,
138
    flat::LIST_HEADER_ACTIVE_SHADOW_LEFT,
139
    flat::LIST_HEADER_ACTIVE_SHADOW_LEFT_DARK,
140
    flat::LIST_ACTIVE_BORDER_BOTTOM_WIDTH,
141
    flat::LIST_ACTIVE_BORDER_BOTTOM_WIDTH_DARK,
142
    flat::LIST_ACTIVE_BORDER_LEFT_WIDTH,
143
    flat::LIST_ACTIVE_BORDER_LEFT_WIDTH_DARK,
144
    flat::LIST_ACTIVE_BORDER_RIGHT_WIDTH,
145
    flat::LIST_ACTIVE_BORDER_RIGHT_WIDTH_DARK,
146
    flat::LIST_ACTIVE_BORDER_TOP_WIDTH,
147
    flat::LIST_ACTIVE_BORDER_TOP_WIDTH_DARK,
148
    flat::LIST_ACTIVE_BORDER_BOTTOM_STYLE,
149
    flat::LIST_ACTIVE_BORDER_BOTTOM_STYLE_DARK,
150
    flat::LIST_ACTIVE_BORDER_LEFT_STYLE,
151
    flat::LIST_ACTIVE_BORDER_LEFT_STYLE_DARK,
152
    flat::LIST_ACTIVE_BORDER_RIGHT_STYLE,
153
    flat::LIST_ACTIVE_BORDER_RIGHT_STYLE_DARK,
154
    flat::LIST_ACTIVE_BORDER_TOP_STYLE,
155
    flat::LIST_ACTIVE_BORDER_TOP_STYLE_DARK,
156
    flat::LIST_HEADER_ACTIVE_BORDER_BOTTOM_COLOR,
157
    flat::LIST_HEADER_ACTIVE_BORDER_BOTTOM_COLOR_DARK,
158
    flat::LIST_HEADER_ACTIVE_BORDER_LEFT_COLOR,
159
    flat::LIST_HEADER_ACTIVE_BORDER_LEFT_COLOR_DARK,
160
    flat::LIST_HEADER_ACTIVE_BORDER_RIGHT_COLOR,
161
    flat::LIST_HEADER_ACTIVE_BORDER_RIGHT_COLOR_DARK,
162
    flat::LIST_HEADER_ACTIVE_BORDER_TOP_COLOR,
163
    flat::LIST_HEADER_ACTIVE_BORDER_TOP_COLOR_DARK,
164
    flat::LIST_HEADER_ACTIVE_BG,
165
    flat::LIST_HEADER_ACTIVE_BG_DARK,
166
    // .__azul_native-list-header-item
167
    // Centre the label in the header's height: without it the text sat on the
168
    // top edge and the gradient's grey half read as an empty band under it.
169
    CssPropertyWithConditions::simple(CssProperty::JustifyContent(
170
        LayoutJustifyContentValue::Exact(LayoutJustifyContent::Center),
171
    )),
172
    CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
173
        LayoutPosition::Relative,
174
    ))),
175
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
176
        LayoutPaddingLeft {
177
            inner: PixelValue::const_px(7),
178
        },
179
    ))),
180
    CssPropertyWithConditions::simple(CssProperty::MinWidth(LayoutMinWidthValue::Exact(
181
        LayoutMinWidth {
182
            inner: PixelValue::const_px(100),
183
        },
184
    ))),
185
    CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
186
        LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
187
            inner: PixelValue::const_px(1),
188
        }),
189
    )),
190
    CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
191
        StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
192
            inner: BorderStyle::Solid,
193
        }),
194
    )),
195
    CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
196
        StyleBorderRightColorValue::Exact(StyleBorderRightColor {
197
            inner: ColorU {
198
                r: 243,
199
                g: 244,
200
                b: 246,
201
                a: 255,
202
            },
203
        }),
204
    )),
205
];
206
const CSS_MATCH_12498280255863106397: CssPropertyWithConditionsVec =
207
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_12498280255863106397_PROPERTIES);
208

            
209
const CSS_MATCH_12980082330151137475_PROPERTIES: &[CssPropertyWithConditions] = &[
210
    // .__azul_native-list-rows-row-cell
211
    // A cell holds one line of a record, like a table cell: it clips rather
212
    // than wrapping, so a row keeps the height the list gave it and a long
213
    // value cannot push the rows below it out of place.
214
    CssPropertyWithConditions::simple(CssProperty::WhiteSpace(StyleWhiteSpaceValue::Exact(
215
        StyleWhiteSpace::Nowrap,
216
    ))),
217
    CssPropertyWithConditions::simple(CssProperty::OverflowX(LayoutOverflowValue::Exact(
218
        LayoutOverflow::Hidden,
219
    ))),
220
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
221
        LayoutPaddingLeft {
222
            inner: PixelValue::const_px(7),
223
        },
224
    ))),
225
    CssPropertyWithConditions::simple(CssProperty::MinWidth(LayoutMinWidthValue::Exact(
226
        LayoutMinWidth {
227
            inner: PixelValue::const_px(100),
228
        },
229
    ))),
230
    CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
231
        StyleFontSize {
232
            inner: PixelValue::const_px(11),
233
        },
234
    ))),
235
    CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
236
        StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
237
    ))),
238
    // Same reason as the tree's label: a conditional inline value is not
239
    // inherited, so the cell states its own dark colour.
240
    CssPropertyWithConditions::dark_theme(CssProperty::TextColor(StyleTextColorValue::Exact(
241
        StyleTextColor {
242
            inner: ColorU {
243
                r: 230,
244
                g: 230,
245
                b: 230,
246
                a: 255,
247
            },
248
        },
249
    ))),
250
];
251
const CSS_MATCH_12980082330151137475: CssPropertyWithConditionsVec =
252
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_12980082330151137475_PROPERTIES);
253

            
254
const CSS_MATCH_15295293133676720691_PROPERTIES: &[CssPropertyWithConditions] = &[
255
    // .__azul_native-list-header-dragwidth-drag
256
    CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
257
        LayoutWidth::Px(PixelValue::const_px(2)),
258
    ))),
259
    CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
260
        LayoutPosition::Absolute,
261
    ))),
262
];
263
const CSS_MATCH_15295293133676720691: CssPropertyWithConditionsVec =
264
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_15295293133676720691_PROPERTIES);
265

            
266
const CSS_MATCH_15315949193378715186_PROPERTIES: &[CssPropertyWithConditions] = &[
267
    // A flex container: `flex-direction` / `justify-content` / `align-items`
268
    // below do nothing without it (this rule had none, so the box laid out as
269
    // a block and its children stacked vertically).
270
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
271
        LayoutDisplay::Flex,
272
    ))),
273
    // .__azul_native-list-header
274
    CssPropertyWithConditions::simple(CssProperty::Height(LayoutHeightValue::Exact(
275
        LayoutHeight::Px(PixelValue::const_px(25)),
276
    ))),
277
    CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
278
        StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
279
            STYLE_BACKGROUND_CONTENT_7422581697888665934_ITEMS,
280
        )),
281
    )),
282
    CssPropertyWithConditions::dark_theme(CssProperty::BackgroundContent(
283
        StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(&[
284
            StyleBackgroundContent::Color(ColorU {
285
                r: 43,
286
                g: 43,
287
                b: 43,
288
                a: 255,
289
            }),
290
        ])),
291
    )),
292
];
293
const CSS_MATCH_15315949193378715186: CssPropertyWithConditionsVec =
294
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_15315949193378715186_PROPERTIES);
295

            
296
const CSS_MATCH_15673486787900743642_PROPERTIES: &[CssPropertyWithConditions] = &[
297
    // .__azul_native-list-header .__azul_native-list-header-item p
298
    CssPropertyWithConditions::simple(CssProperty::FontSize(StyleFontSizeValue::Exact(
299
        StyleFontSize {
300
            inner: PixelValue::const_px(11),
301
        },
302
    ))),
303
    CssPropertyWithConditions::simple(CssProperty::FontFamily(StyleFontFamilyVecValue::Exact(
304
        StyleFontFamilyVec::from_const_slice(STYLE_FONT_FAMILY_8122988506401935406_ITEMS),
305
    ))),
306
    CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
307
        LayoutFlexGrow {
308
            inner: FloatValue::const_new(1),
309
        },
310
    ))),
311
    CssPropertyWithConditions::simple(CssProperty::TextColor(StyleTextColorValue::Exact(
312
        StyleTextColor {
313
            inner: ColorU {
314
                r: 0,
315
                g: 0,
316
                b: 0,
317
                a: 255,
318
            },
319
        },
320
    ))),
321
    CssPropertyWithConditions::simple(CssProperty::AlignItems(LayoutAlignItemsValue::Exact(
322
        LayoutAlignItems::Center,
323
    ))),
324
    CssPropertyWithConditions::dark_theme(CssProperty::TextColor(StyleTextColorValue::Exact(
325
        StyleTextColor {
326
            inner: ColorU {
327
                r: 230,
328
                g: 230,
329
                b: 230,
330
                a: 255,
331
            },
332
        },
333
    ))),
334
];
335
const CSS_MATCH_15673486787900743642: CssPropertyWithConditionsVec =
336
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_15673486787900743642_PROPERTIES);
337

            
338
const CSS_MATCH_17553577885456905601_PROPERTIES: &[CssPropertyWithConditions] = &[
339
    // .__azul_native_list-container
340
    CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
341
        LayoutFlexGrow {
342
            inner: FloatValue::const_new(1),
343
        },
344
    ))),
345
    CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
346
        StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
347
            STYLE_BACKGROUND_CONTENT_2444935983575427872_ITEMS,
348
        )),
349
    )),
350
    // Dark defaults. Inline CSS takes `@theme dark` conditions and the last
351
    // matching property wins, so each dark value sits after the light one it
352
    // replaces. A list is a FIELD: in a dark window it must not stay white.
353
    CssPropertyWithConditions::dark_theme(CssProperty::BackgroundContent(
354
        StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(&[
355
            StyleBackgroundContent::Color(ColorU {
356
                r: 31,
357
                g: 31,
358
                b: 31,
359
                a: 255,
360
            }),
361
        ])),
362
    )),
363
    CssPropertyWithConditions::dark_theme(CssProperty::TextColor(StyleTextColorValue::Exact(
364
        StyleTextColor {
365
            inner: ColorU {
366
                r: 230,
367
                g: 230,
368
                b: 230,
369
                a: 255,
370
            },
371
        },
372
    ))),
373
];
374
const CSS_MATCH_17553577885456905601: CssPropertyWithConditionsVec =
375
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_17553577885456905601_PROPERTIES);
376

            
377
const CSS_MATCH_2883986488332352590_PROPERTIES: &[CssPropertyWithConditions] = &[
378
    // body
379
    CssPropertyWithConditions::simple(CssProperty::PaddingRight(LayoutPaddingRightValue::Exact(
380
        LayoutPaddingRight {
381
            inner: PixelValue::const_px(5),
382
        },
383
    ))),
384
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
385
        LayoutPaddingLeft {
386
            inner: PixelValue::const_px(5),
387
        },
388
    ))),
389
    CssPropertyWithConditions::simple(CssProperty::PaddingBottom(LayoutPaddingBottomValue::Exact(
390
        LayoutPaddingBottom {
391
            inner: PixelValue::const_px(5),
392
        },
393
    ))),
394
    CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
395
        LayoutPaddingTop {
396
            inner: PixelValue::const_px(5),
397
        },
398
    ))),
399
    CssPropertyWithConditions::simple(CssProperty::BackgroundContent(
400
        StyleBackgroundContentVecValue::Exact(StyleBackgroundContentVec::from_const_slice(
401
            STYLE_BACKGROUND_CONTENT_11062356617965867290_ITEMS,
402
        )),
403
    )),
404
];
405
const CSS_MATCH_2883986488332352590: CssPropertyWithConditionsVec =
406
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_2883986488332352590_PROPERTIES);
407

            
408
const CSS_MATCH_4852927511892172364_PROPERTIES: &[CssPropertyWithConditions] = &[
409
    // A flex container: `flex-direction` / `justify-content` / `align-items`
410
    // below do nothing without it (this rule had none, so the box laid out as
411
    // a block and its children stacked vertically).
412
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
413
        LayoutDisplay::Flex,
414
    ))),
415
    // .__azul_native-list-rows
416
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
417
        LayoutFlexDirection::Column,
418
    ))),
419
];
420
const CSS_MATCH_4852927511892172364: CssPropertyWithConditionsVec =
421
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_4852927511892172364_PROPERTIES);
422

            
423
const CSS_MATCH_6002662151290653203_PROPERTIES: &[CssPropertyWithConditions] = &[
424
    // .__azul_native-list-header-dragwidth
425
    CssPropertyWithConditions::simple(CssProperty::Width(LayoutWidthValue::Exact(
426
        LayoutWidth::Px(PixelValue::const_px(0)),
427
    ))),
428
    CssPropertyWithConditions::simple(CssProperty::Position(LayoutPositionValue::Exact(
429
        LayoutPosition::Relative,
430
    ))),
431
    CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
432
        LayoutFlexGrow {
433
            inner: FloatValue::const_new(1),
434
        },
435
    ))),
436
];
437
const CSS_MATCH_6002662151290653203: CssPropertyWithConditionsVec =
438
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_6002662151290653203_PROPERTIES);
439

            
440
const CSS_MATCH_7894335449545988724_PROPERTIES: &[CssPropertyWithConditions] = &[
441
    // A flex container: `flex-direction` / `justify-content` / `align-items`
442
    // below do nothing without it (this rule had none, so the box laid out as
443
    // a block and its children stacked vertically).
444
    CssPropertyWithConditions::simple(CssProperty::Display(LayoutDisplayValue::Exact(
445
        LayoutDisplay::Flex,
446
    ))),
447
    // .__azul_native-list-rows-row.focused, light AND dark. Declared in the
448
    // theme module — see `themes::flat::LIST_ROW_FOCUS_BG` — because the dark
449
    // half of each pair needs a palette this file cannot see; declared here it
450
    // could only ever name the light-mode colour, which is how the focused row
451
    // kept its light ring on a dark surface. Each light rule is followed by
452
    // its dark twin so the twin wins in dark mode (inline CSS is last-wins).
453
    flat::LIST_FOCUS_BORDER_BOTTOM_WIDTH,
454
    flat::LIST_FOCUS_BORDER_BOTTOM_WIDTH_DARK,
455
    flat::LIST_FOCUS_BORDER_LEFT_WIDTH,
456
    flat::LIST_FOCUS_BORDER_LEFT_WIDTH_DARK,
457
    flat::LIST_FOCUS_BORDER_RIGHT_WIDTH,
458
    flat::LIST_FOCUS_BORDER_RIGHT_WIDTH_DARK,
459
    flat::LIST_FOCUS_BORDER_TOP_WIDTH,
460
    flat::LIST_FOCUS_BORDER_TOP_WIDTH_DARK,
461
    flat::LIST_FOCUS_BORDER_BOTTOM_STYLE,
462
    flat::LIST_FOCUS_BORDER_BOTTOM_STYLE_DARK,
463
    flat::LIST_FOCUS_BORDER_LEFT_STYLE,
464
    flat::LIST_FOCUS_BORDER_LEFT_STYLE_DARK,
465
    flat::LIST_FOCUS_BORDER_RIGHT_STYLE,
466
    flat::LIST_FOCUS_BORDER_RIGHT_STYLE_DARK,
467
    flat::LIST_FOCUS_BORDER_TOP_STYLE,
468
    flat::LIST_FOCUS_BORDER_TOP_STYLE_DARK,
469
    flat::LIST_ROW_FOCUS_BORDER_BOTTOM_COLOR,
470
    flat::LIST_ROW_FOCUS_BORDER_BOTTOM_COLOR_DARK,
471
    flat::LIST_ROW_FOCUS_BORDER_LEFT_COLOR,
472
    flat::LIST_ROW_FOCUS_BORDER_LEFT_COLOR_DARK,
473
    flat::LIST_ROW_FOCUS_BORDER_RIGHT_COLOR,
474
    flat::LIST_ROW_FOCUS_BORDER_RIGHT_COLOR_DARK,
475
    flat::LIST_ROW_FOCUS_BORDER_TOP_COLOR,
476
    flat::LIST_ROW_FOCUS_BORDER_TOP_COLOR_DARK,
477
    flat::LIST_ROW_FOCUS_BG,
478
    flat::LIST_ROW_FOCUS_BG_DARK,
479
    // .__azul_native-list-rows-row:hover, light AND dark. Declared in the
480
    // theme module — see `themes::flat::LIST_ROW_HOVER_BG` — because the dark
481
    // half of each pair needs a palette this file cannot see. Each light rule
482
    // is followed by its dark twin so the twin wins in dark mode.
483
    flat::LIST_HOVER_BORDER_BOTTOM_WIDTH,
484
    flat::LIST_HOVER_BORDER_BOTTOM_WIDTH_DARK,
485
    flat::LIST_HOVER_BORDER_LEFT_WIDTH,
486
    flat::LIST_HOVER_BORDER_LEFT_WIDTH_DARK,
487
    flat::LIST_HOVER_BORDER_RIGHT_WIDTH,
488
    flat::LIST_HOVER_BORDER_RIGHT_WIDTH_DARK,
489
    flat::LIST_HOVER_BORDER_TOP_WIDTH,
490
    flat::LIST_HOVER_BORDER_TOP_WIDTH_DARK,
491
    flat::LIST_HOVER_BORDER_BOTTOM_STYLE,
492
    flat::LIST_HOVER_BORDER_BOTTOM_STYLE_DARK,
493
    flat::LIST_HOVER_BORDER_LEFT_STYLE,
494
    flat::LIST_HOVER_BORDER_LEFT_STYLE_DARK,
495
    flat::LIST_HOVER_BORDER_RIGHT_STYLE,
496
    flat::LIST_HOVER_BORDER_RIGHT_STYLE_DARK,
497
    flat::LIST_HOVER_BORDER_TOP_STYLE,
498
    flat::LIST_HOVER_BORDER_TOP_STYLE_DARK,
499
    flat::LIST_ROW_HOVER_BORDER_BOTTOM_COLOR,
500
    flat::LIST_ROW_HOVER_BORDER_BOTTOM_COLOR_DARK,
501
    flat::LIST_ROW_HOVER_BORDER_LEFT_COLOR,
502
    flat::LIST_ROW_HOVER_BORDER_LEFT_COLOR_DARK,
503
    flat::LIST_ROW_HOVER_BORDER_RIGHT_COLOR,
504
    flat::LIST_ROW_HOVER_BORDER_RIGHT_COLOR_DARK,
505
    flat::LIST_ROW_HOVER_BORDER_TOP_COLOR,
506
    flat::LIST_ROW_HOVER_BORDER_TOP_COLOR_DARK,
507
    flat::LIST_ROW_HOVER_BG,
508
    flat::LIST_ROW_HOVER_BG_DARK,
509
    // .__azul_native-list-rows-row
510
    CssPropertyWithConditions::simple(CssProperty::PaddingRight(LayoutPaddingRightValue::Exact(
511
        LayoutPaddingRight {
512
            inner: PixelValue::const_px(0),
513
        },
514
    ))),
515
    CssPropertyWithConditions::simple(CssProperty::PaddingLeft(LayoutPaddingLeftValue::Exact(
516
        LayoutPaddingLeft {
517
            inner: PixelValue::const_px(0),
518
        },
519
    ))),
520
    CssPropertyWithConditions::simple(CssProperty::PaddingBottom(LayoutPaddingBottomValue::Exact(
521
        LayoutPaddingBottom {
522
            inner: PixelValue::const_px(2),
523
        },
524
    ))),
525
    CssPropertyWithConditions::simple(CssProperty::PaddingTop(LayoutPaddingTopValue::Exact(
526
        LayoutPaddingTop {
527
            inner: PixelValue::const_px(2),
528
        },
529
    ))),
530
    CssPropertyWithConditions::simple(CssProperty::FlexGrow(LayoutFlexGrowValue::Exact(
531
        LayoutFlexGrow {
532
            inner: FloatValue::const_new(1),
533
        },
534
    ))),
535
    CssPropertyWithConditions::simple(CssProperty::FlexDirection(LayoutFlexDirectionValue::Exact(
536
        LayoutFlexDirection::Row,
537
    ))),
538
    CssPropertyWithConditions::simple(CssProperty::BorderBottomWidth(
539
        LayoutBorderBottomWidthValue::Exact(LayoutBorderBottomWidth {
540
            inner: PixelValue::const_px(1),
541
        }),
542
    )),
543
    CssPropertyWithConditions::simple(CssProperty::BorderLeftWidth(
544
        LayoutBorderLeftWidthValue::Exact(LayoutBorderLeftWidth {
545
            inner: PixelValue::const_px(1),
546
        }),
547
    )),
548
    CssPropertyWithConditions::simple(CssProperty::BorderRightWidth(
549
        LayoutBorderRightWidthValue::Exact(LayoutBorderRightWidth {
550
            inner: PixelValue::const_px(1),
551
        }),
552
    )),
553
    CssPropertyWithConditions::simple(CssProperty::BorderTopWidth(
554
        LayoutBorderTopWidthValue::Exact(LayoutBorderTopWidth {
555
            inner: PixelValue::const_px(1),
556
        }),
557
    )),
558
    CssPropertyWithConditions::simple(CssProperty::BorderBottomStyle(
559
        StyleBorderBottomStyleValue::Exact(StyleBorderBottomStyle {
560
            inner: BorderStyle::Solid,
561
        }),
562
    )),
563
    CssPropertyWithConditions::simple(CssProperty::BorderLeftStyle(
564
        StyleBorderLeftStyleValue::Exact(StyleBorderLeftStyle {
565
            inner: BorderStyle::Solid,
566
        }),
567
    )),
568
    CssPropertyWithConditions::simple(CssProperty::BorderRightStyle(
569
        StyleBorderRightStyleValue::Exact(StyleBorderRightStyle {
570
            inner: BorderStyle::Solid,
571
        }),
572
    )),
573
    CssPropertyWithConditions::simple(CssProperty::BorderTopStyle(
574
        StyleBorderTopStyleValue::Exact(StyleBorderTopStyle {
575
            inner: BorderStyle::Solid,
576
        }),
577
    )),
578
    CssPropertyWithConditions::simple(CssProperty::BorderBottomColor(
579
        StyleBorderBottomColorValue::Exact(StyleBorderBottomColor {
580
            inner: ColorU {
581
                r: 255,
582
                g: 255,
583
                b: 255,
584
                a: 0,
585
            },
586
        }),
587
    )),
588
    CssPropertyWithConditions::simple(CssProperty::BorderLeftColor(
589
        StyleBorderLeftColorValue::Exact(StyleBorderLeftColor {
590
            inner: ColorU {
591
                r: 255,
592
                g: 255,
593
                b: 255,
594
                a: 0,
595
            },
596
        }),
597
    )),
598
    CssPropertyWithConditions::simple(CssProperty::BorderRightColor(
599
        StyleBorderRightColorValue::Exact(StyleBorderRightColor {
600
            inner: ColorU {
601
                r: 255,
602
                g: 255,
603
                b: 255,
604
                a: 0,
605
            },
606
        }),
607
    )),
608
    CssPropertyWithConditions::simple(CssProperty::BorderTopColor(
609
        StyleBorderTopColorValue::Exact(StyleBorderTopColor {
610
            inner: ColorU {
611
                r: 255,
612
                g: 255,
613
                b: 255,
614
                a: 0,
615
            },
616
        }),
617
    )),
618
];
619
const CSS_MATCH_7894335449545988724: CssPropertyWithConditionsVec =
620
    CssPropertyWithConditionsVec::from_const_slice(CSS_MATCH_7894335449545988724_PROPERTIES);
621

            
622
const IDS_AND_CLASSES_790316832563530605: &[IdOrClass] = &[Class(AzString::from_const_str(
623
    "__azul_native-list-rows-row",
624
))];
625
const ROW_CLASS: IdOrClassVec = IdOrClassVec::from_const_slice(IDS_AND_CLASSES_790316832563530605);
626

            
627
const IDS_AND_CLASSES_3034181810805097699: &[IdOrClass] = &[Class(AzString::from_const_str(
628
    "__azul_native-list-rows-row-cell",
629
))];
630
const CELL_CLASS: IdOrClassVec =
631
    IdOrClassVec::from_const_slice(IDS_AND_CLASSES_3034181810805097699);
632

            
633
const IDS_AND_CLASSES_6012478019077291002: &[IdOrClass] =
634
    &[Class(AzString::from_const_str("__azul_native-list-rows"))];
635
const ROW_CONTAINER_CLASS: IdOrClassVec =
636
    IdOrClassVec::from_const_slice(IDS_AND_CLASSES_6012478019077291002);
637

            
638
const IDS_AND_CLASSES_10742579426112804392: &[IdOrClass] =
639
    &[Class(AzString::from_const_str("__azul_native-list-header"))];
640
const HEADER_CONTAINER_CLASS: IdOrClassVec =
641
    IdOrClassVec::from_const_slice(IDS_AND_CLASSES_10742579426112804392);
642

            
643
const IDS_AND_CLASSES_9205819539370539587: &[IdOrClass] = &[Class(AzString::from_const_str(
644
    "__azul_native_list-container",
645
))];
646
const LIST_VIEW_CONTAINER_CLASS: IdOrClassVec =
647
    IdOrClassVec::from_const_slice(IDS_AND_CLASSES_9205819539370539587);
648

            
649
const IDS_AND_CLASSES_18330792117162403422: &[IdOrClass] = &[Class(AzString::from_const_str(
650
    "__azul_native-list-header-item",
651
))];
652
const COLUMN_NAME_CLASS: IdOrClassVec =
653
    IdOrClassVec::from_const_slice(IDS_AND_CLASSES_18330792117162403422);
654

            
655
const IDS_AND_CLASSES_SORT_ARROW: &[IdOrClass] = &[Class(AzString::from_const_str(
656
    "__azul_native-list-header-arrow-down",
657
))];
658
const SORT_ARROW_CLASS: IdOrClassVec = IdOrClassVec::from_const_slice(IDS_AND_CLASSES_SORT_ARROW);
659

            
660
/// The sort indicator a header shows on the column the list is sorted by.
661
///
662
/// `sorted_by` used to change nothing on screen: the three
663
/// `__azul_native-list-header-arrow-down*` rules had been in this widget's
664
/// stylesheet from the start and no element ever matched them. They describe a
665
/// rotated square with two shadowed edges — a CSS triangle — and rendering it
666
/// produced a filled grey SQUARE, because nothing clips the rotated box. The
667
/// indicator is a glyph instead, the same way the tree view draws its
668
/// disclosure chevrons, so it is a triangle at any size and inherits the
669
/// header's own colour.
670
2
fn sort_arrow() -> Dom {
671
2
    Dom::create_icon(AzString::from_const_str("arrow_drop_up"))
672
2
        .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
673
2
            SORT_ARROW_STYLE,
674
        ))
675
2
        .with_ids_and_classes(SORT_ARROW_CLASS)
676
2
}
677

            
678
/// A small glyph, vertically centred by the header item's own flex box, that
679
/// never competes with the label for width.
680
static SORT_ARROW_STYLE: &[CssPropertyWithConditions] = &[
681
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(14))),
682
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
683
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
684
        inner: ColorU {
685
            r: 0x67,
686
            g: 0x67,
687
            b: 0x67,
688
            a: 255,
689
        },
690
    })),
691
];
692

            
693
pub type ListViewOnLazyLoadScrollCallbackType =
694
    extern "C" fn(RefAny, CallbackInfo, ListViewState) -> Update;
695
impl_widget_callback!(
696
    ListViewOnLazyLoadScroll,
697
    OptionListViewOnLazyLoadScroll,
698
    ListViewOnLazyLoadScrollCallback,
699
    ListViewOnLazyLoadScrollCallbackType
700
);
701

            
702
azul_core::impl_managed_callback! {
703
    wrapper:        ListViewOnLazyLoadScrollCallback,
704
    info_ty:        CallbackInfo,
705
    return_ty:      Update,
706
    default_ret:    Update::DoNothing,
707
    invoker_static: LIST_VIEW_ON_LAZY_LOAD_SCROLL_INVOKER,
708
    invoker_ty:     AzListViewOnLazyLoadScrollCallbackInvoker,
709
    thunk_fn:       az_list_view_on_lazy_load_scroll_callback_thunk,
710
    setter_fn:      AzApp_setListViewOnLazyLoadScrollCallbackInvoker,
711
    from_handle_fn: AzListViewOnLazyLoadScrollCallback_createFromHostHandle,
712
    extra_args:     [ state: ListViewState ],
713
}
714

            
715
pub type ListViewOnColumnClickCallbackType =
716
    extern "C" fn(RefAny, CallbackInfo, ListViewState, column_clicked: usize) -> Update;
717
impl_widget_callback!(
718
    ListViewOnColumnClick,
719
    OptionListViewOnColumnClick,
720
    ListViewOnColumnClickCallback,
721
    ListViewOnColumnClickCallbackType
722
);
723

            
724
azul_core::impl_managed_callback! {
725
    wrapper:        ListViewOnColumnClickCallback,
726
    info_ty:        CallbackInfo,
727
    return_ty:      Update,
728
    default_ret:    Update::DoNothing,
729
    invoker_static: LIST_VIEW_ON_COLUMN_CLICK_INVOKER,
730
    invoker_ty:     AzListViewOnColumnClickCallbackInvoker,
731
    thunk_fn:       az_list_view_on_column_click_callback_thunk,
732
    setter_fn:      AzApp_setListViewOnColumnClickCallbackInvoker,
733
    from_handle_fn: AzListViewOnColumnClickCallback_createFromHostHandle,
734
    extra_args:     [ state: ListViewState, column_clicked: usize ],
735
}
736

            
737
pub type ListViewOnRowClickCallbackType =
738
    extern "C" fn(RefAny, CallbackInfo, ListViewState, row_clicked: usize) -> Update;
739
impl_widget_callback!(
740
    ListViewOnRowClick,
741
    OptionListViewOnRowClick,
742
    ListViewOnRowClickCallback,
743
    ListViewOnRowClickCallbackType
744
);
745

            
746
azul_core::impl_managed_callback! {
747
    wrapper:        ListViewOnRowClickCallback,
748
    info_ty:        CallbackInfo,
749
    return_ty:      Update,
750
    default_ret:    Update::DoNothing,
751
    invoker_static: LIST_VIEW_ON_ROW_CLICK_INVOKER,
752
    invoker_ty:     AzListViewOnRowClickCallbackInvoker,
753
    thunk_fn:       az_list_view_on_row_click_callback_thunk,
754
    setter_fn:      AzApp_setListViewOnRowClickCallbackInvoker,
755
    from_handle_fn: AzListViewOnRowClickCallback_createFromHostHandle,
756
    extra_args:     [ state: ListViewState, row_clicked: usize ],
757
}
758

            
759
/// State of the `ListView`, but without row data
760
#[derive(Debug, Clone)]
761
#[repr(C)]
762
pub struct ListViewState {
763
    /// Copy of the current column names
764
    pub columns: StringVec,
765
    /// Which column the rows are currently sorted by
766
    pub sorted_by: OptionUsize,
767
    /// Row count of rows currently loaded in the DOM
768
    pub current_row_count: usize,
769
    /// Y-offset currently applied to the rows
770
    pub scroll_offset: PixelValueNoPercent,
771
    /// Current position where the user has scrolled the `ListView` to
772
    pub current_scroll_position: LogicalPosition,
773
    /// Current height of the row container
774
    pub current_content_height: LogicalSize,
775
}
776

            
777
/// List view, optionally able to lazy-load data
778
#[derive(Debug, Clone)]
779
#[repr(C)]
780
pub struct ListView {
781
    /// Column names
782
    pub columns: StringVec,
783
    /// Currently rendered rows. Note that the `ListView` does not
784
    /// have to render all rows at once, usually you'd only render
785
    /// the top 100 rows
786
    pub rows: ListViewRowVec,
787
    /// Which column is the list view sorted by (default = None)?
788
    pub sorted_by: OptionUsize,
789
    /// Offset to add to the rows used when layouting row positions
790
    /// during lazy-loaded scrolling. Also affects the scroll position
791
    pub scroll_offset: PixelValueNoPercent,
792
    /// Height of the content, if not all rows are loaded
793
    pub content_height: OptionPixelValueNoPercent,
794
    /// Context menu for the columns (usually opens a context menu
795
    /// to select which columns to show)
796
    pub column_context_menu: OptionMenu,
797
    /// Indicates that this `ListView` is being lazily loaded, allows
798
    /// control over what happens when the user scrolls the `ListView`.
799
    pub on_lazy_load_scroll: OptionListViewOnLazyLoadScroll,
800
    /// What to do when the user left-clicks the column
801
    /// (usually used for storing which column to sort by)
802
    pub on_column_click: OptionListViewOnColumnClick,
803
    /// What to do when the user left-clicks a row
804
    /// (usually used for selecting the row depending on the state)
805
    pub on_row_click: OptionListViewOnRowClick,
806
}
807

            
808
impl Default for ListView {
809
53
    fn default() -> Self {
810
53
        Self {
811
53
            columns: StringVec::from_const_slice(&[]),
812
53
            rows: ListViewRowVec::from_const_slice(&[]),
813
53
            sorted_by: None.into(),
814
53
            scroll_offset: PixelValueNoPercent {
815
53
                inner: PixelValue::const_px(0),
816
53
            },
817
53
            content_height: None.into(),
818
53
            column_context_menu: None.into(),
819
53
            on_lazy_load_scroll: None.into(),
820
53
            on_column_click: None.into(),
821
53
            on_row_click: None.into(),
822
53
        }
823
53
    }
824
}
825

            
826
/// Row of the `ListView`
827
#[derive(Debug, Clone)]
828
#[repr(C)]
829
pub struct ListViewRow {
830
    /// Each cell is an opaque Dom object
831
    pub cells: DomVec,
832
    /// Height of the row, if known beforehand
833
    pub height: OptionPixelValueNoPercent,
834
}
835

            
836
impl_option!(ListViewRow, OptionListViewRow, copy = false, [Debug, Clone]);
837
impl_vec!(
838
    ListViewRow,
839
    ListViewRowVec,
840
    ListViewRowVecDestructor,
841
    ListViewRowVecDestructorType,
842
    ListViewRowVecSlice,
843
    OptionListViewRow
844
);
845
impl_vec_clone!(ListViewRow, ListViewRowVec, ListViewRowVecDestructor);
846
impl_vec_mut!(ListViewRow, ListViewRowVec);
847
impl_vec_debug!(ListViewRow, ListViewRowVec);
848

            
849
impl ListView {
850
    #[must_use]
851
20
    pub fn create(columns: StringVec) -> Self {
852
20
        Self {
853
20
            columns,
854
20
            ..Default::default()
855
20
        }
856
20
    }
857

            
858
    #[must_use]
859
3
    pub fn swap_with_default(&mut self) -> Self {
860
3
        let mut m = Self::default();
861
3
        core::mem::swap(&mut m, self);
862
3
        m
863
3
    }
864

            
865
    #[must_use]
866
3
    pub fn with_columns(mut self, columns: StringVec) -> Self {
867
3
        self.set_columns(columns);
868
3
        self
869
3
    }
870

            
871
5
    pub fn set_columns(&mut self, columns: StringVec) {
872
5
        self.columns = columns;
873
5
    }
874

            
875
    #[must_use]
876
10
    pub fn with_rows(mut self, rows: ListViewRowVec) -> Self {
877
10
        self.set_rows(rows);
878
10
        self
879
10
    }
880

            
881
11
    pub fn set_rows(&mut self, rows: ListViewRowVec) {
882
11
        self.rows = rows;
883
11
    }
884

            
885
    /// The half-open range `[first, last)` of row indices visible in a
886
    /// vertically-scrolled, fixed-row-height list — the windowing core for
887
    /// virtualizing a long `ListView` (render only these rows instead of all of
888
    /// them, the way the `MapWidget`'s `VirtualView` renders only visible tiles).
889
    /// `scroll_y` is pixels scrolled past the top, `viewport_height` the visible
890
    /// height; one extra row is included so a row straddling the bottom edge
891
    /// still renders. Returns `(0, 0)` for degenerate input (no rows, a
892
    /// non-positive/non-finite height, or non-finite scroll), and an empty range
893
    /// `(total, total)` once scrolled past the end.
894
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded layout/render numeric cast
895
    #[must_use]
896
123
    pub fn visible_row_range(
897
123
        scroll_y: f32,
898
123
        viewport_height: f32,
899
123
        row_height: f32,
900
123
        total_rows: usize,
901
123
    ) -> (usize, usize) {
902
123
        if total_rows == 0
903
120
            || !row_height.is_finite()
904
116
            || row_height <= 0.0
905
112
            || !viewport_height.is_finite()
906
109
            || viewport_height <= 0.0
907
106
            || !scroll_y.is_finite()
908
        {
909
21
            return (0, 0);
910
102
        }
911
102
        let first = (scroll_y.max(0.0) / row_height).floor() as usize;
912
102
        if first >= total_rows {
913
8
            return (total_rows, total_rows);
914
94
        }
915
        // Saturating: a sub-pixel `row_height` makes `viewport_height / row_height`
916
        // astronomically large, whose `as usize` cast saturates to `usize::MAX`, so
917
        // `+ 1` (and `first + visible`) would overflow. The `.min(total_rows)` clamp
918
        // makes the saturated value harmless.
919
94
        let visible = ((viewport_height / row_height).ceil() as usize).saturating_add(1);
920
94
        let last = first.saturating_add(visible).min(total_rows);
921
94
        (first, last)
922
123
    }
923

            
924
    #[must_use]
925
6
    pub const fn with_sorted_by(mut self, sorted_by: OptionUsize) -> Self {
926
6
        self.set_sorted_by(sorted_by);
927
6
        self
928
6
    }
929

            
930
8
    pub const fn set_sorted_by(&mut self, sorted_by: OptionUsize) {
931
8
        self.sorted_by = sorted_by;
932
8
    }
933

            
934
    #[must_use]
935
15
    pub const fn with_scroll_offset(mut self, scroll_offset: PixelValueNoPercent) -> Self {
936
15
        self.set_scroll_offset(scroll_offset);
937
15
        self
938
15
    }
939

            
940
17
    pub const fn set_scroll_offset(&mut self, scroll_offset: PixelValueNoPercent) {
941
17
        self.scroll_offset = scroll_offset;
942
17
    }
943

            
944
    #[must_use]
945
2
    pub fn with_content_height(mut self, content_height: PixelValueNoPercent) -> Self {
946
2
        self.set_content_height(content_height);
947
2
        self
948
2
    }
949

            
950
7
    pub fn set_content_height(&mut self, content_height: PixelValueNoPercent) {
951
7
        self.content_height = Some(content_height).into();
952
7
    }
953

            
954
    #[must_use]
955
2
    pub fn with_column_context_menu(mut self, context_menu: Menu) -> Self {
956
2
        self.set_column_context_menu(context_menu);
957
2
        self
958
2
    }
959

            
960
4
    pub fn set_column_context_menu(&mut self, column_context_menu: Menu) {
961
4
        self.column_context_menu = Some(column_context_menu).into();
962
4
    }
963

            
964
    #[must_use]
965
3
    pub fn with_on_column_click<C: Into<ListViewOnColumnClickCallback>>(
966
3
        mut self,
967
3
        refany: RefAny,
968
3
        on_column_click: C,
969
3
    ) -> Self {
970
3
        self.set_on_column_click(refany, on_column_click);
971
3
        self
972
3
    }
973

            
974
3
    pub fn set_on_column_click<C: Into<ListViewOnColumnClickCallback>>(
975
3
        &mut self,
976
3
        refany: RefAny,
977
3
        on_column_click: C,
978
3
    ) {
979
3
        self.on_column_click = Some(ListViewOnColumnClick {
980
3
            refany,
981
3
            callback: on_column_click.into(),
982
3
        })
983
3
        .into();
984
3
    }
985

            
986
    #[must_use]
987
5
    pub fn with_on_row_click<C: Into<ListViewOnRowClickCallback>>(
988
5
        mut self,
989
5
        refany: RefAny,
990
5
        on_row_click: C,
991
5
    ) -> Self {
992
5
        self.set_on_row_click(refany, on_row_click);
993
5
        self
994
5
    }
995

            
996
8
    pub fn set_on_row_click<C: Into<ListViewOnRowClickCallback>>(
997
8
        &mut self,
998
8
        refany: RefAny,
999
8
        on_row_click: C,
8
    ) {
8
        self.on_row_click = Some(ListViewOnRowClick {
8
            refany,
8
            callback: on_row_click.into(),
8
        })
8
        .into();
8
    }
    #[must_use]
23
    pub fn dom(self) -> Dom {
        // Snapshot the state handed to row/column click callbacks. Runtime-only
        // fields (scroll position / content height) aren't known at build time,
        // so they default to zero; columns/sorted_by/row-count/scroll-offset are.
23
        let state = ListViewState {
23
            columns: self.columns.clone(),
23
            sorted_by: self.sorted_by,
23
            current_row_count: self.rows.as_ref().len(),
23
            scroll_offset: self.scroll_offset,
23
            current_scroll_position: LogicalPosition::zero(),
23
            current_content_height: LogicalSize::zero(),
23
        };
23
        let on_column_click = self.on_column_click.clone();
23
        let on_row_click = self.on_row_click.clone();
23
        Dom::create_div()
23
            .with_css_props(CSS_MATCH_17553577885456905601)
23
            .with_ids_and_classes(LIST_VIEW_CONTAINER_CLASS)
23
            .with_children(DomVec::from_vec(vec![
                // header
23
                Dom::create_div()
23
                    .with_css_props(CSS_MATCH_15315949193378715186)
23
                    .with_ids_and_classes(HEADER_CONTAINER_CLASS)
23
                    .with_children(
23
                        self.columns
23
                            .iter()
23
                            .enumerate()
102
                            .map(|(col_index, col)| {
102
                                let mut col_dom = Dom::create_div()
102
                                    .with_css_props(CSS_MATCH_12498280255863106397)
102
                                    .with_ids_and_classes(COLUMN_NAME_CLASS)
102
                                    .with_child({
102
                                        crate::widgets::widget_p_with_text(col.clone())
102
                                            .with_css_props(CSS_MATCH_15673486787900743642)
                                    });
102
                                if self.sorted_by.into_option() == Some(col_index) {
2
                                    col_dom = col_dom.with_child(sort_arrow());
100
                                }
                                // Wire the click only when the app set a handler.
102
                                match &on_column_click {
3
                                    OptionListViewOnColumnClick::Some(_) => col_dom.with_callbacks(
3
                                        vec![CoreCallbackData {
3
                                            event: EventFilter::Hover(HoverEventFilter::Click),
3
                                            refany: RefAny::new(ColumnClickData {
3
                                                col_index,
3
                                                state: state.clone(),
3
                                                on_column_click: on_column_click.clone(),
3
                                            }),
3
                                            callback: CoreCallback {
3
                                                cb: on_list_view_column_click as usize,
3
                                                ctx: OptionRefAny::None,
3
                                            },
3
                                        }]
3
                                        .into(),
                                    ),
99
                                    OptionListViewOnColumnClick::None => col_dom,
                                }
102
                            })
23
                            .collect::<Vec<_>>()
23
                            .into(),
                    ),
                // rows
23
                Dom::create_div()
23
                    .with_css_props(CSS_MATCH_4852927511892172364)
23
                    .with_ids_and_classes(ROW_CONTAINER_CLASS)
23
                    .with_children(
23
                        self.rows
23
                            .into_iter()
23
                            .enumerate()
78
                            .map(|(row_index, row)| {
78
                                let row_dom = Dom::create_div()
78
                                    .with_css_props(CSS_MATCH_7894335449545988724)
78
                                    .with_ids_and_classes(ROW_CLASS)
78
                                    .with_tab_index(TabIndex::Auto)
            // Role so the accessibility tree knows what this IS:
            // a list, so a reader can say "3 of 12". The NAME comes from the widget's own text,
            // which azul derives when a readable label is present.
78
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
78
                role: azul_core::a11y::AccessibilityRole::List,
78
                ..Default::default()
78
            })
78
                                    .with_children(
78
                                        row.cells
78
                                            .as_ref()
78
                                            .iter()
4119
                                            .map(|cell| {
4119
                                                Dom::create_div()
4119
                                                    .with_css_props(CSS_MATCH_12980082330151137475)
4119
                                                    .with_ids_and_classes(CELL_CLASS)
4119
                                                    .with_child(cell.clone())
4119
                                            })
78
                                            .collect::<Vec<_>>()
78
                                            .into(),
                                    );
78
                                match &on_row_click {
70
                                    OptionListViewOnRowClick::Some(_) => row_dom.with_callbacks(
70
                                        vec![CoreCallbackData {
70
                                            event: EventFilter::Hover(HoverEventFilter::Click),
70
                                            refany: RefAny::new(RowClickData {
70
                                                row_index,
70
                                                state: state.clone(),
70
                                                on_row_click: on_row_click.clone(),
70
                                            }),
70
                                            callback: CoreCallback {
70
                                                cb: on_list_view_row_click as usize,
70
                                                ctx: OptionRefAny::None,
70
                                            },
70
                                        }]
70
                                        .into(),
                                    ),
8
                                    OptionListViewOnRowClick::None => row_dom,
                                }
78
                            })
23
                            .collect::<Vec<_>>()
23
                            .into(),
                    ),
            ]))
23
    }
}
/// Per-row data carried to the internal `MouseUp` handler (the row index plus a
/// snapshot of the list state and the app's `on_row_click` hook).
struct RowClickData {
    row_index: usize,
    state: ListViewState,
    on_row_click: OptionListViewOnRowClick,
}
/// Per-column equivalent of [`RowClickData`].
struct ColumnClickData {
    col_index: usize,
    state: ListViewState,
    on_column_click: OptionListViewOnColumnClick,
}
/// `MouseUp` on a row → invoke the app's `on_row_click(state, row_index)`.
extern "C" fn on_list_view_row_click(mut refany: RefAny, info: CallbackInfo) -> Update {
    let Some(data) = refany.downcast_ref::<RowClickData>() else {
        return Update::DoNothing;
    };
    match data.on_row_click.as_ref() {
        Some(ListViewOnRowClick {
            refany: user_data,
            callback,
        }) => (callback.cb)(user_data.clone(), info, data.state.clone(), data.row_index),
        None => Update::DoNothing,
    }
}
/// `MouseUp` on a column header → invoke the app's `on_column_click(state, col_index)`.
extern "C" fn on_list_view_column_click(mut refany: RefAny, info: CallbackInfo) -> Update {
    let Some(data) = refany.downcast_ref::<ColumnClickData>() else {
        return Update::DoNothing;
    };
    match data.on_column_click.as_ref() {
        Some(ListViewOnColumnClick {
            refany: user_data,
            callback,
        }) => (callback.cb)(user_data.clone(), info, data.state.clone(), data.col_index),
        None => Update::DoNothing,
    }
}
#[cfg(test)]
mod list_view_click_tests {
    use super::*;
    /// The windowing core for `ListView` virtualization: only the visible rows
    /// (+1 straddling the bottom) are in range, the range tracks scroll, clamps
    /// to the row count, and degenerate input yields an empty range.
    #[test]
1
    fn visible_row_range_windows_correctly() {
        // 100 rows x 20px, 200px viewport → 10 full rows + 1 partial.
1
        assert_eq!(ListView::visible_row_range(0.0, 200.0, 20.0, 100), (0, 11));
        // Scrolled 50px → first row = floor(50/20) = 2.
1
        assert_eq!(ListView::visible_row_range(50.0, 200.0, 20.0, 100), (2, 13));
        // Near the end → clamped to the row count.
1
        assert_eq!(
1
            ListView::visible_row_range(1900.0, 200.0, 20.0, 100),
            (95, 100)
        );
        // Scrolled past the end → empty range at the tail.
1
        assert_eq!(
1
            ListView::visible_row_range(5000.0, 200.0, 20.0, 100),
            (100, 100)
        );
        // Degenerate inputs → empty.
1
        assert_eq!(ListView::visible_row_range(0.0, 200.0, 20.0, 0), (0, 0));
1
        assert_eq!(ListView::visible_row_range(0.0, 200.0, 0.0, 100), (0, 0));
1
        assert_eq!(
1
            ListView::visible_row_range(f32::NAN, 200.0, 20.0, 100),
            (0, 0)
        );
1
    }
    extern "C" fn noop_row(_: RefAny, _: CallbackInfo, _: ListViewState, _: usize) -> Update {
        Update::DoNothing
    }
3
    fn empty_row() -> ListViewRow {
3
        ListViewRow {
3
            cells: DomVec::from_const_slice(&[]),
3
            height: None.into(),
3
        }
3
    }
    /// Rows must carry a click callback exactly when `on_row_click` is set —
    /// previously `dom()` wired nothing, so the hook was dead.
    #[test]
    #[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a
                                                  // struct literal is not clearer here
1
    fn rows_get_a_click_callback_only_when_on_row_click_is_set() {
1
        let mut lv = ListView::default();
1
        lv.rows = ListViewRowVec::from_vec(vec![empty_row(), empty_row()]);
1
        let on_row_click: ListViewOnRowClickCallbackType = noop_row;
1
        lv.set_on_row_click(RefAny::new(()), on_row_click);
1
        let dom = lv.dom();
        // children = [header, rows]; each row div carries the MouseUp callback.
1
        let rows = dom.children.as_ref()[1].children.as_ref();
1
        assert_eq!(rows.len(), 2);
3
        for row in rows {
2
            assert_eq!(
2
                row.root.callbacks.as_ref().len(),
                1,
                "row must carry the click callback when on_row_click is set"
            );
        }
        // Without the hook → no callbacks (opt-in, no wasted dispatch).
1
        let mut bare = ListView::default();
1
        bare.rows = ListViewRowVec::from_vec(vec![empty_row()]);
1
        let dom2 = bare.dom();
1
        let rows2 = dom2.children.as_ref()[1].children.as_ref();
1
        assert_eq!(rows2.len(), 1);
1
        assert!(
1
            rows2[0].root.callbacks.as_ref().is_empty(),
            "no callback when on_row_click is unset"
        );
1
    }
}
#[cfg(test)]
#[allow(clippy::float_cmp)] // exact float compares are deliberate here (saturation / identity
                            // checks)
mod autotest_generated {
    use azul_core::{
        dom::NodeType,
        menu::{MenuItem, MenuItemVec},
    };
    use azul_css::{
        dynamic_selector::{DynamicSelector, PseudoStateType, ThemeCondition},
        props::property::CssPropertyType,
    };
    use super::*;
    use crate::widgets::theme_probe;
    // ------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------
    fn cols(names: &[&str]) -> StringVec {
        StringVec::from_vec(names.iter().map(|s| AzString::from(*s)).collect::<Vec<_>>())
    }
    /// A row with `n` text cells (`n == 0` is allowed and deliberately used).
    fn row_with(n: usize) -> ListViewRow {
        ListViewRow {
            cells: DomVec::from_vec(
                (0..n)
                    .map(|i| {
                        Dom::create_text_do_not_use_without_block_level_wrapper(format!("c{i}"))
                    })
                    .collect::<Vec<_>>(),
            ),
            height: None.into(),
        }
    }
    fn px(v: f32) -> PixelValueNoPercent {
        PixelValueNoPercent {
            inner: PixelValue::px(v),
        }
    }
    extern "C" fn noop_row_cb(_: RefAny, _: CallbackInfo, _: ListViewState, _: usize) -> Update {
        Update::DoNothing
    }
    extern "C" fn noop_col_cb(_: RefAny, _: CallbackInfo, _: ListViewState, _: usize) -> Update {
        Update::DoNothing
    }
    /// The `[header, rows]` container pair every `ListView` DOM is built from.
    fn header_and_rows(dom: &Dom) -> (&Dom, &Dom) {
        let ch = dom.children.as_ref();
        assert_eq!(ch.len(), 2, "list view DOM = [header, rows]");
        (&ch[0], &ch[1])
    }
    /// The text of a text node, looking through the `<p>` block wrapper the
    /// label convention mandates (`p > text`).
    fn text_of(dom: &Dom) -> &str {
        match &dom.root.node_type {
            NodeType::Text(s) => s.as_ref().as_str(),
            NodeType::P => match dom.children.as_ref() {
                [only] => text_of(only),
                _ => panic!("a label <p> must wrap exactly one text node"),
            },
            _ => panic!("expected a text node"),
        }
    }
    // ------------------------------------------------------------------
    // `visible_row_range` — numeric core (zero / negative / NaN / limits)
    // ------------------------------------------------------------------
    /// Every degenerate input documented as "empty" really returns `(0, 0)`,
    /// including `-0.0` (which must count as non-positive, not as a valid height).
    #[test]
    fn visible_row_range_zero_and_degenerate_inputs_are_empty() {
        assert_eq!(ListView::visible_row_range(0.0, 100.0, 10.0, 0), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, 100.0, 0.0, 5), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, 100.0, -0.0, 5), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, 100.0, -10.0, 5), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, 0.0, 10.0, 5), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, -0.0, 10.0, 5), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, -100.0, 10.0, 5), (0, 0));
        assert_eq!(ListView::visible_row_range(0.0, 0.0, 0.0, 0), (0, 0));
    }
    /// A negative scroll offset (rubber-band / over-scroll) must clamp to the
    /// top window rather than wrapping through the `as usize` cast.
    #[test]
    fn visible_row_range_negative_scroll_clamps_to_the_top_window() {
        let top = ListView::visible_row_range(0.0, 200.0, 20.0, 100);
        assert_eq!(top, (0, 11), "10 full rows + 1 straddling the bottom edge");
        for s in [-0.0_f32, -1.0, -0.5, -1e9, -f32::MAX, -f32::MIN_POSITIVE] {
            assert_eq!(
                ListView::visible_row_range(s, 200.0, 20.0, 100),
                top,
                "negative scroll {s} must clamp to the top window"
            );
        }
    }
    /// NaN / ±inf in any float argument yields the documented empty range — no
    /// panic, no garbage index out of the float→int cast.
    #[test]
    fn visible_row_range_nan_and_infinite_inputs_are_empty() {
        for b in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            assert_eq!(
                ListView::visible_row_range(b, 200.0, 20.0, 100),
                (0, 0),
                "scroll_y = {b}"
            );
            assert_eq!(
                ListView::visible_row_range(0.0, b, 20.0, 100),
                (0, 0),
                "viewport_height = {b}"
            );
            assert_eq!(
                ListView::visible_row_range(0.0, 200.0, b, 100),
                (0, 0),
                "row_height = {b}"
            );
        }
        // All-NaN with the largest possible row count is still empty.
        assert_eq!(
            ListView::visible_row_range(f32::NAN, f32::NAN, f32::NAN, usize::MAX),
            (0, 0)
        );
    }
    /// Scrolling past the end returns the empty tail range, and a `scroll_y`
    /// large enough to saturate the `as usize` cast takes the same path.
    #[test]
    fn visible_row_range_past_the_end_is_an_empty_tail_range() {
        // 10 rows x 20px = 200px of content; scrolling exactly to the end.
        assert_eq!(
            ListView::visible_row_range(200.0, 100.0, 20.0, 10),
            (10, 10)
        );
        assert_eq!(
            ListView::visible_row_range(1e9, 200.0, 20.0, 100),
            (100, 100)
        );
        // f32::MAX / 20 overflows usize; the saturating cast keeps it >= total.
        assert_eq!(
            ListView::visible_row_range(f32::MAX, 200.0, 20.0, 100),
            (100, 100)
        );
        // ... one float ULP before the end is still a live window.
        let (first, last) = ListView::visible_row_range(199.0, 100.0, 20.0, 10);
        assert!(first < last, "just before the end the range is non-empty");
        assert_eq!(last, 10, "and clamps to the row count");
    }
    /// A huge `total_rows` must not make the window huge — only the viewport
    /// decides how many rows are returned.
    #[test]
    fn visible_row_range_window_size_is_bounded_by_the_viewport_not_the_row_count() {
        for total in [1_usize, 2, 1000, u32::MAX as usize, usize::MAX] {
            let (first, last) = ListView::visible_row_range(0.0, 200.0, 20.0, total);
            assert_eq!(first, 0);
            assert_eq!(
                last,
                11.min(total),
                "window stays viewport-sized for total_rows = {total}"
            );
        }
    }
    /// Property: whatever the inputs, the returned window is well-ordered,
    /// clamped to the row count, and actually covers the visible strip.
    #[test]
    fn visible_row_range_window_always_covers_the_viewport() {
        let total = 1000_usize;
        for &h in &[1.0_f32, 7.5, 20.0, 33.3] {
            for &vp in &[1.0_f32, 17.0, 200.0, 999.0] {
                for &s in &[0.0_f32, 0.1, 19.0, 123.456, 5000.0] {
                    let (first, last) = ListView::visible_row_range(s, vp, h, total);
                    assert!(first <= last, "well-ordered range for ({s}, {vp}, {h})");
                    assert!(last <= total, "range clamps to the row count");
                    if first == last {
                        continue; // empty tail range: nothing to cover
                    }
                    let top = first as f32 * h;
                    let bottom = last as f32 * h;
                    assert!(top <= s, "window starts at or above scroll {s} (top {top})");
                    let needed = (s + vp).min(total as f32 * h);
                    assert!(
                        bottom >= needed,
                        "window bottom {bottom} must reach {needed} for ({s}, {vp}, {h})"
                    );
                }
            }
        }
    }
    /// KNOWN BUG — pinned deliberately, do NOT weaken to make it pass.
    ///
    /// `visible_row_range` computes `(viewport_height / row_height).ceil() as
    /// usize + 1` and then `first + visible`. The float→int cast *saturates* to
    /// `usize::MAX`, so the `+ 1` (and the later addition) overflow and panic
    /// under the default dev/test `overflow-checks`. Both inputs below are
    /// finite, positive and pass every existing guard. Expected safe behaviour
    /// is to saturate and clamp to `total_rows`, as the doc comment promises.
    #[test]
    fn visible_row_range_does_not_overflow_on_extreme_but_finite_input() {
        // Sub-pixel row height (degenerate zoom): 1000 / 1e-30 = 1e33, which
        // saturates the cast to usize::MAX -> `+ 1` overflows.
        assert_eq!(ListView::visible_row_range(0.0, 1000.0, 1e-30, 10), (0, 10));
        // `first + visible` overflows even when neither term alone saturates:
        // ~1e19 + ~1e19 > usize::MAX (~1.84e19).
        let (first, last) = ListView::visible_row_range(1.0e19, 1.0e19, 1.0, usize::MAX);
        assert!(first > 0, "a huge scroll lands deep in the list");
        assert_eq!(last, usize::MAX, "the window must clamp to the row count");
    }
    // ------------------------------------------------------------------
    // Constructors / setters — round-trip + invariants
    // ------------------------------------------------------------------
    #[test]
    fn create_sets_columns_and_leaves_everything_else_default() {
        let lv = ListView::create(cols(&["a", "b", "c"]));
        assert_eq!(lv.columns.len(), 3);
        assert_eq!(lv.columns.as_ref()[1].as_str(), "b");
        assert!(lv.rows.is_empty());
        assert!(lv.sorted_by.is_none());
        assert!(lv.content_height.is_none());
        assert!(lv.column_context_menu.is_none());
        assert!(lv.on_lazy_load_scroll.is_none());
        assert!(lv.on_column_click.is_none());
        assert!(lv.on_row_click.is_none());
        assert_eq!(lv.scroll_offset, PixelValueNoPercent::zero());
        // An empty column list is accepted, not rejected or defaulted.
        let empty = ListView::create(StringVec::from_const_slice(&[]));
        assert!(empty.columns.is_empty());
    }
    #[test]
    fn with_and_set_columns_replace_rather_than_append() {
        let b = cols(&["x", "y"]);
        let lv = ListView::default()
            .with_columns(cols(&["one"]))
            .with_columns(b.clone());
        assert_eq!(lv.columns, b, "the last write wins");
        let mut m = ListView::default();
        m.set_columns(b.clone());
        assert_eq!(m.columns, b);
        m.set_columns(StringVec::from_const_slice(&[]));
        assert!(m.columns.is_empty(), "columns can be cleared again");
    }
    /// Column names are opaque payload: empty strings, interior NULs, astral /
    /// ZWJ / RTL / combining sequences and very long strings must survive the
    /// builder *and* the DOM build byte-for-byte.
    #[test]
    fn columns_round_trip_unicode_and_pathological_strings() {
        let names: Vec<String> = vec![
            String::new(),
            "\u{0}".to_string(),
            "🦀👨‍👩‍👧‍👦".to_string(),
            "مرحبا بالعالم".to_string(),
            "e\u{301}\u{301}\u{301}".to_string(),
            "\u{feff}leading BOM".to_string(),
            "line\nbreak\ttab".to_string(),
            "x".repeat(10_000),
        ];
        let sv = StringVec::from_vec(
            names
                .iter()
                .map(|s| AzString::from(s.clone()))
                .collect::<Vec<_>>(),
        );
        let lv = ListView::default().with_columns(sv);
        assert_eq!(lv.columns.len(), names.len());
        for (got, want) in lv.columns.iter().zip(names.iter()) {
            assert_eq!(got.as_str(), want.as_str(), "column name must round-trip");
        }
        let dom = lv.dom();
        let (header, _) = header_and_rows(&dom);
        let hdr = header.children.as_ref();
        assert_eq!(hdr.len(), names.len());
        for (col, want) in hdr.iter().zip(names.iter()) {
            let text = col.children.as_ref();
            assert_eq!(text.len(), 1, "each header cell holds one text node");
            assert_eq!(text_of(&text[0]), want.as_str());
        }
    }
    #[test]
    fn with_and_set_rows_round_trip_including_empty_and_ragged_rows() {
        let lv = ListView::default().with_rows(ListViewRowVec::from_vec(vec![
            row_with(0),
            row_with(1),
            row_with(5),
        ]));
        assert_eq!(lv.rows.len(), 3);
        assert_eq!(lv.rows.as_ref()[0].cells.len(), 0);
        assert_eq!(lv.rows.as_ref()[2].cells.len(), 5);
        let mut m = ListView::default().with_rows(ListViewRowVec::from_vec(vec![row_with(2)]));
        m.set_rows(ListViewRowVec::from_const_slice(&[]));
        assert!(m.rows.is_empty(), "rows can be cleared again");
    }
    /// `sorted_by` is a raw column index with no validation — an out-of-range
    /// value is stored verbatim and must not break the DOM build.
    #[test]
    fn sorted_by_is_stored_verbatim_even_when_out_of_range() {
        for v in [None, Some(0_usize), Some(2), Some(usize::MAX)] {
            let lv = ListView::create(cols(&["a", "b"])).with_sorted_by(v.into());
            assert_eq!(
                lv.sorted_by.as_ref().copied(),
                v,
                "sorted_by is not validated against the column count"
            );
            let dom = lv.dom();
            let (header, _) = header_and_rows(&dom);
            assert_eq!(header.children.as_ref().len(), 2);
        }
        let mut m = ListView::default();
        m.set_sorted_by(Some(7_usize).into());
        assert_eq!(m.sorted_by.as_ref().copied(), Some(7));
        m.set_sorted_by(None.into());
        assert!(m.sorted_by.is_none(), "sorted_by can be reset to None");
    }
    /// The fixed-point `PixelValue` encoding saturates (NaN -> 0, ±inf -> the
    /// isize limits) instead of trapping, and the setter stores the value bit
    /// for bit.
    #[test]
    fn scroll_offset_round_trips_extreme_and_non_finite_values() {
        for v in [
            0.0_f32,
            -0.0,
            1.0,
            -1.0,
            0.001,
            -12345.678,
            f32::MAX,
            f32::MIN,
            f32::MIN_POSITIVE,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ] {
            let p = px(v);
            let lv = ListView::default().with_scroll_offset(p);
            assert_eq!(lv.scroll_offset, p, "scroll_offset stored verbatim ({v})");
            let got = lv.scroll_offset.inner.number.get();
            assert!(
                got.is_finite(),
                "encoded offset stays finite for {v} (got {got})"
            );
        }
        assert_eq!(px(f32::NAN).inner.number.get(), 0.0, "NaN saturates to 0");
        assert!(px(f32::INFINITY).inner.number.get() > 0.0);
        assert!(px(f32::NEG_INFINITY).inner.number.get() < 0.0);
        let mut m = ListView::default();
        m.set_scroll_offset(px(5.0));
        m.set_scroll_offset(px(-5.0));
        assert_eq!(m.scroll_offset, px(-5.0), "the last write wins");
    }
    /// `PixelValueNoPercent` does not actually reject a `%` metric — the setter
    /// takes whatever it is handed. Pinned so a future validation change is a
    /// deliberate decision, not a silent one.
    #[test]
    fn scroll_offset_accepts_a_percent_metric_despite_the_type_name() {
        let percent = PixelValueNoPercent {
            inner: PixelValue::percent(50.0),
        };
        let lv = ListView::default().with_scroll_offset(percent);
        assert_eq!(lv.scroll_offset, percent);
        assert_eq!(lv.scroll_offset.inner.metric, SizeMetric::Percent);
    }
    #[test]
    fn content_height_wraps_in_some_and_has_no_clearing_setter() {
        let mut m = ListView::default();
        assert!(m.content_height.is_none(), "unset by default");
        for v in [0.0_f32, -1.0, f32::MAX, f32::NAN, f32::NEG_INFINITY] {
            let p = px(v);
            m.set_content_height(p);
            assert_eq!(m.content_height.as_ref(), Some(&p), "stores {v} verbatim");
            assert!(m
                .content_height
                .as_ref()
                .expect("just set")
                .inner
                .number
                .get()
                .is_finite());
        }
        assert!(
            m.content_height.is_some(),
            "Some() is sticky — no unset API"
        );
        let lv = ListView::default().with_content_height(px(42.0));
        assert_eq!(lv.content_height.as_ref(), Some(&px(42.0)));
    }
    #[test]
    fn column_context_menu_is_stored_and_replaced() {
        let mut m = ListView::default();
        assert!(m.column_context_menu.is_none());
        let empty_menu = Menu::create(MenuItemVec::from_const_slice(&[]));
        m.set_column_context_menu(empty_menu.clone());
        assert_eq!(
            m.column_context_menu.as_ref(),
            Some(&empty_menu),
            "an empty menu is accepted, not silently dropped"
        );
        let full = Menu::create(MenuItemVec::from_vec(vec![MenuItem::Separator; 256]));
        m.set_column_context_menu(full.clone());
        assert_eq!(
            m.column_context_menu.as_ref(),
            Some(&full),
            "last write wins"
        );
        assert!(
            m.column_context_menu.is_some(),
            "there is no way to unset it"
        );
        let lv = ListView::default().with_column_context_menu(full.clone());
        assert_eq!(lv.column_context_menu.as_ref(), Some(&full));
        // The menu is metadata only — it must not alter the DOM shape.
        let dom = lv.dom();
        let (header, rows) = header_and_rows(&dom);
        assert!(header.children.as_ref().is_empty());
        assert!(rows.children.as_ref().is_empty());
    }
    #[test]
    fn click_hook_setters_replace_rather_than_accumulate() {
        let rcb: ListViewOnRowClickCallbackType = noop_row_cb;
        let ccb: ListViewOnColumnClickCallbackType = noop_col_cb;
        let mut m = ListView::default();
        assert!(m.on_row_click.is_none());
        assert!(m.on_column_click.is_none());
        m.set_on_row_click(RefAny::new(1_u32), rcb);
        m.set_on_row_click(RefAny::new(2_u32), rcb);
        assert!(m.on_row_click.is_some());
        let mut payload = m.on_row_click.as_ref().expect("just set").refany.clone();
        assert_eq!(
            *payload.downcast_ref::<u32>().expect("u32 payload"),
            2,
            "the second registration replaces the first"
        );
        let lv = ListView::default()
            .with_on_row_click(RefAny::new(()), rcb)
            .with_on_column_click(RefAny::new(()), ccb);
        assert!(lv.on_row_click.is_some());
        assert!(lv.on_column_click.is_some());
        assert!(
            lv.on_lazy_load_scroll.is_none(),
            "unrelated hooks stay unset"
        );
    }
    // ------------------------------------------------------------------
    // `swap_with_default`
    // ------------------------------------------------------------------
    #[test]
    fn swap_with_default_moves_state_out_and_leaves_a_pristine_default() {
        let rcb: ListViewOnRowClickCallbackType = noop_row_cb;
        let mut lv = ListView::create(cols(&["a", "b"]))
            .with_rows(ListViewRowVec::from_vec(vec![row_with(1)]))
            .with_sorted_by(Some(1_usize).into())
            .with_scroll_offset(px(9.0))
            .with_content_height(px(1000.0))
            .with_column_context_menu(Menu::create(MenuItemVec::from_const_slice(&[])))
            .with_on_row_click(RefAny::new(()), rcb);
        let taken = lv.swap_with_default();
        assert_eq!(taken.columns.len(), 2);
        assert_eq!(taken.rows.len(), 1);
        assert_eq!(taken.sorted_by.as_ref().copied(), Some(1));
        assert_eq!(taken.scroll_offset, px(9.0));
        assert!(taken.content_height.is_some());
        assert!(taken.column_context_menu.is_some());
        assert!(taken.on_row_click.is_some());
        assert!(lv.columns.is_empty());
        assert!(lv.rows.is_empty());
        assert!(lv.sorted_by.is_none());
        assert_eq!(lv.scroll_offset, PixelValueNoPercent::zero());
        assert!(lv.content_height.is_none());
        assert!(lv.column_context_menu.is_none());
        assert!(lv.on_row_click.is_none());
        assert!(lv.on_column_click.is_none());
        assert!(lv.on_lazy_load_scroll.is_none());
        // Repeated swaps of an already-default value are a no-op, not a
        // double-free of the moved-out heap buffers.
        let again = lv.swap_with_default();
        assert!(again.columns.is_empty() && again.rows.is_empty());
        let third = lv.swap_with_default();
        assert!(third.columns.is_empty() && third.rows.is_empty());
        drop(taken);
    }
    // ------------------------------------------------------------------
    // `dom()` — shape + callback wiring
    // ------------------------------------------------------------------
    #[test]
    fn dom_shape_matches_the_column_and_row_counts() {
        let empty = ListView::default().dom();
        let (h, r) = header_and_rows(&empty);
        assert!(h.children.as_ref().is_empty());
        assert!(r.children.as_ref().is_empty());
        // Columns without rows and rows without columns are both legal.
        let no_rows = ListView::create(cols(&["a", "b"])).dom();
        let (h, r) = header_and_rows(&no_rows);
        assert_eq!(h.children.as_ref().len(), 2);
        assert!(r.children.as_ref().is_empty());
        let no_cols = ListView::default()
            .with_rows(ListViewRowVec::from_vec(vec![row_with(3)]))
            .dom();
        let (h, r) = header_and_rows(&no_cols);
        assert!(h.children.as_ref().is_empty());
        assert_eq!(r.children.as_ref().len(), 1);
        assert_eq!(
            r.children.as_ref()[0].children.as_ref().len(),
            3,
            "cells are rendered even with no matching column headers"
        );
        // Ragged rows keep their own cell counts (no padding to the column count).
        let ragged = ListView::create(cols(&["a", "b", "c"]))
            .with_rows(ListViewRowVec::from_vec(vec![
                row_with(0),
                row_with(1),
                row_with(3),
                row_with(7),
            ]))
            .dom();
        let (h, r) = header_and_rows(&ragged);
        assert_eq!(h.children.as_ref().len(), 3);
        let rows = r.children.as_ref();
        assert_eq!(rows.len(), 4);
        for (row, want) in rows.iter().zip([0_usize, 1, 3, 7]) {
            assert_eq!(row.children.as_ref().len(), want);
            for cell in row.children.as_ref() {
                assert_eq!(cell.children.as_ref().len(), 1, "one child per cell");
            }
        }
    }
    /// The wired-in `MouseUp` handler must receive the *right* index and a
    /// faithful snapshot of the list state — this exercises the exact
    /// `downcast_ref` path `on_list_view_{row,column}_click` take.
    #[test]
    fn dom_wires_click_payloads_with_the_right_index_and_state_snapshot() {
        let rcb: ListViewOnRowClickCallbackType = noop_row_cb;
        let ccb: ListViewOnColumnClickCallbackType = noop_col_cb;
        let lv = ListView::create(cols(&["c0", "c1"]))
            .with_rows(ListViewRowVec::from_vec(vec![
                row_with(2),
                row_with(2),
                row_with(2),
            ]))
            .with_sorted_by(Some(1_usize).into())
            .with_scroll_offset(px(-17.5))
            .with_on_row_click(RefAny::new(()), rcb)
            .with_on_column_click(RefAny::new(()), ccb);
        let dom = lv.dom();
        let (header, rows) = header_and_rows(&dom);
        for (i, col) in header.children.as_ref().iter().enumerate() {
            let cbs = col.root.callbacks.as_ref();
            assert_eq!(cbs.len(), 1);
            assert!(matches!(
                cbs[0].event,
                EventFilter::Hover(HoverEventFilter::Click)
            ));
            assert_eq!(cbs[0].callback.cb, on_list_view_column_click as usize);
            let mut any = cbs[0].refany.clone();
            let data = any
                .downcast_ref::<ColumnClickData>()
                .expect("ColumnClickData payload");
            assert_eq!(data.col_index, i, "each header carries its own index");
            assert_eq!(data.state.current_row_count, 3);
            assert_eq!(data.state.columns.len(), 2);
            assert_eq!(data.state.sorted_by.as_ref().copied(), Some(1));
            assert_eq!(data.state.scroll_offset, px(-17.5));
            assert!(data.on_column_click.is_some());
        }
        for (i, row) in rows.children.as_ref().iter().enumerate() {
            let cbs = row.root.callbacks.as_ref();
            assert_eq!(cbs.len(), 1);
            assert!(matches!(
                cbs[0].event,
                EventFilter::Hover(HoverEventFilter::Click)
            ));
            assert_eq!(cbs[0].callback.cb, on_list_view_row_click as usize);
            let mut any = cbs[0].refany.clone();
            let data = any
                .downcast_ref::<RowClickData>()
                .expect("RowClickData payload");
            assert_eq!(data.row_index, i, "each row carries its own index");
            assert_eq!(data.state.current_row_count, 3);
            assert!(data.on_row_click.is_some());
        }
    }
    /// Row and column hooks are wired independently — setting one must not
    /// attach a dispatcher to the other.
    #[test]
    fn click_callbacks_are_wired_per_hook_and_only_when_set() {
        let rcb: ListViewOnRowClickCallbackType = noop_row_cb;
        let ccb: ListViewOnColumnClickCallbackType = noop_col_cb;
        let bare = ListView::create(cols(&["a", "b"])).dom();
        let (h, _) = header_and_rows(&bare);
        for col in h.children.as_ref() {
            assert!(
                col.root.callbacks.as_ref().is_empty(),
                "no hook, no dispatch"
            );
        }
        let row_only = ListView::create(cols(&["a"]))
            .with_rows(ListViewRowVec::from_vec(vec![row_with(1)]))
            .with_on_row_click(RefAny::new(()), rcb)
            .dom();
        let (h, r) = header_and_rows(&row_only);
        assert!(h.children.as_ref()[0].root.callbacks.as_ref().is_empty());
        assert_eq!(r.children.as_ref()[0].root.callbacks.as_ref().len(), 1);
        let col_only = ListView::create(cols(&["a"]))
            .with_rows(ListViewRowVec::from_vec(vec![row_with(1)]))
            .with_on_column_click(RefAny::new(()), ccb)
            .dom();
        let (h, r) = header_and_rows(&col_only);
        assert_eq!(h.children.as_ref()[0].root.callbacks.as_ref().len(), 1);
        assert!(r.children.as_ref()[0].root.callbacks.as_ref().is_empty());
    }
    /// A wrong-typed payload must make the internal handlers bail out rather
    /// than reinterpreting foreign memory. `CallbackInfo` cannot be built here
    /// without the full `LayoutWindow` harness, so this pins the guard that
    /// runs *before* any `CallbackInfo` use: the `downcast_ref` type check.
    #[test]
    fn click_handler_payload_downcast_rejects_foreign_types() {
        let mut wrong = RefAny::new(0_u64);
        assert!(
            wrong.downcast_ref::<RowClickData>().is_none(),
            "handler must not accept a foreign payload type"
        );
        assert!(wrong.downcast_ref::<ColumnClickData>().is_none());
        // ... and a RowClickData payload is not mistaken for a ColumnClickData.
        let mut row_payload = RefAny::new(RowClickData {
            row_index: 0,
            state: ListViewState {
                columns: StringVec::from_const_slice(&[]),
                sorted_by: None.into(),
                current_row_count: 0,
                scroll_offset: PixelValueNoPercent::zero(),
                current_scroll_position: LogicalPosition::zero(),
                current_content_height: LogicalSize::zero(),
            },
            on_row_click: None.into(),
        });
        assert!(row_payload.downcast_ref::<ColumnClickData>().is_none());
        assert!(row_payload.downcast_ref::<RowClickData>().is_some());
    }
    #[test]
    fn dom_survives_a_large_column_and_row_count() {
        const N_COLS: usize = 64;
        const N_ROWS: usize = 64;
        let rcb: ListViewOnRowClickCallbackType = noop_row_cb;
        let names = (0..N_COLS)
            .map(|i| AzString::from(format!("col{i}")))
            .collect::<Vec<_>>();
        let rows = (0..N_ROWS).map(|_| row_with(N_COLS)).collect::<Vec<_>>();
        let dom = ListView::create(StringVec::from_vec(names))
            .with_rows(ListViewRowVec::from_vec(rows))
            .with_on_row_click(RefAny::new(()), rcb)
            .dom();
        let (h, r) = header_and_rows(&dom);
        assert_eq!(h.children.as_ref().len(), N_COLS);
        assert_eq!(r.children.as_ref().len(), N_ROWS);
        for row in r.children.as_ref() {
            assert_eq!(row.children.as_ref().len(), N_COLS);
            assert_eq!(row.root.callbacks.as_ref().len(), 1);
        }
    }
    // ------------------------------------------------------------------
    // Interactive states — the theme's contribution
    // ------------------------------------------------------------------
    /// The property types of the declarations on `node` gated on `state`,
    /// split into the light half (no theme condition) and the dark twins
    /// (gated on the dark theme as well). Each entry carries its position in
    /// declaration order, and both halves are sorted by type so they line up.
    /// `(property type, count)` per declaration kind — one vec for the light
    /// state rules on a node, one for their dark twins. Named because clippy's
    /// `type_complexity` (pedantic, on in this crate) refuses the tuple inline.
    type StateCounts = Vec<(CssPropertyType, usize)>;
    fn state_halves(node: &Dom, state: PseudoStateType) -> (StateCounts, StateCounts) {
        let mut light = Vec::new();
        let mut dark = Vec::new();
        for (i, (p, conds)) in node.root.style.iter_inline_properties().enumerate() {
            let conds = conds.as_ref();
            let gated_on_state = conds
                .iter()
                .any(|c| matches!(c, DynamicSelector::PseudoState(s) if *s == state));
            if !gated_on_state {
                continue;
            }
            let dark_gated = conds
                .iter()
                .any(|c| matches!(c, DynamicSelector::Theme(ThemeCondition::Dark)));
            if dark_gated {
                dark.push((p.get_type(), i));
            } else {
                light.push((p.get_type(), i));
            }
        }
        light.sort();
        dark.sort();
        (light, dark)
    }
    /// The hover / pressed / focus rules moved OUT of this file and into the
    /// theme module — a move nothing else in this suite would notice: no
    /// compiler error, and every other assertion still passes if a slice
    /// silently drops a rule or a dark twin. So this counts what a rendered
    /// column header and row actually carry, per state, light and dark.
    #[test]
    fn dom_carries_the_themes_header_and_row_states_with_dark_twins() {
        let dom = ListView::create(cols(&["a"]))
            .with_rows(ListViewRowVec::from_vec(vec![row_with(1)]))
            .dom();
        let (header, rows) = header_and_rows(&dom);
        let header_item = &header.children.as_ref()[0];
        let row = &rows.children.as_ref()[0];
        // (what, node, state, how many light rules it declares in that state)
        let expected = [
            // a hovered header: the bottom edge (width, style, colour) + the face
            ("header item", header_item, PseudoStateType::Hover, 4),
            // a pressed header: four inset shadows, four edges x (width, style,
            // colour), + the face
            ("header item", header_item, PseudoStateType::Active, 17),
            // a header does not take focus
            ("header item", header_item, PseudoStateType::Focus, 0),
            // a hovered row: four edges x (width, style, colour) + the fill
            ("row", row, PseudoStateType::Hover, 13),
            // the focused row: the same ring and fill in stronger colours
            ("row", row, PseudoStateType::Focus, 13),
            // a row is chosen on release, not on press
            ("row", row, PseudoStateType::Active, 0),
        ];
        for (what, node, state, want) in expected {
            let (light, dark) = state_halves(node, state);
            assert_eq!(
                light.len(),
                want,
                "{what} {state:?}: expected {want} light rule(s), got {light:?}",
            );
            let types = |half: &[(CssPropertyType, usize)]| {
                half.iter().map(|(t, _)| *t).collect::<Vec<_>>()
            };
            assert_eq!(
                types(light.as_slice()),
                types(dark.as_slice()),
                "{what} {state:?}: every light rule needs a dark twin on the same property, or \
                 the {what} keeps its light-mode look on a dark surface",
            );
            // Inline CSS is last-wins, so a twin must FOLLOW its light rule or
            // dark mode would never see it.
            for ((t, light_at), (_, dark_at)) in light.iter().zip(&dark) {
                assert!(
                    light_at < dark_at,
                    "{what} {state:?} {t}: the dark twin is declared before its light rule, so \
                     the light rule wins in dark mode",
                );
            }
        }
        // And the dark declarations really are gated, not unconditional.
        assert!(
            !theme_probe::dark(row).is_empty() && !theme_probe::dark(header_item).is_empty(),
            "the theme contributed no dark-mode declarations at all"
        );
    }
}