Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add note about using conditional widgets with enums #67

Merged
merged 1 commit into from
May 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/component_macro/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ set_child: important_label = gtk::Label { ... }
### Conditional widgets

The `view` macro allows you to include `if` and `match` statements for conditionally showing widgets.

Internally, the macro will use a `gtk::Stack`, so you can also use different [transition types](https://gtk-rs.org/gtk4-rs/git/docs/gtk4/enum.StackTransitionType.html).

```rust,ignore
Expand All @@ -130,7 +131,9 @@ if model.value % 2 == 0 {
set_label: "The value is odd",
}
}
```

```rust,ignore
// Use a transition type to set an animation when the visible widget changes
#[transition = "SlideRight"]
match model.value {
Expand All @@ -147,6 +150,50 @@ match model.value {
}
```

If your conditional widget uses a `match` statement over an enum, you can destructure the enum in the `match` arms to access its variables with the help of the `#[track]` or `#[watch]` macros:

```rust,ignore
enum Foo {
Bar(f32),
Baz(String),
}

struct FooView {
foo: Foo
}

impl Component for FooView {
type Init = Foo;

// snip

view! {
#[root]
gtk::Box {
append = match &model.foo {
Foo::Bar(num_value) => {
gtk::SpinButton {
// adding the `watch` macro lets you reference the destructured variables
#[watch]
set_value: num_value
}
}
Foo::Baz(str_value) => {
gtk::Label {
#[watch]
set_text: &str_value
}
}
}
}
}

// snip
}
```

Please note: if you attempt to destructure in the normal way - without the `track` or `watch` macros - you will get a compilation error, and Rust will 'fail to see' the destructured variables at the point where your code uses them. This is due to limitations in Relm4's component initialization strategy. Please ensure that you use one of those macros to avoid this.

### Returned widgets

Sometimes, methods used for assigning widgets return another widget.
Expand Down