Skip to main content

swiftui_native/views/
conditional.rs

1//! Conditional content.
2
3use super::*;
4use crate::mangle;
5
6// ── Conditional content ──
7
8mangle::result_types! {
9    /// `_ConditionalContent<AnyView, AnyView>`
10    /// `_ConditionalContent<AnyView, AnyView>`
11    pub(crate) CONDITIONAL_T = ty("_ConditionalContent").of(vec![ty("AnyView"), ty("AnyView")]);
12}
13
14/// The `if`/`else` a `ViewBuilder` produces.
15///
16/// This matters beyond picking a view. Branching in Rust and handing SwiftUI the
17/// winner erases the branch: both arms are `AnyView`, so SwiftUI sees one view
18/// whose *value* changed. `_ConditionalContent` tells it a *branch* changed,
19/// which is what drives insertion and removal transitions and keeps each arm's
20/// identity — and therefore its `@State` — separate.
21///
22/// The type is one `AnyView` followed by a one-byte tag, so it is built directly.
23pub fn conditional(flag: bool, if_true: &ViewHandle, if_false: &ViewHandle) -> ViewHandle {
24    unsafe {
25        let (meta, wt, size) = result_type(&CONDITIONAL_T);
26        let mut buf = vec![0u8; size];
27        let chosen = if flag { if_true } else { if_false };
28        let owned = chosen.clone();
29        buf[..8].copy_from_slice(&owned.to_anyview_word().to_le_bytes());
30        buf[8] = u8::from(!flag); // 0 = first branch, 1 = second
31        wrap_buf(&buf, meta, wt)
32    }
33}