Skip to main content

waft_winui/controls/
tab_view.rs

1//! TabView's collection policy, keyboarding, width allocation and template from TabView.cpp/.xaml.
2
3mod drag;
4use drag::TabDragState;
5pub use drag::{
6    TabViewReorderRequestedEventArgs, TabViewTabDragCompletedEventArgs,
7    TabViewTabDragStartingEventArgs, TabViewTabStripDropEventArgs,
8};
9
10use super::tab_view_item::{TabBottomBorderState, TabViewItemHeader};
11use super::{TabScrollViewer, bottom_border_line};
12use crate::*;
13use std::{
14    collections::{HashMap, HashSet},
15    fmt,
16    rc::Rc,
17    time::Duration,
18};
19use waft_animation::Curves;
20use waft_embedder::{FontWeight, TextDirection};
21use waft_foundation::{App, Handle, Listenable, Listener, OptionRetained, Ref, ValueKey};
22use waft_painting::{Alignment, Axis, EdgeInsetsGeometry};
23use waft_rendering::{BoxConstraints, StackFit};
24use waft_scheduler::{FrameCallback, SchedulerBinding};
25use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
26use waft_widgets::*;
27
28/// Requests selection of an item, or no item when the collection becomes empty.
29pub type TabViewSelectionChanged = Rc<dyn Fn(&mut App, Option<usize>)>;
30
31/// Identifies the tab whose close was requested; removing it remains the owner's choice.
32#[derive(Clone, Debug)]
33pub struct TabViewTabCloseRequestedEventArgs {
34    /// Collection index at the time of the request.
35    pub index: usize,
36
37    /// The stable tab item supplied by the owner.
38    pub item: TabViewItem,
39}
40
41/// Receives a close request before the item's CloseRequested callback.
42pub type TabViewTabCloseRequested = Rc<dyn Fn(&mut App, TabViewTabCloseRequestedEventArgs)>;
43
44/// Receives an owner-managed collection reorder request.
45pub type TabViewReorderRequested = Rc<dyn Fn(&mut App, TabViewReorderRequestedEventArgs)>;
46
47/// Builds an independent native drag avatar at the measured tab width.
48pub type TabViewDragFeedbackBuilder = Rc<dyn Fn(&mut App, &TabViewItem, f64) -> WidgetRef>;
49
50/// Receives a cancelable drag-start event.
51pub type TabViewTabDragStarting = Rc<dyn Fn(&mut App, &mut TabViewTabDragStartingEventArgs)>;
52
53/// Receives the final acceptance of a completed drag.
54pub type TabViewTabDragCompleted = Rc<dyn Fn(&mut App, TabViewTabDragCompletedEventArgs)>;
55
56/// Receives an item dropped without an accepted target.
57pub type TabViewTabDroppedOutside = Rc<dyn Fn(&mut App, TabViewItem)>;
58
59/// Decides whether a strip accepts an incoming item.
60pub type TabViewTabStripDragOver = Rc<dyn Fn(&mut App, &mut TabViewTabStripDropEventArgs)>;
61
62/// Transfers an accepted incoming item to its owner.
63pub type TabViewTabStripDrop = Rc<dyn Fn(&mut App, TabViewTabStripDropEventArgs)>;
64
65/// A tab strip and selected content presenter, with source width and keyboard behavior.
66#[derive(Clone)]
67pub struct TabView {
68    /// Identity retained when the surrounding widget tree rebuilds.
69    pub key: Option<KeyRef>,
70
71    /// Tabs in collection order; ids must be unique and stable across moves.
72    pub tab_items: Vec<TabViewItem>,
73
74    /// Index selected by the owner, or no selection.
75    pub selected_index: Option<usize>,
76
77    /// Requests selection changes from pointer, keyboard and collection reconciliation.
78    pub selection_changed: TabViewSelectionChanged,
79
80    /// How the available strip width is allocated to headers.
81    pub tab_width_mode: TabViewWidthMode,
82
83    /// When closable tabs expose their close button.
84    pub close_button_overlay_mode: TabViewCloseButtonOverlayMode,
85
86    /// Optional content before the first tab.
87    pub tab_strip_header: Option<WidgetRef>,
88
89    /// Optional content following the add button, stretched into remaining space.
90    pub tab_strip_footer: Option<WidgetRef>,
91
92    /// Whether the add-tab button is displayed.
93    pub is_add_tab_button_visible: bool,
94
95    /// Raised when the add-tab button activates; adding the tab remains the owner's choice.
96    pub add_tab_button_click: Option<Listener>,
97
98    /// Raised for close-button, middle-click and Ctrl+F4 close requests.
99    pub tab_close_requested: Option<TabViewTabCloseRequested>,
100
101    /// Allows drag events and drops into another tab strip; defaults to false.
102    pub can_drag_tabs: bool,
103
104    /// Enables pointer and Alt+Shift+arrow reordering; defaults to true.
105    pub can_reorder_tabs: bool,
106
107    /// Allows drops onto this tab strip; defaults to true.
108    pub allow_drop_tabs: bool,
109
110    /// Requests the owner move an item, preserving the selected identity.
111    pub tab_reorder_requested: Option<TabViewReorderRequested>,
112
113    /// Builds an independent visual subtree for native drag feedback.
114    ///
115    /// The feedback must not reuse GlobalKeys or externally owned focus nodes from the live header.
116    pub tab_drag_feedback_builder: Option<TabViewDragFeedbackBuilder>,
117
118    /// Raised before an externally enabled drag starts; set cancel to prevent it.
119    pub tab_drag_starting: Option<TabViewTabDragStarting>,
120
121    /// Raised after an externally enabled drag ends.
122    pub tab_drag_completed: Option<TabViewTabDragCompleted>,
123
124    /// Raised when an externally enabled drag finishes without an accepted drop.
125    pub tab_dropped_outside: Option<TabViewTabDroppedOutside>,
126
127    /// Decides whether an incoming drag is accepted; the owner sets accepted.
128    pub tab_strip_drag_over: Option<TabViewTabStripDragOver>,
129
130    /// Receives accepted cross-strip drops; ownership transfer remains the owner's responsibility.
131    pub tab_strip_drop: Option<TabViewTabStripDrop>,
132}
133
134impl fmt::Debug for TabView {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        f.debug_struct("TabView")
137            .field("selected_index", &self.selected_index)
138            .field("tab_items", &self.tab_items)
139            .finish_non_exhaustive()
140    }
141}
142
143impl TabView {
144    /// Creates tabs with owner-managed selection, matching the kit's other value controls.
145    pub fn new(
146        items: Vec<TabViewItem>,
147        selected_index: Option<usize>,
148        selection_changed: impl Fn(&mut App, Option<usize>) + 'static,
149    ) -> Self {
150        Self {
151            key: None,
152            tab_items: items,
153            selected_index,
154            selection_changed: Rc::new(selection_changed),
155            tab_width_mode: TabViewWidthMode::Equal,
156            close_button_overlay_mode: TabViewCloseButtonOverlayMode::Auto,
157            tab_strip_header: None,
158            tab_strip_footer: None,
159            is_add_tab_button_visible: true,
160            add_tab_button_click: None,
161            tab_close_requested: None,
162            can_drag_tabs: false,
163            can_reorder_tabs: true,
164            allow_drop_tabs: true,
165            tab_reorder_requested: None,
166            tab_drag_feedback_builder: None,
167            tab_drag_starting: None,
168            tab_drag_completed: None,
169            tab_dropped_outside: None,
170            tab_strip_drag_over: None,
171            tab_strip_drop: None,
172        }
173    }
174
175    /// Sets the identity retained across rebuilds.
176    pub fn key(mut self, key: KeyRef) -> Self {
177        self.key = Some(key);
178        self
179    }
180
181    /// Selects Equal, SizeToContent or Compact header allocation.
182    pub fn tab_width_mode(mut self, mode: TabViewWidthMode) -> Self {
183        self.tab_width_mode = mode;
184        self
185    }
186
187    /// Sets close-button visibility policy.
188    pub fn close_button_overlay_mode(mut self, mode: TabViewCloseButtonOverlayMode) -> Self {
189        self.close_button_overlay_mode = mode;
190        self
191    }
192
193    /// Supplies the leading strip content.
194    #[cfg_attr(debug_assertions, track_caller)]
195    pub fn tab_strip_header<K>(mut self, child: impl IntoWidget<K>) -> Self {
196        self.tab_strip_header = Some(child.into_widget());
197        self
198    }
199
200    /// Supplies the trailing strip content.
201    #[cfg_attr(debug_assertions, track_caller)]
202    pub fn tab_strip_footer<K>(mut self, child: impl IntoWidget<K>) -> Self {
203        self.tab_strip_footer = Some(child.into_widget());
204        self
205    }
206
207    /// Controls visibility of the add-tab button.
208    pub fn is_add_tab_button_visible(mut self, value: bool) -> Self {
209        self.is_add_tab_button_visible = value;
210        self
211    }
212
213    /// Receives activation of the add-tab button.
214    pub fn add_tab_button_click(mut self, callback: Listener) -> Self {
215        self.add_tab_button_click = Some(callback);
216        self
217    }
218
219    /// Receives requests to close individual tabs.
220    pub fn tab_close_requested(mut self, callback: TabViewTabCloseRequested) -> Self {
221        self.tab_close_requested = Some(callback);
222        self
223    }
224
225    /// Returns the selected item if its index is in range.
226    pub fn selected_item(&self) -> Option<&TabViewItem> {
227        self.selected_index
228            .and_then(|index| self.tab_items.get(index))
229    }
230}
231
232/// Persistent native identity and focus handles for one logical tab.
233#[derive(Clone)]
234struct TabContainer {
235    /// Identifies the realized header independently of its collection index.
236    key: GlobalKey,
237
238    /// Owns keyboard focus for the header surface.
239    tab_focus: FocusNodeRef,
240
241    /// Owns keyboard focus for the close button.
242    close_focus: FocusNodeRef,
243
244    /// Retains traversal history for this tab’s page.
245    content_focus: Ref<FocusScopeNode>,
246}
247
248impl TabContainer {
249    /// Creates identity and focus handles without realizing the header or page.
250    fn new(app: &mut App, id: &str) -> Self {
251        let content_focus = FocusScopeNode::new(app);
252        content_focus.set_traversal_edge_behavior(app, TraversalEdgeBehavior::ParentScope);
253        Self {
254            key: GlobalKey::labeled(format!("Tab {id}")),
255            tab_focus: FocusNode::new(app).into_erased(),
256            close_focus: FocusNode::new(app).into_erased(),
257            content_focus,
258        }
259    }
260
261    /// Releases caller-owned focus nodes after their widgets have detached.
262    fn dispose(self, app: &mut App) {
263        for node in [
264            self.tab_focus.handle(),
265            self.close_focus.handle(),
266            self.content_focus.as_node(),
267        ] {
268            node.dispose(app);
269        }
270    }
271}
272
273/// Retains containers across reorders and tracks source strip sizing and hover state.
274pub struct TabViewState {
275    /// Native widget lifecycle and element association.
276    state: StateData<TabView>,
277
278    /// Persistent handles indexed by stable tab identity.
279    containers: HashMap<String, TabContainer>,
280
281    /// Pages that have been selected and must retain their native subtree.
282    visited: HashSet<String>,
283
284    /// Controller for the native horizontal list viewport.
285    scroll: Option<Ref<ScrollViewportController>>,
286
287    /// Updates scroll-button state when the viewport moves.
288    scroll_listener: Option<Listener>,
289
290    /// Owned focus node for the add-tab button.
291    add_focus: Option<FocusNodeRef>,
292
293    /// Stable identity of the currently hovered tab.
294    hovered: Option<String>,
295
296    /// Whether closing a tab should defer equal-width expansion.
297    pointer_in_strip: bool,
298
299    /// Keeps neighboring close buttons stationary until the pointer leaves.
300    deferred_width_update: bool,
301
302    /// Most recently allocated common header width; the theme's `TabViewItemMaxWidth` before
303    /// the first layout.
304    equal_width: Option<f64>,
305
306    /// Measured width reserved before the first tab.
307    header_width: f64,
308
309    /// Measured width reserved after the add button.
310    footer_width: f64,
311
312    /// Measured variable widths used for realization estimates.
313    tab_widths: HashMap<String, f64>,
314
315    /// Invalidates older asynchronous bring-into-view requests.
316    bring_epoch: u64,
317
318    /// Source drag and destination insertion state.
319    drag: TabDragState,
320
321    /// Selected object identity, reconciled before the owner receives collection changes.
322    selected_id: Option<String>,
323
324    /// Invalidates queued collection selection notifications.
325    selection_epoch: u64,
326
327    /// Carries page focus across owner-driven selection reconciliation.
328    pending_content_focus: bool,
329}
330
331impl StatefulWidget for TabView {
332    type State = TabViewState;
333
334    fn key(&self) -> Option<&KeyRef> {
335        self.key.as_ref()
336    }
337
338    fn create_state(&self) -> Self::State {
339        Self::State {
340            state: StateData::new(),
341            containers: HashMap::new(),
342            visited: HashSet::new(),
343            scroll: None,
344            scroll_listener: None,
345            add_focus: None,
346            hovered: None,
347            pointer_in_strip: false,
348            deferred_width_update: false,
349            equal_width: None,
350            header_width: 2.0,
351            footer_width: 0.0,
352            tab_widths: HashMap::new(),
353            bring_epoch: 0,
354            drag: TabDragState::default(),
355            pending_content_focus: false,
356            selected_id: self.selected_item().map(|item| item.id.clone()),
357            selection_epoch: 0,
358        }
359    }
360}
361
362impl TabViewState {
363    /// Resolves the retained selected object against the current collection.
364    fn selected_index(self: Handle<Self>, app: &App) -> Option<usize> {
365        let id = app.get(self).selected_id.as_ref()?;
366        self.widget(app)
367            .tab_items
368            .iter()
369            .position(|item| &item.id == id)
370    }
371
372    /// Supplies the reconciled selection to template and interaction code.
373    fn effective_widget(self: Handle<Self>, app: &App) -> TabView {
374        let mut widget = self.widget(app).clone();
375        widget.selected_index = self.selected_index(app);
376        widget
377    }
378
379    /// Looks up a realized header without forcing every list item to mount.
380    pub fn container_from_index(
381        self: Handle<Self>,
382        app: &mut App,
383        index: usize,
384    ) -> Option<BuildContext> {
385        let id = self.widget(app).tab_items.get(index)?.id.clone();
386        let key = app.get(self).containers.get(&id)?.key.clone();
387        key.current_context(app)
388    }
389
390    /// Resolves stable item identity to its currently realized header.
391    pub fn container_from_item(
392        self: Handle<Self>,
393        app: &mut App,
394        id: &str,
395    ) -> Option<BuildContext> {
396        let key = app.get(self).containers.get(id)?.key.clone();
397        key.current_context(app)
398    }
399
400    /// Synchronizes persistent identity without creating offscreen widgets.
401    fn sync_items(self: Handle<Self>, app: &mut App) {
402        let ids: Vec<_> = self
403            .widget(app)
404            .tab_items
405            .iter()
406            .map(|item| item.id.clone())
407            .collect();
408        let unique: HashSet<_> = ids.iter().cloned().collect();
409        assert_eq!(unique.len(), ids.len(), "TabView item ids must be unique");
410        let removed: Vec<_> = app
411            .get(self)
412            .containers
413            .keys()
414            .filter(|id| !unique.contains(*id))
415            .cloned()
416            .collect();
417        for id in removed {
418            let container = app.get_mut(self).containers.remove(&id).unwrap();
419            app.get_mut(self).visited.remove(&id);
420            app.get_mut(self).tab_widths.remove(&id);
421            SchedulerBinding::add_post_frame_callback(
422                app,
423                FrameCallback::new(move |app, _| container.clone().dispose(app)),
424                View::maybe_id_of(app, self.context(app)),
425            );
426        }
427        for id in ids {
428            if !app.get(self).containers.contains_key(&id) {
429                let container = TabContainer::new(app, &id);
430                app.get_mut(self).containers.insert(id, container);
431            }
432        }
433        if let Some(id) = app.get(self).selected_id.clone() {
434            app.get_mut(self).visited.insert(id);
435        }
436    }
437
438    /// Requests selection only for a visible, enabled tab.
439    fn select(self: Handle<Self>, app: &mut App, index: usize) {
440        let widget = self.effective_widget(app);
441        if widget
442            .tab_items
443            .get(index)
444            .is_some_and(|item| item.is_enabled && item.is_visible)
445            && widget.selected_index != Some(index)
446        {
447            let callback = widget.selection_changed.clone();
448            callback(app, Some(index));
449        }
450    }
451
452    /// Raises parent and item close events without removing the tab itself.
453    fn request_close(self: Handle<Self>, app: &mut App, index: usize) {
454        let widget = self.effective_widget(app);
455        let Some(item) = widget
456            .tab_items
457            .get(index)
458            .cloned()
459            .filter(|item| item.is_closable && item.is_enabled)
460        else {
461            return;
462        };
463        let focus_in_header =
464            app.get(self)
465                .containers
466                .get(&item.id)
467                .cloned()
468                .is_some_and(|container| {
469                    container.tab_focus.has_focus(app) || container.close_focus.has_focus(app)
470                });
471        let focus_candidates: Vec<_> = ((index + 1)..widget.tab_items.len())
472            .chain((0..index).rev())
473            .map(|index| widget.tab_items[index].id.clone())
474            .collect();
475        let closing_id = item.id.clone();
476        if let Some(callback) = widget.tab_close_requested {
477            callback(
478                app,
479                TabViewTabCloseRequestedEventArgs {
480                    index,
481                    item: item.clone(),
482                },
483            );
484        }
485        if let Some(callback) = item.close_requested {
486            callback.call(app);
487        }
488        if focus_in_header {
489            SchedulerBinding::add_post_frame_callback(
490                app,
491                FrameCallback::new(move |app, _| {
492                    if !app.contains(self)
493                        || !self.mounted(app)
494                        || self
495                            .widget(app)
496                            .tab_items
497                            .iter()
498                            .any(|item| item.id == closing_id)
499                    {
500                        return;
501                    }
502                    let next = focus_candidates.iter().find_map(|id| {
503                        self.widget(app)
504                            .tab_items
505                            .iter()
506                            .position(|item| &item.id == id && item.is_enabled && item.is_visible)
507                    });
508                    if let Some(index) = next {
509                        let id = self.widget(app).tab_items[index].id.clone();
510                        let focus = app.get(self).containers[&id].tab_focus.handle();
511                        self.bring_tab_into_view(app, index, Some(focus));
512                    } else if self.widget(app).is_add_tab_button_visible
513                        && let Some(focus) = app.get(self).add_focus.handle()
514                    {
515                        focus.request_focus(app, None);
516                    }
517                }),
518                View::maybe_id_of(app, self.context(app)),
519            );
520        }
521    }
522
523    /// Moves selection with wraparound, skipping unavailable tabs.
524    fn move_selection(self: Handle<Self>, app: &mut App, forward: bool) -> bool {
525        let widget = self.effective_widget(app);
526        let count = widget.tab_items.len();
527        if count == 0 {
528            return false;
529        }
530        let start = widget
531            .selected_index
532            .unwrap_or(if forward { count - 1 } else { 0 })
533            .min(count - 1);
534        let candidate = (1..=count)
535            .map(|step| {
536                if forward {
537                    (start + step) % count
538                } else {
539                    (start + count - step % count) % count
540                }
541            })
542            .find(|index| {
543                widget.tab_items[*index].is_enabled && widget.tab_items[*index].is_visible
544            });
545        if let Some(index) = candidate {
546            self.select(app, index);
547            true
548        } else {
549            false
550        }
551    }
552
553    /// The source arrow order includes each close button and wraps through AddButton.
554    fn move_focus(self: Handle<Self>, app: &mut App, forward: bool) -> bool {
555        let widget = self.effective_widget(app);
556        let mut order = Vec::new();
557        for (index, item) in widget
558            .tab_items
559            .iter()
560            .enumerate()
561            .filter(|(_, item)| item.is_enabled && item.is_visible)
562        {
563            let container = app.get(self).containers[&item.id].clone();
564            order.push((Some(index), container.tab_focus.handle()));
565            let show_close = item.is_closable
566                && (widget.close_button_overlay_mode
567                    != TabViewCloseButtonOverlayMode::OnPointerOver
568                    || widget.selected_index == Some(index)
569                    || app.get(self).hovered.as_ref() == Some(&item.id));
570            if show_close {
571                order.push((Some(index), container.close_focus.handle()));
572            }
573        }
574        if widget.is_add_tab_button_visible {
575            order.push((None, app.get(self).add_focus.handle().unwrap()));
576        }
577        let Some(primary) = primary_focus(app) else {
578            return false;
579        };
580        let Some(current) = order.iter().position(|(_, node)| *node == primary) else {
581            return false;
582        };
583        let next = if forward {
584            (current + 1) % order.len()
585        } else {
586            (current + order.len() - 1) % order.len()
587        };
588        let (index, node) = order[next];
589        if let Some(index) = index {
590            self.bring_tab_into_view(app, index, Some(node));
591        } else {
592            node.request_focus(app, None);
593        }
594        true
595    }
596
597    /// Handles source accelerators in the TabView scope, including page content.
598    fn on_key(self: Handle<Self>, app: &mut App, event: &KeyEvent, rtl: bool) -> KeyEventResult {
599        if !matches!(event, KeyEvent::Down(_)) {
600            return KeyEventResult::Ignored;
601        }
602        let keyboard = HardwareKeyboard::instance(app);
603        let control = keyboard.is_control_pressed(app);
604        let shift = keyboard.is_shift_pressed(app);
605        let key = event.logical_key();
606        if app.get(self).drag.item.is_some() {
607            return KeyEventResult::Handled;
608        }
609        let arrow = matches!(
610            key,
611            LogicalKeyboardKey::ARROW_LEFT
612                | LogicalKeyboardKey::ARROW_RIGHT
613                | LogicalKeyboardKey::ARROW_UP
614                | LogicalKeyboardKey::ARROW_DOWN
615        );
616        let handled = if arrow && keyboard.is_alt_pressed(app) && shift && !control {
617            self.keyboard_reorder(
618                app,
619                (matches!(
620                    key,
621                    LogicalKeyboardKey::ARROW_RIGHT | LogicalKeyboardKey::ARROW_DOWN
622                )) != rtl,
623            )
624        } else if control && key == LogicalKeyboardKey::TAB {
625            self.move_selection(app, !shift)
626        } else if control && key == LogicalKeyboardKey::F4 {
627            if let Some(index) = self.selected_index(app).filter(|index| {
628                self.widget(app)
629                    .tab_items
630                    .get(*index)
631                    .is_some_and(|item| item.is_closable)
632            }) {
633                self.request_close(app, index);
634                true
635            } else {
636                false
637            }
638        } else if (key == LogicalKeyboardKey::ARROW_LEFT || key == LogicalKeyboardKey::ARROW_RIGHT)
639            && !(keyboard.is_alt_pressed(app) && shift)
640        {
641            self.move_focus(app, (key == LogicalKeyboardKey::ARROW_RIGHT) != rtl)
642        } else {
643            false
644        };
645        if handled {
646            KeyEventResult::Handled
647        } else {
648            KeyEventResult::Ignored
649        }
650    }
651
652    /// Uses native realization and ensure-visible; equal-width offsets are exact.
653    fn bring_tab_into_view(
654        self: Handle<Self>,
655        app: &mut App,
656        index: usize,
657        focus: Option<AnyFocusNode>,
658    ) {
659        app.get_mut(self).bring_epoch += 1;
660        let epoch = app.get(self).bring_epoch;
661        self.bring_step(app, index, focus, epoch, 0);
662    }
663
664    /// Estimates an offscreen variable-width position, then corrects after native layout.
665    fn bring_step(
666        self: Handle<Self>,
667        app: &mut App,
668        index: usize,
669        focus: Option<AnyFocusNode>,
670        epoch: u64,
671        attempt: usize,
672    ) {
673        let r = ThemeResources::of(app, self.context(app));
674        after_next_frame(
675            app,
676            View::maybe_id_of(app, self.context(app)),
677            FrameCallback::new(move |app, _| {
678                if !app.contains(self) || !self.mounted(app) || app.get(self).bring_epoch != epoch {
679                    return;
680                }
681                if let Some(context) = self.container_from_index(app, index) {
682                    drop(Scrollable::ensure_visible(
683                        app,
684                        context,
685                        0.0,
686                        Duration::ZERO,
687                        Curves::linear(),
688                        ScrollPositionAlignmentPolicy::KeepVisibleAtStart,
689                    ));
690                    drop(Scrollable::ensure_visible(
691                        app,
692                        context,
693                        1.0,
694                        Duration::ZERO,
695                        Curves::linear(),
696                        ScrollPositionAlignmentPolicy::KeepVisibleAtEnd,
697                    ));
698                    if let Some(node) = focus {
699                        node.request_focus(app, None);
700                    }
701                    return;
702                }
703                let widget = self.effective_widget(app);
704                if index >= widget.tab_items.len() {
705                    return;
706                }
707                let widths = &app.get(self).tab_widths;
708                let estimate = if widget.tab_width_mode == TabViewWidthMode::Equal {
709                    app.get(self)
710                        .equal_width
711                        .unwrap_or(r.tab_view_item_max_width)
712                } else if widths.is_empty() {
713                    r.tab_view_item_min_width
714                } else {
715                    widths.values().sum::<f64>() / widths.len() as f64
716                };
717                let target = widget
718                    .tab_items
719                    .iter()
720                    .take(index)
721                    .filter(|item| item.is_visible)
722                    .map(|item| widths.get(&item.id).copied().unwrap_or(estimate))
723                    .sum::<f64>();
724                let scroll = app.get(self).scroll.clone().unwrap();
725                let moved = scroll.change_view(app, target, true);
726                if moved && attempt < self.widget(app).tab_items.len() {
727                    self.bring_step(app, index, focus, epoch, attempt + 1);
728                }
729            }),
730        );
731    }
732}
733
734impl State for TabViewState {
735    type Widget = TabView;
736    waft_widgets::state_accessors!();
737
738    fn init_state(self: Handle<Self>, app: &mut App) {
739        let scroll = ScrollViewportController::new(app);
740        let listener = Listener::new(move |app| {
741            if self.mounted(app) {
742                self.set_state(app, |_| {});
743            }
744        });
745        scroll.add_listener(app, listener.clone());
746        app.get_mut(self).scroll = Some(scroll.clone());
747        app.get_mut(self).scroll_listener = Some(listener);
748        app.get_mut(self).add_focus = Some(FocusNode::new(app).into_erased());
749        self.sync_items(app);
750        if let Some(index) = self.selected_index(app) {
751            self.bring_tab_into_view(app, index, None);
752        }
753    }
754
755    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &TabView) {
756        if old.tab_width_mode != self.widget(app).tab_width_mode {
757            app.get_mut(self).tab_widths.clear();
758        }
759        let old_selected = app.get(self).selected_id.clone();
760        let content_had_focus = app.get(self).pending_content_focus
761            || old_selected
762                .as_ref()
763                .and_then(|id| app.get(self).containers.get(id))
764                .map(|entry| entry.content_focus.as_node())
765                .is_some_and(|node| node.has_focus(app));
766        let widget = self.widget(app);
767        let old_index = old_selected
768            .as_ref()
769            .and_then(|id| old.tab_items.iter().position(|item| &item.id == id));
770        let retained_index = old_selected
771            .as_ref()
772            .and_then(|id| widget.tab_items.iter().position(|item| &item.id == id));
773        let single_removal = if old.tab_items.len() == widget.tab_items.len() + 1 {
774            let removed = old
775                .tab_items
776                .iter()
777                .zip(&widget.tab_items)
778                .position(|(old, new)| old.id != new.id)
779                .unwrap_or(widget.tab_items.len());
780            old.tab_items
781                .iter()
782                .skip(removed + 1)
783                .map(|item| &item.id)
784                .eq(widget.tab_items.iter().skip(removed).map(|item| &item.id))
785                .then_some(removed)
786        } else {
787            None
788        };
789        let removed_index = old_index
790            .filter(|_| retained_index.is_none())
791            .or(single_removal.filter(|_| old_selected.is_none()));
792        let owner_changed = old.selected_index != widget.selected_index;
793        let next = if owner_changed && widget.selected_item().is_some() {
794            widget.selected_index
795        } else if let Some(removed) = removed_index {
796            let count = widget.tab_items.len();
797            if count == 0 {
798                None
799            } else {
800                let start = removed.min(count - 1);
801                (0..count).map(|step| (start + step) % count).find(|index| {
802                    widget.tab_items[*index].is_enabled && widget.tab_items[*index].is_visible
803                })
804            }
805        } else if owner_changed {
806            widget
807                .selected_index
808                .filter(|index| *index < widget.tab_items.len())
809        } else {
810            retained_index
811        };
812        let selected_id = next.map(|index| widget.tab_items[index].id.clone());
813        let notify = next != widget.selected_index;
814        let callback = widget.selection_changed.clone();
815        let state = app.get_mut(self);
816        state.selected_id = selected_id.clone();
817        state.selection_epoch += 1;
818        let epoch = state.selection_epoch;
819        self.sync_items(app);
820        if notify {
821            SchedulerBinding::add_post_frame_callback(
822                app,
823                FrameCallback::new(move |app, _| {
824                    if app.contains(self)
825                        && self.mounted(app)
826                        && app.get(self).selection_epoch == epoch
827                    {
828                        callback(app, next);
829                    }
830                }),
831                View::maybe_id_of(app, self.context(app)),
832            );
833        }
834        if single_removal
835            .or(removed_index)
836            .is_some_and(|removed| removed < self.widget(app).tab_items.len())
837            && app.get(self).pointer_in_strip
838        {
839            app.get_mut(self).deferred_width_update = true;
840        }
841        if (old_selected != selected_id || app.get(self).pending_content_focus)
842            && let Some(index) = next
843        {
844            self.bring_tab_into_view(app, index, None);
845            if content_had_focus {
846                app.get_mut(self).pending_content_focus = false;
847                let id = selected_id.unwrap();
848                let container = app.get(self).containers[&id].clone();
849                SchedulerBinding::add_post_frame_callback(
850                    app,
851                    FrameCallback::new(move |app, _| {
852                        if app.contains(self)
853                            && self.mounted(app)
854                            && app.get(self).selected_id.as_ref() == Some(&id)
855                        {
856                            let candidates =
857                                container.content_focus.as_node().traversal_descendants(app);
858                            if let Some(first) = candidates.first() {
859                                first.request_focus(app, None);
860                            } else {
861                                container.tab_focus.request_focus(app, None);
862                            }
863                        }
864                    }),
865                    View::maybe_id_of(app, self.context(app)),
866                );
867            }
868        }
869        if self.widget(app).tab_items.is_empty() {
870            app.get_mut(self).pending_content_focus = false;
871        }
872    }
873
874    fn dispose(self: Handle<Self>, app: &mut App) {
875        self.dispose_drag(app);
876        let scroll = app.get(self).scroll.clone().unwrap();
877        if let Some(listener) = app.get_mut(self).scroll_listener.take() {
878            scroll.remove_listener(app, &listener);
879        }
880        scroll.dispose(app);
881        for (_, container) in std::mem::take(&mut app.get_mut(self).containers) {
882            container.dispose(app);
883        }
884        if let Some(node) = app.get_mut(self).add_focus.take() {
885            node.dispose(app);
886        }
887    }
888
889    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
890        let rtl = Directionality::of(app, context) == TextDirection::Rtl;
891        Focus::new(
892            LayoutBuilder::new(move |app, context, constraints| {
893                self.template(app, context, constraints.constraints())
894            })
895            .into_widget(),
896        )
897        .can_request_focus(false)
898        .skip_traversal(true)
899        .on_key_event(Rc::new(move |app, _, event| self.on_key(app, event, rtl)))
900        .into_widget()
901    }
902}
903
904impl TabViewState {
905    /// LayoutRoot and TabContainerGrid, with source row/column ownership.
906    fn template(
907        self: Handle<Self>,
908        app: &mut App,
909        context: BuildContext,
910        constraints: BoxConstraints,
911    ) -> WidgetRef {
912        let widget = self.effective_widget(app);
913        let theme = ThemeResources::of(app, context);
914        let r = theme.clone();
915        let visible: Vec<_> = widget
916            .tab_items
917            .iter()
918            .enumerate()
919            .filter(|(_, item)| item.is_visible)
920            .map(|(index, _)| index)
921            .collect();
922        let taken = app.get(self).header_width
923            + app.get(self).footer_width
924            + if widget.is_add_tab_button_visible {
925                r.tab_view_item_add_button_width + r.tab_view_item_add_button_container_padding[0]
926            } else {
927                0.0
928            };
929        let available = (constraints.max_width - taken).max(0.0);
930        if !app.get(self).deferred_width_update {
931            app.get_mut(self).equal_width = Some(if visible.is_empty() {
932                r.tab_view_item_max_width
933            } else {
934                ((available - 8.0) / visible.len() as f64)
935                    .clamp(r.tab_view_item_min_width, r.tab_view_item_max_width)
936            });
937        }
938        let width = app
939            .get(self)
940            .equal_width
941            .unwrap_or(r.tab_view_item_max_width);
942        let equal = widget.tab_width_mode == TabViewWidthMode::Equal;
943        let required = if equal {
944            width * visible.len() as f64 + 8.0
945        } else {
946            visible
947                .iter()
948                .map(|index| {
949                    app.get(self)
950                        .tab_widths
951                        .get(&widget.tab_items[*index].id)
952                        .copied()
953                        .unwrap_or(r.tab_view_item_min_width)
954                })
955                .sum::<f64>()
956                + 8.0
957        };
958        let strip_width = required.min(available);
959        let scroll = app.get(self).scroll.clone().unwrap();
960        let show_scroll = if equal {
961            required > available
962        } else {
963            scroll.metrics(app).scrollable_length > 0.1
964        };
965        let item_indices = visible.clone();
966        let source = widget.clone();
967        let list = ListView::builder(move |app, _, visual_index| {
968            let index = *item_indices.get(visual_index as usize)?;
969            let item = source.tab_items[index].clone();
970            let id = item.id.clone();
971            let container = app.get(self).containers[&id].clone();
972            let hovered = app.get(self).hovered.clone();
973            let selected = source.selected_index == Some(index);
974            let separator_visible = source.selected_index != Some(index)
975                && source.selected_index != Some(index + 1)
976                && hovered.as_ref() != Some(&id)
977                && source
978                    .tab_items
979                    .get(index + 1)
980                    .is_none_or(|next| hovered.as_ref() != Some(&next.id))
981                && index + 1 < source.tab_items.len();
982            let bottom = if app.get(self).drag.item.is_some() || selected {
983                TabBottomBorderState::NoBottomBorderLine
984            } else if source.selected_index == Some(index + 1) {
985                TabBottomBorderState::LeftOfSelectedTab
986            } else if source
987                .selected_index
988                .is_some_and(|selected| index == selected + 1)
989            {
990                TabBottomBorderState::RightOfSelectedTab
991            } else {
992                TabBottomBorderState::Normal
993            };
994            let header = TabViewItemHeader {
995                item,
996                selected,
997                width_mode: source.tab_width_mode,
998                close_overlay_mode: source.close_button_overlay_mode,
999                bottom_border: bottom,
1000                separator_visible,
1001                focus_node: container.tab_focus.clone(),
1002                close_focus_node: container.close_focus.clone(),
1003                select: Listener::new(move |app| self.select(app, index)),
1004                close: Listener::new(move |app| self.request_close(app, index)),
1005                hover_changed: Rc::new(move |app, hovered| {
1006                    let id = self
1007                        .widget(app)
1008                        .tab_items
1009                        .get(index)
1010                        .map(|item| item.id.clone());
1011                    self.set_state(app, |state| {
1012                        if hovered {
1013                            state.hovered = id;
1014                        } else if state.hovered == id {
1015                            state.hovered = None;
1016                        }
1017                    });
1018                }),
1019            };
1020            let header = self.draggable_header(
1021                app,
1022                header,
1023                if equal {
1024                    width
1025                } else {
1026                    app.get(self)
1027                        .tab_widths
1028                        .get(&id)
1029                        .copied()
1030                        .unwrap_or(r.tab_view_item_min_width)
1031                },
1032            );
1033            let measured_id = id.clone();
1034            let header = SizeObserver::new(
1035                header,
1036                Rc::new(move |app, _, size| {
1037                    if app.contains(self)
1038                        && self.mounted(app)
1039                        && app.get(self).tab_widths.get(&measured_id).copied() != Some(size.width())
1040                    {
1041                        self.set_state(app, |state| {
1042                            state.tab_widths.insert(measured_id.clone(), size.width());
1043                        });
1044                    }
1045                }),
1046            )
1047            .key(container.key.into());
1048            let mut sized = SizedBox::new().child(header);
1049            if equal {
1050                sized = sized.width(width);
1051            }
1052            Some(sized.key(ValueKey::new(id).into()).into_widget())
1053        })
1054        .item_count(visible.len() as i32)
1055        .find_child_index_callback(Rc::new(move |key| {
1056            (key.key() as &dyn std::any::Any)
1057                .downcast_ref::<ValueKey<String>>()
1058                .and_then(|key| {
1059                    visible
1060                        .iter()
1061                        .position(|index| widget.tab_items[*index].id == key.value)
1062                })
1063                .map(|index| index as i32)
1064        }))
1065        .build()
1066        .scroll_direction(Axis::Horizontal)
1067        .controller(scroll.native_controller(app))
1068        .padding(EdgeInsetsGeometry::only(4.0, 0.0, 4.0, 0.0));
1069        let list = if equal { list.item_extent(width) } else { list };
1070        let strip = SizedBox::new()
1071            .width(strip_width)
1072            .height(theme.tab_view_item_min_height)
1073            .child(
1074                TabScrollViewer::new(scroll, list)
1075                    .scroll_buttons_visible(show_scroll)
1076                    .bottom_border_visible(app.get(self).drag.item.is_none()),
1077            );
1078        let strip = Padding::new(EdgeInsetsGeometry::only(
1079            0.0,
1080            theme.tab_view_header_padding[1],
1081            0.0,
1082            0.0,
1083        ))
1084        .child(strip);
1085        let strip = self.drop_target(strip.into_widget());
1086        let strip = MouseRegion::new()
1087            .on_enter(Rc::new(move |app, _| {
1088                app.get_mut(self).pointer_in_strip = true
1089            }))
1090            .on_exit(Rc::new(move |app, _| {
1091                self.set_state(app, |state| {
1092                    state.pointer_in_strip = false;
1093                    state.deferred_width_update = false;
1094                })
1095            }))
1096            .child(strip);
1097        let widget = self.effective_widget(app);
1098        let leading = widget
1099            .tab_strip_header
1100            .clone()
1101            .unwrap_or_else(|| SizedBox::new().width(2.0).into_widget());
1102        let trailing = widget
1103            .tab_strip_footer
1104            .clone()
1105            .unwrap_or_else(|| SizedBox::shrink().into_widget());
1106        let leading = SizeObserver::new(
1107            leading,
1108            Rc::new(move |app, _, size| {
1109                if app.contains(self)
1110                    && self.mounted(app)
1111                    && app.get(self).header_width != size.width()
1112                {
1113                    self.set_state(app, |state| state.header_width = size.width());
1114                }
1115            }),
1116        );
1117        let trailing = SizeObserver::new(
1118            trailing,
1119            Rc::new(move |app, _, size| {
1120                if app.contains(self)
1121                    && self.mounted(app)
1122                    && app.get(self).footer_width != size.width()
1123                {
1124                    self.set_state(app, |state| state.footer_width = size.width());
1125                }
1126            }),
1127        );
1128        let trailing = Align::new()
1129            .alignment(Alignment::CENTER_LEFT.into())
1130            .width_factor(1.0)
1131            .height_factor(1.0)
1132            .child(trailing);
1133        let mut strip_children = vec![
1134            GridCell::new(leading).into_widget(),
1135            GridCell::new(strip).column(1).into_widget(),
1136            GridCell::new(trailing).column(3).into_widget(),
1137        ];
1138        if widget.is_add_tab_button_visible {
1139            let click = widget
1140                .add_tab_button_click
1141                .unwrap_or_else(|| Listener::new(|_| {}));
1142            let button = Button::new(
1143                FontIcon::symbol(FluentSymbol::Add)
1144                    .font_size(theme.tab_view_item_add_button_font_size),
1145                click,
1146            )
1147            .focus_node(app.get(self).add_focus.clone().unwrap())
1148            .template(add_button_template);
1149            strip_children.push(
1150                GridCell::new(
1151                    Align::new()
1152                        .alignment(Alignment::BOTTOM_CENTER.into())
1153                        .child(
1154                            Padding::new(EdgeInsetsGeometry::only(
1155                                theme.tab_view_item_add_button_container_padding[0],
1156                                0.0,
1157                                0.0,
1158                                theme.tab_view_item_add_button_container_padding[3],
1159                            ))
1160                            .child(ToolTipService::new(button, ToolTip::text("Add new tab"))),
1161                        ),
1162                )
1163                .column(2)
1164                .into_widget(),
1165            );
1166        }
1167        // LeftBottomBorderLine / RightBottomBorderLine remain beneath their column content. While
1168        // a tab is dragged, `SingleBottomBorderLine` spans the left one across the strip and
1169        // collapses the right one.
1170        let lines: &[_] = if app.get(self).drag.item.is_some() {
1171            &[("LeftBottomBorderLine", 0, 4)]
1172        } else {
1173            &[
1174                ("LeftBottomBorderLine", 0, 1),
1175                ("RightBottomBorderLine", 2, 2),
1176            ]
1177        };
1178        for &(name, column, span) in lines {
1179            strip_children.insert(
1180                0,
1181                bottom_border_line(name, theme.tab_view_border_brush)
1182                    .column(column)
1183                    .column_span(span)
1184                    .into_widget(),
1185            );
1186        }
1187        let strip = Grid::new()
1188            .background(Brush::Solid(theme.tab_view_background))
1189            .column_definitions([
1190                ColumnDefinition::new(GridLength::AUTO),
1191                ColumnDefinition::new(GridLength::AUTO),
1192                ColumnDefinition::new(GridLength::AUTO),
1193                ColumnDefinition::new(GridLength::star(1.0)),
1194            ])
1195            .children(strip_children);
1196        let pages: Vec<_> = widget
1197            .tab_items
1198            .iter()
1199            .enumerate()
1200            .filter(|(_, item)| app.get(self).visited.contains(&item.id))
1201            .map(|(index, item)| {
1202                let selected = widget.selected_index == Some(index);
1203                let scope = app.get(self).containers[&item.id].content_focus.clone();
1204                Offstage::new()
1205                    .offstage(!selected)
1206                    .child(TickerMode::new(
1207                        selected,
1208                        ExcludeFocus::new(
1209                            FocusScope::new(item.content.clone()).node(scope.clone()),
1210                        )
1211                        .excluding(!selected),
1212                    ))
1213                    .key(ValueKey::new(item.id.clone()).into())
1214                    .into_widget()
1215            })
1216            .collect();
1217        let content = Stack::new().fit(StackFit::Passthrough).children(pages);
1218        let layout_root = Grid::new()
1219            .row_definitions([
1220                RowDefinition::new(GridLength::AUTO),
1221                RowDefinition::new(GridLength::star(1.0)),
1222            ])
1223            .children([
1224                GridCell::new(strip).into_widget(),
1225                GridCell::new(content).row(1).into_widget(),
1226            ]);
1227        // Like a page-level container, the TabView fills a bounded width; in an unbounded one it
1228        // is as wide as its strip.
1229        if constraints.has_bounded_width() {
1230            SizedBox::new()
1231                .width(constraints.max_width)
1232                .child(layout_root)
1233                .into_widget()
1234        } else {
1235            layout_root.into_widget()
1236        }
1237    }
1238}
1239
1240/// TabViewButtonStyle's ContentPresenter and discrete CommonStates.
1241fn add_button_template(
1242    app: &mut App,
1243    context: BuildContext,
1244    states: ControlStates,
1245    content: WidgetRef,
1246) -> WidgetRef {
1247    let theme = ThemeResources::of(app, context);
1248    let r = &theme;
1249    let (background, foreground, border) = match states.common {
1250        CommonState::Normal => (
1251            r.tab_view_button_background,
1252            r.tab_view_button_foreground,
1253            r.tab_view_button_border_brush,
1254        ),
1255        CommonState::PointerOver => (
1256            r.tab_view_button_background_pointer_over,
1257            r.tab_view_button_foreground_pointer_over,
1258            r.tab_view_button_border_brush_pointer_over,
1259        ),
1260        CommonState::Pressed => (
1261            r.tab_view_button_background_pressed,
1262            r.tab_view_button_foreground_pressed,
1263            r.tab_view_button_border_brush_pressed,
1264        ),
1265        CommonState::Disabled => (
1266            r.tab_view_button_background_disabled,
1267            r.tab_view_button_foreground_disabled,
1268            r.tab_view_button_border_brush_disabled,
1269        ),
1270    };
1271    FocusVisual::new(
1272        SizedBox::new()
1273            .width(r.tab_view_item_add_button_width)
1274            .height(r.tab_view_item_add_button_height)
1275            .child(
1276                ControlBorder::new(Brush::Solid(background), Brush::Solid(border))
1277                    .border_thickness_ltrb(r.tab_view_button_border_thickness)
1278                    .corner_radius(r.control_corner_radius[0])
1279                    .child(Center::new().child(DefaultTextStyle::new(
1280                        control_text_style(
1281                            &theme,
1282                            r.tab_view_item_add_button_font_size,
1283                            FontWeight::NORMAL,
1284                            foreground,
1285                        ),
1286                        content,
1287                    ))),
1288            ),
1289        theme.theme,
1290    )
1291    .visible(states.focused)
1292    .margin([-3.0; 4])
1293    .corner_radius(r.control_corner_radius[0])
1294    .into_widget()
1295}