1
//! Pagination widget — a page-number navigator: `Prev`, a joined row of
2
//! page-number buttons, then `Next`. A near-clone of
3
//! [`crate::widgets::segmented::Segmented`] (a joined button bar whose clicked
4
//! item is derived from sibling position and whose active item is live-restyled
5
//! via `set_css_property`), specialised to page navigation.
6
//!
7
//! State is `{ current_page, total_pages }` (`current_page` is 1-based). Clicking
8
//! a page button selects it; clicking `Prev`/`Next` steps one page within
9
//! `[1, total_pages]`. Any change updates `current_page`, invokes the optional
10
//! `on_change(state)`, and live-restyles every button (the active page gets the
11
//! accent fill + white text; the others the neutral fill). `Prev`/`Next` show a
12
//! muted "disabled" text colour (style only) when `current_page` is at the
13
//! respective end; clicking a disabled end (or the already-current page) is a
14
//! no-op (returns `Update::DoNothing`, fires no callback).
15
//!
16
//! Index derivation: the children are `[Prev, page1 … pageN, Next]`, so page `p`
17
//! sits at sibling position `p`, `Prev` at position `0` and `Next` at the last
18
//! position. The handler reads the clicked node's position and the live child
19
//! count, so it stays correct regardless of `total_pages` drift.
20
//!
21
//! Key types: [`Pagination`], [`PaginationState`], [`PaginationOnChange`].
22

            
23
use std::vec::Vec;
24

            
25
use azul_core::{
26
    callbacks::{CoreCallbackData, Update},
27
    dom::{Dom, IdOrClass, IdOrClass::Class, IdOrClassVec, TabIndex},
28
    refany::RefAny,
29
};
30
use azul_css::{
31
    dynamic_selector::{
32
        CssPropertyWithConditions, CssPropertyWithConditionsVec, OptionCssPropertyWithConditionsVec,
33
    },
34
    impl_option_inner,
35
    props::{
36
        basic::{color::ColorU, StyleFontSize},
37
        layout::{
38
            LayoutAlignItems, LayoutAlignSelf, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow,
39
            LayoutJustifyContent, LayoutMinWidth, LayoutPaddingBottom, LayoutPaddingLeft,
40
            LayoutPaddingRight, LayoutPaddingTop,
41
        },
42
        property::{CssProperty, *},
43
        style::{
44
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
45
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
46
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
47
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
48
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
49
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
50
            StyleTextAlign, StyleTextColor, StyleUserSelect,
51
        },
52
    },
53
    AzString,
54
};
55

            
56
use crate::callbacks::{Callback, CallbackInfo};
57

            
58
static PAGINATION_CLASS: &[IdOrClass] =
59
    &[Class(AzString::from_const_str("__azul-native-pagination"))];
60
static PAGINATION_PAGE_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
61
    "__azul-native-pagination-page",
62
))];
63
static PAGINATION_NAV_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
64
    "__azul-native-pagination-nav",
65
))];
66

            
67
const PREV_LABEL: AzString = AzString::from_const_str("Prev");
68
const NEXT_LABEL: AzString = AzString::from_const_str("Next");
69

            
70
/// Callback function type invoked when the current page changes.
71
pub type PaginationOnChangeCallbackType =
72
    extern "C" fn(RefAny, CallbackInfo, PaginationState) -> Update;
73
impl_widget_callback!(
74
    PaginationOnChange,
75
    OptionPaginationOnChange,
76
    PaginationOnChangeCallback,
77
    PaginationOnChangeCallbackType
78
);
79

            
80
azul_core::impl_managed_callback! {
81
    wrapper:        PaginationOnChangeCallback,
82
    info_ty:        CallbackInfo,
83
    return_ty:      Update,
84
    default_ret:    Update::DoNothing,
85
    invoker_static: PAGINATION_ON_CHANGE_INVOKER,
86
    invoker_ty:     AzPaginationOnChangeCallbackInvoker,
87
    thunk_fn:       az_pagination_on_change_callback_thunk,
88
    setter_fn:      AzApp_setPaginationOnChangeCallbackInvoker,
89
    from_handle_fn: AzPaginationOnChangeCallback_createFromHostHandle,
90
    extra_args:     [ state: PaginationState ],
91
}
92

            
93
/// A `Prev` / page-numbers / `Next` page navigator with a change callback.
94
#[derive(Debug, Clone, PartialEq, Eq)]
95
#[repr(C)]
96
pub struct Pagination {
97
    pub pagination_state: PaginationStateWrapper,
98
    /// Style for the row container, or `None` for "no opinion" — in which case
99
    /// the widget's default applies.
100
    ///
101
    /// `None` and `Some(empty)` are different answers: the first means the
102
    /// widget picks, the second means the caller asked for no properties at all
103
    /// and gets none.
104
    pub container_style: OptionCssPropertyWithConditionsVec,
105
}
106

            
107
#[derive(Debug, Default, Clone, PartialEq, Eq)]
108
#[repr(C)]
109
pub struct PaginationStateWrapper {
110
    /// The current page + total page count.
111
    pub inner: PaginationState,
112
    /// Optional: function to call when the current page changes.
113
    pub on_change: OptionPaginationOnChange,
114
}
115

            
116
/// State of a [`Pagination`]: the current (1-based) page and the total page count.
117
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
118
#[repr(C)]
119
pub struct PaginationState {
120
    /// The 1-based index of the current page.
121
    pub current_page: usize,
122
    /// The total number of pages.
123
    pub total_pages: usize,
124
}
125

            
126
// ---- colours (mirroring segmented's palette) ----
127
/// Page border colour (#ced4da).
128
const PAGE_BORDER_COLOR: ColorU = ColorU {
129
    r: 206,
130
    g: 212,
131
    b: 218,
132
    a: 255,
133
};
134
/// Active-page background (#0d6efd, accent blue).
135
const ACCENT_BG_COLOR: ColorU = ColorU {
136
    r: 13,
137
    g: 110,
138
    b: 253,
139
    a: 255,
140
};
141
/// Neutral (inactive) background (white).
142
const NEUTRAL_BG_COLOR: ColorU = ColorU {
143
    r: 255,
144
    g: 255,
145
    b: 255,
146
    a: 255,
147
};
148
/// Active-page text colour (white).
149
const ACTIVE_TEXT: ColorU = ColorU {
150
    r: 255,
151
    g: 255,
152
    b: 255,
153
    a: 255,
154
};
155
/// Neutral text colour (#212529, dark).
156
const NEUTRAL_TEXT: ColorU = ColorU {
157
    r: 33,
158
    g: 37,
159
    b: 41,
160
    a: 255,
161
};
162
/// Disabled (Prev/Next at a bound) text colour (#adb5bd, muted grey).
163
const DISABLED_TEXT: ColorU = ColorU {
164
    r: 173,
165
    g: 181,
166
    b: 189,
167
    a: 255,
168
};
169

            
170
const ACCENT_BG_ITEMS: &[StyleBackgroundContent] =
171
    &[StyleBackgroundContent::Color(ACCENT_BG_COLOR)];
172
const ACCENT_BG: StyleBackgroundContentVec =
173
    StyleBackgroundContentVec::from_const_slice(ACCENT_BG_ITEMS);
174
const NEUTRAL_BG_ITEMS: &[StyleBackgroundContent] =
175
    &[StyleBackgroundContent::Color(NEUTRAL_BG_COLOR)];
176
const NEUTRAL_BG: StyleBackgroundContentVec =
177
    StyleBackgroundContentVec::from_const_slice(NEUTRAL_BG_ITEMS);
178

            
179
const PAGE_RADIUS: isize = 6;
180

            
181
/// Row container: a horizontal flex row that hugs its content.
182
static PAGINATION_CONTAINER_STYLE: &[CssPropertyWithConditions] = &[
183
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
184
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
185
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
186
    CssPropertyWithConditions::simple(CssProperty::align_self(LayoutAlignSelf::Start)),
187
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
188
];
189

            
190
/// Builds the style for one button. The active/disabled colours and the rounding
191
/// of the outer corners (only the first button — `Prev` — is rounded on the left,
192
/// only the last — `Next` — on the right) are position-dependent, so the style is
193
/// built at runtime (mirroring `segmented::build_segment_style`).
194
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
195
#[allow(clippy::fn_params_excessive_bools)] // independent boolean render flags, not a state enum
196
2628
fn build_button_style(
197
2628
    active: bool,
198
2628
    disabled: bool,
199
2628
    is_first: bool,
200
2628
    is_last: bool,
201
2628
) -> CssPropertyWithConditionsVec {
202
2628
    let bg = if active { ACCENT_BG } else { NEUTRAL_BG };
203
2628
    let text = if active {
204
148
        ACTIVE_TEXT
205
2480
    } else if disabled {
206
83
        DISABLED_TEXT
207
    } else {
208
2397
        NEUTRAL_TEXT
209
    };
210

            
211
2628
    let mut v: Vec<CssPropertyWithConditions> = vec![
212
2628
        CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
213
2628
        CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
214
2628
            LayoutFlexDirection::Row,
215
        )),
216
2628
        CssPropertyWithConditions::simple(CssProperty::const_justify_content(
217
2628
            LayoutJustifyContent::Center,
218
        )),
219
2628
        CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
220
2628
        CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(
221
            0,
222
        ))),
223
        // Keep single-digit page buttons from collapsing too narrow.
224
2628
        CssPropertyWithConditions::simple(CssProperty::const_min_width(LayoutMinWidth::const_px(
225
            36,
226
        ))),
227
        // padding: 6px 12px
228
2628
        CssPropertyWithConditions::simple(CssProperty::const_padding_top(
229
2628
            LayoutPaddingTop::const_px(6),
230
        )),
231
2628
        CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
232
2628
            LayoutPaddingBottom::const_px(6),
233
        )),
234
2628
        CssPropertyWithConditions::simple(CssProperty::const_padding_left(
235
2628
            LayoutPaddingLeft::const_px(12),
236
        )),
237
2628
        CssPropertyWithConditions::simple(CssProperty::const_padding_right(
238
2628
            LayoutPaddingRight::const_px(12),
239
        )),
240
        // top/bottom/right borders (the left border is added only for the first
241
        // button, so adjacent buttons share a single 1px separator)
242
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
243
2628
            LayoutBorderTopWidth::const_px(1),
244
        )),
245
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
246
2628
            LayoutBorderBottomWidth::const_px(1),
247
        )),
248
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
249
2628
            LayoutBorderRightWidth::const_px(1),
250
        )),
251
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_top_style(
252
2628
            StyleBorderTopStyle {
253
2628
                inner: BorderStyle::Solid,
254
2628
            },
255
        )),
256
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
257
2628
            StyleBorderBottomStyle {
258
2628
                inner: BorderStyle::Solid,
259
2628
            },
260
        )),
261
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
262
2628
            StyleBorderRightStyle {
263
2628
                inner: BorderStyle::Solid,
264
2628
            },
265
        )),
266
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_top_color(
267
2628
            StyleBorderTopColor {
268
2628
                inner: PAGE_BORDER_COLOR,
269
2628
            },
270
        )),
271
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
272
2628
            StyleBorderBottomColor {
273
2628
                inner: PAGE_BORDER_COLOR,
274
2628
            },
275
        )),
276
2628
        CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
277
2628
            StyleBorderRightColor {
278
2628
                inner: PAGE_BORDER_COLOR,
279
2628
            },
280
        )),
281
2628
        CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
282
2628
        CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(
283
            13,
284
        ))),
285
2628
        CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Center)),
286
2628
        CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
287
2628
        CssPropertyWithConditions::simple(CssProperty::const_background_content(bg)),
288
2628
        CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
289
2628
            inner: text,
290
2628
        })),
291
    ];
292

            
293
2628
    if is_first {
294
151
        v.push(CssPropertyWithConditions::simple(
295
151
            CssProperty::const_border_left_width(LayoutBorderLeftWidth::const_px(1)),
296
151
        ));
297
151
        v.push(CssPropertyWithConditions::simple(
298
151
            CssProperty::const_border_left_style(StyleBorderLeftStyle {
299
151
                inner: BorderStyle::Solid,
300
151
            }),
301
151
        ));
302
151
        v.push(CssPropertyWithConditions::simple(
303
151
            CssProperty::const_border_left_color(StyleBorderLeftColor {
304
151
                inner: PAGE_BORDER_COLOR,
305
151
            }),
306
151
        ));
307
151
        v.push(CssPropertyWithConditions::simple(
308
151
            CssProperty::const_border_top_left_radius(StyleBorderTopLeftRadius::const_px(
309
151
                PAGE_RADIUS,
310
151
            )),
311
151
        ));
312
151
        v.push(CssPropertyWithConditions::simple(
313
151
            CssProperty::const_border_bottom_left_radius(StyleBorderBottomLeftRadius::const_px(
314
151
                PAGE_RADIUS,
315
151
            )),
316
151
        ));
317
2477
    }
318
2628
    if is_last {
319
151
        v.push(CssPropertyWithConditions::simple(
320
151
            CssProperty::const_border_top_right_radius(StyleBorderTopRightRadius::const_px(
321
151
                PAGE_RADIUS,
322
151
            )),
323
151
        ));
324
151
        v.push(CssPropertyWithConditions::simple(
325
151
            CssProperty::const_border_bottom_right_radius(StyleBorderBottomRightRadius::const_px(
326
151
                PAGE_RADIUS,
327
151
            )),
328
151
        ));
329
2477
    }
330

            
331
2628
    CssPropertyWithConditionsVec::from_vec(v)
332
2628
}
333

            
334
impl Pagination {
335
    /// Creates a pager for `total_pages` pages with `current_page` (1-based)
336
    /// selected. `current_page` is clamped into `[1, total_pages.max(1)]`.
337
    #[must_use]
338
492
    pub fn create(current_page: usize, total_pages: usize) -> Self {
339
492
        let total_pages = total_pages.max(1);
340
492
        let current_page = current_page.clamp(1, total_pages);
341
492
        Self {
342
492
            pagination_state: PaginationStateWrapper {
343
492
                inner: PaginationState {
344
492
                    current_page,
345
492
                    total_pages,
346
492
                },
347
492
                ..Default::default()
348
492
            },
349
492
            container_style: OptionCssPropertyWithConditionsVec::None,
350
492
        }
351
492
    }
352

            
353
    /// The container CSS this pagination row renders with.
354
    ///
355
    /// `None` means no opinion, so the widget's default applies — the same
356
    /// answer both themes give, asked in one place so they cannot drift.
357
    #[must_use]
358
81
    pub fn resolved_container_style(&self) -> CssPropertyWithConditionsVec {
359
81
        self.container_style
360
81
            .clone()
361
81
            .into_option()
362
81
            .unwrap_or_else(|| {
363
81
                CssPropertyWithConditionsVec::from_const_slice(PAGINATION_CONTAINER_STYLE)
364
81
            })
365
81
    }
366

            
367
    /// Sets the current (1-based) page, clamped into `[1, total_pages]`.
368
    #[inline]
369
36
    pub fn set_current_page(&mut self, current_page: usize) {
370
36
        let total = self.pagination_state.inner.total_pages.max(1);
371
36
        self.pagination_state.inner.current_page = current_page.clamp(1, total);
372
36
    }
373

            
374
    /// Builder-style setter for the current page.
375
    #[inline]
376
    #[must_use]
377
6
    pub fn with_current_page(mut self, current_page: usize) -> Self {
378
6
        self.set_current_page(current_page);
379
6
        self
380
6
    }
381

            
382
    #[inline]
383
    #[must_use]
384
104
    pub fn swap_with_default(&mut self) -> Self {
385
104
        let mut s = Self::create(1, 1);
386
104
        core::mem::swap(&mut s, self);
387
104
        s
388
104
    }
389

            
390
    #[inline]
391
8
    pub fn set_on_change<C: Into<PaginationOnChangeCallback>>(
392
8
        &mut self,
393
8
        data: RefAny,
394
8
        on_change: C,
395
8
    ) {
396
8
        self.pagination_state.on_change = Some(PaginationOnChange {
397
8
            callback: on_change.into(),
398
8
            refany: data,
399
8
        })
400
8
        .into();
401
8
    }
402

            
403
    #[inline]
404
    #[must_use]
405
6
    pub fn with_on_change<C: Into<PaginationOnChangeCallback>>(
406
6
        mut self,
407
6
        data: RefAny,
408
6
        on_change: C,
409
6
    ) -> Self {
410
6
        self.set_on_change(data, on_change);
411
6
        self
412
6
    }
413

            
414
    #[must_use]
415
78
    pub fn dom(self) -> Dom {
416
        use azul_core::{
417
            callbacks::CoreCallback,
418
            dom::{EventFilter, HoverEventFilter},
419
            refany::OptionRefAny,
420
        };
421

            
422
78
        let current = self.pagination_state.inner.current_page;
423
78
        let total = self.pagination_state.inner.total_pages;
424
        // Resolved before `self.pagination_state` is moved out below.
425
78
        let container_style = self.resolved_container_style();
426

            
427
        // One shared RefAny across every button's callback (RefAny::clone shares
428
        // the underlying state — same pattern as segmented/tabs/map).
429
78
        let state = RefAny::new(self.pagination_state);
430

            
431
78
        let make_button =
432
2476
            |label: AzString, class: &'static [IdOrClass], style: CssPropertyWithConditionsVec| {
433
2476
                crate::widgets::widget_p_with_text(label)
434
2476
                    .with_ids_and_classes(IdOrClassVec::from_const_slice(class))
435
2476
                    .with_css_props(style)
436
2476
                    .with_callbacks(
437
2476
                        vec![CoreCallbackData {
438
2476
                            event: EventFilter::Hover(HoverEventFilter::Click),
439
2476
                            callback: CoreCallback {
440
2476
                                cb: on_page_click as usize,
441
2476
                                ctx: OptionRefAny::None,
442
2476
                            },
443
2476
                            refany: state.clone(),
444
2476
                        }]
445
2476
                        .into(),
446
                    )
447
2476
                    .with_tab_index(TabIndex::Auto)
448
            // Role so the accessibility tree knows what this IS:
449
            // each page control is a button. The NAME comes from the widget's own text,
450
            // which azul derives when a readable label is present.
451
2476
            .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
452
2476
                role: azul_core::a11y::AccessibilityRole::PushButton,
453
2476
                ..Default::default()
454
2476
            })
455
2476
            };
456

            
457
78
        let mut children: Vec<Dom> = Vec::with_capacity(total.saturating_add(2));
458

            
459
        // Prev (first, left-rounded; disabled-look at page 1).
460
78
        children.push(make_button(
461
78
            PREV_LABEL,
462
78
            PAGINATION_NAV_CLASS,
463
78
            build_button_style(false, current <= 1, true, false),
464
78
        ));
465

            
466
        // Page-number buttons 1..=total.
467
2320
        for page in 1..=total {
468
2320
            children.push(make_button(
469
2320
                AzString::from(format!("{page}").as_str()),
470
2320
                PAGINATION_PAGE_CLASS,
471
2320
                build_button_style(page == current, false, false, false),
472
2320
            ));
473
2320
        }
474

            
475
        // Next (last, right-rounded; disabled-look at the final page).
476
78
        children.push(make_button(
477
78
            NEXT_LABEL,
478
78
            PAGINATION_NAV_CLASS,
479
78
            build_button_style(false, current >= total, false, true),
480
78
        ));
481

            
482
78
        Dom::create_div()
483
78
            .with_ids_and_classes(IdOrClassVec::from_const_slice(PAGINATION_CLASS))
484
78
            .with_css_props(container_style)
485
78
            .with_children(children.into())
486
78
    }
487
}
488

            
489
impl Default for Pagination {
490
203
    fn default() -> Self {
491
203
        Self::create(1, 1)
492
203
    }
493
}
494

            
495
/// Click handler shared by all buttons. Resolves the clicked button from its
496
/// sibling position (`Prev`=0, page `p`=`p`, `Next`=last), computes the new page
497
/// within bounds, and — only if it actually changed — updates the state, invokes
498
/// the user callback, and live-restyles every button.
499
52
extern "C" fn on_page_click(mut data: RefAny, mut info: CallbackInfo) -> Update {
500
    use azul_core::dom::DomNodeId;
501

            
502
52
    let clicked = info.get_hit_node();
503
52
    let Some(parent) = info.get_parent(clicked) else {
504
3
        return Update::DoNothing;
505
    };
506

            
507
    // Collect the buttons in document order: [Prev, page1 … pageN, Next].
508
49
    let mut buttons: Vec<DomNodeId> = Vec::new();
509
49
    let mut cur = info.get_first_child(parent);
510
373
    while let Some(node) = cur {
511
324
        buttons.push(node);
512
324
        cur = info.get_next_sibling(node);
513
324
    }
514
49
    let n = buttons.len();
515
49
    if n < 2 {
516
1
        return Update::DoNothing;
517
48
    }
518
    // Page buttons occupy positions 1..=total; Prev=0, Next=n-1.
519
48
    let total = n - 2;
520

            
521
197
    let Some(pos) = buttons.iter().position(|b| *b == clicked) else {
522
        return Update::DoNothing;
523
    };
524

            
525
46
    let current = {
526
48
        let Some(pg) = data.downcast_ref::<PaginationStateWrapper>() else {
527
2
            return Update::DoNothing;
528
        };
529
46
        pg.inner.current_page
530
    };
531

            
532
46
    let new_page = if pos == 0 {
533
        // Prev
534
14
        if current > 1 {
535
8
            current - 1
536
        } else {
537
6
            current
538
        }
539
32
    } else if pos == n - 1 {
540
        // Next
541
18
        if current < total {
542
8
            current + 1
543
        } else {
544
10
            current
545
        }
546
    } else {
547
        // A page-number button: its 1-based page equals its sibling position.
548
14
        pos
549
    };
550

            
551
46
    if new_page == current {
552
        // Clicked the current page, or a disabled Prev/Next at a bound.
553
19
        return Update::DoNothing;
554
27
    }
555

            
556
27
    let result = {
557
27
        let Some(mut pg) = data.downcast_mut::<PaginationStateWrapper>() else {
558
            return Update::DoNothing;
559
        };
560
27
        pg.inner.current_page = new_page;
561
27
        let inner = pg.inner;
562
27
        let pg = &mut *pg;
563
27
        match pg.on_change.as_mut() {
564
4
            Some(PaginationOnChange { callback, refany }) => {
565
4
                (callback.cb)(refany.clone(), info, inner)
566
            }
567
23
            None => Update::DoNothing,
568
        }
569
    };
570

            
571
    // Live-restyle: active page gets the accent fill + light text; Prev/Next show
572
    // the muted disabled text at their bounds; everything else is neutral.
573
199
    for (i, node) in buttons.iter().enumerate() {
574
199
        let (bg, text) = if i == 0 {
575
            // Prev
576
27
            let disabled = new_page <= 1;
577
            (
578
27
                NEUTRAL_BG,
579
27
                if disabled {
580
3
                    DISABLED_TEXT
581
                } else {
582
24
                    NEUTRAL_TEXT
583
                },
584
            )
585
172
        } else if i == n - 1 {
586
            // Next
587
27
            let disabled = new_page >= total;
588
            (
589
27
                NEUTRAL_BG,
590
27
                if disabled {
591
5
                    DISABLED_TEXT
592
                } else {
593
22
                    NEUTRAL_TEXT
594
                },
595
            )
596
145
        } else if i == new_page {
597
26
            (ACCENT_BG, ACTIVE_TEXT)
598
        } else {
599
119
            (NEUTRAL_BG, NEUTRAL_TEXT)
600
        };
601
199
        info.set_css_property(*node, CssProperty::const_background_content(bg));
602
199
        info.set_css_property(
603
199
            *node,
604
199
            CssProperty::const_text_color(StyleTextColor { inner: text }),
605
        );
606
    }
607

            
608
27
    result
609
52
}
610

            
611
impl From<Pagination> for Dom {
612
1
    fn from(p: Pagination) -> Self {
613
1
        p.dom()
614
1
    }
615
}
616

            
617
#[cfg(test)]
618
#[allow(clippy::float_cmp, clippy::too_many_lines)]
619
mod autotest_generated {
620
    use std::{
621
        collections::{BTreeMap, HashMap},
622
        sync::{Arc, Mutex},
623
    };
624

            
625
    use azul_core::{
626
        dom::{DomId, DomNodeId, EventFilter, HoverEventFilter, NodeId, NodeType},
627
        geom::{LogicalRect, OptionLogicalPosition},
628
        gl::OptionGlContextPtr,
629
        hit_test::ScrollPosition,
630
        refany::OptionRefAny,
631
        resources::RendererResources,
632
        styled_dom::{NodeHierarchyItemId, StyledDom},
633
        window::{MonitorVec, RawWindowHandle},
634
    };
635
    use azul_css::{
636
        props::{
637
            basic::{length::SizeMetric, pixel::PixelValue},
638
            property::CssPropertyType,
639
        },
640
        system::SystemStyle,
641
    };
642
    use rust_fontconfig::FcFontCache;
643

            
644
    use super::*;
645
    #[cfg(feature = "icu")]
646
    use crate::icu::IcuLocalizerHandle;
647
    use crate::{
648
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
649
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
650
        window::{DomLayoutResult, LayoutWindow},
651
        window_state::FullWindowState,
652
    };
653

            
654
    // ------------------------------------------------------------------
655
    // Helpers
656
    // ------------------------------------------------------------------
657

            
658
    /// The declared properties of a style vec, in declaration order.
659
    fn declared(v: &CssPropertyWithConditionsVec) -> Vec<CssProperty> {
660
        v.as_ref().iter().map(|p| p.property.clone()).collect()
661
    }
662

            
663
    /// The declared properties of a rendered node's inline style, in declaration
664
    /// order (`with_css_props` folds the vec into a `Css`; this reads it back).
665
    fn inline_props(node: &Dom) -> Vec<CssProperty> {
666
        node.root
667
            .style
668
            .iter_inline_properties()
669
            .map(|(p, _)| p.clone())
670
            .collect()
671
    }
672

            
673
    fn text_of(node: &Dom) -> Option<&str> {
674
        match node.root.get_node_type() {
675
            NodeType::Text(s) => Some(s.as_ref().as_str()),
676
            NodeType::P => match node.children.as_ref() {
677
                [only] => match only.root.get_node_type() {
678
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
679
                    _ => None,
680
                },
681
                _ => None,
682
            },
683
            _ => None,
684
        }
685
    }
686

            
687
    fn classes(node: &Dom) -> Vec<String> {
688
        node.root
689
            .get_ids_and_classes()
690
            .as_ref()
691
            .iter()
692
            .filter_map(|c| match c {
693
                Class(s) => Some(s.as_str().to_string()),
694
                IdOrClass::Id(_) => None,
695
            })
696
            .collect()
697
    }
698

            
699
    /// The one text colour a button declares (asserting there is at most one — a
700
    /// second declaration would silently shadow the first at cascade time).
701
    fn text_color(props: &[CssProperty]) -> Option<ColorU> {
702
        let found: Vec<ColorU> = props
703
            .iter()
704
            .filter_map(|p| match p {
705
                CssProperty::TextColor(v) => v.get_property().map(|c| c.inner),
706
                _ => None,
707
            })
708
            .collect();
709
        assert!(
710
            found.len() <= 1,
711
            "a button must declare at most one text colour"
712
        );
713
        found.first().copied()
714
    }
715

            
716
    /// The one flat background colour a button declares.
717
    fn background_color(props: &[CssProperty]) -> Option<ColorU> {
718
        let found: Vec<&StyleBackgroundContentVec> = props
719
            .iter()
720
            .filter_map(|p| match p {
721
                CssProperty::BackgroundContent(v) => v.get_property(),
722
                _ => None,
723
            })
724
            .collect();
725
        assert!(
726
            found.len() <= 1,
727
            "a button must declare at most one background"
728
        );
729
        let bg: &StyleBackgroundContentVec = *found.first()?;
730
        assert_eq!(
731
            bg.as_ref().len(),
732
            1,
733
            "a button must declare exactly one background layer"
734
        );
735
        match &bg.as_ref()[0] {
736
            StyleBackgroundContent::Color(c) => Some(*c),
737
            other => panic!("pagination background is not a flat colour: {other:?}"),
738
        }
739
    }
740

            
741
    /// The `f32` of a `PixelValue`, asserting the length is an absolute `px`. An
742
    /// `em`/`%` slipping into the button chrome would resolve against the parent
743
    /// font/box instead of the intended fixed padding, border or radius.
744
    fn px(pv: &PixelValue) -> f32 {
745
        assert_eq!(
746
            pv.metric,
747
            SizeMetric::Px,
748
            "pagination geometry must be absolute px, got {:?}",
749
            pv.metric
750
        );
751
        pv.number.get()
752
    }
753

            
754
    /// Every length a style declares (min-width, paddings, border widths, font
755
    /// size, corner radii).
756
    fn pixel_values(props: &[CssProperty]) -> Vec<PixelValue> {
757
        props
758
            .iter()
759
            .filter_map(|p| match p {
760
                CssProperty::MinWidth(v) => v.get_property().map(|x| x.inner),
761
                CssProperty::PaddingTop(v) => v.get_property().map(|x| x.inner),
762
                CssProperty::PaddingBottom(v) => v.get_property().map(|x| x.inner),
763
                CssProperty::PaddingLeft(v) => v.get_property().map(|x| x.inner),
764
                CssProperty::PaddingRight(v) => v.get_property().map(|x| x.inner),
765
                CssProperty::BorderTopWidth(v) => v.get_property().map(|x| x.inner),
766
                CssProperty::BorderBottomWidth(v) => v.get_property().map(|x| x.inner),
767
                CssProperty::BorderLeftWidth(v) => v.get_property().map(|x| x.inner),
768
                CssProperty::BorderRightWidth(v) => v.get_property().map(|x| x.inner),
769
                CssProperty::FontSize(v) => v.get_property().map(|x| x.inner),
770
                CssProperty::BorderTopLeftRadius(v) => v.get_property().map(|x| x.inner),
771
                CssProperty::BorderBottomLeftRadius(v) => v.get_property().map(|x| x.inner),
772
                CssProperty::BorderTopRightRadius(v) => v.get_property().map(|x| x.inner),
773
                CssProperty::BorderBottomRightRadius(v) => v.get_property().map(|x| x.inner),
774
                _ => None,
775
            })
776
            .collect()
777
    }
778

            
779
    /// The four corner radii a style declares, as `(top-left, bottom-left,
780
    /// top-right, bottom-right)`; `None` where the corner is left square.
781
    fn radii(props: &[CssProperty]) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
782
        let find = |f: &dyn Fn(&CssProperty) -> Option<f32>| props.iter().find_map(f);
783
        (
784
            find(&|p| match p {
785
                CssProperty::BorderTopLeftRadius(v) => v.get_property().map(|r| px(&r.inner)),
786
                _ => None,
787
            }),
788
            find(&|p| match p {
789
                CssProperty::BorderBottomLeftRadius(v) => v.get_property().map(|r| px(&r.inner)),
790
                _ => None,
791
            }),
792
            find(&|p| match p {
793
                CssProperty::BorderTopRightRadius(v) => v.get_property().map(|r| px(&r.inner)),
794
                _ => None,
795
            }),
796
            find(&|p| match p {
797
                CssProperty::BorderBottomRightRadius(v) => v.get_property().map(|r| px(&r.inner)),
798
                _ => None,
799
            }),
800
        )
801
    }
802

            
803
    /// Whether the style declares a *left* border on all three of width/style/colour
804
    /// — the "I am the first button in the joined bar" marker.
805
    fn has_left_border(props: &[CssProperty]) -> (bool, bool, bool) {
806
        (
807
            props
808
                .iter()
809
                .any(|p| matches!(p, CssProperty::BorderLeftWidth(_))),
810
            props
811
                .iter()
812
                .any(|p| matches!(p, CssProperty::BorderLeftStyle(_))),
813
            props
814
                .iter()
815
                .any(|p| matches!(p, CssProperty::BorderLeftColor(_))),
816
        )
817
    }
818

            
819
    /// Every `(active, disabled, is_first, is_last)` the builder can be handed.
820
    fn all_flag_combinations() -> Vec<(bool, bool, bool, bool)> {
821
        let mut out = Vec::with_capacity(16);
822
        for a in [false, true] {
823
            for d in [false, true] {
824
                for f in [false, true] {
825
                    for l in [false, true] {
826
                        out.push((a, d, f, l));
827
                    }
828
                }
829
            }
830
        }
831
        out
832
    }
833

            
834
    /// A `RefAny` payload recording every state a user `on_change` observes.
835
    struct ChangeLog {
836
        seen: Vec<PaginationState>,
837
    }
838

            
839
    extern "C" fn record_change(
840
        mut data: RefAny,
841
        _: CallbackInfo,
842
        state: PaginationState,
843
    ) -> Update {
844
        if let Some(mut log) = data.downcast_mut::<ChangeLog>() {
845
            log.seen.push(state);
846
        }
847
        Update::RefreshDom
848
    }
849

            
850
    extern "C" fn change_do_nothing(_: RefAny, _: CallbackInfo, _: PaginationState) -> Update {
851
        Update::DoNothing
852
    }
853

            
854
    extern "C" fn change_refresh_all(_: RefAny, _: CallbackInfo, _: PaginationState) -> Update {
855
        Update::RefreshDomAllWindows
856
    }
857

            
858
    /// Forces the `fn`-item -> `fn`-pointer coercion the `Into` bound needs.
859
    fn cb(f: PaginationOnChangeCallbackType) -> PaginationOnChangeCallback {
860
        f.into()
861
    }
862

            
863
    fn logged(data: &mut RefAny) -> Vec<PaginationState> {
864
        data.downcast_ref::<ChangeLog>()
865
            .expect("payload must still be a ChangeLog")
866
            .seen
867
            .clone()
868
    }
869

            
870
    fn current_page_of(data: &mut RefAny) -> usize {
871
        data.downcast_ref::<PaginationStateWrapper>()
872
            .expect("payload must still be a PaginationStateWrapper")
873
            .inner
874
            .current_page
875
    }
876

            
877
    /// The shared state `RefAny` carried by button `i`'s click callback.
878
    fn button_state(dom: &Dom, i: usize) -> RefAny {
879
        dom.children.as_ref()[i]
880
            .root
881
            .get_callbacks()
882
            .as_ref()
883
            .first()
884
            .expect("every pagination button carries a click callback")
885
            .refany
886
            .clone()
887
    }
888

            
889
    /// Flattened node ids. Every button is a `<p>` wrapping one bare text node,
890
    /// so depth-first pre-order lays them out as
891
    /// `0 root / 1 Prev <p> / 2 Prev text / 3 page1 <p> / 4 page1 text / …`.
892
    /// The callbacks sit on the `<p>`s.
893
    const PREV_NODE: usize = 1;
894
    /// Flattened node id of page `p` (1-based).
895
    const fn page_node(p: usize) -> usize {
896
        2 * p + 1
897
    }
898
    /// Flattened node id of the `Next` button for a `total`-page pager.
899
    const fn next_node(total: usize) -> usize {
900
        2 * total + 3
901
    }
902

            
903
    /// A `DomLayoutResult` with an *empty* layout tree: `on_page_click` only walks
904
    /// `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
905
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
906
        DomLayoutResult {
907
            styled_dom,
908
            layout_tree: LayoutTree {
909
                nodes: Vec::new(),
910
                warm: Vec::new(),
911
                cold: Vec::new(),
912
                root: 0,
913
                dom_to_layout: BTreeMap::new(),
914
                children_arena: Vec::new(),
915
                children_offsets: Vec::new(),
916
                subtree_needs_intrinsic: Vec::new(),
917
            },
918
            calculated_positions: Vec::new(),
919
            viewport: LogicalRect::zero(),
920
            display_list: Arc::new(DisplayList::default()),
921
            scroll_ids: HashMap::new(),
922
            scroll_id_to_node_id: HashMap::new(),
923
        }
924
    }
925

            
926
    /// Flattens `p.dom()` and hands back the shared state `RefAny` its buttons carry.
927
    fn flatten(p: Pagination) -> (StyledDom, RefAny) {
928
        let dom = p.dom();
929
        let state = button_state(&dom, 0);
930
        (StyledDom::create_from_dom(dom), state)
931
    }
932

            
933
    /// Invokes `on_page_click` against a `LayoutWindow` holding `styled` (or nothing
934
    /// at all, when `styled` is `None`), with flattened node `hit` as the hit node.
935
    /// Returns the `Update` plus every recorded `CallbackChange`.
936
    fn run_click(
937
        styled: Option<StyledDom>,
938
        hit: usize,
939
        data: RefAny,
940
    ) -> (Update, Vec<CallbackChange>) {
941
        let mut layout_window =
942
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
943
        if let Some(sd) = styled {
944
            layout_window
945
                .layout_results
946
                .insert(DomId::ROOT_ID, layout_result(sd));
947
        }
948

            
949
        let renderer_resources = RendererResources::default();
950
        let previous_window_state: Option<FullWindowState> = None;
951
        let current_window_state = FullWindowState::default();
952
        let gl_context = OptionGlContextPtr::None;
953
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
954
            BTreeMap::new();
955
        let window_handle = RawWindowHandle::Unsupported;
956
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
957

            
958
        let ref_data = CallbackInfoRefData {
959
            layout_window: &layout_window,
960
            renderer_resources: &renderer_resources,
961
            previous_window_state: &previous_window_state,
962
            current_window_state: &current_window_state,
963
            gl_context: &gl_context,
964
            current_scroll_manager: &scroll_states,
965
            current_window_handle: &window_handle,
966
            system_callbacks: &system_callbacks,
967
            system_style: Arc::new(SystemStyle::default()),
968
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
969
            #[cfg(feature = "icu")]
970
            icu_localizer: IcuLocalizerHandle::default(),
971
            ctx: OptionRefAny::None,
972
        };
973

            
974
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
975

            
976
        let info = CallbackInfo::new(
977
            &ref_data,
978
            &changes,
979
            DomNodeId {
980
                dom: DomId::ROOT_ID,
981
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
982
            },
983
            OptionLogicalPosition::None,
984
            OptionLogicalPosition::None,
985
        );
986

            
987
        let update = on_page_click(data, info);
988
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
989
        (update, recorded)
990
    }
991

            
992
    /// Decodes a live-restyle transaction into `(node index, background, text)`
993
    /// triples — the handler pushes exactly one background and one colour write per
994
    /// button, in that order.
995
    fn restyle(changes: &[CallbackChange]) -> Vec<(usize, ColorU, ColorU)> {
996
        assert_eq!(
997
            changes.len() % 2,
998
            0,
999
            "a restyle pass writes background+colour in pairs"
        );
        let decode = |c: &CallbackChange| -> (usize, CssProperty) {
            match c {
                CallbackChange::ChangeNodeCssProperties {
                    dom_id,
                    node_id,
                    properties,
                } => {
                    assert_eq!(*dom_id, DomId::ROOT_ID, "restyle must stay in the root DOM");
                    assert_eq!(
                        properties.as_ref().len(),
                        1,
                        "set_css_property writes exactly one property per change"
                    );
                    (node_id.index(), properties.as_ref()[0].clone())
                }
                other => panic!("unexpected change pushed by on_page_click: {other:?}"),
            }
        };
        changes
            .chunks(2)
            .map(|pair| {
                let (bg_node, bg_prop) = decode(&pair[0]);
                let (fg_node, fg_prop) = decode(&pair[1]);
                assert_eq!(bg_node, fg_node, "both writes must target the same button");
                let bg = background_color(&[bg_prop])
                    .expect("the first write of each pair is the background");
                let fg =
                    text_color(&[fg_prop]).expect("the second write of each pair is the colour");
                (bg_node, bg, fg)
            })
            .collect()
    }
    // ==================================================================
    // build_button_style
    // ==================================================================
    #[test]
    fn build_button_style_never_panics_and_is_deterministic() {
        for (a, d, f, l) in all_flag_combinations() {
            let style = build_button_style(a, d, f, l);
            assert!(
                !style.as_ref().is_empty(),
                "({a},{d},{f},{l}) produced an empty style"
            );
            assert_eq!(
                declared(&style),
                declared(&build_button_style(a, d, f, l)),
                "({a},{d},{f},{l}) is not a pure function of its flags"
            );
        }
    }
    #[test]
    fn build_button_style_declares_every_property_at_most_once() {
        // A duplicate declaration would silently shadow the earlier one at cascade
        // time, making the widget's look depend on declaration order.
        for (a, d, f, l) in all_flag_combinations() {
            let props = declared(&build_button_style(a, d, f, l));
            let mut types: Vec<CssPropertyType> = props.iter().map(CssProperty::get_type).collect();
            let len = types.len();
            types.sort_unstable();
            types.dedup();
            assert_eq!(
                types.len(),
                len,
                "duplicate declaration for ({a},{d},{f},{l})"
            );
        }
    }
    #[test]
    fn build_button_style_is_unconditional() {
        // Every declaration is `simple` — a stray `apply_if` would make the button
        // silently lose its fill under some pseudo-state.
        for (a, d, f, l) in all_flag_combinations() {
            for p in build_button_style(a, d, f, l).as_ref() {
                assert!(
                    p.apply_if.as_ref().is_empty(),
                    "({a},{d},{f},{l}) declared a conditional property: {:?}",
                    p.property
                );
            }
        }
    }
    #[test]
    fn build_button_style_active_wins_over_disabled_for_the_text_colour() {
        // `active` is checked first, so an active-*and*-disabled button reads as
        // active; only a non-active disabled button gets the muted grey.
        for (flags, expected) in [
            ((true, true), ACTIVE_TEXT),
            ((true, false), ACTIVE_TEXT),
            ((false, true), DISABLED_TEXT),
            ((false, false), NEUTRAL_TEXT),
        ] {
            let (a, d) = flags;
            let props = declared(&build_button_style(a, d, false, false));
            assert_eq!(
                text_color(&props),
                Some(expected),
                "active={a} disabled={d} picked the wrong text colour"
            );
        }
    }
    #[test]
    fn build_button_style_paints_the_accent_fill_only_when_active() {
        for (a, d, f, l) in all_flag_combinations() {
            let props = declared(&build_button_style(a, d, f, l));
            let expected = if a { ACCENT_BG_COLOR } else { NEUTRAL_BG_COLOR };
            assert_eq!(
                background_color(&props),
                Some(expected),
                "({a},{d},{f},{l}) has the wrong fill — `disabled` must not tint the background"
            );
        }
    }
    #[test]
    fn build_button_style_rounds_only_the_outer_corners() {
        for (a, d, f, l) in all_flag_combinations() {
            let props = declared(&build_button_style(a, d, f, l));
            let (tl, bl, tr, br) = radii(&props);
            let r = PAGE_RADIUS as f32;
            assert_eq!(
                tl,
                if f { Some(r) } else { None },
                "top-left for is_first={f}"
            );
            assert_eq!(
                bl,
                if f { Some(r) } else { None },
                "bottom-left for is_first={f}"
            );
            assert_eq!(
                tr,
                if l { Some(r) } else { None },
                "top-right for is_last={l}"
            );
            assert_eq!(
                br,
                if l { Some(r) } else { None },
                "bottom-right for is_last={l}"
            );
        }
    }
    #[test]
    fn build_button_style_gives_only_the_first_button_a_left_border() {
        // Adjacent buttons must share a single 1px separator: everyone draws a right
        // border, only the leftmost also draws a left one.
        for (a, d, f, l) in all_flag_combinations() {
            let props = declared(&build_button_style(a, d, f, l));
            assert_eq!(
                has_left_border(&props),
                (f, f, f),
                "left border must be present iff is_first ({a},{d},{f},{l})"
            );
            assert!(
                props
                    .iter()
                    .any(|p| matches!(p, CssProperty::BorderRightWidth(_))),
                "every button draws its own right border"
            );
        }
    }
    #[test]
    fn build_button_style_property_count_is_purely_position_dependent() {
        // The colour flags must not add or drop declarations — only the position
        // flags do (left border + 2 radii for first, 2 radii for last).
        let base = build_button_style(false, false, false, false)
            .as_ref()
            .len();
        for (a, d) in [(false, false), (true, false), (false, true), (true, true)] {
            assert_eq!(
                build_button_style(a, d, false, false).as_ref().len(),
                base,
                "colour flags changed the declaration count"
            );
            assert_eq!(
                build_button_style(a, d, true, false).as_ref().len(),
                base + 5,
                "is_first must add exactly left width/style/colour + 2 radii"
            );
            assert_eq!(
                build_button_style(a, d, false, true).as_ref().len(),
                base + 2,
                "is_last must add exactly 2 radii"
            );
            assert_eq!(
                build_button_style(a, d, true, true).as_ref().len(),
                base + 7,
                "a single-button bar is first *and* last"
            );
        }
    }
    #[test]
    fn build_button_style_uses_only_absolute_px_lengths() {
        for (a, d, f, l) in all_flag_combinations() {
            let props = declared(&build_button_style(a, d, f, l));
            let lengths = pixel_values(&props);
            assert!(!lengths.is_empty(), "a button must declare some geometry");
            for pv in &lengths {
                let v = px(pv); // asserts SizeMetric::Px
                assert!(v.is_finite(), "non-finite length {v} in ({a},{d},{f},{l})");
                assert!(v >= 0.0, "negative length {v} in ({a},{d},{f},{l})");
            }
        }
    }
    #[test]
    fn button_palette_is_opaque_and_the_states_are_visually_distinct() {
        for (name, c) in [
            ("page border", PAGE_BORDER_COLOR),
            ("accent bg", ACCENT_BG_COLOR),
            ("neutral bg", NEUTRAL_BG_COLOR),
            ("active text", ACTIVE_TEXT),
            ("neutral text", NEUTRAL_TEXT),
            ("disabled text", DISABLED_TEXT),
        ] {
            assert_eq!(c.a, 255, "{name} must be fully opaque");
        }
        assert_ne!(
            ACCENT_BG_COLOR, NEUTRAL_BG_COLOR,
            "the active page must stand out"
        );
        assert_ne!(
            ACTIVE_TEXT, NEUTRAL_TEXT,
            "active text must read on the accent fill"
        );
        assert_ne!(
            NEUTRAL_TEXT, DISABLED_TEXT,
            "a disabled end must look disabled"
        );
        // The active-page text sits on the accent fill and must not equal it.
        assert_ne!(
            ACTIVE_TEXT, ACCENT_BG_COLOR,
            "active text would be invisible"
        );
        assert_ne!(
            NEUTRAL_TEXT, NEUTRAL_BG_COLOR,
            "neutral text would be invisible"
        );
        assert_ne!(
            DISABLED_TEXT, NEUTRAL_BG_COLOR,
            "disabled text would be invisible"
        );
    }
    // ==================================================================
    // Pagination::create
    // ==================================================================
    #[test]
    fn create_clamps_current_page_into_range() {
        for (cur, total, want_cur, want_total) in [
            // (input page, input total, expected page, expected total)
            (0usize, 0usize, 1usize, 1usize),
            (0, 1, 1, 1),
            (1, 0, 1, 1),
            (0, 5, 1, 5),
            (1, 5, 1, 5),
            (3, 5, 3, 5),
            (5, 5, 5, 5),
            (6, 5, 5, 5),
            (usize::MAX, 5, 5, 5),
            (usize::MAX, 1, 1, 1),
            (usize::MAX, 0, 1, 1),
            (5, usize::MAX, 5, usize::MAX),
            (0, usize::MAX, 1, usize::MAX),
            (usize::MAX, usize::MAX, usize::MAX, usize::MAX),
        ] {
            let p = Pagination::create(cur, total);
            assert_eq!(
                p.pagination_state.inner,
                PaginationState {
                    current_page: want_cur,
                    total_pages: want_total,
                },
                "create({cur}, {total})"
            );
        }
    }
    #[test]
    fn create_never_yields_a_zero_or_out_of_range_page() {
        // The 1-based invariant is what every consumer (dom(), the click handler,
        // the restyle pass) relies on; a 0 page would mean "no page is current".
        for total in [0usize, 1, 2, 3, 7, 64, 1024, usize::MAX - 1, usize::MAX] {
            for cur in [0usize, 1, 2, 63, 1023, usize::MAX - 1, usize::MAX] {
                let s = Pagination::create(cur, total).pagination_state.inner;
                assert!(s.total_pages >= 1, "create({cur}, {total}) left 0 pages");
                assert!(
                    s.current_page >= 1,
                    "create({cur}, {total}) produced page 0"
                );
                assert!(
                    s.current_page <= s.total_pages,
                    "create({cur}, {total}) escaped the upper bound"
                );
                // Clamping must never *invent* a page: an in-range input survives.
                if cur >= 1 && cur <= total {
                    assert_eq!(s.current_page, cur, "an in-range page must pass through");
                }
            }
        }
    }
    #[test]
    fn create_installs_no_callback_and_the_shared_const_container_style() {
        let p = Pagination::create(2, 4);
        assert!(
            p.pagination_state.on_change.as_ref().is_none(),
            "create must not install a callback"
        );
        assert_eq!(
            p.resolved_container_style().as_ref(),
            PAGINATION_CONTAINER_STYLE,
            "create must reuse the const container style"
        );
    }
    #[test]
    fn default_equals_create_one_one() {
        assert_eq!(Pagination::default(), Pagination::create(1, 1));
        let s = Pagination::default().pagination_state.inner;
        assert_eq!(s.current_page, 1);
        assert_eq!(s.total_pages, 1);
    }
    // ==================================================================
    // Pagination::set_current_page / with_current_page
    // ==================================================================
    #[test]
    fn set_current_page_clamps_into_range() {
        for (input, want) in [
            (0usize, 1usize),
            (1, 1),
            (4, 4),
            (7, 7),
            (8, 7),
            (usize::MAX, 7),
            (usize::MAX - 1, 7),
        ] {
            let mut p = Pagination::create(1, 7);
            p.set_current_page(input);
            assert_eq!(
                p.pagination_state.inner.current_page, want,
                "set_current_page({input}) on a 7-page pager"
            );
            assert_eq!(
                p.pagination_state.inner.total_pages, 7,
                "set_current_page must not touch total_pages"
            );
        }
    }
    #[test]
    fn set_current_page_survives_a_hand_corrupted_zero_total() {
        // `total_pages` is a pub field, so it can be zeroed behind the constructor's
        // back. `clamp(1, 0)` would panic (min > max); the `.max(1)` guard is what
        // prevents that.
        let mut p = Pagination::create(1, 3);
        p.pagination_state.inner.total_pages = 0;
        for input in [0usize, 1, 5, usize::MAX] {
            p.set_current_page(input);
            assert_eq!(
                p.pagination_state.inner.current_page, 1,
                "a 0-page pager must collapse every page to 1"
            );
        }
        assert_eq!(
            p.pagination_state.inner.total_pages, 0,
            "the setter must not silently repair total_pages"
        );
    }
    #[test]
    fn set_current_page_is_idempotent_and_reversible() {
        let mut p = Pagination::create(1, 10);
        for page in [1usize, 10, 5, 5, 1, 10] {
            p.set_current_page(page);
            let once = p.pagination_state.inner.current_page;
            p.set_current_page(page);
            assert_eq!(
                p.pagination_state.inner.current_page, once,
                "not idempotent"
            );
            assert_eq!(once, page);
        }
    }
    #[test]
    fn set_current_page_at_the_usize_max_total_does_not_overflow() {
        let mut p = Pagination::create(1, usize::MAX);
        p.set_current_page(usize::MAX);
        assert_eq!(p.pagination_state.inner.current_page, usize::MAX);
        p.set_current_page(0);
        assert_eq!(p.pagination_state.inner.current_page, 1);
    }
    #[test]
    fn with_current_page_matches_set_current_page_and_keeps_the_callback() {
        for input in [0usize, 1, 3, 9, usize::MAX] {
            let mut expected = Pagination::create(1, 6);
            expected.set_current_page(input);
            let got = Pagination::create(1, 6).with_current_page(input);
            assert_eq!(got, expected, "builder and setter must agree for {input}");
        }
        // The builder form must not drop an already-installed callback.
        let p = Pagination::create(1, 6)
            .with_on_change(
                RefAny::new(ChangeLog { seen: Vec::new() }),
                cb(record_change),
            )
            .with_current_page(4);
        assert_eq!(p.pagination_state.inner.current_page, 4);
        assert!(
            p.pagination_state.on_change.as_ref().is_some(),
            "with_current_page must not disturb the callback"
        );
    }
    // ==================================================================
    // Pagination::swap_with_default
    // ==================================================================
    #[test]
    fn swap_with_default_returns_the_old_value_and_resets_self() {
        let mut p = Pagination::create(3, 9);
        let old = p.swap_with_default();
        assert_eq!(old.pagination_state.inner.current_page, 3);
        assert_eq!(old.pagination_state.inner.total_pages, 9);
        assert_eq!(
            p,
            Pagination::default(),
            "self must be left as a 1-of-1 pager"
        );
    }
    #[test]
    fn swap_with_default_moves_the_callback_out_of_self() {
        let mut p = Pagination::create(1, 3).with_on_change(
            RefAny::new(ChangeLog { seen: Vec::new() }),
            cb(record_change),
        );
        let old = p.swap_with_default();
        assert!(
            old.pagination_state.on_change.as_ref().is_some(),
            "the callback must travel with the returned value"
        );
        assert!(
            p.pagination_state.on_change.as_ref().is_none(),
            "self must not keep a dangling reference to the moved-out callback"
        );
    }
    #[test]
    fn swap_with_default_is_stable_when_repeated() {
        let mut p = Pagination::create(2, 4);
        let _ = p.swap_with_default();
        for _ in 0..100 {
            let out = p.swap_with_default();
            assert_eq!(out, Pagination::default());
            assert_eq!(p, Pagination::default());
        }
    }
    #[test]
    fn swap_with_default_preserves_a_hand_corrupted_state_verbatim() {
        let mut p = Pagination::create(1, 4);
        p.pagination_state.inner.current_page = usize::MAX;
        p.pagination_state.inner.total_pages = 0;
        let old = p.swap_with_default();
        assert_eq!(
            old.pagination_state.inner,
            PaginationState {
                current_page: usize::MAX,
                total_pages: 0,
            },
            "the swap must move state out untouched (no clamping/rewriting)"
        );
        assert_eq!(p.pagination_state.inner.current_page, 1);
        assert_eq!(p.pagination_state.inner.total_pages, 1);
    }
    // ==================================================================
    // Pagination::set_on_change / with_on_change
    // ==================================================================
    #[test]
    fn with_on_change_installs_the_callback_and_touches_nothing_else() {
        let before = Pagination::create(2, 5);
        let after = Pagination::create(2, 5).with_on_change(
            RefAny::new(ChangeLog { seen: Vec::new() }),
            cb(record_change),
        );
        assert_eq!(
            after.pagination_state.inner, before.pagination_state.inner,
            "installing a callback must not disturb the page state"
        );
        assert_eq!(
            after.resolved_container_style(),
            before.resolved_container_style(),
            "installing a callback must not disturb the container style"
        );
        let installed = after
            .pagination_state
            .on_change
            .as_ref()
            .expect("with_on_change must install Some(..)");
        assert_eq!(installed.callback.cb as usize, record_change as usize);
    }
    #[test]
    fn set_on_change_overwrites_the_previous_callback_and_data() {
        let mut p = Pagination::create(1, 3);
        p.set_on_change(
            RefAny::new(ChangeLog { seen: Vec::new() }),
            cb(record_change),
        );
        p.set_on_change(RefAny::new(42u32), cb(change_do_nothing));
        let installed = p
            .pagination_state
            .on_change
            .as_mut()
            .expect("still Some after the overwrite");
        assert_eq!(
            installed.callback.cb as usize, change_do_nothing as usize,
            "the last set_on_change must win"
        );
        assert_eq!(
            installed.refany.downcast_ref::<u32>().map(|v| *v),
            Some(42),
            "the payload must be replaced along with the fn pointer"
        );
        assert!(
            installed.refany.downcast_ref::<ChangeLog>().is_none(),
            "the stale payload must be gone"
        );
    }
    #[test]
    fn generic_callback_conversion_round_trips_the_fn_pointer() {
        // The FFI path (`From<Callback>`) transmutes the fn pointer. The value must
        // round-trip bit-for-bit — a corrupted pointer would be an unconditional
        // jump into garbage at click time. (Never invoked here.)
        let raw = record_change as usize;
        let generic = Callback {
            cb: unsafe { core::mem::transmute::<usize, crate::callbacks::CallbackType>(raw) },
            ctx: OptionRefAny::None,
        };
        let converted: PaginationOnChangeCallback = generic.into();
        assert_eq!(converted.cb as usize, raw);
    }
    // ==================================================================
    // Pagination::dom
    // ==================================================================
    #[test]
    fn dom_lays_out_prev_then_pages_then_next() {
        for total in [1usize, 2, 3, 10, 99] {
            let dom = Pagination::create(1, total).dom();
            let children = dom.children.as_ref();
            assert_eq!(children.len(), total + 2, "Prev + {total} pages + Next");
            assert_eq!(text_of(&children[0]), Some("Prev"));
            assert_eq!(text_of(&children[total + 1]), Some("Next"));
            for (p, child) in children.iter().enumerate().take(total + 1).skip(1) {
                assert_eq!(
                    text_of(child),
                    Some(p.to_string().as_str()),
                    "page {p} must sit at sibling position {p}"
                );
            }
            assert!(dom.root.has_class("__azul-native-pagination"));
            assert!(
                dom.root.is_node_type(NodeType::Div),
                "the bar must be a div"
            );
            assert_eq!(classes(&children[0]), ["__azul-native-pagination-nav"]);
            assert_eq!(
                classes(&children[total + 1]),
                ["__azul-native-pagination-nav"]
            );
            assert_eq!(classes(&children[1]), ["__azul-native-pagination-page"]);
        }
    }
    #[test]
    fn dom_page_labels_are_plain_ascii_decimal() {
        let total = 1000;
        let dom = Pagination::create(1, total).dom();
        let children = dom.children.as_ref();
        for p in [1usize, 9, 10, 99, 100, 999, 1000] {
            let label = text_of(&children[p]).expect("page buttons are text nodes");
            assert_eq!(label, p.to_string(), "page {p} label");
            assert!(
                label.bytes().all(|b| b.is_ascii_digit()),
                "page {p} label {label:?} is not plain decimal"
            );
        }
    }
    #[test]
    fn dom_wires_one_mouseup_handler_per_button() {
        let total = 4;
        let dom = Pagination::create(2, total).dom();
        for (i, child) in dom.children.as_ref().iter().enumerate() {
            let cbs = child.root.get_callbacks();
            assert_eq!(
                cbs.as_ref().len(),
                1,
                "button {i} must carry exactly one handler"
            );
            assert_eq!(
                cbs.as_ref()[0].event,
                EventFilter::Hover(HoverEventFilter::Click)
            );
            assert_eq!(cbs.as_ref()[0].callback.cb, on_page_click as usize);
            assert_eq!(
                child.root.get_tab_index(),
                Some(TabIndex::Auto),
                "button {i} must be keyboard-reachable"
            );
        }
        assert!(
            dom.root.get_callbacks().as_ref().is_empty(),
            "the container itself must not be clickable"
        );
    }
    #[test]
    fn dom_shares_one_state_refany_across_every_button() {
        let dom = Pagination::create(1, 4).dom();
        // Write through Prev's handle…
        let mut first = button_state(&dom, 0);
        {
            let mut w = first
                .downcast_mut::<PaginationStateWrapper>()
                .expect("button state must be a PaginationStateWrapper");
            w.inner.current_page = 3;
        }
        // …and read it back through Next's handle.
        let mut last = button_state(&dom, 5);
        assert_eq!(
            current_page_of(&mut last),
            3,
            "every button must observe the same shared state"
        );
    }
    #[test]
    fn dom_gives_separate_pagers_separate_state() {
        let a = Pagination::create(1, 3).dom();
        let b = Pagination::create(1, 3).dom();
        let mut a0 = button_state(&a, 0);
        {
            let mut w = a0.downcast_mut::<PaginationStateWrapper>().unwrap();
            w.inner.current_page = 3;
        }
        let mut b0 = button_state(&b, 0);
        assert_eq!(
            current_page_of(&mut b0),
            1,
            "two pagers must not alias one another's state"
        );
    }
    #[test]
    fn dom_marks_exactly_the_current_page_active() {
        for total in [1usize, 2, 5, 12] {
            for current in 1..=total {
                let dom = Pagination::create(current, total).dom();
                let children = dom.children.as_ref();
                let active: Vec<usize> = (0..children.len())
                    .filter(|i| {
                        background_color(&inline_props(&children[*i])) == Some(ACCENT_BG_COLOR)
                    })
                    .collect();
                assert_eq!(
                    active,
                    vec![current],
                    "exactly the current page carries the accent fill (total={total})"
                );
                assert_eq!(
                    text_color(&inline_props(&children[current])),
                    Some(ACTIVE_TEXT),
                    "the active page must use the light text"
                );
            }
        }
    }
    #[test]
    fn dom_mutes_prev_at_the_first_page_and_next_at_the_last() {
        let total = 5;
        for current in 1..=total {
            let dom = Pagination::create(current, total).dom();
            let children = dom.children.as_ref();
            let prev = text_color(&inline_props(&children[0]));
            let next = text_color(&inline_props(&children[total + 1]));
            assert_eq!(
                prev,
                Some(if current == 1 {
                    DISABLED_TEXT
                } else {
                    NEUTRAL_TEXT
                }),
                "Prev at page {current}/{total}"
            );
            assert_eq!(
                next,
                Some(if current == total {
                    DISABLED_TEXT
                } else {
                    NEUTRAL_TEXT
                }),
                "Next at page {current}/{total}"
            );
            // A muted end is a *style-only* signal — it stays clickable.
            assert_eq!(children[0].root.get_callbacks().as_ref().len(), 1);
            assert_eq!(children[total + 1].root.get_callbacks().as_ref().len(), 1);
        }
    }
    #[test]
    fn dom_rounds_only_the_two_outer_ends_of_the_bar() {
        let total = 4;
        let dom = Pagination::create(1, total).dom();
        let children = dom.children.as_ref();
        let r = PAGE_RADIUS as f32;
        assert_eq!(
            radii(&inline_props(&children[0])),
            (Some(r), Some(r), None, None),
            "Prev is rounded on the left only"
        );
        assert_eq!(
            radii(&inline_props(&children[total + 1])),
            (None, None, Some(r), Some(r)),
            "Next is rounded on the right only"
        );
        for (p, child) in children.iter().enumerate().take(total + 1).skip(1) {
            assert_eq!(
                radii(&inline_props(child)),
                (None, None, None, None),
                "interior page {p} must stay square"
            );
            assert_eq!(
                has_left_border(&inline_props(child)),
                (false, false, false),
                "only Prev draws a left border, so buttons share one separator"
            );
        }
        assert_eq!(
            has_left_border(&inline_props(&children[0])),
            (true, true, true),
            "Prev closes the left edge of the bar"
        );
    }
    #[test]
    fn dom_carries_the_container_style_and_the_button_styles_verbatim() {
        let p = Pagination::create(2, 3);
        let dom = p.dom();
        assert_eq!(
            inline_props(&dom),
            PAGINATION_CONTAINER_STYLE
                .iter()
                .map(|p| p.property.clone())
                .collect::<Vec<_>>(),
            "the container style must survive the Dom round-trip"
        );
        let children = dom.children.as_ref();
        assert_eq!(
            inline_props(&children[2]),
            declared(&build_button_style(true, false, false, false)),
            "the active page's style must match the builder output verbatim"
        );
        assert_eq!(
            inline_props(&children[0]),
            declared(&build_button_style(false, false, true, false)),
            "Prev's style must match the builder output verbatim"
        );
        // page 2 of 3, so Next is *not* at its bound and stays un-muted.
        assert_eq!(
            inline_props(&children[4]),
            declared(&build_button_style(false, false, false, true)),
            "Next's style must match the builder output verbatim"
        );
    }
    #[test]
    fn dom_estimated_total_children_matches_the_real_child_count() {
        // `estimated_total_children` is a cached count; if it under-counts,
        // `convert_dom_into_compact_dom` under-allocates.
        for total in [1usize, 2, 3, 8, 64, 257] {
            let dom = Pagination::create(1, total).dom();
            assert_eq!(dom.children.as_ref().len(), total + 2);
            assert_eq!(
                dom.estimated_total_children,
                2 * (total + 2),
                "cached descendant count desynced for total={total}"
            );
        }
    }
    #[test]
    fn dom_of_a_hand_zeroed_total_has_only_prev_and_next() {
        // `total_pages` is a pub field: zeroing it must yield an inert two-button
        // bar, not an empty/negative range or a panic.
        let mut p = Pagination::create(1, 3);
        p.pagination_state.inner.total_pages = 0;
        let dom = p.dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 2, "no pages => just Prev and Next");
        assert_eq!(text_of(&children[0]), Some("Prev"));
        assert_eq!(text_of(&children[1]), Some("Next"));
        // current(1) >= total(0), so Next reads as disabled too.
        assert_eq!(text_color(&inline_props(&children[1])), Some(DISABLED_TEXT));
    }
    #[test]
    fn dom_of_an_out_of_range_current_page_marks_nothing_active() {
        // Reachable only by writing the pub field directly. The bar must still
        // render deterministically instead of indexing out of bounds.
        let mut p = Pagination::create(1, 4);
        p.pagination_state.inner.current_page = 99;
        let dom = p.dom();
        let children = dom.children.as_ref();
        assert_eq!(children.len(), 6);
        assert!(
            (0..children.len())
                .all(|i| background_color(&inline_props(&children[i])) == Some(NEUTRAL_BG_COLOR)),
            "no page matches 99, so nothing is painted active"
        );
        assert_eq!(
            text_color(&inline_props(&children[0])),
            Some(NEUTRAL_TEXT),
            "Prev is live (99 > 1)"
        );
        assert_eq!(
            text_color(&inline_props(&children[5])),
            Some(DISABLED_TEXT),
            "Next is muted (99 >= 4)"
        );
    }
    #[test]
    fn dom_of_many_pages_flattens_without_panicking() {
        let total = 500;
        let styled = StyledDom::create_from_dom(Pagination::create(250, total).dom());
        assert_eq!(
            styled.node_hierarchy.as_ref().len(),
            2 * total + 5,
            "root + (Prev + {total} pages + Next), each a <p> wrapping one text node"
        );
    }
    #[test]
    fn from_pagination_for_dom_equals_dom() {
        let dom: Dom = Pagination::create(2, 3).into();
        assert_eq!(dom.children.as_ref().len(), 5);
        assert_eq!(text_of(&dom.children.as_ref()[0]), Some("Prev"));
    }
    // ==================================================================
    // on_page_click
    // ==================================================================
    #[test]
    fn click_next_advances_exactly_one_page() {
        let total = 5;
        let (styled, state) = flatten(Pagination::create(2, total));
        let mut state2 = state.clone();
        let (update, changes) = run_click(Some(styled), next_node(total), state);
        assert_eq!(
            update,
            Update::DoNothing,
            "no user callback => nothing to redraw"
        );
        assert_eq!(current_page_of(&mut state2), 3, "Next must step 2 -> 3");
        assert_eq!(
            restyle(&changes).len(),
            total + 2,
            "every button is restyled after a real change"
        );
    }
    #[test]
    fn click_prev_steps_back_exactly_one_page() {
        let total = 5;
        let (styled, state) = flatten(Pagination::create(4, total));
        let mut state2 = state.clone();
        let (_, _) = run_click(Some(styled), PREV_NODE, state);
        assert_eq!(current_page_of(&mut state2), 3, "Prev must step 4 -> 3");
    }
    #[test]
    fn click_a_page_number_jumps_straight_to_it() {
        let total = 8;
        for target in [1usize, 2, 7, 8] {
            let (styled, state) = flatten(Pagination::create(4, total));
            let mut state2 = state.clone();
            let (_, changes) = run_click(Some(styled), page_node(target), state);
            assert_eq!(
                current_page_of(&mut state2),
                target,
                "page button {target} sits at sibling position {target}"
            );
            assert!(!changes.is_empty(), "a real jump must restyle the bar");
        }
    }
    #[test]
    fn click_the_current_page_is_a_no_op() {
        let total = 6;
        let (styled, state) = flatten(Pagination::create(3, total));
        let mut state2 = state.clone();
        let (update, changes) = run_click(Some(styled), page_node(3), state);
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "an unchanged page must not push a restyle transaction"
        );
        assert_eq!(current_page_of(&mut state2), 3);
    }
    #[test]
    fn click_prev_at_the_first_page_is_a_no_op() {
        let total = 4;
        let (styled, state) = flatten(Pagination::create(1, total));
        let mut state2 = state.clone();
        let (update, changes) = run_click(Some(styled), PREV_NODE, state);
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a disabled end must fire nothing at all"
        );
        assert_eq!(
            current_page_of(&mut state2),
            1,
            "page 1 must not underflow to 0"
        );
    }
    #[test]
    fn click_next_at_the_last_page_is_a_no_op() {
        let total = 4;
        let (styled, state) = flatten(Pagination::create(total, total));
        let mut state2 = state.clone();
        let (update, changes) = run_click(Some(styled), next_node(total), state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(
            current_page_of(&mut state2),
            total,
            "must not run past the end"
        );
    }
    #[test]
    fn click_walks_the_whole_range_without_escaping_its_bounds() {
        let total = 6;
        let (styled, state) = flatten(Pagination::create(1, total));
        let mut probe = state.clone();
        // Press Next more often than there are pages.
        for step in 0..(total + 2) {
            let (_, _) = run_click(Some(styled.clone()), next_node(total), state.clone());
            let page = current_page_of(&mut probe);
            assert!(
                (1..=total).contains(&page),
                "page {page} escaped [1, {total}] after {step} Next presses"
            );
            assert_eq!(
                page,
                (step + 2).min(total),
                "Next must advance one at a time"
            );
        }
        assert_eq!(current_page_of(&mut probe), total);
        // …then all the way back down.
        for step in 0..(total + 2) {
            let (_, _) = run_click(Some(styled.clone()), PREV_NODE, state.clone());
            let page = current_page_of(&mut probe);
            assert!(
                (1..=total).contains(&page),
                "page {page} escaped [1, {total}]"
            );
            assert_eq!(page, total.saturating_sub(step + 1).max(1));
        }
        assert_eq!(current_page_of(&mut probe), 1);
    }
    #[test]
    fn click_on_a_one_page_pager_is_completely_inert() {
        let (styled, state) = flatten(Pagination::create(1, 1));
        let mut probe = state.clone();
        for hit in [PREV_NODE, page_node(1), next_node(1)] {
            let (update, changes) = run_click(Some(styled.clone()), hit, state.clone());
            assert_eq!(update, Update::DoNothing, "node {hit} on a 1-page pager");
            assert!(changes.is_empty(), "node {hit} must not restyle anything");
            assert_eq!(current_page_of(&mut probe), 1);
        }
    }
    #[test]
    fn click_on_a_hand_zeroed_pager_is_inert() {
        // total_pages = 0 => children are just [Prev, Next] (n == 2, total == 0).
        // The `n < 2` guard is not hit, so both ends must fall through the bounds
        // checks instead of computing a 0/underflowing page.
        let mut p = Pagination::create(1, 3);
        p.pagination_state.inner.total_pages = 0;
        let (styled, state) = flatten(p);
        let mut probe = state.clone();
        for hit in [1usize, 2] {
            let (update, changes) = run_click(Some(styled.clone()), hit, state.clone());
            assert_eq!(update, Update::DoNothing, "node {hit} on a 0-page pager");
            assert!(changes.is_empty());
            assert_eq!(current_page_of(&mut probe), 1);
        }
    }
    #[test]
    fn click_invokes_the_user_callback_with_the_new_state() {
        let total = 5;
        let mut log = RefAny::new(ChangeLog { seen: Vec::new() });
        let p = Pagination::create(1, total).with_on_change(log.clone(), cb(record_change));
        let (styled, state) = flatten(p);
        let (update, _) = run_click(Some(styled.clone()), page_node(4), state.clone());
        assert_eq!(
            update,
            Update::RefreshDom,
            "the user's Update must propagate"
        );
        assert_eq!(
            logged(&mut log),
            vec![PaginationState {
                current_page: 4,
                total_pages: total,
            }],
            "the callback sees the *new* page, with total_pages intact"
        );
        // A no-op click must not fire the callback again.
        let (update, _) = run_click(Some(styled.clone()), page_node(4), state.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(logged(&mut log).len(), 1, "an unchanged page fires nothing");
        let (_, _) = run_click(Some(styled), PREV_NODE, state);
        assert_eq!(
            logged(&mut log).len(),
            2,
            "a real change fires the callback again"
        );
        assert_eq!(logged(&mut log)[1].current_page, 3);
    }
    #[test]
    fn click_propagates_every_update_variant_unchanged() {
        for (callback, expected) in [
            (cb(change_do_nothing), Update::DoNothing),
            (cb(change_refresh_all), Update::RefreshDomAllWindows),
        ] {
            let p = Pagination::create(1, 3).with_on_change(RefAny::new(0u8), callback);
            let (styled, state) = flatten(p);
            let (update, _) = run_click(Some(styled), page_node(2), state);
            assert_eq!(update, expected);
        }
    }
    #[test]
    fn click_restyles_every_button_and_marks_only_the_new_page() {
        let total = 5;
        let new_page = 4;
        let (styled, state) = flatten(Pagination::create(1, total));
        let (_, changes) = run_click(Some(styled), page_node(new_page), state);
        let pass = restyle(&changes);
        assert_eq!(pass.len(), total + 2, "one pair of writes per button");
        for (i, (node, bg, fg)) in pass.iter().enumerate() {
            assert_eq!(
                *node,
                2 * i + 1,
                "buttons must be restyled in document order"
            );
            let (want_bg, want_fg) = if i == 0 {
                // Prev: live, because the new page is not 1.
                (NEUTRAL_BG_COLOR, NEUTRAL_TEXT)
            } else if i == total + 1 {
                // Next: live, because the new page is not the last.
                (NEUTRAL_BG_COLOR, NEUTRAL_TEXT)
            } else if i == new_page {
                (ACCENT_BG_COLOR, ACTIVE_TEXT)
            } else {
                (NEUTRAL_BG_COLOR, NEUTRAL_TEXT)
            };
            assert_eq!((*bg, *fg), (want_bg, want_fg), "button {i} after the jump");
        }
    }
    #[test]
    fn click_restyle_mutes_the_end_it_lands_on() {
        let total = 4;
        // Landing on page 1 must mute Prev…
        let (styled, state) = flatten(Pagination::create(3, total));
        let (_, changes) = run_click(Some(styled), page_node(1), state);
        let pass = restyle(&changes);
        assert_eq!(pass[0].2, DISABLED_TEXT, "Prev must go muted at page 1");
        assert_eq!(pass[total + 1].2, NEUTRAL_TEXT, "Next stays live at page 1");
        // …and landing on the last page must mute Next.
        let (styled, state) = flatten(Pagination::create(1, total));
        let (_, changes) = run_click(Some(styled), page_node(total), state);
        let pass = restyle(&changes);
        assert_eq!(pass[0].2, NEUTRAL_TEXT, "Prev is live at the last page");
        assert_eq!(
            pass[total + 1].2,
            DISABLED_TEXT,
            "Next must go muted at the end"
        );
    }
    #[test]
    fn click_on_the_root_node_does_nothing() {
        // The root has no parent -> the handler must bail before touching anything.
        let (styled, state) = flatten(Pagination::create(2, 4));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), 0, state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(current_page_of(&mut probe), 2, "state must be untouched");
    }
    #[test]
    fn click_on_an_out_of_range_node_does_nothing() {
        let (styled, state) = flatten(Pagination::create(2, 4));
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled), 9999, state);
        assert_eq!(
            update,
            Update::DoNothing,
            "a hit node that isn't in the tree must not panic"
        );
        assert!(changes.is_empty());
        assert_eq!(current_page_of(&mut probe), 2);
    }
    #[test]
    fn click_with_no_layout_result_does_nothing() {
        let dom = Pagination::create(2, 4).dom();
        let state = button_state(&dom, 0);
        let (update, changes) = run_click(None, PREV_NODE, state);
        assert_eq!(
            update,
            Update::DoNothing,
            "an empty LayoutWindow must be handled, not unwrapped"
        );
        assert!(changes.is_empty());
    }
    #[test]
    fn click_with_a_foreign_payload_does_nothing() {
        let (styled, _) = flatten(Pagination::create(2, 4));
        let (update, changes) = run_click(Some(styled), page_node(3), RefAny::new(0u32));
        assert_eq!(
            update,
            Update::DoNothing,
            "a failed downcast must bail cleanly"
        );
        assert!(
            changes.is_empty(),
            "no state change => no restyle, even for a foreign payload"
        );
    }
    #[test]
    fn click_with_the_state_already_borrowed_does_nothing() {
        let (styled, state) = flatten(Pagination::create(2, 4));
        // A live mutable borrow on a sibling clone: the handler's own `downcast_ref`
        // must fail (returning DoNothing) instead of aliasing `&mut`.
        let mut held = state.clone();
        let guard = held
            .downcast_mut::<PaginationStateWrapper>()
            .expect("first borrow succeeds");
        let (update, changes) = run_click(Some(styled), page_node(3), state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        drop(guard);
    }
    #[test]
    fn click_derives_the_page_count_from_the_live_dom_not_from_the_state() {
        // The doc promises the handler "stays correct regardless of total_pages
        // drift": it reads the child count, so a stale `total_pages` in the state
        // must not change where Next stops.
        let total = 3;
        let dom = Pagination::create(1, total).dom();
        let mut state = button_state(&dom, 0);
        // Corrupt the *shared* state after the DOM was built: the rendered bar
        // still has 3 page buttons.
        {
            let mut w = state
                .downcast_mut::<PaginationStateWrapper>()
                .expect("the shared payload is a PaginationStateWrapper");
            w.inner.total_pages = 999;
        }
        let styled = StyledDom::create_from_dom(dom);
        let mut probe = state.clone();
        for _ in 0..(total + 3) {
            let (_, _) = run_click(Some(styled.clone()), next_node(total), state.clone());
        }
        assert_eq!(
            current_page_of(&mut probe),
            total,
            "Next must stop at the last *rendered* page, not at the stale total"
        );
        assert_eq!(
            state
                .downcast_ref::<PaginationStateWrapper>()
                .expect("still a PaginationStateWrapper")
                .inner
                .total_pages,
            999,
            "the handler must not rewrite total_pages behind the caller's back"
        );
    }
    #[test]
    fn click_prev_from_an_out_of_range_page_steps_down_by_one() {
        // Only reachable by writing the pub `current_page` field. The handler has no
        // clamp of its own, so it walks down one step at a time rather than snapping
        // back into range — assert that documented-by-construction behaviour rather
        // than a silent repair.
        let total = 4;
        let mut p = Pagination::create(1, total);
        p.pagination_state.inner.current_page = 99;
        let (styled, state) = flatten(p);
        let mut probe = state.clone();
        let (update, changes) = run_click(Some(styled.clone()), PREV_NODE, state.clone());
        assert_eq!(update, Update::DoNothing, "no callback installed");
        assert_eq!(current_page_of(&mut probe), 98, "Prev steps 99 -> 98");
        // Nothing is in range, so the restyle marks no page active.
        let pass = restyle(&changes);
        assert_eq!(pass.len(), total + 2);
        assert!(
            pass.iter().all(|(_, bg, _)| *bg == NEUTRAL_BG_COLOR),
            "an out-of-range page cannot be painted active"
        );
        // Next, by contrast, is a no-op: 98 is already past the last page.
        let (update, changes) = run_click(Some(styled), next_node(total), state);
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert_eq!(current_page_of(&mut probe), 98);
    }
    #[test]
    fn click_a_page_button_snaps_an_out_of_range_page_back_into_range() {
        let total = 4;
        let mut p = Pagination::create(1, total);
        p.pagination_state.inner.current_page = usize::MAX;
        let (styled, state) = flatten(p);
        let mut probe = state.clone();
        let (_, _) = run_click(Some(styled), page_node(2), state);
        assert_eq!(
            current_page_of(&mut probe),
            2,
            "an explicit page click always lands in range"
        );
    }
}