ailloli_ui_widgets/controls/
accordion.rs

1//! Retained single- or multi-open accordion sections.
2
3use std::rc::Rc;
4use std::sync::Arc;
5
6use crate::layout::layout_ext::finish_view_sized;
7use crate::layout::{Column, Container};
8use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
9use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
10use ailloli_ui_core::geometry::{Constraints, Rect, Size};
11use ailloli_ui_core::style::{
12    AlignItems, Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius,
13};
14use ailloli_ui_core::{Color, FontId, IconId, TextStyle, Theme};
15use ailloli_ui_runtime::component::{
16    Binding, ComponentNode, Context, IntoView, IntoViewKeyExt, Signal, View, Widget,
17};
18use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
19use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
20use ailloli_ui_runtime::scene::PaintCtx;
21use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawText};
22use ailloli_ui_text::{PreparedTextLayout, TextLayoutParams, WrapMode};
23use lucide_icons::Icon as LucideIcon;
24
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26/// Built-in density choices for an [`Accordion`].
27///
28/// # Examples
29///
30/// ```
31/// use ailloli_ui_widgets::controls::AccordionSize;
32/// assert_eq!(AccordionSize::default(), AccordionSize::Default);
33/// ```
34pub enum AccordionSize {
35    /// 30-pixel headers with smaller padding and typography.
36    Compact,
37    /// 36-pixel headers with standard padding and typography.
38    #[default]
39    Default,
40}
41
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43/// Cardinality allowed for open accordion IDs.
44///
45/// # Examples
46///
47/// ```
48/// use ailloli_ui_widgets::controls::AccordionMode;
49/// assert_eq!(AccordionMode::default(), AccordionMode::Single);
50/// ```
51pub enum AccordionMode {
52    /// At most the first distinct ID is considered open.
53    #[default]
54    Single,
55    /// Every distinct supplied ID may remain open.
56    Multiple,
57}
58
59#[derive(Clone, Debug, PartialEq)]
60/// Resolved colors, typography, and logical-pixel metrics for an accordion.
61///
62/// `content_padding_x` and `content_indent` are reserved compatibility fields;
63/// current content uses `content_padding_y` uniformly on all four edges.
64///
65/// # Examples
66///
67/// ```
68/// use ailloli_ui_core::Theme;
69/// use ailloli_ui_widgets::controls::{AccordionSize, AccordionStyle};
70/// let style = AccordionStyle::from_theme(Theme::dark(), AccordionSize::Compact);
71/// assert_eq!(style.header_height, 30.0);
72/// assert_eq!(style.title_text.px_size, 12);
73/// ```
74pub struct AccordionStyle {
75    /// Outer container fill.
76    pub background: Color,
77    /// Outer container border.
78    pub border: Border,
79    /// Border painted around focused enabled headers.
80    pub focus_ring: Border,
81    /// Closed idle header fill.
82    pub header_background: Color,
83    /// Closed hovered header fill.
84    pub header_hovered: Color,
85    /// Closed pressed header fill.
86    pub header_pressed: Color,
87    /// Open header fill, taking precedence over interaction fills.
88    pub header_open: Color,
89    /// Enabled header title style.
90    pub title_text: TextStyle,
91    /// Disabled header title style.
92    pub disabled_text: TextStyle,
93    /// Enabled chevron tint.
94    pub icon_tint: Color,
95    /// Disabled chevron tint before opacity multiplication.
96    pub disabled_icon_tint: Color,
97    /// Outer/header corner radii.
98    pub radius: Radius,
99    /// Header intrinsic height.
100    pub header_height: f32,
101    /// Outer container padding on every edge.
102    pub padding: f32,
103    /// Vertical gap between headers and mounted content.
104    pub gap: f32,
105    /// Header horizontal inset.
106    pub header_padding_x: f32,
107    /// Reserved horizontal content padding; currently unused.
108    pub content_padding_x: f32,
109    /// Current content padding applied uniformly on every edge.
110    pub content_padding_y: f32,
111    /// Reserved content indentation; currently unused.
112    pub content_indent: f32,
113    /// Chevron width and height.
114    pub icon_size: f32,
115    /// Alpha multiplier applied to disabled header paint.
116    pub disabled_opacity: f32,
117}
118
119impl Default for AccordionStyle {
120    fn default() -> Self {
121        Self::from_theme(Theme::default(), AccordionSize::Default)
122    }
123}
124
125impl AccordionStyle {
126    /// Resolves accordion colors and geometry from `theme` and `size`.
127    ///
128    /// # Examples
129    ///
130    /// ```
131    /// use ailloli_ui_core::Theme;
132    /// use ailloli_ui_widgets::controls::{AccordionSize, AccordionStyle};
133    /// let style = AccordionStyle::from_theme(Theme::dark(), AccordionSize::Default);
134    /// assert_eq!(style.header_height, 36.0);
135    /// assert_eq!(style.disabled_opacity, 0.42);
136    /// ```
137    pub fn from_theme(theme: Theme, size: AccordionSize) -> Self {
138        let palette = theme.palette();
139        let (header_height, padding, gap, header_padding_x, text_size) = match size {
140            AccordionSize::Compact => (30.0, 6.0, 3.0, 8.0, 12),
141            AccordionSize::Default => (36.0, 8.0, 4.0, 10.0, 13),
142        };
143        Self {
144            background: palette.surface,
145            border: Border::new(1.0, palette.border),
146            focus_ring: Border::new(1.0, palette.focus),
147            header_background: Color::TRANSPARENT,
148            header_hovered: palette.surface_elevated,
149            header_pressed: Color::hex_rgb(0x20252A),
150            header_open: palette.accent.with_alpha(0.16),
151            title_text: TextStyle::new(FontId::Ui, text_size, palette.text),
152            disabled_text: TextStyle::new(
153                FontId::Ui,
154                text_size,
155                palette.text_muted.with_alpha(0.70),
156            ),
157            icon_tint: palette.text_muted,
158            disabled_icon_tint: palette.text_muted.with_alpha(0.58),
159            radius: Radius::uniform(theme.radius().md),
160            header_height,
161            padding,
162            gap,
163            header_padding_x,
164            content_padding_x: 12.0,
165            content_padding_y: 8.0,
166            content_indent: 18.0,
167            icon_size: 16.0,
168            disabled_opacity: 0.42,
169        }
170    }
171}
172
173/// Shared callback receiving `(item_id, requested_open_state)`.
174type AccordionToggleHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String, bool)>;
175
176#[derive(Clone)]
177/// One identified accordion header and its retained content view.
178///
179/// IDs should be unique. They drive open-state comparison and retained view
180/// keys; duplicates are not rejected and can produce duplicate content/keys.
181///
182/// # Examples
183///
184/// ```
185/// use ailloli_ui_widgets::controls::AccordionItem;
186/// use ailloli_ui_widgets::text::Text;
187/// let item = AccordionItem::<()>::new("general", "General").child(Text::new("Settings"));
188/// let _ = item;
189/// ```
190pub struct AccordionItem<A = ()> {
191    /// Identity used by open-state lists and retained keys.
192    id: String,
193    /// Owned unwrapped header title.
194    title: String,
195    /// Live disabled state for the header.
196    disabled: Binding<bool>,
197    /// Retained content mounted only while the ID is open.
198    content: View<A>,
199}
200
201impl<A: 'static> AccordionItem<A> {
202    /// Creates an enabled item with empty content.
203    ///
204    /// Empty IDs and titles are accepted; callers should still use unique,
205    /// stable IDs for correct retained identity.
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// use ailloli_ui_widgets::controls::AccordionItem;
211    /// let item: AccordionItem<()> = AccordionItem::new("advanced", "Advanced");
212    /// let _ = item;
213    /// ```
214    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
215        Self {
216            id: id.into(),
217            title: title.into(),
218            disabled: Binding::Static(false),
219            content: View::empty(),
220        }
221    }
222
223    /// Sets static or reactive disabled state for the header.
224    ///
225    /// Disabled headers ignore events and leave focus traversal. Existing open
226    /// content remains mounted; disabling does not close the item.
227    ///
228    /// # Examples
229    ///
230    /// ```
231    /// use ailloli_ui_widgets::controls::AccordionItem;
232    /// let item: AccordionItem<()> = AccordionItem::new("locked", "Locked").disabled(true);
233    /// let _ = item;
234    /// ```
235    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
236        self.disabled = disabled.into();
237        self
238    }
239
240    /// Replaces the item's sole retained content view.
241    ///
242    /// Content is mounted only while the item ID appears in sanitized open state.
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use ailloli_ui_widgets::controls::AccordionItem;
248    /// use ailloli_ui_widgets::text::Text;
249    /// let item = AccordionItem::<()>::new("about", "About").child(Text::new("Ailloli"));
250    /// let _ = item;
251    /// ```
252    pub fn child(mut self, child: impl IntoView<A>) -> Self {
253        self.content = child.into_view();
254        self
255    }
256}
257
258/// A controlled, bound, or internally managed set of collapsible sections.
259///
260/// Open lists are de-duplicated in order; single mode keeps only the first ID.
261/// Unknown IDs are retained in state but mount no content. Headers activate on
262/// left-button release or pressed Enter/Space. Bound/internal mode writes the
263/// new sanitized list; controlled mode only reports through `on_toggle` and
264/// requires the consumer to update its binding.
265///
266/// # Examples
267///
268/// ```
269/// use ailloli_ui_widgets::controls::{Accordion, AccordionItem};
270/// let accordion = Accordion::<()>::new()
271///     .item(AccordionItem::new("one", "One"))
272///     .default_open("one");
273/// let _ = accordion;
274/// ```
275pub struct Accordion<A = ()> {
276    /// Layout applied to the outer container.
277    pub(crate) layout: LayoutStyle,
278    /// Flex-item behavior used by the parent layout.
279    pub(crate) flex_item: FlexItemStyle,
280    /// Single- or multiple-open sanitation/toggle mode.
281    mode: AccordionMode,
282    /// Items in insertion order; no capacity bound.
283    items: Vec<AccordionItem<A>>,
284    /// Optional controlled or bound open-ID source.
285    open_ids: Option<Binding<Vec<String>>>,
286    /// Writable open-ID signal in bound mode.
287    bound_open_ids: Option<Signal<Vec<String>>>,
288    /// Initial internal open IDs, sanitized on component build.
289    default_open_ids: Vec<String>,
290    /// Optional callback for requested toggles.
291    on_toggle: Option<AccordionToggleHandler<A>>,
292    /// Resolved paint and geometry.
293    style: AccordionStyle,
294}
295
296crate::impl_layout_builders!(Accordion);
297
298impl<A: 'static> Default for Accordion<A> {
299    fn default() -> Self {
300        Self::new()
301    }
302}
303
304impl<A: 'static> Accordion<A> {
305    /// Creates an empty single-open accordion with no initially open IDs.
306    ///
307    /// # Examples
308    ///
309    /// ```
310    /// use ailloli_ui_widgets::controls::Accordion;
311    /// let accordion: Accordion<()> = Accordion::new();
312    /// let _ = accordion;
313    /// ```
314    pub fn new() -> Self {
315        Self {
316            layout: LayoutStyle::default(),
317            flex_item: FlexItemStyle::default(),
318            mode: AccordionMode::Single,
319            items: Vec::new(),
320            open_ids: None,
321            bound_open_ids: None,
322            default_open_ids: Vec::new(),
323            on_toggle: None,
324            style: AccordionStyle::default(),
325        }
326    }
327
328    /// Selects single-open mode and truncates default IDs to the first.
329    ///
330    /// External controlled/bound lists are sanitized when read; this builder
331    /// does not mutate their source.
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// use ailloli_ui_widgets::controls::Accordion;
337    /// let accordion: Accordion<()> = Accordion::new().multiple().single();
338    /// let _ = accordion;
339    /// ```
340    pub fn single(mut self) -> Self {
341        self.mode = AccordionMode::Single;
342        self.default_open_ids.truncate(1);
343        self
344    }
345
346    /// Selects multiple-open mode without changing current default IDs.
347    ///
348    /// # Examples
349    ///
350    /// ```
351    /// use ailloli_ui_widgets::controls::Accordion;
352    /// let accordion: Accordion<()> = Accordion::new().multiple();
353    /// let _ = accordion;
354    /// ```
355    pub fn multiple(mut self) -> Self {
356        self.mode = AccordionMode::Multiple;
357        self
358    }
359
360    /// Sets open cardinality and truncates defaults when selecting single mode.
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// use ailloli_ui_widgets::controls::{Accordion, AccordionMode};
366    /// let accordion: Accordion<()> = Accordion::new().mode(AccordionMode::Multiple);
367    /// let _ = accordion;
368    /// ```
369    pub fn mode(mut self, mode: AccordionMode) -> Self {
370        self.mode = mode;
371        if self.mode == AccordionMode::Single {
372            self.default_open_ids.truncate(1);
373        }
374        self
375    }
376
377    /// Appends one item in display order.
378    ///
379    /// IDs are not validated for uniqueness or membership in existing open lists.
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// use ailloli_ui_widgets::controls::{Accordion, AccordionItem};
385    /// let accordion = Accordion::<()>::new().item(AccordionItem::new("one", "One"));
386    /// let _ = accordion;
387    /// ```
388    pub fn item(mut self, item: AccordionItem<A>) -> Self {
389        self.items.push(item);
390        self
391    }
392
393    /// Adds an initially open ID according to the current mode.
394    ///
395    /// Single mode replaces the list with `id`; multiple mode appends only when
396    /// absent. The ID need not match an item. External open state overrides it.
397    ///
398    /// # Examples
399    ///
400    /// ```
401    /// use ailloli_ui_widgets::controls::Accordion;
402    /// let accordion: Accordion<()> = Accordion::new().default_open("general");
403    /// let _ = accordion;
404    /// ```
405    pub fn default_open(mut self, id: impl Into<String>) -> Self {
406        let id = id.into();
407        if self.mode == AccordionMode::Single {
408            self.default_open_ids = vec![id];
409        } else if !self.default_open_ids.iter().any(|open| open == &id) {
410            self.default_open_ids.push(id);
411        }
412        self
413    }
414
415    /// Replaces initial open IDs after stable de-duplication.
416    ///
417    /// Input order is preserved. Single mode retains at most the first distinct
418    /// ID; multiple mode retains every distinct ID, including unknown ones.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use ailloli_ui_widgets::controls::Accordion;
424    /// let accordion: Accordion<()> =
425    ///     Accordion::new().multiple().default_open_many(["one", "one", "two"]);
426    /// let _ = accordion;
427    /// ```
428    pub fn default_open_many(mut self, ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
429        let mut out = Vec::new();
430        for id in ids {
431            let id = id.into();
432            if !out.iter().any(|open| open == &id) {
433                out.push(id);
434            }
435        }
436        if self.mode == AccordionMode::Single {
437            out.truncate(1);
438        }
439        self.default_open_ids = out;
440        self
441    }
442
443    /// Sets controlled static or reactive open IDs.
444    ///
445    /// IDs are sanitized only when read. Toggle requests cannot mutate a purely
446    /// controlled source and should be handled through [`Self::on_toggle`]. This
447    /// method does not clear a writable signal installed by an earlier
448    /// [`Self::bind_open_ids`] call; choose one ownership mode per builder.
449    ///
450    /// # Examples
451    ///
452    /// ```
453    /// use ailloli_ui_widgets::controls::Accordion;
454    /// let accordion: Accordion<()> = Accordion::new().open_ids(vec!["one".to_string()]);
455    /// let _ = accordion;
456    /// ```
457    pub fn open_ids(mut self, ids: impl Into<Binding<Vec<String>>>) -> Self {
458        self.open_ids = Some(ids.into());
459        self
460    }
461
462    /// Installs a writable signal for two-way open-ID state.
463    ///
464    /// Toggles write a sanitized list to the signal before invoking the optional
465    /// callback. The source itself is not sanitized until a toggle writes it.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// use std::{cell::RefCell, rc::Rc};
471    /// use ailloli_ui_runtime::component::Signal;
472    /// use ailloli_ui_widgets::controls::Accordion;
473    /// let ids = Signal::new(Rc::new(RefCell::new(vec!["one".to_string()])), Rc::new(|| {}));
474    /// let accordion: Accordion<()> = Accordion::new().bind_open_ids(ids);
475    /// let _ = accordion;
476    /// ```
477    pub fn bind_open_ids(mut self, ids: impl Into<Signal<Vec<String>>>) -> Self {
478        let signal = ids.into();
479        self.open_ids = Some(Binding::Signal(signal.clone()));
480        self.bound_open_ids = Some(signal);
481        self
482    }
483
484    /// Replaces the complete resolved style without changing mode or state.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use ailloli_ui_core::Theme;
490    /// use ailloli_ui_widgets::controls::{Accordion, AccordionSize, AccordionStyle};
491    /// let style = AccordionStyle::from_theme(Theme::dark(), AccordionSize::Compact);
492    /// let accordion: Accordion<()> = Accordion::new().accordion_style(style);
493    /// let _ = accordion;
494    /// ```
495    pub fn accordion_style(mut self, style: AccordionStyle) -> Self {
496        self.style = style;
497        self
498    }
499
500    /// Replaces the complete style with the default-theme built-in size.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// use ailloli_ui_widgets::controls::{Accordion, AccordionSize};
506    /// let accordion: Accordion<()> = Accordion::new().accordion_size(AccordionSize::Compact);
507    /// let _ = accordion;
508    /// ```
509    pub fn accordion_size(mut self, size: AccordionSize) -> Self {
510        self.style = AccordionStyle::from_theme(Theme::default(), size);
511        self
512    }
513
514    /// Maps each requested `(id, open)` state to an action and dispatches it.
515    ///
516    /// The callback runs after bound/internal state is updated. In controlled
517    /// mode it is the consumer's opportunity to update open IDs.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use ailloli_ui_widgets::controls::Accordion;
523    /// enum Action { Toggled(String, bool) }
524    /// let accordion = Accordion::new().on_toggle(|id, open| Action::Toggled(id, open));
525    /// let _ = accordion;
526    /// ```
527    pub fn on_toggle(mut self, f: impl Fn(String, bool) -> A + 'static) -> Self {
528        self.on_toggle = Some(Rc::new(move |ctx, id, open| ctx.dispatch(f(id, open))));
529        self
530    }
531
532    /// Installs a context-aware toggle callback.
533    ///
534    /// A later toggle-handler builder replaces it.
535    ///
536    /// # Examples
537    ///
538    /// ```
539    /// use ailloli_ui_widgets::controls::Accordion;
540    /// let accordion = Accordion::<()>::new()
541    ///     .on_toggle_ctx(|ctx, _id, _open| ctx.request_repaint());
542    /// let _ = accordion;
543    /// ```
544    pub fn on_toggle_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String, bool) + 'static) -> Self {
545        self.on_toggle = Some(Rc::new(f));
546        self
547    }
548}
549
550/// Component properties used to allocate internal open-ID state and keyed rows.
551struct AccordionComponent<A> {
552    /// Outer logical sizing policy.
553    layout: LayoutStyle,
554    /// Single-open or multiple-open selection policy.
555    mode: AccordionMode,
556    /// Ordered retained sections.
557    items: Vec<AccordionItem<A>>,
558    /// Optional readable external list of open section IDs.
559    open_ids: Option<Binding<Vec<String>>>,
560    /// Optional writable external list of open section IDs.
561    bound_open_ids: Option<Signal<Vec<String>>>,
562    /// Initial IDs used when the accordion owns its state.
563    default_open_ids: Vec<String>,
564    /// Optional callback receiving section ID and resulting open state.
565    on_toggle: Option<AccordionToggleHandler<A>>,
566    /// Header/content colors and logical-pixel geometry.
567    style: AccordionStyle,
568}
569
570impl<A: 'static> ComponentNode<A> for AccordionComponent<A> {
571    fn build(&self, context: &mut Context<A>) -> View<A> {
572        let internal_open = context.signal(sanitize_open_ids(&self.default_open_ids, self.mode));
573        let open_binding = self
574            .open_ids
575            .clone()
576            .unwrap_or_else(|| Binding::Signal(internal_open.clone()));
577        let mutable_open = self
578            .bound_open_ids
579            .clone()
580            .or_else(|| self.open_ids.is_none().then_some(internal_open));
581        let open_ids = sanitize_open_ids(&open_binding.read(), self.mode);
582
583        let mut content = Column::new()
584            .gap(self.style.gap)
585            .align_items(AlignItems::Stretch);
586
587        for item in &self.items {
588            let is_open = open_ids.iter().any(|open| open == &item.id);
589            content = content.child(
590                AccordionHeader {
591                    id: item.id.clone(),
592                    title: item.title.clone(),
593                    disabled: item.disabled.clone(),
594                    open_ids: open_binding.clone(),
595                    mutable_open: mutable_open.clone(),
596                    mode: self.mode,
597                    open: is_open,
598                    on_toggle: self.on_toggle.clone(),
599                    style: self.style.clone(),
600                }
601                .into_view()
602                .key(format!("accordion-header-{}", item.id)),
603            );
604            if is_open {
605                content = content.child(
606                    Container::new()
607                        .fill_width()
608                        .padding(0.0)
609                        .child(
610                            Container::new()
611                                .fill_width()
612                                .padding(self.style.content_padding_y)
613                                .child(item.content.clone()),
614                        )
615                        .key(format!("accordion-content-{}", item.id)),
616                );
617            }
618        }
619
620        let mut container = Container::<A>::new()
621            .background(self.style.background)
622            .border(self.style.border.widths.top, self.style.border.colors.top)
623            .radius(self.style.radius.tl)
624            .padding(self.style.padding)
625            .child(content);
626        container.layout = self.layout;
627        container.into_view()
628    }
629}
630
631impl<A: 'static> IntoView<A> for Accordion<A> {
632    fn into_view(self) -> View<A> {
633        finish_view_sized(
634            View::component(AccordionComponent {
635                layout: self.layout,
636                mode: self.mode,
637                items: self.items,
638                open_ids: self.open_ids,
639                bound_open_ids: self.bound_open_ids,
640                default_open_ids: self.default_open_ids,
641                on_toggle: self.on_toggle,
642                style: self.style,
643            }),
644            self.flex_item,
645            LayoutSizeHint::from_layout(self.layout),
646        )
647    }
648}
649
650/// Builder-to-view bridge for one keyed accordion header.
651struct AccordionHeader<A> {
652    /// Stable section identifier used in the open-ID collection.
653    id: String,
654    /// User-visible section title.
655    title: String,
656    /// Reactive interaction-disable flag for this section.
657    disabled: Binding<bool>,
658    /// Readable current open-ID collection.
659    open_ids: Binding<Vec<String>>,
660    /// Optional writable open-ID collection.
661    mutable_open: Option<Signal<Vec<String>>>,
662    /// Single-open or multiple-open update policy.
663    mode: AccordionMode,
664    /// Open state captured while building this header/content pair.
665    open: bool,
666    /// Optional retained toggle callback.
667    on_toggle: Option<AccordionToggleHandler<A>>,
668    /// Header/content colors and logical-pixel geometry.
669    style: AccordionStyle,
670}
671
672impl<A: 'static> IntoView<A> for AccordionHeader<A> {
673    fn into_view(self) -> View<A> {
674        View::leaf(AccordionHeaderWidget {
675            id: self.id,
676            title: self.title,
677            disabled: self.disabled,
678            open_ids: self.open_ids,
679            mutable_open: self.mutable_open,
680            mode: self.mode,
681            open: self.open,
682            on_toggle: self.on_toggle,
683            style: self.style,
684        })
685    }
686}
687
688/// Retained focusable header that reads state and applies toggle requests.
689struct AccordionHeaderWidget<A> {
690    /// Stable section identifier used in the open-ID collection.
691    id: String,
692    /// User-visible section title.
693    title: String,
694    /// Reactive interaction-disable flag for this section.
695    disabled: Binding<bool>,
696    /// Readable current open-ID collection.
697    open_ids: Binding<Vec<String>>,
698    /// Optional writable open-ID collection.
699    mutable_open: Option<Signal<Vec<String>>>,
700    /// Single-open or multiple-open update policy.
701    mode: AccordionMode,
702    /// Open state used to paint the current retained frame.
703    open: bool,
704    /// Optional retained toggle callback.
705    on_toggle: Option<AccordionToggleHandler<A>>,
706    /// Header colors and logical-pixel geometry.
707    style: AccordionStyle,
708}
709
710impl<A: 'static> Widget<A> for AccordionHeaderWidget<A> {
711    fn debug_name(&self) -> &'static str {
712        "AccordionHeader"
713    }
714
715    fn layout(
716        &self,
717        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
718        ctx: &mut LayoutCtx<'_>,
719        _children: &mut [LayoutChild],
720        constraints: Constraints,
721    ) -> LayoutResult {
722        let text_w = measure_text(ctx, &self.title, self.text_style()).unwrap_or(120.0);
723        let intrinsic = Size::new(
724            self.style.header_padding_x * 2.0 + self.style.icon_size + self.style.gap + text_w,
725            self.style.header_height,
726        );
727        let size = constraints.constrain(intrinsic);
728        LayoutResult {
729            size,
730            children: Vec::new(),
731            paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
732            visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
733            overlay_hit_bounds: Vec::new(),
734            clip: None,
735            is_window_root_clip: false,
736            artifact: None,
737        }
738    }
739
740    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
741        let disabled = self.disabled.read();
742        let interaction = ctx.interaction();
743        let mut bg = self.style.header_background;
744        if self.open {
745            bg = self.style.header_open;
746        } else if interaction.pressed && !disabled {
747            bg = self.style.header_pressed;
748        } else if interaction.hovered && !disabled {
749            bg = self.style.header_hovered;
750        }
751        let opacity = if disabled {
752            self.style.disabled_opacity
753        } else {
754            1.0
755        };
756
757        if bg.a > 0.0 {
758            ctx.push(DrawCmd::RRect(DrawRRect {
759                rect: bounds,
760                radius: self.style.radius.tl,
761                color: bg.with_alpha(bg.a * opacity),
762            }));
763        }
764
765        let icon_rect = Rect::new(
766            bounds.x + self.style.header_padding_x,
767            bounds.y + (bounds.h - self.style.icon_size) * 0.5,
768            self.style.icon_size,
769            self.style.icon_size,
770        );
771        let icon = if self.open {
772            IconId::Lucide(LucideIcon::ChevronDown)
773        } else {
774            IconId::Lucide(LucideIcon::ChevronRight)
775        };
776        let icon_tint = if disabled {
777            self.style.disabled_icon_tint
778        } else {
779            self.style.icon_tint
780        };
781        ctx.push(DrawCmd::Image(DrawImage {
782            rect: icon_rect,
783            icon,
784            tint: icon_tint.with_alpha(icon_tint.a * opacity),
785            rotation_rad: 0.0,
786        }));
787
788        paint_text_centered(
789            ctx,
790            &self.title,
791            self.text_style(),
792            bounds,
793            icon_rect.right() + self.style.gap,
794            opacity,
795        );
796
797        if interaction.focused && !disabled {
798            ctx.push(DrawCmd::Border(DrawBorder {
799                rect: bounds,
800                radius: self.style.radius,
801                border: self.style.focus_ring,
802            }));
803        }
804    }
805
806    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
807        if self.disabled.read() {
808            return;
809        }
810        match event {
811            Event::Pointer(PointerEvent::Button {
812                pos,
813                button: MouseButton::Left,
814                pressed: false,
815                ..
816            }) if bounds.contains(pos.x, pos.y) => self.toggle(ctx),
817            Event::Keyboard(key) if key.state == KeyState::Pressed => {
818                if matches!(
819                    &key.key,
820                    Key::Named(NamedKey::Enter) | Key::Named(NamedKey::Space)
821                ) {
822                    self.toggle(ctx);
823                }
824            }
825            _ => {}
826        }
827    }
828
829    fn focus_policy(&self) -> FocusPolicy {
830        if self.disabled.read() {
831            FocusPolicy::NotFocusable
832        } else {
833            FocusPolicy::Focusable
834        }
835    }
836}
837
838impl<A> AccordionHeaderWidget<A> {
839    /// Resolves enabled or disabled header text style.
840    fn text_style(&self) -> TextStyle {
841        if self.disabled.read() {
842            self.style.disabled_text
843        } else {
844            self.style.title_text
845        }
846    }
847
848    /// Computes sanitized next state, writes when mutable, reports, and consumes.
849    fn toggle(&self, ctx: &mut EventCtx<A>) {
850        let current = sanitize_open_ids(&self.open_ids.read(), self.mode);
851        let next_open = !current.iter().any(|id| id == &self.id);
852        let next = toggled_open_ids(&current, &self.id, next_open, self.mode);
853        let changed = next != current;
854        if changed {
855            if let Some(open) = &self.mutable_open {
856                open.set(next);
857            }
858            ctx.request_repaint();
859        }
860        if let Some(on_toggle) = &self.on_toggle {
861            on_toggle(ctx, self.id.clone(), next_open);
862        }
863        if changed || self.on_toggle.is_some() {
864            ctx.stop_propagation();
865        }
866    }
867}
868
869/// Stable-de-duplicates IDs and truncates after the first in single mode.
870fn sanitize_open_ids(ids: &[String], mode: AccordionMode) -> Vec<String> {
871    let mut out = Vec::new();
872    for id in ids {
873        if !out.iter().any(|open| open == id) {
874            out.push(id.clone());
875        }
876        if mode == AccordionMode::Single && !out.is_empty() {
877            break;
878        }
879    }
880    out
881}
882
883/// Returns the sanitized semantic result of opening or closing one ID.
884fn toggled_open_ids(
885    current: &[String],
886    id: &str,
887    next_open: bool,
888    mode: AccordionMode,
889) -> Vec<String> {
890    match (mode, next_open) {
891        (AccordionMode::Single, true) => vec![id.to_string()],
892        (AccordionMode::Single, false) => Vec::new(),
893        (AccordionMode::Multiple, true) => {
894            let mut out = current.to_vec();
895            if !out.iter().any(|open| open == id) {
896                out.push(id.to_string());
897            }
898            out
899        }
900        (AccordionMode::Multiple, false) => current
901            .iter()
902            .filter(|open| open.as_str() != id)
903            .cloned()
904            .collect(),
905    }
906}
907
908/// Measures one unwrapped header line, returning `None` without a text system.
909fn measure_text(ctx: &mut LayoutCtx<'_>, text: &str, style: TextStyle) -> Option<f32> {
910    ctx.text_system.as_deref_mut().map(|text_system| {
911        text_system
912            .layout_cached(TextLayoutParams {
913                text,
914                style,
915                max_width: None,
916                wrap_mode: WrapMode::NoWrap,
917            })
918            .metrics
919            .width
920    })
921}
922
923/// Prepares one unwrapped header line, returning `None` without a text system.
924fn layout_text(
925    ctx: &mut PaintCtx<'_>,
926    text: &str,
927    style: TextStyle,
928) -> Option<Arc<PreparedTextLayout>> {
929    ctx.text_system.as_deref_mut().map(|text_system| {
930        text_system.layout_cached(TextLayoutParams {
931            text,
932            style,
933            max_width: None,
934            wrap_mode: WrapMode::NoWrap,
935        })
936    })
937}
938
939/// Paints left-anchored header text vertically centered with alpha multiplication.
940fn paint_text_centered(
941    ctx: &mut PaintCtx<'_>,
942    text: &str,
943    style: TextStyle,
944    bounds: Rect,
945    x: f32,
946    opacity: f32,
947) {
948    let Some(layout) = layout_text(ctx, text, style) else {
949        return;
950    };
951    let baseline = layout
952        .lines
953        .first()
954        .map(|line| line.baseline_y)
955        .unwrap_or(0.0);
956    let y = bounds.y + (bounds.h - layout.metrics.height) * 0.5 + baseline;
957    ctx.push(DrawCmd::Text(DrawText {
958        pos: [x, y],
959        color: style.color.with_alpha(style.color.a * opacity),
960        decoration: ailloli_ui_core::TextDecoration::None,
961        layout,
962    }));
963}