swiftui-native 0.0.1

SwiftUI from pure Rust — no Swift bridge, no shim, only swift-runtime calls
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
//! Declarative macros for building view trees.
//!
//! The function forms take slices, which means spelling out `&[...]` and often a
//! `Vec` when children have different origins. These macros take a plain,
//! comma-separated list instead, so a tree reads top to bottom the way the
//! SwiftUI it mirrors does:
//!
//! ```ignore
//! use swiftui_native::prelude::*;
//!
//! let ui = vstack![
//!     text("Dashboard").text_style(TextStyle::Title),
//!     divider(),
//!     hstack![image("star.fill"), text("starred"), spacer()],
//!     zstack![
//!         rounded_rectangle(12.0).fg(Color::hex(0x2E86DE)),
//!         text("badge").fg(Color::WHITE),
//!     ],
//! ]
//! .padding(20.0);
//! ```
//!
//! Every element goes through [`IntoView`](crate::view::IntoView), so string
//! literals can be written directly:
//!
//! ```ignore
//! vstack!["first", "second", text("third").bold()]
//! ```
//!
//! A trailing comma is allowed everywhere.

/// `Text("…")` with interpolation, the way Swift writes `Text("\(name)!")`.
///
/// The function form takes a `&str`, so an interpolated label reads
/// `text(&format!("{}!", name))`. This says the same thing in the order Swift
/// says it:
///
/// ```ignore
/// text!("{}!", selected)
/// ```
#[macro_export]
macro_rules! text {
    ($fmt:literal $(, $arg:expr)* $(,)?) => {
        $crate::view::text(&::std::format!($fmt $(, $arg)*))
    };
}

/// `Image(systemName: "…")` with interpolation — see [`text!`].
///
/// ```ignore
/// image!("figure.{}", activity.to_lowercase())
/// ```
#[macro_export]
macro_rules! image {
    ($fmt:literal $(, $arg:expr)* $(,)?) => {
        $crate::view::image(&::std::format!($fmt $(, $arg)*))
    };
}

/// Build a `VStack` from a list of children.
///
/// `VStack(spacing: 12) { … }` is written `vstack![spacing: 12.0; …]`: the
/// configuration first, then a semicolon, then the children.
#[macro_export]
macro_rules! vstack {
    (spacing: $spacing:expr; $($child:expr),* $(,)?) => {
        $crate::view::vstack_spacing(
            &[$($crate::view::IntoView::into_view($child)),*],
            $spacing,
        )
    };
    ($($child:expr),* $(,)?) => {
        $crate::view::vstack(&[$($crate::view::IntoView::into_view($child)),*])
    };
}

/// Build an `HStack` from a list of children — see [`vstack!`].
#[macro_export]
macro_rules! hstack {
    (spacing: $spacing:expr; $($child:expr),* $(,)?) => {
        $crate::view::hstack_spacing(
            &[$($crate::view::IntoView::into_view($child)),*],
            $spacing,
        )
    };
    ($($child:expr),* $(,)?) => {
        $crate::view::hstack(&[$($crate::view::IntoView::into_view($child)),*])
    };
}

/// Build a `ZStack` from a list of children, back to front.
///
/// `ZStack(alignment: .topLeading) { … }` is
/// `zstack![alignment: Alignment::TopLeading; …]`.
#[macro_export]
macro_rules! zstack {
    (alignment: $alignment:expr; $($child:expr),* $(,)?) => {
        $crate::view::zstack_aligned(
            &[$($crate::view::IntoView::into_view($child)),*],
            $alignment,
        )
    };
    ($($child:expr),* $(,)?) => {
        $crate::view::zstack(&[$($crate::view::IntoView::into_view($child)),*])
    };
}

/// Build a `LazyVStack` from a list of children.
#[macro_export]
macro_rules! lazy_vstack {
    ($($child:expr),* $(,)?) => {
        $crate::view::lazy_vstack(&[$($crate::view::IntoView::into_view($child)),*])
    };
}

/// Build a `LazyHStack` from a list of children.
#[macro_export]
macro_rules! lazy_hstack {
    ($($child:expr),* $(,)?) => {
        $crate::view::lazy_hstack(&[$($crate::view::IntoView::into_view($child)),*])
    };
}

/// Build a `GridRow` from a list of cells.
#[macro_export]
macro_rules! grid_row {
    ($($cell:expr),* $(,)?) => {
        $crate::view::grid_row(&[$($crate::view::IntoView::into_view($cell)),*])
    };
}

/// Build a `Grid` from a list of rows.
#[macro_export]
macro_rules! grid {
    ($($row:expr),* $(,)?) => {
        $crate::view::grid(&[$($row),*])
    };
}

/// A Rust layout, given children — `MyLayout { … }` in Swift.
///
/// ```ignore
/// laid_out!(cascade, text("a"), text("b"), text("c"))
/// ```
#[macro_export]
macro_rules! laid_out {
    ($layout:expr, $($child:expr),* $(,)?) => {
        $crate::view::laid_out(&$layout, &[$($child),*])
    };
}

/// `ForEach` over a range or a collection.
///
/// ```ignore
/// foreach!(0..4, |i| text(&format!("row {i}")))
/// foreach!(&["a", "b", "c"], |s| text(s))
/// ```
#[macro_export]
macro_rules! foreach {
    ($range:expr, $body:expr) => {
        $crate::view::for_each($range, $body)
    };
}

/// A `ViewBuilder`-style conditional that keeps each branch's identity.
///
/// Unlike a plain Rust `if`, which picks a view and erases the branch, this
/// builds a `_ConditionalContent` — so SwiftUI sees a *branch* change and can
/// run insertion and removal transitions, and each arm keeps its own state.
///
/// ```ignore
/// view_if!(is_open, text("open"), text("closed"))
/// ```
#[macro_export]
macro_rules! view_if {
    // No else branch, which is the common shape: `if cond { view }`. The absent
    // arm is an `EmptyView`, so the branch is still a branch and transitions
    // still run, rather than the whole thing collapsing to nothing.
    ($cond:expr, $then:expr $(,)?) => {
        $crate::view::conditional(
            $cond,
            $crate::view::IntoView::into_view($then),
            $crate::view::empty(),
        )
    };
    ($cond:expr, $then:expr, $else:expr $(,)?) => {
        $crate::view::conditional(
            $cond,
            $crate::view::IntoView::into_view($then),
            $crate::view::IntoView::into_view($else),
        )
    };
}

/// `List { … }` over several rows.
///
/// `List { Text("a"); Text("b") }` is `list![text("a"), text("b")]` — two rows,
/// because the children become a `TupleView` and a `List` renders each element
/// of its content as a row. Passing a stack instead, which is what the free
/// function [`crate::view::list`] takes, gives *one* row holding a stack.
#[macro_export]
macro_rules! list {
    ($($child:expr),* $(,)?) => {
        $crate::view::list($crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `Form { … }` over several rows.
#[macro_export]
macro_rules! form {
    ($($child:expr),* $(,)?) => {
        $crate::view::form($crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `Section { … }`, optionally with a header: `section![header: text("Title"); …]`.
#[macro_export]
macro_rules! section {
    (header: $header:expr, footer: $footer:expr; $($child:expr),* $(,)?) => {
        $crate::view::section_titled_footer(
            $crate::view::IntoView::into_view($header),
            $crate::view::IntoView::into_view($footer),
            $crate::view::tuple_view(&[$($crate::view::IntoView::into_view($child)),*]),
        )
    };
    (footer: $footer:expr; $($child:expr),* $(,)?) => {
        $crate::view::section_footer(
            $crate::view::IntoView::into_view($footer),
            $crate::view::tuple_view(&[$($crate::view::IntoView::into_view($child)),*]),
        )
    };
    (header: $header:expr; $($child:expr),* $(,)?) => {
        $crate::view::section_titled(
            $crate::view::IntoView::into_view($header),
            $crate::view::tuple_view(&[$($crate::view::IntoView::into_view($child)),*]),
        )
    };
    ($($child:expr),* $(,)?) => {
        $crate::view::section($crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `Group { … }` — several views where one is wanted, with no layout of its own.
#[macro_export]
macro_rules! group {
    ($($child:expr),* $(,)?) => {
        $crate::view::group($crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `ControlGroup { … }`
#[macro_export]
macro_rules! control_group {
    ($($child:expr),* $(,)?) => {
        $crate::view::control_group($crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `TabView { … }` over several tabs.
#[macro_export]
macro_rules! tab_view {
    ($($child:expr),* $(,)?) => {
        $crate::view::tab_view($crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `TabView { Tab(…); … }` over several [`tab`](crate::view::tab)s.
///
/// ```no_run
/// # use swiftui_native::prelude::*;
/// # use swiftui_native::tabs;
/// let view = tabs![
///     tab("Home", "house", text("home page")),
///     tab("Settings", "gear", text("settings page")),
/// ];
/// ```
#[macro_export]
macro_rules! tabs {
    ($($tab:expr),* $(,)?) => {
        $crate::view::tab_view_tabs(vec![$($tab),*])
    };
}

/// `Menu(_:) { … }` over several items.
#[macro_export]
macro_rules! menu {
    ($label:expr, $($child:expr),* $(,)?) => {
        $crate::view::menu($label, $crate::view::tuple_view(
            &[$($crate::view::IntoView::into_view($child)),*],
        ))
    };
}

/// `Picker(_:selection:)` over rows, bound to Rust state.
///
/// The rows are a `@ViewBuilder` block in Swift, so they are a list here rather
/// than something the caller has to wrap in a `tuple_view` by hand.
///
/// ```ignore
/// picker_bound!("Theme", &theme, text("System").tag_int(0), text("Dark").tag_int(1))
/// ```
#[macro_export]
macro_rules! picker_bound {
    ($title:expr, $state:expr, $($row:expr),* $(,)?) => {
        $crate::view::picker_bound(
            $title,
            $state,
            $crate::view::tuple_view(&[$($crate::view::IntoView::into_view($row)),*]),
        )
    };
}

/// `Picker(_:selection:)` over rows with a fixed selection — see
/// [`picker_bound!`] for the one the user can change.
#[macro_export]
macro_rules! picker {
    ($title:expr, $selection:expr, $($row:expr),* $(,)?) => {
        $crate::view::picker(
            $title,
            $selection,
            $crate::view::tuple_view(&[$($crate::view::IntoView::into_view($row)),*]),
        )
    };
}

macro_rules! swift_statics {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $($(#[$vmeta:meta])* $variant:ident = $symbol:expr),* $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        $vis enum $name {
            $($(#[$vmeta])* $variant),*
        }

        impl $name {
            /// The mangled symbol of the static property this variant names.
            ///
            /// `allow(unused_doc_comments)`: the arms carry each variant's
            /// attributes so that a `#[cfg]` gating a variant gates its arm
            /// too, and a `///` comes along with it.
            #[allow(unused_doc_comments)]
            pub(crate) fn getter(self) -> &'static core::ffi::CStr {
                match self {
                    $($(#[$vmeta])* Self::$variant => $symbol),*
                }
            }

            /// The resolved getter, cached per variant.
            ///
            /// `allow(dead_code)`: the macro generates this for every statics
            /// enum, and a few of them have no caller yet.
            ///
            /// Each variant names one fixed symbol, so it can keep the answer
            /// beside itself the way a `cached!` entry does and the way Swift's
            /// own `…Ml` cache words do: a relaxed load, a compare, and a store
            /// on the miss.
            ///
            /// Going through [`crate::resolve::sym`] instead took an `RwLock`
            /// and hashed the mangled name on *every* read, and these are read
            /// once per enum argument per view — measured at ~35 ns each, which
            /// was more than the whole of `.padding(_:)` beside it.
            #[allow(dead_code)]
            pub(crate) fn resolved(self) -> *const core::ffi::c_void {
                use std::sync::atomic::{AtomicUsize, Ordering};
                // Counts *every* variant, including ones this platform gates
                // out: an attribute cannot sit on an array element, and a
                // cache longer than the enum costs a few unused words where a
                // shorter one would index out of range.
                const N: usize = [$(stringify!($variant)),*].len();
                static CACHE: [AtomicUsize; N] = [const { AtomicUsize::new(0) }; N];
                let slot = &CACHE[self as usize];
                let v = slot.load(Ordering::Relaxed);
                if v != 0 {
                    // Report even on a hit, so a symbol trace sees the statics
                    // a build used and not only the ones it resolved first.
                    $crate::resolve::note(self.getter());
                    return v as *const core::ffi::c_void;
                }
                let p = $crate::resolve::require(self.getter());
                slot.store(p as usize, Ordering::Relaxed);
                p
            }
        }

    };
}

/// An app's `body`, written the way Swift writes it.
///
/// `scene::commands(scene::group(vec![…]), vec![…])` is the same thing inside
/// out: the scenes read bottom-up, the commands are a second list far from what
/// they attach to, and every body ends in `.into_handle()`. This reads in the
/// order the app is built.
///
/// ```no_run
/// # use swiftui_native::{app, prelude::*, scenes};
/// app::run_scene(|| scenes! {
///     window_group { text("main") }
///     settings { text("preferences") }
///     window("Utility", "utility") { text("a second window") }
///     menu_bar_extra("Status", "star.fill") { text("in the menu bar") }
///     commands {
///         menu("Counter") { button("Reset", || {}) }
///         replacing(NewItem) { button("New Count", || {}) }
///         after(Help) { button("About", || {}) }
///     }
/// });
/// ```
///
/// Each body is an ordinary block returning anything that is a view — a `View`,
/// a `ViewHandle`, or a `&str`. `commands` is optional and goes last, which is
/// also where Swift's `.commands { }` ends up.
///
/// The `window`, `settings` and `menu_bar_extra` clauses are macOS-only, as the
/// scenes themselves are; a `scenes!` using them does not compile for iOS, which
/// is the same answer Swift gives.
#[macro_export]
macro_rules! scenes {
    ($($clause:tt)*) => {
        $crate::scenes_build!(@scene [] $($clause)*)
    };
}

/// The muncher behind [`scenes!`]. Not for direct use.
#[doc(hidden)]
#[macro_export]
macro_rules! scenes_build {
    // `commands { … }` ends the list and wraps everything built so far.
    (@scene [$($s:expr),* $(,)?] commands { $($c:tt)* }) => {
        $crate::scene::commands(
            $crate::scene::group(::std::vec![$($s),*]),
            $crate::scenes_build!(@commands [] $($c)*),
        )
    };

    (@scene [$($s:expr),* $(,)?] window_group $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@scene [$($s,)* $crate::scene::window_group(move || $body)] $($rest)*)
    };
    (@scene [$($s:expr),* $(,)?] settings $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@scene [$($s,)* $crate::scene::settings(move || $body)] $($rest)*)
    };
    (@scene [$($s:expr),* $(,)?] window($title:expr, $id:expr) $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@scene [$($s,)* $crate::scene::window($title, $id, move || $body)] $($rest)*)
    };
    (@scene [$($s:expr),* $(,)?] menu_bar_extra($title:expr, $image:expr) $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@scene [$($s,)* $crate::scene::menu_bar_extra($title, $image, move || $body)] $($rest)*)
    };

    // No commands: the scenes are the whole body.
    (@scene [$($s:expr),* $(,)?]) => {
        $crate::scene::group(::std::vec![$($s),*])
    };

    (@commands [$($c:expr),* $(,)?] menu($title:expr) $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@commands [$($c,)* $crate::scene::command_menu($title, move || $body)] $($rest)*)
    };
    (@commands [$($c:expr),* $(,)?] replacing($place:ident) $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@commands [$($c,)* $crate::scene::command_group(
            $crate::scene::CommandPlacement::$place,
            $crate::scene::Relative::Replacing,
            move || $body,
        )] $($rest)*)
    };
    (@commands [$($c:expr),* $(,)?] after($place:ident) $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@commands [$($c,)* $crate::scene::command_group(
            $crate::scene::CommandPlacement::$place,
            $crate::scene::Relative::After,
            move || $body,
        )] $($rest)*)
    };
    (@commands [$($c:expr),* $(,)?] before($place:ident) $body:block $($rest:tt)*) => {
        $crate::scenes_build!(@commands [$($c,)* $crate::scene::command_group(
            $crate::scene::CommandPlacement::$place,
            $crate::scene::Relative::Before,
            move || $body,
        )] $($rest)*)
    };
    (@commands [$($c:expr),* $(,)?]) => { ::std::vec![$($c),*] };
}

/// Declare environment keys of your own.
///
/// A key is inherently a global: one name is one `EnvironmentKey` conformance and
/// one key path, minted once and shared by everything that reads or writes it. So
/// the declaration is a `static` — and writing that by hand was the noisiest
/// thing in this crate:
///
/// ```ignore
/// static KEY: OnceLock<&'static CustomEnvKey<String>> = OnceLock::new();
/// let key = *KEY.get_or_init(|| Box::leak(Box::new(env_key("greeting", "hello".to_string()))));
/// ```
///
/// This says the same thing in one line per key:
///
/// ```
/// # use swiftui_native::{environment_keys, prelude::*};
/// environment_keys! {
///     /// How deeply this row is nested.
///     depth: i64 = 3,
///     /// What to greet the reader with.
///     greeting: String = "hello",
/// }
///
/// # fn body() -> View {
/// text("hi").environment_value(depth(), 7).environment_value(greeting(), "bonjour")
/// # }
/// ```
///
/// Each entry becomes a function returning the one key, so `depth()` in two
/// places is one key in both. Reading one is
/// [`EnvironmentValues::value_for`](crate::views::EnvironmentValues::value_for),
/// which is typed by the key and so cannot be read as the wrong thing.
///
/// The name SwiftUI sees includes the declaring module, so two modules may each
/// have a `depth` without colliding — a key is shared by *calling* the same
/// function, not by agreeing on a string.
#[macro_export]
macro_rules! environment_keys {
    ($(
        $(#[$meta:meta])*
        $name:ident : $ty:ty = $default:expr
    ),* $(,)?) => {$(
        $(#[$meta])*
        pub fn $name() -> &'static $crate::views::CustomEnvKey<$ty> {
            static KEY: ::std::sync::OnceLock<$crate::views::CustomEnvKey<$ty>> =
                ::std::sync::OnceLock::new();
            KEY.get_or_init(|| {
                $crate::views::env_key(
                    concat!(module_path!(), "::", stringify!($name)),
                    $default,
                )
            })
        }
    )*};
}

/// Declare container-value keys of your own — as [`environment_keys!`], for
/// `ContainerValues`.
///
/// What a row tells the container it is in, rather than what a container tells
/// the views inside it.
///
/// ```
/// # use swiftui_native::{container_keys, prelude::*};
/// container_keys! {
///     /// How much of the row's width the leading column takes.
///     ratio: f64 = 0.5,
/// }
///
/// # fn row() -> View {
/// text("row").container_value(ratio(), 0.25)
/// # }
/// ```
#[macro_export]
macro_rules! container_keys {
    ($(
        $(#[$meta:meta])*
        $name:ident : $ty:ty = $default:expr
    ),* $(,)?) => {$(
        $(#[$meta])*
        pub fn $name() -> &'static $crate::views::CustomContainerKey<$ty> {
            static KEY: ::std::sync::OnceLock<$crate::views::CustomContainerKey<$ty>> =
                ::std::sync::OnceLock::new();
            KEY.get_or_init(|| {
                $crate::views::container_key(
                    concat!(module_path!(), "::", stringify!($name)),
                    $default,
                )
            })
        }
    )*};
}

/// Declare focused-value keys of your own — as [`environment_keys!`], for
/// `FocusedValues`.
///
/// No default: a focused value is `T?` and absent until something publishes it,
/// which is what lets a menu command know whether anything is focused at all.
///
/// ```
/// # use swiftui_native::{focused_keys, prelude::*};
/// focused_keys! {
///     /// What the focused window has selected.
///     selection: String,
/// }
///
/// # fn body() -> View {
/// text("row").focused_scene_value(selection(), "the third row")
/// # }
/// ```
#[macro_export]
macro_rules! focused_keys {
    ($(
        $(#[$meta:meta])*
        $name:ident : $ty:ty
    ),* $(,)?) => {$(
        $(#[$meta])*
        pub fn $name() -> &'static $crate::views::FocusKey<$ty> {
            static KEY: ::std::sync::OnceLock<$crate::views::FocusKey<$ty>> =
                ::std::sync::OnceLock::new();
            KEY.get_or_init(|| {
                $crate::views::focus_key(concat!(module_path!(), "::", stringify!($name)))
            })
        }
    )*};
}

/// Declare an `@Observable` model — the properties, not the plumbing.
///
/// `@Observable class Model { var count = 0; var name = "Ada" }` in Swift. Here it
/// is a type whose fields are the properties, so the names are checked and the
/// types come from the declaration:
///
/// ```
/// # use swiftui_native::{observable, prelude::*};
/// observable! {
///     /// Everything the app's windows share.
///     pub AppModel {
///         count: i64 = 0,
///         name: String = "Ada",
///     }
/// }
///
/// let model = AppModel::new();
/// model.count.set(model.count.peek() + 1);
/// assert_eq!(model.count.peek(), 1);
/// assert_eq!(model.name.peek(), "Ada");
/// ```
///
/// Each field is a [`Property`](crate::observable::Property), with its own key
/// path, so a view body that read `count` is rebuilt when `count` changes and left
/// alone when `name` does. [`shared`](crate::observable::Model) is the form an app
/// usually wants — one model for the process, reachable from every window:
///
/// ```no_run
/// # use swiftui_native::{app, observable, prelude::*};
/// # observable! { pub AppModel { count: i64 = 0 } }
/// app::run(|| {
///     let model = AppModel::shared();
///     text(&format!("{}", model.count.get())).environment_model(model.as_model())
/// });
/// ```
///
/// Reading through `get` inside a body is what subscribes it; `peek` reads without
/// subscribing, for assertions that must not.
#[macro_export]
macro_rules! observable {
    ($(
        $(#[$meta:meta])*
        $vis:vis $name:ident {
            $(
                $(#[$field_meta:meta])*
                $field:ident : $ty:ty = $default:expr
            ),* $(,)?
        }
    )*) => {$(
        $(#[$meta])*
        $vis struct $name {
            model: $crate::observable::Model,
            $(
                $(#[$field_meta])*
                pub $field: $crate::observable::Property<$ty>,
            )*
        }

        impl $name {
            /// A new model, with every property at its declared value.
            ///
            /// Two of these are two models: a write to one is not a change to the
            /// other, which is what makes [`shared`](Self::shared) the interesting
            /// one for an app.
            pub fn new() -> Self {
                let model = $crate::observable::object();
                $name {
                    $($field: model.property(
                        concat!(module_path!(), "::", stringify!($name), ".", stringify!($field)),
                        $default,
                    ),)*
                    model,
                }
            }

            /// The one model for this process, made on first use.
            pub fn shared() -> &'static Self {
                static SHARED: ::std::sync::OnceLock<$name> = ::std::sync::OnceLock::new();
                SHARED.get_or_init($name::new)
            }

            /// The model itself, for `.environment_model(…)` and
            /// `.focused_value_model(…)`.
            pub fn as_model(&self) -> &$crate::observable::Model {
                &self.model
            }
        }

        impl ::core::default::Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }
    )*};
}