1
//! Accordion / expander widget — one or more collapsible titled sections. Each
2
//! section is a clickable header row plus a body that shows or hides. Combines
3
//! the expand/collapse state of [`crate::widgets::tree_view::TreeView`] with a
4
//! flat list of sections (each carrying an arbitrary content [`Dom`]).
5
//!
6
//! Sections toggle independently (any number may be open at once). Clicking a
7
//! header flips that section's `is_open` flag in a per-header [`RefAny`] (the
8
//! self-contained per-row data pattern of `tree_view`), invokes the optional
9
//! user `on_toggle(section_index)`, and shows/hides the section body by setting
10
//! `display: block | none` on it via `set_css_property` (mirroring tree_view /
11
//! check_box live restyling).
12
//!
13
//! TODO2: the header is a plain styled clickable bar with no animated disclosure
14
//! chevron — a glyph cannot be re-textured via `set_css_property` without a
15
//! relayout, so an indicator that flips on toggle is deferred. The `display`
16
//! toggle itself follows the proven live-restyle pattern but the `display:none`
17
//! relayout is not GUI-verified in this build.
18
//!
19
//! Key types: [`Accordion`], [`AccordionSection`], [`AccordionOnToggle`].
20

            
21
use std::vec::Vec;
22

            
23
use azul_core::{
24
    callbacks::{CoreCallback, CoreCallbackData, Update},
25
    dom::{
26
        Dom, DomVec, EventFilter, HoverEventFilter, IdOrClass, IdOrClass::Class, IdOrClassVec,
27
        TabIndex,
28
    },
29
    refany::{OptionRefAny, RefAny},
30
};
31
use azul_css::{
32
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
33
    impl_option, impl_option_inner, impl_vec, impl_vec_clone, impl_vec_debug, impl_vec_mut,
34
    impl_vec_partialeq,
35
    props::{
36
        basic::{
37
            color::ColorU,
38
            font::{StyleFontFamily, StyleFontFamilyVec},
39
            StyleFontSize,
40
        },
41
        layout::{
42
            LayoutAlignItems, LayoutDisplay, LayoutFlexDirection, LayoutFlexGrow, LayoutOverflow,
43
            LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop,
44
        },
45
        property::{CssProperty, CssPropertyType},
46
        style::{
47
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
48
            LayoutBorderTopWidth, StyleBackgroundContent, StyleBackgroundContentVec,
49
            StyleBorderBottomColor, StyleBorderBottomLeftRadius, StyleBorderBottomRightRadius,
50
            StyleBorderBottomStyle, StyleBorderLeftColor, StyleBorderLeftStyle,
51
            StyleBorderRightColor, StyleBorderRightStyle, StyleBorderTopColor,
52
            StyleBorderTopLeftRadius, StyleBorderTopRightRadius, StyleBorderTopStyle, StyleCursor,
53
            StyleTextAlign, StyleTextColor, StyleUserSelect,
54
        },
55
    },
56
    AzString,
57
};
58

            
59
use crate::callbacks::{Callback, CallbackInfo};
60

            
61
static ACCORDION_CLASS: &[IdOrClass] =
62
    &[Class(AzString::from_const_str("__azul-native-accordion"))];
63
static ACCORDION_SECTION_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
64
    "__azul-native-accordion-section",
65
))];
66
static ACCORDION_HEADER_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
67
    "__azul-native-accordion-header",
68
))];
69
static ACCORDION_TITLE_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
70
    "__azul-native-accordion-title",
71
))];
72
static ACCORDION_BODY_CLASS: &[IdOrClass] = &[Class(AzString::from_const_str(
73
    "__azul-native-accordion-body",
74
))];
75

            
76
const SYSTEM_UI_STR: AzString = AzString::from_const_str("system:ui");
77
const SYSTEM_UI_FAMILIES: &[StyleFontFamily] = &[StyleFontFamily::System(SYSTEM_UI_STR)];
78
const SYSTEM_UI_FAMILY: StyleFontFamilyVec =
79
    StyleFontFamilyVec::from_const_slice(SYSTEM_UI_FAMILIES);
80

            
81
/// Callback invoked when a section header is clicked. The `usize` is the
82
/// zero-based index of the toggled section.
83
pub type AccordionOnToggleCallbackType = extern "C" fn(RefAny, CallbackInfo, usize) -> Update;
84
impl_widget_callback!(
85
    AccordionOnToggle,
86
    OptionAccordionOnToggle,
87
    AccordionOnToggleCallback,
88
    AccordionOnToggleCallbackType
89
);
90

            
91
azul_core::impl_managed_callback! {
92
    wrapper:        AccordionOnToggleCallback,
93
    info_ty:        CallbackInfo,
94
    return_ty:      Update,
95
    default_ret:    Update::DoNothing,
96
    invoker_static: ACCORDION_ON_TOGGLE_INVOKER,
97
    invoker_ty:     AzAccordionOnToggleCallbackInvoker,
98
    thunk_fn:       az_accordion_on_toggle_callback_thunk,
99
    setter_fn:      AzApp_setAccordionOnToggleCallbackInvoker,
100
    from_handle_fn: AzAccordionOnToggleCallback_createFromHostHandle,
101
    extra_args:     [ section_index: usize ],
102
}
103

            
104
// ---- colours ----
105
const BORDER_COLOR: ColorU = ColorU {
106
    r: 222,
107
    g: 226,
108
    b: 230,
109
    a: 255,
110
}; // #dee2e6
111
const HEADER_BG: ColorU = ColorU {
112
    r: 248,
113
    g: 249,
114
    b: 250,
115
    a: 255,
116
}; // #f8f9fa
117
const TEXT_COLOR: ColorU = ColorU {
118
    r: 33,
119
    g: 37,
120
    b: 41,
121
    a: 255,
122
}; // #212529
123

            
124
const HEADER_BG_ITEMS: &[StyleBackgroundContent] = &[StyleBackgroundContent::Color(HEADER_BG)];
125
const HEADER_BG_VEC: StyleBackgroundContentVec =
126
    StyleBackgroundContentVec::from_const_slice(HEADER_BG_ITEMS);
127

            
128
/// One collapsible section: a header title and an arbitrary content body.
129
#[derive(Debug, Clone, PartialEq, Eq)]
130
#[repr(C)]
131
pub struct AccordionSection {
132
    /// The header text shown for this section.
133
    pub title: AzString,
134
    /// The body content revealed when the section is open.
135
    pub content: Dom,
136
    /// Whether this section starts open (body visible).
137
    pub is_open: bool,
138
}
139

            
140
impl AccordionSection {
141
    /// Creates a new collapsed section with the given title and content.
142
1094
    pub fn new<S: Into<AzString>>(title: S, content: Dom) -> Self {
143
1094
        Self {
144
1094
            title: title.into(),
145
1094
            content,
146
1094
            is_open: false,
147
1094
        }
148
1094
    }
149

            
150
    /// Builder method: sets the initial open state.
151
    #[must_use]
152
1084
    pub const fn with_open(mut self, open: bool) -> Self {
153
1084
        self.is_open = open;
154
1084
        self
155
1084
    }
156
}
157

            
158
impl_option!(
159
    AccordionSection,
160
    OptionAccordionSection,
161
    copy = false,
162
    [Debug, Clone, PartialEq, Eq]
163
);
164
impl_vec!(
165
    AccordionSection,
166
    AccordionSectionVec,
167
    AccordionSectionVecDestructor,
168
    AccordionSectionVecDestructorType,
169
    AccordionSectionVecSlice,
170
    OptionAccordionSection
171
);
172
impl_vec_clone!(
173
    AccordionSection,
174
    AccordionSectionVec,
175
    AccordionSectionVecDestructor
176
);
177
impl_vec_debug!(AccordionSection, AccordionSectionVec);
178
impl_vec_partialeq!(AccordionSection, AccordionSectionVec);
179
impl_vec_mut!(AccordionSection, AccordionSectionVec);
180

            
181
/// A vertical stack of collapsible titled sections.
182
#[derive(Debug, Clone, PartialEq)]
183
#[repr(C)]
184
pub struct Accordion {
185
    /// The sections, in display order.
186
    pub sections: AccordionSectionVec,
187
    /// Optional callback fired when any section header is toggled.
188
    pub on_toggle: OptionAccordionOnToggle,
189
}
190

            
191
// ---- styles ----
192

            
193
static ACCORDION_CONTAINER_STYLE: &[CssPropertyWithConditions] = &[
194
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
195
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
196
        LayoutFlexDirection::Column,
197
    )),
198
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
199
    CssPropertyWithConditions::simple(CssProperty::const_font_size(StyleFontSize::const_px(14))),
200
    CssPropertyWithConditions::simple(CssProperty::const_font_family(SYSTEM_UI_FAMILY)),
201
    CssPropertyWithConditions::simple(CssProperty::const_text_color(StyleTextColor {
202
        inner: TEXT_COLOR,
203
    })),
204
    // border: 1px solid #dee2e6
205
    CssPropertyWithConditions::simple(CssProperty::const_border_top_width(
206
        LayoutBorderTopWidth::const_px(1),
207
    )),
208
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
209
        LayoutBorderBottomWidth::const_px(1),
210
    )),
211
    CssPropertyWithConditions::simple(CssProperty::const_border_left_width(
212
        LayoutBorderLeftWidth::const_px(1),
213
    )),
214
    CssPropertyWithConditions::simple(CssProperty::const_border_right_width(
215
        LayoutBorderRightWidth::const_px(1),
216
    )),
217
    CssPropertyWithConditions::simple(CssProperty::const_border_top_style(StyleBorderTopStyle {
218
        inner: BorderStyle::Solid,
219
    })),
220
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
221
        StyleBorderBottomStyle {
222
            inner: BorderStyle::Solid,
223
        },
224
    )),
225
    CssPropertyWithConditions::simple(CssProperty::const_border_left_style(StyleBorderLeftStyle {
226
        inner: BorderStyle::Solid,
227
    })),
228
    CssPropertyWithConditions::simple(CssProperty::const_border_right_style(
229
        StyleBorderRightStyle {
230
            inner: BorderStyle::Solid,
231
        },
232
    )),
233
    CssPropertyWithConditions::simple(CssProperty::const_border_top_color(StyleBorderTopColor {
234
        inner: BORDER_COLOR,
235
    })),
236
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
237
        StyleBorderBottomColor {
238
            inner: BORDER_COLOR,
239
        },
240
    )),
241
    CssPropertyWithConditions::simple(CssProperty::const_border_left_color(StyleBorderLeftColor {
242
        inner: BORDER_COLOR,
243
    })),
244
    CssPropertyWithConditions::simple(CssProperty::const_border_right_color(
245
        StyleBorderRightColor {
246
            inner: BORDER_COLOR,
247
        },
248
    )),
249
    // rounded corners, clipping the per-section separators
250
    CssPropertyWithConditions::simple(CssProperty::const_border_top_left_radius(
251
        StyleBorderTopLeftRadius::const_px(6),
252
    )),
253
    CssPropertyWithConditions::simple(CssProperty::const_border_top_right_radius(
254
        StyleBorderTopRightRadius::const_px(6),
255
    )),
256
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_left_radius(
257
        StyleBorderBottomLeftRadius::const_px(6),
258
    )),
259
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_right_radius(
260
        StyleBorderBottomRightRadius::const_px(6),
261
    )),
262
    CssPropertyWithConditions::simple(CssProperty::const_overflow_x(LayoutOverflow::Hidden)),
263
    CssPropertyWithConditions::simple(CssProperty::const_overflow_y(LayoutOverflow::Hidden)),
264
];
265

            
266
static ACCORDION_SECTION_STYLE: &[CssPropertyWithConditions] = &[
267
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
268
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(
269
        LayoutFlexDirection::Column,
270
    )),
271
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
272
    // a thin separator between stacked sections
273
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_width(
274
        LayoutBorderBottomWidth::const_px(1),
275
    )),
276
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_style(
277
        StyleBorderBottomStyle {
278
            inner: BorderStyle::Solid,
279
        },
280
    )),
281
    CssPropertyWithConditions::simple(CssProperty::const_border_bottom_color(
282
        StyleBorderBottomColor {
283
            inner: BORDER_COLOR,
284
        },
285
    )),
286
];
287

            
288
static ACCORDION_HEADER_STYLE: &[CssPropertyWithConditions] = &[
289
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Flex)),
290
    CssPropertyWithConditions::simple(CssProperty::const_flex_direction(LayoutFlexDirection::Row)),
291
    CssPropertyWithConditions::simple(CssProperty::const_align_items(LayoutAlignItems::Center)),
292
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(0))),
293
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
294
        10,
295
    ))),
296
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
297
        LayoutPaddingBottom::const_px(10),
298
    )),
299
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
300
        LayoutPaddingLeft::const_px(12),
301
    )),
302
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
303
        LayoutPaddingRight::const_px(12),
304
    )),
305
    CssPropertyWithConditions::simple(CssProperty::const_cursor(StyleCursor::Pointer)),
306
    CssPropertyWithConditions::simple(CssProperty::user_select(StyleUserSelect::None)),
307
    CssPropertyWithConditions::simple(CssProperty::const_background_content(HEADER_BG_VEC)),
308
];
309

            
310
static ACCORDION_TITLE_STYLE: &[CssPropertyWithConditions] = &[
311
    CssPropertyWithConditions::simple(CssProperty::const_flex_grow(LayoutFlexGrow::const_new(1))),
312
    CssPropertyWithConditions::simple(CssProperty::const_text_align(StyleTextAlign::Left)),
313
];
314

            
315
/// Body style when the section is OPEN: a padded block with a top separator.
316
static ACCORDION_BODY_STYLE_OPEN: &[CssPropertyWithConditions] = &[
317
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::Block)),
318
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
319
        12,
320
    ))),
321
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
322
        LayoutPaddingBottom::const_px(12),
323
    )),
324
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
325
        LayoutPaddingLeft::const_px(12),
326
    )),
327
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
328
        LayoutPaddingRight::const_px(12),
329
    )),
330
];
331

            
332
/// Body style when the section is CLOSED: not laid out at all.
333
///
334
/// This MUST declare everything the open style declares except `display`.
335
/// The runtime toggle (`on_accordion_header_click`) writes ONLY `display`, so
336
/// any property that exists solely in the open table is missing from a body
337
/// that reached the open state by CLICK rather than by being built open. That
338
/// is exactly what happened: the padding lived only in the open table, so a
339
/// clicked-open section rendered its text flush against the container's
340
/// rounded border while a born-open section was correctly inset by 12 px.
341
static ACCORDION_BODY_STYLE_CLOSED: &[CssPropertyWithConditions] = &[
342
    CssPropertyWithConditions::simple(CssProperty::const_display(LayoutDisplay::None)),
343
    CssPropertyWithConditions::simple(CssProperty::const_padding_top(LayoutPaddingTop::const_px(
344
        12,
345
    ))),
346
    CssPropertyWithConditions::simple(CssProperty::const_padding_bottom(
347
        LayoutPaddingBottom::const_px(12),
348
    )),
349
    CssPropertyWithConditions::simple(CssProperty::const_padding_left(
350
        LayoutPaddingLeft::const_px(12),
351
    )),
352
    CssPropertyWithConditions::simple(CssProperty::const_padding_right(
353
        LayoutPaddingRight::const_px(12),
354
    )),
355
];
356

            
357
impl Accordion {
358
    /// Creates a new accordion from the given sections, with no toggle callback.
359
    #[must_use]
360
32
    pub fn new(sections: AccordionSectionVec) -> Self {
361
32
        Self {
362
32
            sections,
363
32
            on_toggle: None.into(),
364
32
        }
365
32
    }
366

            
367
    /// Creates an empty accordion.
368
    #[must_use]
369
13
    pub fn create() -> Self {
370
13
        Self::new(AccordionSectionVec::from_const_slice(&[]))
371
13
    }
372

            
373
    /// Sets the callback invoked when any section header is toggled.
374
6
    pub fn set_on_toggle<C: Into<AccordionOnToggleCallback>>(&mut self, data: RefAny, callback: C) {
375
6
        self.on_toggle = Some(AccordionOnToggle {
376
6
            callback: callback.into(),
377
6
            refany: data,
378
6
        })
379
6
        .into();
380
6
    }
381

            
382
    /// Builder method: sets the toggle callback.
383
    #[must_use]
384
3
    pub fn with_on_toggle<C: Into<AccordionOnToggleCallback>>(
385
3
        mut self,
386
3
        data: RefAny,
387
3
        callback: C,
388
3
    ) -> Self {
389
3
        self.set_on_toggle(data, callback);
390
3
        self
391
3
    }
392

            
393
    /// Replaces `self` with an empty default accordion and returns the original.
394
    #[must_use]
395
2
    pub fn swap_with_default(&mut self) -> Self {
396
2
        let mut s = Self::create();
397
2
        core::mem::swap(&mut s, self);
398
2
        s
399
2
    }
400

            
401
    /// Renders the accordion into a [`Dom`] subtree.
402
    #[must_use]
403
17
    pub fn dom(self) -> Dom {
404
17
        let on_toggle = self.on_toggle;
405
17
        let sections = self.sections;
406

            
407
17
        let mut section_doms: Vec<Dom> = Vec::with_capacity(sections.as_ref().len());
408

            
409
86
        for (index, section) in sections.as_ref().iter().enumerate() {
410
86
            let title = crate::widgets::widget_p_with_text(section.title.clone())
411
86
                .with_ids_and_classes(IdOrClassVec::from_const_slice(ACCORDION_TITLE_CLASS))
412
86
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
413
86
                    ACCORDION_TITLE_STYLE,
414
                ));
415

            
416
            // Read the open state before it is moved into the click data.
417
86
            let section_is_open = section.is_open;
418

            
419
            // Per-header self-contained click data (mirrors tree_view's NodeClickData).
420
86
            let header_data = HeaderClickData {
421
86
                index,
422
86
                is_open: section.is_open,
423
86
                on_toggle: clone_option_on_toggle(&on_toggle),
424
86
            };
425

            
426
86
            let header = Dom::create_div()
427
86
                .with_ids_and_classes(IdOrClassVec::from_const_slice(ACCORDION_HEADER_CLASS))
428
86
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
429
86
                    ACCORDION_HEADER_STYLE,
430
                ))
431
86
                .with_tab_index(TabIndex::Auto)
432
                // A section header must report whether it is open. Expanded /
433
                // Collapsed is the difference between "Details" and "Details,
434
                // collapsed, activate to expand" — without it the header reads
435
                // identically in both states and the control appears inert.
436
86
                .with_accessibility_info(azul_core::a11y::AccessibilityInfo {
437
86
                    role: azul_core::a11y::AccessibilityRole::OutlineItem,
438
86
                    states: azul_core::a11y::AccessibilityStateVec::from_vec(vec![
439
86
                        if section_is_open {
440
29
                            azul_core::a11y::AccessibilityState::Expanded
441
                        } else {
442
57
                            azul_core::a11y::AccessibilityState::Collapsed
443
                        },
444
                    ]),
445
86
                    ..Default::default()
446
                })
447
86
                .with_callbacks(
448
86
                    alloc::vec![CoreCallbackData {
449
86
                        event: EventFilter::Hover(HoverEventFilter::Click),
450
86
                        callback: CoreCallback {
451
86
                            cb: on_accordion_header_click as usize,
452
86
                            ctx: OptionRefAny::None,
453
86
                        },
454
86
                        refany: RefAny::new(header_data),
455
86
                    }]
456
86
                    .into(),
457
                )
458
86
                .with_children(DomVec::from_vec(alloc::vec![title]));
459

            
460
86
            let body_style = if section.is_open {
461
29
                ACCORDION_BODY_STYLE_OPEN
462
            } else {
463
57
                ACCORDION_BODY_STYLE_CLOSED
464
            };
465
86
            let body = Dom::create_div()
466
86
                .with_ids_and_classes(IdOrClassVec::from_const_slice(ACCORDION_BODY_CLASS))
467
86
                .with_css_props(CssPropertyWithConditionsVec::from_const_slice(body_style))
468
86
                .with_children(DomVec::from_vec(alloc::vec![section.content.clone()]));
469

            
470
86
            section_doms.push(
471
86
                Dom::create_div()
472
86
                    .with_ids_and_classes(IdOrClassVec::from_const_slice(ACCORDION_SECTION_CLASS))
473
86
                    .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
474
86
                        ACCORDION_SECTION_STYLE,
475
                    ))
476
86
                    .with_children(DomVec::from_vec(alloc::vec![header, body])),
477
            );
478
        }
479

            
480
17
        Dom::create_div()
481
17
            .with_ids_and_classes(IdOrClassVec::from_const_slice(ACCORDION_CLASS))
482
17
            .with_css_props(CssPropertyWithConditionsVec::from_const_slice(
483
17
                ACCORDION_CONTAINER_STYLE,
484
            ))
485
17
            .with_children(DomVec::from_vec(section_doms))
486
17
    }
487
}
488

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

            
495
/// Clones an `OptionAccordionOnToggle` (the callback wrapper is not `Copy`).
496
90
fn clone_option_on_toggle(opt: &OptionAccordionOnToggle) -> OptionAccordionOnToggle {
497
90
    match opt.as_ref() {
498
3
        Some(AccordionOnToggle { callback, refany }) => Some(AccordionOnToggle {
499
3
            callback: callback.clone(),
500
3
            refany: refany.clone(),
501
3
        })
502
3
        .into(),
503
87
        None => None.into(),
504
    }
505
90
}
506

            
507
/// Per-header callback payload (kept internal, like `tree_view::NodeClickData`).
508
struct HeaderClickData {
509
    index: usize,
510
    is_open: bool,
511
    on_toggle: OptionAccordionOnToggle,
512
}
513

            
514
/// Header click handler. The hit node is the header (the callback-bearing node,
515
/// per `currentTarget` semantics — see `radio_group`); its next sibling is the
516
/// body. Flips this section's `is_open`, invokes the optional user callback with
517
/// the section index, then shows/hides the body via `display`.
518
8
extern "C" fn on_accordion_header_click(mut data: RefAny, mut info: CallbackInfo) -> Update {
519
8
    let header = info.get_hit_node();
520
8
    let Some(body) = info.get_next_sibling(header) else {
521
3
        return Update::DoNothing;
522
    };
523

            
524
4
    let (now_open, result) = {
525
5
        let Some(mut hd) = data.downcast_mut::<HeaderClickData>() else {
526
1
            return Update::DoNothing;
527
        };
528
4
        hd.is_open = !hd.is_open;
529
4
        let now_open = hd.is_open;
530
4
        let index = hd.index;
531
4
        let result = match hd.on_toggle.as_mut() {
532
2
            Some(AccordionOnToggle { callback, refany }) => {
533
2
                (callback.cb)(refany.clone(), info, index)
534
            }
535
2
            None => Update::DoNothing,
536
        };
537
4
        (now_open, result)
538
    };
539

            
540
    // WHO OWNS THE VISUAL STATE decides what we write here.
541
    //
542
    // `set_css_property` does not just restyle this frame: it records a USER
543
    // OVERRIDE that `migrate_user_overrides_from` copies onto the matched node
544
    // of every later rebuild, and an override outranks the freshly cascaded
545
    // inline style. So if the host rebuilds the accordion from its own flag,
546
    // an override left behind here wins forever — the section that was clicked
547
    // open could never close again, and vice versa. That latch, not the toggle
548
    // itself, is what made the accordion "not properly expand/collapse".
549
    //
550
    // - Host rebuilds (`RefreshDom*`): it owns the flag. CLEAR the override (`initial` removes it)
551
    //   and let the rebuilt DOM's own style decide.
552
    // - Host does nothing: the widget owns the flag, so write the override — that is what makes a
553
    //   self-contained accordion work with no host state.
554
4
    if matches!(result, Update::RefreshDom | Update::RefreshDomAllWindows) {
555
2
        info.set_css_property(body, CssProperty::initial(CssPropertyType::Display));
556
2
    } else {
557
2
        let display = if now_open {
558
1
            LayoutDisplay::Block
559
        } else {
560
1
            LayoutDisplay::None
561
        };
562
2
        info.set_css_property(body, CssProperty::const_display(display));
563
    }
564

            
565
    // The header's ANNOUNCED state must follow the rendered one. This toggle
566
    // changes a css property and returns Update::DoNothing — no rebuild — so
567
    // the Expanded/Collapsed published when the DOM was built would be frozen
568
    // at whatever it was then. A sighted user sees the section close; a screen
569
    // reader would still say "expanded". Applying this marks the a11y tree
570
    // dirty, so the platform adapter re-reads the node.
571
4
    info.set_accessibility_state(
572
4
        info.get_hit_node(),
573
4
        azul_core::a11y::AccessibilityStateVec::from_vec(vec![if now_open {
574
2
            azul_core::a11y::AccessibilityState::Expanded
575
        } else {
576
2
            azul_core::a11y::AccessibilityState::Collapsed
577
        }]),
578
    );
579

            
580
4
    result
581
8
}
582

            
583
impl From<Accordion> for Dom {
584
1
    fn from(a: Accordion) -> Self {
585
1
        a.dom()
586
1
    }
587
}
588

            
589
#[cfg(all(test, feature = "std"))]
590
mod autotest_generated {
591
    use std::{
592
        collections::{BTreeMap, HashMap},
593
        sync::{Arc, Mutex},
594
    };
595

            
596
    use azul_core::{
597
        dom::{DomId, DomNodeId, NodeId, NodeType},
598
        geom::{LogicalRect, OptionLogicalPosition},
599
        gl::OptionGlContextPtr,
600
        hit_test::ScrollPosition,
601
        resources::RendererResources,
602
        styled_dom::{NodeHierarchyItemId, StyledDom},
603
        window::{MonitorVec, RawWindowHandle},
604
    };
605
    use azul_css::system::SystemStyle;
606
    use rust_fontconfig::FcFontCache;
607

            
608
    use super::*;
609
    #[cfg(feature = "icu")]
610
    use crate::icu::IcuLocalizerHandle;
611
    use crate::{
612
        callbacks::{CallbackChange, CallbackInfoRefData, ExternalSystemCallbacks},
613
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
614
        window::{DomLayoutResult, LayoutWindow},
615
        window_state::FullWindowState,
616
    };
617

            
618
    // ------------------------------------------------------------------
619
    // Helpers
620
    // ------------------------------------------------------------------
621

            
622
    /// True if `node` carries the CSS class `name`.
623
    fn has_class(node: &Dom, name: &str) -> bool {
624
        node.root
625
            .get_ids_and_classes()
626
            .as_ref()
627
            .iter()
628
            .any(|c| matches!(c, Class(s) if s.as_str() == name))
629
    }
630

            
631
    /// The text of a text node, looking through the `<p>` block wrapper the
632
    /// label convention mandates (`p > text`).
633
    fn text_of(node: &Dom) -> Option<&str> {
634
        match node.root.get_node_type() {
635
            NodeType::Text(s) => Some(s.as_ref().as_str()),
636
            NodeType::P => match node.children.as_ref() {
637
                [only] => match only.root.get_node_type() {
638
                    NodeType::Text(s) => Some(s.as_ref().as_str()),
639
                    _ => None,
640
                },
641
                _ => None,
642
            },
643
            _ => None,
644
        }
645
    }
646

            
647
    /// The `display` value in a node's *inline* style, if it sets one.
648
    fn inline_display(node: &Dom) -> Option<LayoutDisplay> {
649
        node.root
650
            .style
651
            .iter_inline_properties()
652
            .find_map(|(p, _)| match p {
653
                CssProperty::Display(v) => v.get_property().copied(),
654
                _ => None,
655
            })
656
    }
657

            
658
    /// `(header, body)` of the `n`-th section of a rendered accordion DOM.
659
    fn section_parts(dom: &Dom, n: usize) -> (&Dom, &Dom) {
660
        let section = &dom.children.as_ref()[n];
661
        assert!(has_class(section, "__azul-native-accordion-section"));
662
        let children = section.children.as_ref();
663
        assert_eq!(children.len(), 2, "a section is exactly [header, body]");
664
        (&children[0], &children[1])
665
    }
666

            
667
    /// A three-node styled DOM — `root(0)` with children `header(1)` and
668
    /// `body(2)` — i.e. the exact hierarchy `on_accordion_header_click` walks
669
    /// (`hit node` -> `next sibling`).
670
    fn header_body_dom() -> StyledDom {
671
        let styled = StyledDom::create_from_dom(
672
            Dom::create_div()
673
                .with_child(Dom::create_div())
674
                .with_child(Dom::create_div()),
675
        );
676
        assert_eq!(
677
            styled.node_hierarchy.as_ref().len(),
678
            3,
679
            "fixture must flatten to exactly root/header/body"
680
        );
681
        styled
682
    }
683

            
684
    /// A `DomLayoutResult` with an *empty* layout tree: the click handler only
685
    /// walks `styled_dom.node_hierarchy`, so no real layout (and no font) is needed.
686
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
687
        DomLayoutResult {
688
            styled_dom,
689
            layout_tree: LayoutTree {
690
                nodes: Vec::new(),
691
                warm: Vec::new(),
692
                cold: Vec::new(),
693
                root: 0,
694
                dom_to_layout: BTreeMap::new(),
695
                children_arena: Vec::new(),
696
                children_offsets: Vec::new(),
697
                subtree_needs_intrinsic: Vec::new(),
698
            },
699
            calculated_positions: Vec::new(),
700
            viewport: LogicalRect::zero(),
701
            display_list: Arc::new(DisplayList::default()),
702
            scroll_ids: HashMap::new(),
703
            scroll_id_to_node_id: HashMap::new(),
704
        }
705
    }
706

            
707
    /// Invokes `on_accordion_header_click` against a `LayoutWindow` holding
708
    /// `styled` (or nothing at all, when `styled` is `None`), with `hit` as the
709
    /// hit node. Returns the `Update` plus every recorded `CallbackChange`.
710
    fn run_click(
711
        styled: Option<StyledDom>,
712
        hit: usize,
713
        data: RefAny,
714
    ) -> (Update, Vec<CallbackChange>) {
715
        let mut layout_window =
716
            LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
717
        if let Some(sd) = styled {
718
            layout_window
719
                .layout_results
720
                .insert(DomId::ROOT_ID, layout_result(sd));
721
        }
722

            
723
        let renderer_resources = RendererResources::default();
724
        let previous_window_state: Option<FullWindowState> = None;
725
        let current_window_state = FullWindowState::default();
726
        let gl_context = OptionGlContextPtr::None;
727
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
728
            BTreeMap::new();
729
        let window_handle = RawWindowHandle::Unsupported;
730
        let system_callbacks = ExternalSystemCallbacks::rust_internal();
731

            
732
        let ref_data = CallbackInfoRefData {
733
            layout_window: &layout_window,
734
            renderer_resources: &renderer_resources,
735
            previous_window_state: &previous_window_state,
736
            current_window_state: &current_window_state,
737
            gl_context: &gl_context,
738
            current_scroll_manager: &scroll_states,
739
            current_window_handle: &window_handle,
740
            system_callbacks: &system_callbacks,
741
            system_style: Arc::new(SystemStyle::default()),
742
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
743
            #[cfg(feature = "icu")]
744
            icu_localizer: IcuLocalizerHandle::default(),
745
            ctx: OptionRefAny::None,
746
        };
747

            
748
        let changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));
749

            
750
        let info = CallbackInfo::new(
751
            &ref_data,
752
            &changes,
753
            DomNodeId {
754
                dom: DomId::ROOT_ID,
755
                node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(hit))),
756
            },
757
            OptionLogicalPosition::None,
758
            OptionLogicalPosition::None,
759
        );
760

            
761
        let update = on_accordion_header_click(data, info);
762
        let recorded = core::mem::take(&mut *changes.lock().expect("change log poisoned"));
763
        (update, recorded)
764
    }
765

            
766
    /// Every `display` write recorded in the change log, as `(node index, display)`.
767
    fn display_writes(changes: &[CallbackChange]) -> Vec<(usize, LayoutDisplay)> {
768
        let mut out = Vec::new();
769
        for change in changes {
770
            if let CallbackChange::ChangeNodeCssProperties {
771
                node_id,
772
                properties,
773
                ..
774
            } = change
775
            {
776
                for p in properties.as_ref() {
777
                    if let CssProperty::Display(v) = p {
778
                        if let Some(d) = v.get_property() {
779
                            out.push((node_id.index(), *d));
780
                        }
781
                    }
782
                }
783
            }
784
        }
785
        out
786
    }
787

            
788
    /// `is_open` of a `HeaderClickData` payload.
789
    fn payload_is_open(data: &mut RefAny) -> bool {
790
        data.downcast_ref::<HeaderClickData>()
791
            .expect("payload must still be a HeaderClickData")
792
            .is_open
793
    }
794

            
795
    /// Records the section indices it is invoked with; used as a user `on_toggle`.
796
    struct ToggleLog {
797
        calls: Vec<usize>,
798
    }
799

            
800
    extern "C" fn record_toggle(mut data: RefAny, _: CallbackInfo, index: usize) -> Update {
801
        if let Some(mut log) = data.downcast_mut::<ToggleLog>() {
802
            log.calls.push(index);
803
        }
804
        Update::RefreshDom
805
    }
806

            
807
    extern "C" fn toggle_do_nothing(_: RefAny, _: CallbackInfo, _: usize) -> Update {
808
        Update::DoNothing
809
    }
810

            
811
    fn toggle_cb(f: AccordionOnToggleCallbackType) -> AccordionOnToggleCallback {
812
        f.into()
813
    }
814

            
815
    // ------------------------------------------------------------------
816
    // AccordionSection::new / with_open  (constructor, invariants)
817
    // ------------------------------------------------------------------
818

            
819
    #[test]
820
    fn section_new_stores_args_and_starts_closed() {
821
        let content = Dom::create_div().with_child(
822
            Dom::create_text_do_not_use_without_block_level_wrapper("body"),
823
        );
824
        let sec = AccordionSection::new("Title", content.clone());
825

            
826
        assert_eq!(sec.title.as_str(), "Title");
827
        assert_eq!(sec.content, content);
828
        assert!(!sec.is_open, "a fresh section must start collapsed");
829
    }
830

            
831
    #[test]
832
    fn section_new_survives_extreme_titles() {
833
        // empty, interior NUL, emoji + combining marks + RTL, and a 100k-char title
834
        let long = "ab".repeat(50_000);
835
        let cases: Vec<AzString> = alloc::vec![
836
            AzString::from(""),
837
            AzString::from("a\0b"),
838
            AzString::from("👨‍👩‍👧‍👦 e\u{0301}\u{0327} مرحبا שלום 🇩🇪"),
839
            AzString::from("\u{feff}\u{202e}rtl-override"),
840
            AzString::from(long.as_str()),
841
        ];
842

            
843
        for title in cases {
844
            let sec = AccordionSection::new(title.clone(), Dom::create_div());
845
            assert_eq!(sec.title.as_str(), title.as_str());
846
            assert!(!sec.is_open);
847

            
848
            // and the title survives the trip through the DOM unchanged
849
            let dom = Accordion::new(AccordionSectionVec::from_vec(alloc::vec![sec])).dom();
850
            let (header, _) = section_parts(&dom, 0);
851
            let title_node = &header.children.as_ref()[0];
852
            assert_eq!(text_of(title_node), Some(title.as_str()));
853
        }
854
    }
855

            
856
    #[test]
857
    fn section_with_open_sets_flag_without_touching_other_fields() {
858
        let content = Dom::create_text_do_not_use_without_block_level_wrapper("x");
859
        let base = AccordionSection::new("t", content.clone());
860

            
861
        let opened = base.clone().with_open(true);
862
        assert!(opened.is_open);
863
        assert_eq!(opened.title.as_str(), "t");
864
        assert_eq!(opened.content, content);
865

            
866
        // last write wins; applying the same value twice is idempotent
867
        assert!(!base.clone().with_open(true).with_open(false).is_open);
868
        assert!(base.clone().with_open(false).with_open(true).is_open);
869
        assert!(base.clone().with_open(true).with_open(true).is_open);
870
        assert!(!base.with_open(false).is_open);
871
    }
872

            
873
    // ------------------------------------------------------------------
874
    // Accordion::new / create / Default
875
    // ------------------------------------------------------------------
876

            
877
    #[test]
878
    fn accordion_new_preserves_section_count_and_has_no_callback() {
879
        for count in [0usize, 1, 3, 1000] {
880
            let mut sections = Vec::with_capacity(count);
881
            for i in 0..count {
882
                sections.push(
883
                    AccordionSection::new(alloc::format!("s{i}"), Dom::create_div())
884
                        .with_open(i % 2 == 0),
885
                );
886
            }
887
            let acc = Accordion::new(AccordionSectionVec::from_vec(sections));
888

            
889
            assert_eq!(acc.sections.len(), count);
890
            assert!(acc.on_toggle.is_none(), "Accordion::new sets no callback");
891
            for (i, s) in acc.sections.as_ref().iter().enumerate() {
892
                assert_eq!(s.title.as_str(), alloc::format!("s{i}"));
893
                assert_eq!(s.is_open, i % 2 == 0);
894
            }
895
        }
896
    }
897

            
898
    #[test]
899
    fn accordion_create_is_empty_and_equals_default() {
900
        let acc = Accordion::create();
901
        assert!(acc.sections.is_empty());
902
        assert!(acc.on_toggle.is_none());
903
        assert_eq!(acc, Accordion::default());
904
    }
905

            
906
    // ------------------------------------------------------------------
907
    // set_on_toggle / with_on_toggle / swap_with_default
908
    // ------------------------------------------------------------------
909

            
910
    #[test]
911
    fn set_on_toggle_last_call_wins() {
912
        let mut acc = Accordion::create();
913

            
914
        acc.set_on_toggle(RefAny::new(1u8), toggle_cb(toggle_do_nothing));
915
        assert!(acc.on_toggle.is_some());
916
        assert_eq!(
917
            acc.on_toggle.as_ref().unwrap().refany.get_type_id(),
918
            RefAny::new(1u8).get_type_id()
919
        );
920

            
921
        // a second call must *replace* (not append / leak / panic)
922
        acc.set_on_toggle(RefAny::new(9i64), toggle_cb(record_toggle));
923
        let set = acc.on_toggle.as_ref().expect("still Some");
924
        assert_eq!(set.refany.get_type_id(), RefAny::new(0i64).get_type_id());
925
        assert_eq!(set.callback, toggle_cb(record_toggle));
926
        assert_ne!(set.callback, toggle_cb(toggle_do_nothing));
927
    }
928

            
929
    #[test]
930
    fn with_on_toggle_matches_set_on_toggle() {
931
        let built = Accordion::create().with_on_toggle(RefAny::new(7u32), toggle_cb(record_toggle));
932

            
933
        let mut mutated = Accordion::create();
934
        mutated.set_on_toggle(RefAny::new(7u32), toggle_cb(record_toggle));
935

            
936
        assert!(built.on_toggle.is_some());
937
        assert_eq!(
938
            built.on_toggle.as_ref().unwrap().callback,
939
            mutated.on_toggle.as_ref().unwrap().callback
940
        );
941
        // the builder form must not disturb the sections
942
        assert!(built.sections.is_empty());
943
    }
944

            
945
    #[test]
946
    fn swap_with_default_moves_all_state_out() {
947
        let sections = AccordionSectionVec::from_vec(alloc::vec![
948
            AccordionSection::new("a", Dom::create_div()),
949
            AccordionSection::new("b", Dom::create_div()).with_open(true),
950
        ]);
951
        let mut acc =
952
            Accordion::new(sections).with_on_toggle(RefAny::new(5u8), toggle_cb(record_toggle));
953

            
954
        let original = acc.swap_with_default();
955

            
956
        assert_eq!(original.sections.len(), 2);
957
        assert!(original.on_toggle.is_some());
958
        assert!(original.sections.as_ref()[1].is_open);
959

            
960
        assert!(acc.sections.is_empty(), "self must be left empty");
961
        assert!(acc.on_toggle.is_none(), "self must lose the callback");
962
        assert_eq!(acc, Accordion::create());
963

            
964
        // swapping an already-empty accordion is a no-op, not a panic
965
        let second = acc.swap_with_default();
966
        assert_eq!(second, Accordion::create());
967
        assert_eq!(acc, Accordion::create());
968
    }
969

            
970
    // ------------------------------------------------------------------
971
    // Accordion::dom
972
    // ------------------------------------------------------------------
973

            
974
    #[test]
975
    fn dom_of_empty_accordion_has_no_children() {
976
        let dom = Accordion::create().dom();
977
        assert!(has_class(&dom, "__azul-native-accordion"));
978
        assert!(dom.children.as_ref().is_empty());
979
        assert_eq!(dom.estimated_total_children, 0);
980
    }
981

            
982
    #[test]
983
    fn dom_display_follows_is_open() {
984
        let acc = Accordion::new(AccordionSectionVec::from_vec(alloc::vec![
985
            AccordionSection::new(
986
                "closed",
987
                Dom::create_text_do_not_use_without_block_level_wrapper("c0")
988
            ),
989
            AccordionSection::new(
990
                "open",
991
                Dom::create_text_do_not_use_without_block_level_wrapper("c1")
992
            )
993
            .with_open(true),
994
        ]));
995
        let dom = acc.dom();
996
        assert_eq!(dom.children.as_ref().len(), 2);
997

            
998
        let (h0, b0) = section_parts(&dom, 0);
999
        let (h1, b1) = section_parts(&dom, 1);
        assert!(has_class(h0, "__azul-native-accordion-header"));
        assert!(has_class(b0, "__azul-native-accordion-body"));
        // a closed section is `display: none`, an open one `display: block`
        assert_eq!(inline_display(b0), Some(LayoutDisplay::None));
        assert_eq!(inline_display(b1), Some(LayoutDisplay::Block));
        // the body wraps exactly the caller's content
        assert_eq!(text_of(&b0.children.as_ref()[0]), Some("c0"));
        assert_eq!(text_of(&b1.children.as_ref()[0]), Some("c1"));
        // the header is focusable and carries exactly one MouseUp callback
        for h in [h0, h1] {
            assert!(matches!(h.root.get_tab_index(), Some(TabIndex::Auto)));
            let cbs = h.root.get_callbacks();
            assert_eq!(cbs.len(), 1);
            assert_eq!(
                cbs.as_ref()[0].event,
                EventFilter::Hover(HoverEventFilter::Click)
            );
            assert_eq!(
                cbs.as_ref()[0].callback.cb,
                on_accordion_header_click as usize
            );
        }
    }
    #[test]
    fn dom_header_payload_carries_the_section_index_and_open_state() {
        let count = 64usize;
        let mut sections = Vec::with_capacity(count);
        for i in 0..count {
            sections.push(
                AccordionSection::new(alloc::format!("s{i}"), Dom::create_div())
                    .with_open(i % 3 == 0),
            );
        }
        let dom = Accordion::new(AccordionSectionVec::from_vec(sections)).dom();
        for i in 0..count {
            let (header, body) = section_parts(&dom, i);
            let mut payload = header.root.get_callbacks().as_ref()[0].refany.clone();
            let hd = payload
                .downcast_ref::<HeaderClickData>()
                .expect("header payload is a HeaderClickData");
            assert_eq!(hd.index, i, "each header must know its own section index");
            assert_eq!(hd.is_open, i % 3 == 0);
            assert!(hd.on_toggle.is_none(), "no user callback was set");
            assert_eq!(
                inline_display(body),
                Some(if i % 3 == 0 {
                    LayoutDisplay::Block
                } else {
                    LayoutDisplay::None
                })
            );
        }
    }
    #[test]
    fn dom_child_count_cache_stays_consistent() {
        // deeply nested content + many sections: `estimated_total_children` must
        // still equal the real descendant count, otherwise the compact-DOM arena
        // under-allocates and panics later.
        let mut deep = Dom::create_text_do_not_use_without_block_level_wrapper("leaf");
        for _ in 0..64 {
            deep = Dom::create_div().with_child(deep);
        }
        let sections = AccordionSectionVec::from_vec(alloc::vec![
            AccordionSection::new("deep", deep),
            AccordionSection::new("flat", Dom::create_div()).with_open(true),
            AccordionSection::new("", Dom::create_div()),
        ]);
        let dom = Accordion::new(sections).dom();
        assert_eq!(
            dom.estimated_total_children,
            dom.recompute_estimated_total_children(),
            "cached descendant count desynced from the real tree"
        );
    }
    #[test]
    fn from_accordion_for_dom_matches_dom() {
        // Only meaningful for a section-less accordion: every `dom()` call mints
        // fresh per-header `RefAny`s, and two distinct `RefAny`s never compare equal.
        assert_eq!(Dom::from(Accordion::create()), Accordion::create().dom());
    }
    #[test]
    fn dom_leaves_the_original_on_toggle_payload_alive() {
        let log = RefAny::new(ToggleLog { calls: Vec::new() });
        let mut kept = log.clone();
        let acc = Accordion::new(AccordionSectionVec::from_vec(alloc::vec![
            AccordionSection::new("a", Dom::create_div()),
            AccordionSection::new("b", Dom::create_div()),
        ]))
        .with_on_toggle(log, toggle_cb(record_toggle));
        let dom = acc.dom();
        // every header got its own clone of the callback...
        for i in 0..2 {
            let (header, _) = section_parts(&dom, i);
            let mut payload = header.root.get_callbacks().as_ref()[0].refany.clone();
            let hd = payload.downcast_ref::<HeaderClickData>().unwrap();
            assert!(hd.on_toggle.is_some());
        }
        // ...and the caller's handle to the shared payload is still valid (no free)
        assert!(kept.downcast_ref::<ToggleLog>().unwrap().calls.is_empty());
    }
    // ------------------------------------------------------------------
    // clone_option_on_toggle
    // ------------------------------------------------------------------
    #[test]
    fn clone_option_on_toggle_of_none_is_none() {
        let none: OptionAccordionOnToggle = None.into();
        assert!(clone_option_on_toggle(&none).is_none());
        // cloning the clone stays None
        assert!(clone_option_on_toggle(&clone_option_on_toggle(&none)).is_none());
    }
    #[test]
    fn clone_option_on_toggle_shares_the_payload() {
        let mut some: OptionAccordionOnToggle = Some(AccordionOnToggle {
            callback: toggle_cb(record_toggle),
            refany: RefAny::new(0usize),
        })
        .into();
        let mut cloned = clone_option_on_toggle(&some);
        let cloned_inner = cloned.as_mut().expect("clone of Some must be Some");
        assert_eq!(cloned_inner.callback, toggle_cb(record_toggle));
        // the RefAny is shared, not deep-copied: a write through the clone is
        // visible through the original.
        *cloned_inner
            .refany
            .downcast_mut::<usize>()
            .expect("payload type is preserved") = 42;
        let original_inner = some.as_mut().unwrap();
        assert_eq!(*original_inner.refany.downcast_ref::<usize>().unwrap(), 42);
    }
    // ------------------------------------------------------------------
    // on_accordion_header_click
    // ------------------------------------------------------------------
    #[test]
    fn header_click_without_any_layout_result_is_a_noop() {
        let mut data = RefAny::new(HeaderClickData {
            index: 0,
            is_open: false,
            on_toggle: None.into(),
        });
        let (update, changes) = run_click(None, 0, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty(), "nothing may be restyled without a body");
        assert!(!payload_is_open(&mut data), "state must not flip");
    }
    #[test]
    fn header_click_without_next_sibling_does_not_flip_state() {
        // node 2 is the *last* child -> no next sibling -> early return, and
        // crucially `is_open` must NOT have been toggled.
        let mut data = RefAny::new(HeaderClickData {
            index: 3,
            is_open: true,
            on_toggle: None.into(),
        });
        let (update, changes) = run_click(Some(header_body_dom()), 2, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(payload_is_open(&mut data), "state must be untouched");
    }
    #[test]
    fn header_click_with_stale_hit_node_is_a_noop() {
        let mut data = RefAny::new(HeaderClickData {
            index: 0,
            is_open: false,
            on_toggle: None.into(),
        });
        // node 999 does not exist in the 3-node fixture
        let (update, changes) = run_click(Some(header_body_dom()), 999, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(changes.is_empty());
        assert!(!payload_is_open(&mut data));
    }
    #[test]
    fn header_click_with_foreign_payload_is_a_noop() {
        // the callback-bearing node carries a RefAny of the *wrong* type
        let data = RefAny::new(0xdead_beef_u64);
        let (update, changes) = run_click(Some(header_body_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert!(
            changes.is_empty(),
            "a foreign payload must not restyle the body"
        );
    }
    #[test]
    fn header_click_toggles_body_display_and_flips_state() {
        let mut data = RefAny::new(HeaderClickData {
            index: 0,
            is_open: false,
            on_toggle: None.into(),
        });
        // closed -> open
        let (update, changes) = run_click(Some(header_body_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing, "no user callback -> DoNothing");
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(2usize, LayoutDisplay::Block)]
        );
        assert!(payload_is_open(&mut data));
        // open -> closed (same payload, so the flip must be stateful)
        let (update, changes) = run_click(Some(header_body_dom()), 1, data.clone());
        assert_eq!(update, Update::DoNothing);
        assert_eq!(
            display_writes(&changes),
            alloc::vec![(2usize, LayoutDisplay::None)]
        );
        assert!(!payload_is_open(&mut data));
    }
    #[test]
    fn header_click_invokes_user_callback_and_propagates_its_update() {
        let mut log = RefAny::new(ToggleLog { calls: Vec::new() });
        let data = RefAny::new(HeaderClickData {
            index: 17,
            is_open: false,
            on_toggle: Some(AccordionOnToggle {
                callback: toggle_cb(record_toggle),
                refany: log.clone(),
            })
            .into(),
        });
        let (update, changes) = run_click(Some(header_body_dom()), 1, data.clone());
        // the user's return value wins over the internal DoNothing
        assert_eq!(update, Update::RefreshDom);
        // The host asked for a rebuild, so it owns the open flag: the widget
        // must CLEAR its `display` override instead of writing one. A written
        // override survives the rebuild (`migrate_user_overrides_from`) and
        // outranks the freshly cascaded style, which latched the section open
        // (or shut) forever — the "accordion doesn't properly expand/collapse"
        // bug. `initial` is what removes an override (`restyle_user_property`).
        let writes: Vec<_> = changes
            .iter()
            .filter_map(|c| match c {
                CallbackChange::ChangeNodeCssProperties {
                    node_id,
                    properties,
                    ..
                } => Some((
                    node_id.index(),
                    properties
                        .as_ref()
                        .iter()
                        .map(|p| p.get_type())
                        .collect::<Vec<_>>(),
                )),
                _ => None,
            })
            .collect();
        assert_eq!(
            writes,
            alloc::vec![(2usize, alloc::vec![CssPropertyType::Display])],
            "a rebuild-requesting toggle must still address the body's display",
        );
        assert!(
            display_writes(&changes).is_empty(),
            "…but as `initial` (override cleared), never as a concrete value that would outrank \
             the rebuilt DOM: {:?}",
            display_writes(&changes),
        );
        assert_eq!(
            log.downcast_ref::<ToggleLog>().unwrap().calls.as_slice(),
            &[17],
            "the user callback must receive this section's index"
        );
        // a second click reports the same index again
        let (_, _) = run_click(Some(header_body_dom()), 1, data);
        assert_eq!(
            log.downcast_ref::<ToggleLog>().unwrap().calls.as_slice(),
            &[17, 17]
        );
    }
}