either/
either.rs

1// Copyright 2019 The Druid Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! An example using the Either widget to show/hide a slider.
16//! This is a very simple example, it uses a bool to determine
17//! which widget gets shown.
18
19// On Windows platform, don't show a console when opening the app.
20#![windows_subsystem = "windows"]
21
22use druid::widget::prelude::*;
23use druid::widget::{Checkbox, Either, Flex, Label, Slider};
24use druid::{AppLauncher, Data, Lens, WidgetExt, WindowDesc};
25
26#[derive(Clone, Default, Data, Lens)]
27struct AppState {
28    which: bool,
29    value: f64,
30}
31
32fn ui_builder() -> impl Widget<AppState> {
33    // Our UI consists of a column with a button and an `Either` widget
34    let button = Checkbox::new("Toggle slider")
35        .lens(AppState::which)
36        .padding(5.0);
37
38    // The `Either` widget has two children, only one of which is visible at a time.
39    // To determine which child is visible, you pass it a closure that takes the
40    // `Data` and the `Env` and returns a bool; if it returns `true`, the first
41    // widget will be visible, and if `false`, the second.
42    let either = Either::new(
43        |data, _env| data.which,
44        Slider::new().lens(AppState::value).padding(5.0),
45        Label::new("Click to reveal slider").padding(5.0),
46    );
47    Flex::column().with_child(button).with_child(either)
48}
49
50pub fn main() {
51    let main_window = WindowDesc::new(ui_builder()).title("Switcheroo");
52    AppLauncher::with_window(main_window)
53        .log_to_console()
54        .launch(AppState::default())
55        .expect("launch failed");
56}