fyrox-ui 0.36.2

Extendable UI library
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! The Tab Control handles the visibility of several tabs, only showing a single tab that the user has selected via the
//! tab header buttons. See docs for [`TabControl`] widget for more info and usage examples.

#![warn(missing_docs)]

use crate::style::resource::StyleResourceExt;
use crate::style::{Style, StyledProperty};
use crate::{
    border::BorderBuilder,
    brush::Brush,
    button::{ButtonBuilder, ButtonMessage},
    core::{
        color::Color, pool::Handle, reflect::prelude::*, type_traits::prelude::*, uuid_provider,
        visitor::prelude::*,
    },
    decorator::{DecoratorBuilder, DecoratorMessage},
    define_constructor,
    grid::{Column, GridBuilder, Row},
    message::{MessageDirection, MouseButton, UiMessage},
    stack_panel::StackPanelBuilder,
    utils::make_cross_primitive,
    vector_image::VectorImageBuilder,
    widget::{Widget, WidgetBuilder, WidgetMessage},
    BuildContext, Control, HorizontalAlignment, Orientation, Thickness, UiNode, UserInterface,
    VerticalAlignment,
};
use fyrox_core::variable::InheritableVariable;
use fyrox_graph::constructor::{ConstructorProvider, GraphNodeConstructor};
use std::{
    any::Any,
    cmp::Ordering,
    fmt::{Debug, Formatter},
    ops::{Deref, DerefMut},
    sync::Arc,
};

/// A set of messages for [`TabControl`] widget.
#[derive(Debug, Clone, PartialEq)]
pub enum TabControlMessage {
    /// Used to change the active tab of a [`TabControl`] widget (with [`MessageDirection::ToWidget`]) or to fetch if the active
    /// tab has changed (with [`MessageDirection::FromWidget`]).
    /// When the active tab changes, `ActiveTabUuid` will also be sent from the widget.
    /// When the active tab changes, `ActiveTabUuid` will also be sent from the widget.
    ActiveTab(Option<usize>),
    /// Used to change the active tab of a [`TabControl`] widget (with [`MessageDirection::ToWidget`]) or to fetch if the active
    /// tab has changed (with [`MessageDirection::FromWidget`]).
    /// When teh active tab changes, `ActiveTab` will also be sent from the widget.
    ActiveTabUuid(Option<Uuid>),
    /// Emitted by a tab that needs to be closed (and removed). Does **not** remove the tab, its main usage is to catch the moment
    /// when the tab wants to be closed. To remove the tab use [`TabControlMessage::RemoveTab`] message.
    CloseTab(usize),
    /// Emitted by a tab that needs to be closed (and removed). Does **not** remove the tab, its main usage is to catch the moment
    /// when the tab wants to be closed. To remove the tab use [`TabControlMessage::RemoveTab`] message.
    CloseTabByUuid(Uuid),
    /// Used to remove a particular tab by its position in the tab list.
    RemoveTab(usize),
    /// Used to remove a particular tab by its UUID.
    RemoveTabByUuid(Uuid),
    /// Adds a new tab using its definition and activates the tab.
    AddTab(TabDefinition),
}

impl TabControlMessage {
    define_constructor!(
        /// Creates [`TabControlMessage::ActiveTab`] message.
        TabControlMessage:ActiveTab => fn active_tab(Option<usize>), layout: false
    );
    define_constructor!(
        /// Creates [`TabControlMessage::ActiveTabUuid`] message.
        TabControlMessage:ActiveTabUuid => fn active_tab_uuid(Option<Uuid>), layout: false
    );
    define_constructor!(
        /// Creates [`TabControlMessage::CloseTab`] message.
        TabControlMessage:CloseTab => fn close_tab(usize), layout: false
    );
    define_constructor!(
        /// Creates [`TabControlMessage::CloseTabByUuid`] message.
        TabControlMessage:CloseTabByUuid => fn close_tab_by_uuid(Uuid), layout: false
    );
    define_constructor!(
        /// Creates [`TabControlMessage::RemoveTab`] message.
        TabControlMessage:RemoveTab => fn remove_tab(usize), layout: false
    );
    define_constructor!(
        /// Creates [`TabControlMessage::RemoveTabByUuid`] message.
        TabControlMessage:RemoveTabByUuid => fn remove_tab_by_uuid(Uuid), layout: false
    );
    define_constructor!(
        /// Creates [`TabControlMessage::AddTab`] message.
        TabControlMessage:AddTab => fn add_tab(TabDefinition), layout: false
    );
}

/// User-defined data of a tab.
#[derive(Clone)]
pub struct TabUserData(pub Arc<dyn Any + Send + Sync>);

impl TabUserData {
    /// Creates new instance of the tab data.
    pub fn new<T>(data: T) -> Self
    where
        T: Any + Send + Sync,
    {
        Self(Arc::new(data))
    }
}

impl PartialEq for TabUserData {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(
            (&*self.0) as *const _ as *const (),
            (&*other.0) as *const _ as *const (),
        )
    }
}

impl Debug for TabUserData {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "User-defined data")
    }
}

/// Tab of the [`TabControl`] widget. It stores important tab data, that is widely used at runtime.
#[derive(Default, Clone, PartialEq, Visit, Reflect, Debug)]
pub struct Tab {
    /// Unique identifier of this tab.
    pub uuid: Uuid,
    /// A handle of the header button, that is used to switch tabs.
    pub header_button: Handle<UiNode>,
    /// Tab's content.
    pub content: Handle<UiNode>,
    /// A handle of a button, that is used to close the tab.
    pub close_button: Handle<UiNode>,
    /// A handle to a container widget, that holds the header.
    pub header_container: Handle<UiNode>,
    /// User-defined data.
    #[visit(skip)]
    #[reflect(hidden)]
    pub user_data: Option<TabUserData>,
    /// A handle of a node that is used to highlight tab's state.
    pub decorator: Handle<UiNode>,
    /// Content of the tab-switching (header) button.
    pub header_content: Handle<UiNode>,
}

/// The Tab Control handles the visibility of several tabs, only showing a single tab that the user has selected via the
/// tab header buttons. Each tab is defined via a Tab Definition struct which takes two widgets, one representing the tab
/// header and the other representing the tab's contents.
///
/// The following example makes a 2 tab, Tab Control containing some simple text widgets:
///
/// ```rust,no_run
/// # use fyrox_ui::{
/// #     BuildContext,
/// #     widget::WidgetBuilder,
/// #     text::TextBuilder,
/// #     tab_control::{TabControlBuilder, TabDefinition},
/// # };
/// fn create_tab_control(ctx: &mut BuildContext) {
///     TabControlBuilder::new(WidgetBuilder::new())
///         .with_tab(
///             TabDefinition{
///                 header: TextBuilder::new(WidgetBuilder::new())
///                             .with_text("First")
///                             .build(ctx),
///
///                 content: TextBuilder::new(WidgetBuilder::new())
///                             .with_text("First tab's contents!")
///                             .build(ctx),
///                 can_be_closed: true,
///                 user_data: None
///             }
///         )
///         .with_tab(
///             TabDefinition{
///                 header: TextBuilder::new(WidgetBuilder::new())
///                             .with_text("Second")
///                             .build(ctx),
///
///                 content: TextBuilder::new(WidgetBuilder::new())
///                             .with_text("Second tab's contents!")
///                             .build(ctx),
///                 can_be_closed: true,
///                 user_data: None
///             }
///         )
///         .build(ctx);
/// }
/// ```
///
/// As usual, we create the widget via the builder TabControlBuilder. Tabs are added via the [`TabControlBuilder::with_tab`]
/// function in the order you want them to appear, passing each call to the function a directly constructed [`TabDefinition`]
/// struct. Tab headers will appear from left to right at the top with tab contents shown directly below the tabs. As usual, if no
/// constraints are given to the base [`WidgetBuilder`] of the [`TabControlBuilder`], then the tab content area will resize to fit
/// whatever is in the current tab.
///
/// Each tab's content is made up of one widget, so to be useful you will want to use one of the container widgets to help
/// arrange additional widgets within the tab.
///
/// ## Tab Header Styling
///
/// Notice that you can put any widget into the tab header, so if you want images to denote each tab you can add an Image
/// widget to each header, and if you want an image *and* some text you can insert a stack panel with an image on top and
/// text below it.
///
/// You will also likely want to style whatever widgets you add. As can be seen when running the code example above, the
/// tab headers are scrunched when there are no margins provided to your text widgets. Simply add something like the below
/// code example and you will get a decent look:
///
/// ```rust,no_run
/// # use fyrox_ui::{
/// #     BuildContext,
/// #     widget::WidgetBuilder,
/// #     text::TextBuilder,
/// #     Thickness,
/// #     tab_control::{TabDefinition},
/// # };
/// # fn build(ctx: &mut BuildContext) {
/// # TabDefinition{
/// header: TextBuilder::new(
///             WidgetBuilder::new()
///                 .with_margin(Thickness::uniform(4.0))
///         )
///             .with_text("First")
///             .build(ctx),
/// # content: Default::default(),
/// # can_be_closed: true,
/// # user_data: None
/// # };
/// # }
///
/// ```
#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
pub struct TabControl {
    /// Base widget of the tab control.
    pub widget: Widget,
    /// A set of tabs used by the tab control.
    pub tabs: Vec<Tab>,
    /// Active tab of the tab control.
    pub active_tab: Option<usize>,
    /// A handle of a widget, that holds content of every tab.
    pub content_container: Handle<UiNode>,
    /// A handle of a widget, that holds headers of every tab.
    pub headers_container: Handle<UiNode>,
    /// A brush, that will be used to highlight active tab.
    pub active_tab_brush: InheritableVariable<StyledProperty<Brush>>,
}

impl ConstructorProvider<UiNode, UserInterface> for TabControl {
    fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
        GraphNodeConstructor::new::<Self>()
            .with_variant("Tab Control", |ui| {
                TabControlBuilder::new(WidgetBuilder::new().with_name("Tab Control"))
                    .build(&mut ui.build_ctx())
                    .into()
            })
            .with_group("Layout")
    }
}

crate::define_widget_deref!(TabControl);

uuid_provider!(TabControl = "d54cfac3-0afc-464b-838a-158b3a2253f5");

impl TabControl {
    /// Use a tab's UUID to look up the tab.
    pub fn get_tab_by_uuid(&self, uuid: Uuid) -> Option<&Tab> {
        self.tabs.iter().find(|t| t.uuid == uuid)
    }
    /// Send the necessary messages to activate the tab at the given index, or deactivate all tabs if no index is given.
    /// Do nothing if the given index does not refer to any existing tab.
    /// If the index was valid, send FromWidget messages to notify listeners of the change, using messages with the given flags.
    fn set_active_tab(&mut self, active_tab: Option<usize>, ui: &mut UserInterface, flags: u64) {
        if let Some(index) = active_tab {
            if self.tabs.len() <= index {
                return;
            }
        }
        // Send messages to update the state of each tab.
        for (existing_tab_index, tab) in self.tabs.iter().enumerate() {
            ui.send_message(WidgetMessage::visibility(
                tab.content,
                MessageDirection::ToWidget,
                active_tab == Some(existing_tab_index),
            ));
            ui.send_message(DecoratorMessage::select(
                tab.decorator,
                MessageDirection::ToWidget,
                active_tab == Some(existing_tab_index),
            ))
        }

        self.active_tab = active_tab;

        // Notify potential listeners that the active tab has changed.
        // First we notify by tab index.
        let mut msg =
            TabControlMessage::active_tab(self.handle, MessageDirection::FromWidget, active_tab);
        msg.flags = flags;
        ui.send_message(msg);
        // Next we notify by the tab's uuid, which does not change even as the tab moves.
        let tab_id = active_tab.and_then(|i| self.tabs.get(i)).map(|t| t.uuid);
        let mut msg =
            TabControlMessage::active_tab_uuid(self.handle, MessageDirection::FromWidget, tab_id);
        msg.flags = flags;
        ui.send_message(msg);
    }
    /// Send the messages necessary to remove the tab at the given index and update the currently active tab.
    /// This does not include sending FromWidget messages to notify listeners.
    /// If the given index does not refer to any tab, do nothing and return false.
    /// Otherwise, return true to indicate that some tab was removed.
    fn remove_tab(&mut self, index: usize, ui: &mut UserInterface) -> bool {
        let Some(tab) = self.tabs.get(index) else {
            return false;
        };
        ui.send_message(WidgetMessage::remove(
            tab.header_container,
            MessageDirection::ToWidget,
        ));
        ui.send_message(WidgetMessage::remove(
            tab.content,
            MessageDirection::ToWidget,
        ));

        self.tabs.remove(index);

        if let Some(active_tab) = &self.active_tab {
            match index.cmp(active_tab) {
                Ordering::Less => self.active_tab = Some(active_tab - 1), // Just the index needs to change, not the actual tab.
                Ordering::Equal => {
                    // The active tab was removed, so we need to change the active tab.
                    if self.tabs.is_empty() {
                        self.set_active_tab(None, ui, 0);
                    } else if *active_tab == 0 {
                        // The index has not changed, but this is actually a different tab,
                        // so we need to activate it.
                        self.set_active_tab(Some(0), ui, 0);
                    } else {
                        self.set_active_tab(Some(active_tab - 1), ui, 0);
                    }
                }
                Ordering::Greater => (), // Do nothing, since removed tab was to the right of active tab.
            }
        }

        true
    }
}

impl Control for TabControl {
    fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
        self.widget.handle_routed_message(ui, message);

        if let Some(ButtonMessage::Click) = message.data() {
            for (tab_index, tab) in self.tabs.iter().enumerate() {
                if message.destination() == tab.header_button && tab.header_button.is_some() {
                    ui.send_message(TabControlMessage::active_tab_uuid(
                        self.handle,
                        MessageDirection::ToWidget,
                        Some(tab.uuid),
                    ));
                    break;
                } else if message.destination() == tab.close_button {
                    // Send two messages, one containing the index, one containing the UUID,
                    // to allow listeners their choice of which system they prefer.
                    ui.send_message(TabControlMessage::close_tab(
                        self.handle,
                        MessageDirection::FromWidget,
                        tab_index,
                    ));
                    ui.send_message(TabControlMessage::close_tab_by_uuid(
                        self.handle,
                        MessageDirection::FromWidget,
                        tab.uuid,
                    ));
                }
            }
        } else if let Some(WidgetMessage::MouseDown { button, .. }) = message.data() {
            if *button == MouseButton::Middle {
                for (tab_index, tab) in self.tabs.iter().enumerate() {
                    if ui.is_node_child_of(message.destination(), tab.header_button) {
                        ui.send_message(TabControlMessage::close_tab(
                            self.handle,
                            MessageDirection::FromWidget,
                            tab_index,
                        ));
                        ui.send_message(TabControlMessage::close_tab_by_uuid(
                            self.handle,
                            MessageDirection::FromWidget,
                            tab.uuid,
                        ));
                    }
                }
            }
        } else if let Some(msg) = message.data::<TabControlMessage>() {
            if message.destination() == self.handle()
                && message.direction() == MessageDirection::ToWidget
            {
                match msg {
                    TabControlMessage::ActiveTab(active_tab) => {
                        if self.active_tab != *active_tab {
                            self.set_active_tab(*active_tab, ui, message.flags);
                        }
                    }
                    TabControlMessage::ActiveTabUuid(uuid) => match uuid {
                        Some(uuid) => {
                            if let Some(active_tab) = self.tabs.iter().position(|t| t.uuid == *uuid)
                            {
                                if self.active_tab != Some(active_tab) {
                                    self.set_active_tab(Some(active_tab), ui, message.flags);
                                }
                            }
                        }
                        None if self.active_tab.is_some() => {
                            self.set_active_tab(None, ui, message.flags)
                        }
                        _ => (),
                    },
                    TabControlMessage::CloseTab(_) | TabControlMessage::CloseTabByUuid(_) => {
                        // Nothing to do.
                    }
                    TabControlMessage::RemoveTab(index) => {
                        // If a tab was removed, then resend the message.
                        // Users that remove tabs using the index-based message only get the index-based message in reponse,
                        // since presumably their application is not using UUIDs.
                        if self.remove_tab(*index, ui) {
                            ui.send_message(message.reverse());
                        }
                    }
                    TabControlMessage::RemoveTabByUuid(uuid) => {
                        // Find the tab that has the given uuid.
                        let index = self.tabs.iter().position(|t| t.uuid == *uuid);
                        // Users that remove tabs using the UUID-based message only get the UUID-based message in reponse,
                        // since presumably their application is not using tab indices.
                        if let Some(index) = index {
                            if self.remove_tab(index, ui) {
                                ui.send_message(message.reverse());
                            }
                        }
                    }
                    TabControlMessage::AddTab(definition) => {
                        let header = Header::build(
                            definition,
                            false,
                            (*self.active_tab_brush).clone(),
                            &mut ui.build_ctx(),
                        );

                        ui.send_message(WidgetMessage::link(
                            header.button,
                            MessageDirection::ToWidget,
                            self.headers_container,
                        ));

                        ui.send_message(WidgetMessage::link(
                            definition.content,
                            MessageDirection::ToWidget,
                            self.content_container,
                        ));

                        ui.send_message(message.reverse());

                        self.tabs.push(Tab {
                            uuid: Uuid::new_v4(),
                            header_button: header.button,
                            content: definition.content,
                            close_button: header.close_button,
                            header_container: header.button,
                            user_data: definition.user_data.clone(),
                            decorator: header.decorator,
                            header_content: header.content,
                        });

                        self.set_active_tab(Some(self.tabs.len() - 1), ui, 0);
                    }
                }
            }
        }
    }
}

/// Tab control builder is used to create [`TabControl`] widget instances and add them to the user interface.
pub struct TabControlBuilder {
    widget_builder: WidgetBuilder,
    tabs: Vec<TabDefinition>,
    active_tab_brush: Option<StyledProperty<Brush>>,
    initial_tab: usize,
}

/// Tab definition is used to describe content of each tab for the [`TabControlBuilder`] builder.
#[derive(Debug, Clone, PartialEq)]
pub struct TabDefinition {
    /// Content of the tab-switching (header) button.
    pub header: Handle<UiNode>,
    /// Content of the tab.
    pub content: Handle<UiNode>,
    /// A flag, that defines whether the tab can be closed or not.
    pub can_be_closed: bool,
    /// User-defined data.
    pub user_data: Option<TabUserData>,
}

struct Header {
    button: Handle<UiNode>,
    close_button: Handle<UiNode>,
    decorator: Handle<UiNode>,
    content: Handle<UiNode>,
}

impl Header {
    fn build(
        tab_definition: &TabDefinition,
        selected: bool,
        active_tab_brush: StyledProperty<Brush>,
        ctx: &mut BuildContext,
    ) -> Self {
        let close_button;
        let decorator;

        let button = ButtonBuilder::new(WidgetBuilder::new().on_row(0).on_column(0))
            .with_back({
                decorator = DecoratorBuilder::new(
                    BorderBuilder::new(WidgetBuilder::new())
                        .with_stroke_thickness(Thickness::uniform(0.0).into()),
                )
                .with_normal_brush(ctx.style.property(Style::BRUSH_DARK))
                .with_selected_brush(active_tab_brush)
                .with_pressed_brush(ctx.style.property(Style::BRUSH_LIGHTEST))
                .with_hover_brush(ctx.style.property(Style::BRUSH_LIGHT))
                .with_selected(selected)
                .build(ctx);
                decorator
            })
            .with_content(
                GridBuilder::new(
                    WidgetBuilder::new()
                        .with_child(tab_definition.header)
                        .with_child({
                            close_button = if tab_definition.can_be_closed {
                                ButtonBuilder::new(
                                    WidgetBuilder::new()
                                        .with_margin(Thickness::right(1.0))
                                        .on_row(0)
                                        .on_column(1)
                                        .with_width(16.0)
                                        .with_height(16.0),
                                )
                                .with_back(
                                    DecoratorBuilder::new(
                                        BorderBuilder::new(WidgetBuilder::new())
                                            .with_corner_radius(5.0f32.into())
                                            .with_pad_by_corner_radius(false)
                                            .with_stroke_thickness(Thickness::uniform(0.0).into()),
                                    )
                                    .with_normal_brush(Brush::Solid(Color::TRANSPARENT).into())
                                    .with_hover_brush(ctx.style.property(Style::BRUSH_DARK))
                                    .build(ctx),
                                )
                                .with_content(
                                    VectorImageBuilder::new(
                                        WidgetBuilder::new()
                                            .with_horizontal_alignment(HorizontalAlignment::Center)
                                            .with_vertical_alignment(VerticalAlignment::Center)
                                            .with_width(8.0)
                                            .with_height(8.0)
                                            .with_foreground(
                                                ctx.style.property(Style::BRUSH_BRIGHTEST),
                                            ),
                                    )
                                    .with_primitives(make_cross_primitive(8.0, 2.0))
                                    .build(ctx),
                                )
                                .build(ctx)
                            } else {
                                Handle::NONE
                            };
                            close_button
                        }),
                )
                .add_row(Row::auto())
                .add_column(Column::stretch())
                .add_column(Column::auto())
                .build(ctx),
            )
            .build(ctx);

        Header {
            button,
            close_button,
            decorator,
            content: tab_definition.header,
        }
    }
}

impl TabControlBuilder {
    /// Creates new tab control builder.
    pub fn new(widget_builder: WidgetBuilder) -> Self {
        Self {
            tabs: Default::default(),
            active_tab_brush: None,
            initial_tab: 0,
            widget_builder,
        }
    }

    /// Adds a new tab to the builder.
    pub fn with_tab(mut self, tab: TabDefinition) -> Self {
        self.tabs.push(tab);
        self
    }

    /// Sets a desired brush for active tab.
    pub fn with_active_tab_brush(mut self, brush: StyledProperty<Brush>) -> Self {
        self.active_tab_brush = Some(brush);
        self
    }

    /// Finishes [`TabControl`] building and adds it to the user interface and returns its handle.
    pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
        let tab_count = self.tabs.len();
        // Hide everything but first tab content.
        for tab in self.tabs.iter().skip(1) {
            if let Some(content) = ctx.try_get_node_mut(tab.content) {
                content.set_visibility(false);
            }
        }

        let active_tab_brush = self
            .active_tab_brush
            .unwrap_or_else(|| ctx.style.property::<Brush>(Style::BRUSH_LIGHTEST));

        let tab_headers = self
            .tabs
            .iter()
            .enumerate()
            .map(|(i, tab_definition)| {
                Header::build(
                    tab_definition,
                    i == self.initial_tab,
                    active_tab_brush.clone(),
                    ctx,
                )
            })
            .collect::<Vec<_>>();

        let headers_container = StackPanelBuilder::new(
            WidgetBuilder::new()
                .with_children(tab_headers.iter().map(|h| h.button))
                .on_row(0),
        )
        .with_orientation(Orientation::Horizontal)
        .build(ctx);

        let content_container = GridBuilder::new(
            WidgetBuilder::new()
                .with_children(self.tabs.iter().map(|t| t.content))
                .on_row(1),
        )
        .add_row(Row::stretch())
        .add_column(Column::stretch())
        .build(ctx);

        let grid = GridBuilder::new(
            WidgetBuilder::new()
                .with_child(headers_container)
                .with_child(content_container),
        )
        .add_column(Column::stretch())
        .add_row(Row::auto())
        .add_row(Row::stretch())
        .build(ctx);

        let border = BorderBuilder::new(
            WidgetBuilder::new()
                .with_background(ctx.style.property(Style::BRUSH_DARK))
                .with_child(grid),
        )
        .build(ctx);

        let tc = TabControl {
            widget: self.widget_builder.with_child(border).build(ctx),
            active_tab: if tab_count == 0 {
                None
            } else {
                Some(self.initial_tab)
            },
            tabs: tab_headers
                .iter()
                .zip(self.tabs)
                .map(|(header, tab)| Tab {
                    uuid: Uuid::new_v4(),
                    header_button: header.button,
                    content: tab.content,
                    close_button: header.close_button,
                    header_container: header.button,
                    user_data: tab.user_data,
                    decorator: header.decorator,
                    header_content: header.content,
                })
                .collect(),
            content_container,
            headers_container,
            active_tab_brush: active_tab_brush.into(),
        };

        ctx.add_node(UiNode::new(tc))
    }
}

#[cfg(test)]
mod test {
    use crate::tab_control::TabControlBuilder;
    use crate::{test::test_widget_deletion, widget::WidgetBuilder};

    #[test]
    fn test_deletion() {
        test_widget_deletion(|ctx| TabControlBuilder::new(WidgetBuilder::new()).build(ctx));
    }
}