teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `DropdownPanel` — the overlay-content widget shown when the combo
//! is open. Owns the Tab / ArrowDown / ArrowUp key handling, the
//! `TextInput`-backed search field, and the inner `FilteredItemList`
//! child that binds the query + version signals.
//!
//! The non-searchable path uses `build_static_item_list` to assemble a
//! padded `VStack` of `DropdownItem`s directly; the searchable path
//! instead renders a stable `TextInput` above a `FilteredItemList`
//! child that rebuilds on query changes — the sibling `TextInput`
//! survives each keystroke so the cursor doesn't jump.

use std::cell::Cell;
use std::rc::Rc;
use teksilo_i18n::lit;

use teksilo_canvas::{Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, WidgetEvent};
use teksilo_core::overlay::OverlayPlacement;
use teksilo_core::signal::Signal;
use teksilo_core::styles::{PopoverStyleConfig, PopoverVariant};
use teksilo_core::widget::{EventContext, LayoutContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;

use crate::list_view::ListView;
use crate::primitives::{FixedSize, HStack, Padding, VStack};
use crate::scroll_bar::{ScrollBar, ScrollBarOrientation};

use super::item::DropdownItem;
use super::state::ItemSource;
use teksilo_i18n::LocalizedString;

/// Selection-commit callback threaded down from `ComboBox::on_select`,
/// fired by each `DropdownItem`'s tap with a live `EventContext`.
pub(super) type OnSelect<T> = Option<Rc<dyn Fn(&T, &mut EventContext)>>;

/// Build the static (unfiltered) item list subtree.
///
/// Two paths:
/// - **Small list** (`total <= max_visible_items`): a padded `VStack`
///   of eagerly-materialized `DropdownItem`s. Simple, cheap — no
///   reason to pay the `ListView` bookkeeping cost for a handful of
///   rows.
/// - **Large list**: a virtualized `ListView` sized to
///   `max_visible_items * item_height`, wrapped in the same 4 px
///   padding. Only the rows in the visible range (plus ListView's
///   small buffer) are actually built, so a 10 000-item combo no
///   longer materializes 10 000 widget subtrees on open.
///
/// Returns the root id for insertion into the panel's `ZStack`.
/// Shared by the non-searchable path of `DropdownPanel` and —
/// indirectly via `FilteredItemList` — the searchable path.
pub(super) fn build_static_item_list<T: Clone + PartialEq + 'static>(
    ctx: &mut BuildContext,
    source: &ItemSource<T>,
    selected: &Signal<Option<T>>,
    item_label: &Rc<dyn Fn(&T) -> LocalizedString>,
    render_item: &Option<Rc<dyn Fn(&T, bool) -> Box<dyn Widget>>>,
    on_select: &OnSelect<T>,
    max_visible_items: usize,
) -> WidgetId {
    let total = source.len();
    if total <= max_visible_items {
        let mut vstack = VStack::new();
        for i in 0..total {
            if let Some(value) = source.get(i) {
                // Panel is ephemeral (rebuilt on open / panel_version change),
                // so resolving the label at build time is acceptable even in
                // reactive mode; the persistent trigger is the live-reactive one.
                let label = (item_label)(&value).resolve_now();
                vstack = vstack.child(DropdownItem {
                    value,
                    label,
                    position: i + 1,
                    total,
                    selected_signal: selected.clone(),
                    render: render_item.clone(),
                    on_select: on_select.clone(),
                    root_child_id: None,
                });
            }
        }
        let vstack_id = ctx.add(vstack);
        return ctx.add(Padding::uniform(4.0).child_id(vstack_id));
    }

    build_virtualized_list(
        ctx,
        source,
        selected,
        item_label,
        render_item,
        on_select,
        max_visible_items,
        None,
    )
}

/// Virtualized variant of the dropdown item list. When
/// `filtered_indices` is `None`, the list addresses the full source
/// directly; when `Some`, it projects each filtered position through
/// the stored index list. In both cases `ListView` only materializes
/// the rows in the viewport (plus its internal buffer) — the large-
/// list regression (combos with thousands of items building a full
/// widget subtree per row) is fixed here.
fn build_virtualized_list<T: Clone + PartialEq + 'static>(
    ctx: &mut BuildContext,
    source: &ItemSource<T>,
    selected: &Signal<Option<T>>,
    item_label: &Rc<dyn Fn(&T) -> LocalizedString>,
    render_item: &Option<Rc<dyn Fn(&T, bool) -> Box<dyn Widget>>>,
    on_select: &OnSelect<T>,
    max_visible_items: usize,
    filtered_indices: Option<Vec<usize>>,
) -> WidgetId {
    use crate::styles::recipe_menu_item_style as menu;
    let item_height = menu::MENU_ITEM_HEIGHT;
    let viewport_height = max_visible_items as f32 * item_height;

    // Either address the raw source directly (unfiltered, saves an
    // O(n) identity-mapping allocation for large lists) or project
    // through a filter index list shared between the ListView source
    // and the scroll-into-view effect.
    let filtered_indices: Option<Rc<Vec<usize>>> = filtered_indices.map(Rc::new);
    let visible_count = match &filtered_indices {
        Some(indices) => indices.len(),
        None => source.len(),
    };

    // Build a `ListSource<T>` that resolves rows back into the
    // underlying `ItemSource` so the raw source keeps its reactivity
    // and observer plumbing.
    let list_source = match &filtered_indices {
        None => source.to_list_source(),
        Some(indices) => {
            let src = source.clone();
            let indices = indices.clone();
            let len_fn: Rc<dyn Fn() -> usize> = Rc::new({
                let indices = indices.clone();
                move || indices.len()
            });
            let item_at: Rc<dyn Fn(usize) -> Option<T>> = Rc::new({
                let src = src.clone();
                let indices = indices.clone();
                move |pos| indices.get(pos).and_then(|&i| src.get(i))
            });
            let observe_fn = src.observe.clone();
            crate::list_source::ListSource::from_cloning_accessors(len_fn, item_at, observe_fn)
        }
    };

    // Delegate: wrap each visible row in the existing `DropdownItem`
    // so tap-to-select, highlight, and a11y keep working unchanged.
    // `index` here is the *filtered* position — the one visible to the
    // user — which is also what `position_in_set` / `size_of_set`
    // should reflect.
    let selected_for_delegate = selected.clone();
    let item_label_for_delegate = item_label.clone();
    let render_item_for_delegate = render_item.clone();
    let on_select_for_delegate = on_select.clone();
    let delegate = move |index: usize, value: &T, _selected: bool| -> Box<dyn Widget> {
        // Panel is ephemeral (rebuilt on open / panel_version change),
        // so resolving the label at build time is acceptable even in
        // reactive mode; the persistent trigger is the live-reactive one.
        let label = (item_label_for_delegate)(value).resolve_now();
        Box::new(DropdownItem {
            value: value.clone(),
            label,
            position: index + 1,
            total: visible_count,
            selected_signal: selected_for_delegate.clone(),
            render: render_item_for_delegate.clone(),
            on_select: on_select_for_delegate.clone(),
            root_child_id: None,
        })
    };

    // Build the ListView with the internal scrollbar disabled. The
    // panel mounts its own `ScrollBar` as a sibling (see below) so
    // that thumb drags survive the ListView's scroll-driven rebuilds:
    // if the scrollbar lived inside the ListView, each rebuild
    // (triggered when the visible range crosses the buffer mid-drag)
    // would destroy the scrollbar widget and cancel its in-flight
    // gesture, making the drag look like it does nothing.
    let list_view = ListView::from_list_source(list_source, delegate)
        .item_height(item_height)
        .show_scrollbar(false);
    let scroll_y = list_view.scroll_y_signal().clone();
    let max_scroll_y = list_view.max_scroll_y_signal().clone();
    let viewport_ratio_y = list_view.viewport_ratio_y_signal().clone();
    let list_view_id = ctx.add(list_view);

    // External scrollbar — lives as a sibling of the ListView inside
    // the panel so ListView rebuilds leave it untouched. Wired to the
    // same reactive state the list already updates during layout.
    let external_scrollbar = ScrollBar::new(
        ScrollBarOrientation::Vertical,
        scroll_y.clone(),
        max_scroll_y,
        viewport_ratio_y,
    );
    let scrollbar_id = ctx.add(external_scrollbar);

    // HStack { ListView | ScrollBar } — the list fills the remaining
    // width, the scrollbar takes its fixed thickness. Both ride
    // together under the outer `FixedSize` so the viewport height
    // exactly equals `max_visible_items * item_height`.
    let row_id = ctx.add(
        HStack::new()
            .spacing(0.0)
            .add_child(list_view_id)
            .add_child(scrollbar_id),
    );

    let padded_id = ctx.add(Padding::uniform(4.0).child_id(row_id));
    let outer_height = viewport_height + 8.0;
    let sized_id = ctx.add(FixedSize::new().height(outer_height).child_id(padded_id));

    register_scroll_into_view(
        ctx,
        source.clone(),
        selected.clone(),
        scroll_y,
        filtered_indices,
        item_height,
        viewport_height,
    );

    sized_id
}

/// Register a `ctx.effect` on `selected` that scrolls the `ListView`'s
/// scroll signal so the currently-selected row stays inside the
/// viewport. Called once synchronously to sync the initial scroll
/// position, then registered as an effect for subsequent selection
/// changes. Shared by both `build_static_item_list` and
/// `FilteredItemList` so non-searchable and searchable paths behave
/// identically.
///
/// `filtered_indices` maps the filtered-list position to the raw
/// `source` index — `None` for the non-searchable path (filtered
/// position equals source index), `Some` for searchable mode's
/// current filter output. The scroll coordinate space is the
/// ListView's own content-space (row 0 starts at y=0), so no extra
/// padding offset is applied here — the outer `Padding::uniform(4.0)`
/// lives outside the scroll region.
fn register_scroll_into_view<T: Clone + PartialEq + 'static>(
    ctx: &mut BuildContext,
    source: ItemSource<T>,
    selected: Signal<Option<T>>,
    scroll_y: Signal<f32>,
    filtered_indices: Option<Rc<Vec<usize>>>,
    item_height: f32,
    viewport_height: f32,
) {
    let scroll_into_view = {
        let source = source.clone();
        let scroll_y = scroll_y.clone();
        move |sel: &Option<T>| {
            let Some(v) = sel.as_ref() else { return };
            let pos = match &filtered_indices {
                None => match super::state::index_of(&source, v) {
                    Some(i) => i,
                    None => return,
                },
                Some(indices) => match indices
                    .iter()
                    .position(|&i| source.get(i).as_ref() == Some(v))
                {
                    Some(p) => p,
                    None => return,
                },
            };
            let item_top = pos as f32 * item_height;
            let item_bot = item_top + item_height;
            let cur_scroll = scroll_y.get();
            let cur_bot = cur_scroll + viewport_height;
            if item_top < cur_scroll {
                scroll_y.set(item_top);
            } else if item_bot > cur_bot {
                scroll_y.set(item_bot - viewport_height);
            }
        }
    };
    // Initial sync so a pre-selected value opens already in view.
    scroll_into_view(&selected.get());
    ctx.effect(&selected, move |sel| scroll_into_view(sel));
}

/// Dropdown panel content (internal widget — shown as overlay).
///
/// In non-searchable mode the panel's own `build` renders the item
/// `VStack` directly. In searchable mode it instead renders a static
/// `TextInput` above a `FilteredItemList` child — only the inner list
/// binds the query signal at `BindingLevel::Rebuild`, so typing a
/// character re-filters the items without destroying (and un-focusing)
/// the search field.
pub(super) struct DropdownPanel<T: Clone + PartialEq + 'static> {
    pub(super) source: ItemSource<T>,
    pub(super) selected: Signal<Option<T>>,
    pub(super) item_label: Rc<dyn Fn(&T) -> LocalizedString>,
    pub(super) render_item: Option<Rc<dyn Fn(&T, bool) -> Box<dyn Widget>>>,
    /// Fired (with a live `EventContext`) when the user commits a row by
    /// tapping it; threaded from `ComboBox::on_select`.
    pub(super) on_select: OnSelect<T>,
    pub(super) max_visible_items: usize,
    /// Bumped on every model mutation so the panel rebuilds.
    pub(super) version: Signal<u64>,
    /// Active search query (searchable mode only).
    pub(super) search_query: Option<Signal<String>>,
    /// Custom filter predicate for searchable mode. When `None`, the
    /// default is a case-insensitive substring match on the label.
    pub(super) filter: Option<Rc<dyn Fn(&str, &T) -> bool>>,
    /// Shared slot populated during `build` with the `TextInput`'s
    /// widget id so the owning `ComboBox` can `ctx.request_focus(..)`
    /// the field when the overlay opens.
    pub(super) search_input_slot: Rc<Cell<Option<WidgetId>>>,
    pub(super) root_child_id: Option<WidgetId>,
}

/// Inner widget for the searchable dropdown's filtered item list.
/// Binds both the model-version signal and the search-query signal at
/// `BindingLevel::Rebuild`, while the sibling `TextInput` remains a
/// stable arena child of `DropdownPanel` across query-driven rebuilds —
/// so focus stays on the search field as the user types.
struct FilteredItemList<T: Clone + PartialEq + 'static> {
    source: ItemSource<T>,
    selected: Signal<Option<T>>,
    item_label: Rc<dyn Fn(&T) -> LocalizedString>,
    render_item: Option<Rc<dyn Fn(&T, bool) -> Box<dyn Widget>>>,
    on_select: OnSelect<T>,
    max_visible_items: usize,
    version: Signal<u64>,
    search_query: Signal<String>,
    filter: Option<Rc<dyn Fn(&str, &T) -> bool>>,
    root_child_id: Option<WidgetId>,
}

impl<T: Clone + PartialEq + 'static> std::fmt::Debug for FilteredItemList<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FilteredItemList")
            .field("item_count", &self.source.len())
            .finish()
    }
}

impl<T: Clone + PartialEq + 'static> Widget for FilteredItemList<T> {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        use teksilo_core::binding::BindingLevel;

        // Rebuild on model mutation AND on query change. Both bindings
        // sit here rather than on the outer panel so the sibling
        // `TextInput` is not torn down on every keystroke.
        self.version
            .bind_to(ctx.self_id(), ctx.binding_registry(), BindingLevel::Rebuild);
        self.search_query
            .bind_to(ctx.self_id(), ctx.binding_registry(), BindingLevel::Rebuild);

        let total = self.source.len();
        let q = self.search_query.get();
        let visible_indices: Vec<usize> = if q.is_empty() {
            (0..total).collect()
        } else {
            let q_lower = q.to_lowercase();
            let mut keep = Vec::new();
            for i in 0..total {
                if let Some(value) = self.source.get(i) {
                    let matches = match &self.filter {
                        Some(f) => f(&q, &value),
                        None => (self.item_label)(&value)
                            .resolve_now()
                            .to_lowercase()
                            .contains(&q_lower),
                    };
                    if matches {
                        keep.push(i);
                    }
                }
            }
            keep
        };
        let visible_count = visible_indices.len();

        // Large filtered result — hand off to the shared virtualized
        // path so only the visible rows are materialized even when the
        // query matches thousands of items.
        let root_id = if visible_count > self.max_visible_items {
            build_virtualized_list(
                ctx,
                &self.source,
                &self.selected,
                &self.item_label,
                &self.render_item,
                &self.on_select,
                self.max_visible_items,
                Some(visible_indices),
            )
        } else {
            let mut vstack = VStack::new();
            for (pos, &i) in visible_indices.iter().enumerate() {
                if let Some(value) = self.source.get(i) {
                    // Panel is ephemeral (rebuilt on open / panel_version change),
                    // so resolving the label at build time is acceptable even in
                    // reactive mode; the persistent trigger is the live-reactive one.
                    let label = (self.item_label)(&value).resolve_now();
                    vstack = vstack.child(DropdownItem {
                        value,
                        label,
                        position: pos + 1,
                        total: visible_count,
                        selected_signal: self.selected.clone(),
                        render: self.render_item.clone(),
                        on_select: self.on_select.clone(),
                        root_child_id: None,
                    });
                }
            }
            let vstack_id = ctx.add(vstack);
            ctx.add(Padding::uniform(4.0).child_id(vstack_id))
        };
        self.root_child_id = Some(root_id);
        vec![root_id]
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        match self.root_child_id {
            Some(id) => ctx
                .child_size(id, proposal)
                .unwrap_or_else(|| proposal.resolve(120.0, 0.0)),
            None => proposal.resolve(120.0, 0.0),
        }
        .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }
}

impl<T: Clone + PartialEq + 'static> std::fmt::Debug for DropdownPanel<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DropdownPanel")
            .field("item_count", &self.source.len())
            .finish()
    }
}

impl<T: Clone + PartialEq + 'static> Widget for DropdownPanel<T> {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let _theme_signal = ctx.theme_signal();

        // In non-searchable mode the panel itself binds the model-version
        // signal so the item list rebuilds on mutation. In searchable mode
        // both the model-version AND query bindings live on the inner
        // `FilteredItemList`, keeping the panel (and the `TextInput`
        // inside it) stable across query-driven rebuilds.
        let searchable = self.search_query.is_some();
        if !searchable {
            use teksilo_core::binding::BindingLevel;
            self.version
                .bind_to(ctx.self_id(), ctx.binding_registry(), BindingLevel::Rebuild);
        }

        // Build the item-list portion of the panel. In searchable mode
        // that's a `FilteredItemList` child widget that owns the query
        // binding. Otherwise it's the static padded VStack.
        let list_id = if let Some(query) = &self.search_query {
            ctx.add(FilteredItemList {
                source: self.source.clone(),
                selected: self.selected.clone(),
                item_label: self.item_label.clone(),
                render_item: self.render_item.clone(),
                on_select: self.on_select.clone(),
                max_visible_items: self.max_visible_items,
                version: self.version.clone(),
                search_query: query.clone(),
                filter: self.filter.clone(),
                root_child_id: None,
            })
        } else {
            build_static_item_list(
                ctx,
                &self.source,
                &self.selected,
                &self.item_label,
                &self.render_item,
                &self.on_select,
                self.max_visible_items,
            )
        };

        // Searchable mode: prepend a `TextInput` with a trailing
        // `IconButton::clear()` so the user can wipe the query back
        // to empty. Both sit in a VStack above the filtered items. The
        // input's widget id is captured in a shared slot so the owning
        // `ComboBox` can programmatically focus it when the overlay opens.
        let content_id = if let Some(query) = &self.search_query {
            // `show_clear_button(true)` inserts a clear button
            // into `TextInput`'s trailing slot, wired to empty
            // the bound text signal, and — critically — binds
            // its visibility to `text.is_empty().not()` so the
            // button only appears once something has been typed.
            // Using the built-in option here rather than a
            // hand-wired `IconButton::clear()` in the
            // trailing slot avoids reaching for the trailing
            // widget's id from the outside (it lives inside
            // TextInput's build) just to register
            // `ctx.visible_when`.
            //
            // `on_submit` dismisses the overlay on Enter. The
            // `TextInputField` consumes `Enter` before it can
            // bubble to the panel's own key handler, so we
            // rely on this hook instead. The selection
            // tracked in `selected` (driven by the panel's
            // ArrowDown/ArrowUp handler) is already correct
            // when the user confirms.
            let search_input = crate::text_input::TextInput::new(query.clone())
                .placeholder(lit!("Search…"))
                .show_clear_button(true)
                .on_submit_fn(|ctx| ctx.dismiss_top_overlay());
            let search_id = ctx.add(search_input);
            self.search_input_slot.set(Some(search_id));
            let search_wrapped = ctx.add(Padding::new(4.0, 4.0, 0.0, 4.0).child_id(search_id));
            let col = VStack::new()
                .spacing(0.0)
                .add_child(search_wrapped)
                .add_child(list_id);
            ctx.add(col)
        } else {
            list_id
        };

        // Dropdown panel surface — routed through `PopoverStyle` (the
        // `Menu`-flavoured variant). The panel's background, border,
        // corner radius, and the trigger-attached drop shadow are all
        // owned by the active popover style; the panel stays pure
        // composition. Combo dropdowns always open below the trigger
        // (flipping above when there's no room), so `BelowPreferred`
        // makes `PopoverSurface` suppress the trigger-side shadow.
        let popover_style: teksilo_core::styles::SharedPopoverStyle = ctx
            .theme()
            .style_slots
            .popover
            .clone()
            .unwrap_or_else(|| Rc::new(crate::styles::RecipePopoverStyle::default()));
        let surface_cfg = PopoverStyleConfig {
            content: content_id,
            variant: PopoverVariant::Menu,
            name: String::new(),
            placement: OverlayPlacement::BelowPreferred,
            show_caret: false,
            caret_size: 0.0,
        };
        let root_id = popover_style.make_body(&surface_cfg, ctx);
        self.root_child_id = Some(root_id);

        // Panel-level key handler. Events bubble up from the focused
        // descendant; in practice that's the search `TextInputField`
        // in searchable mode (non-searchable combos keep focus on the
        // trigger and navigate there). Handles:
        //
        // - ArrowDown / ArrowUp / Home / End: navigate the filtered
        //   item list while the search field retains focus, so the
        //   user can type a query then arrow through the matches
        //   without losing the cursor.
        // - Enter: confirm the current selection and close. The
        //   `selected` signal was already updated by the arrow keys;
        //   the item's own tap handler would duplicate that, so here
        //   we just dismiss.
        //
        // Tab is deliberately absent: the framework dismisses a non-modal
        // overlay the keyboard walks out of, so letting Tab reach the ordinary
        // focus cycle closes this panel *and* advances in one press.
        //
        // Returning `Handled` suppresses the `TextInputField`'s downstream key
        // handling (arrows would otherwise fall through as printable-
        // character candidates and be rejected as non-text).
        let source_for_nav = self.source.clone();
        let selected_for_nav = self.selected.clone();
        let item_label_for_nav = self.item_label.clone();
        let search_query_for_nav = self.search_query.clone();
        let filter_for_nav = self.filter.clone();
        let panel_handlers = HandlerSet::new().on_key(move |event, _ctx| {
            // `TextInputField` consumes `Enter`, `Home`, and `End` for
            // its own cursor semantics and never lets them bubble — so
            // Home/End naturally move the caret inside the search
            // string (expected text-field behavior), and Enter is
            // routed through `TextInput::on_submit(..)` set below. Only
            // `ArrowDown`/`ArrowUp` fall through as unhandled from the
            // text field and reach this handler; we use them to walk
            // the filtered item list.
            let nav_key = match event {
                WidgetEvent::KeyDown {
                    key: k @ (Key::ArrowDown | Key::ArrowUp),
                    ..
                } => *k,
                _ => return EventResponse::Ignored,
            };

            // Compute the visible-index list under the current filter.
            // Mirrors `FilteredItemList::build` — kept in sync manually
            // because the panel's key handler needs to navigate the
            // same filtered subset without reaching into the child's
            // internal state.
            let total = source_for_nav.len();
            let filtered: Vec<usize> = if let Some(query) = &search_query_for_nav {
                let q = query.get();
                if q.is_empty() {
                    (0..total).collect()
                } else {
                    let q_lower = q.to_lowercase();
                    (0..total)
                        .filter(|&i| {
                            source_for_nav
                                .get(i)
                                .map(|v| match &filter_for_nav {
                                    Some(f) => f(&q, &v),
                                    None => (item_label_for_nav)(&v)
                                        .resolve_now()
                                        .to_lowercase()
                                        .contains(&q_lower),
                                })
                                .unwrap_or(false)
                        })
                        .collect()
                }
            } else {
                (0..total).collect()
            };
            let n = filtered.len();
            if n == 0 {
                return EventResponse::Handled;
            }

            // Find the currently-selected value's position within the
            // filtered list. A selection that has been filtered out
            // counts as no-selection for navigation purposes.
            let current = selected_for_nav.get();
            let current_in_filtered = current.as_ref().and_then(|v| {
                filtered
                    .iter()
                    .position(|&i| source_for_nav.get(i).as_ref() == Some(v))
            });

            let next_idx = match nav_key {
                Key::ArrowDown => match current_in_filtered {
                    None => 0,
                    Some(i) => (i + 1) % n,
                },
                Key::ArrowUp => match current_in_filtered {
                    None | Some(0) => n - 1,
                    Some(i) => i - 1,
                },
                _ => return EventResponse::Handled,
            };
            if let Some(v) = source_for_nav.get(filtered[next_idx]) {
                selected_for_nav.set(Some(v));
            }
            EventResponse::Handled
        });
        ctx.apply_self_handlers(panel_handlers);

        vec![root_id]
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        match self.root_child_id {
            Some(id) => ctx
                .child_size(id, proposal)
                .unwrap_or_else(|| proposal.resolve(120.0, 0.0)),
            None => proposal.resolve(120.0, 0.0),
        }
        .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    // No `paint()`: the panel is pure composition. The drop shadow is
    // the `DropdownShadow` leaf at the back of the panel's ZStack.

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        builder.set_role(teksilo_core::accesskit::Role::ListBox);
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }
}