day-pieces 0.6.1

Declarative app development API using native UI toolkits
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
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The inspector (docs/inspector.md): window content beside a trailing properties panel,
//! show/hidden by one app-owned `Signal<bool>`, the same signal a `toolbar_toggle` and a menu
//! item bind to, so every affordance stays in step. Where `Cap::Inspector` is `Native` the
//! split is the toolkit's own trailing-pane container; everywhere else the pane is composed
//! from plain containers, and on a compact window the panel presents as a fullscreen sheet
//! instead of a pane.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use day_core::*;
use day_geometry::{Insets, Proposal, Rect};
use day_reactive::{bind_seeded, untrack};
use day_spec::props::{InspectorPaneProps, InspectorPatch, InspectorProps, PaneEdge};
use day_spec::{Cap, Event, Size, Support, kinds};

use crate::*;

/// The pane's default width in points; Keynote-class inspectors sit in the 250–300 range.
pub const INSPECTOR_WIDTH: f64 = 280.0;

/// Window content beside a trailing inspector panel, visibility bound to `visible`
/// (docs/inspector.md).
///
/// ```ignore
/// let show = Signal::global(false);
/// inspector(show, editor(), || form((section((/* property rows */,)),)))
/// ```
///
/// `panel` is a builder rather than a piece because the panel can be re-homed: on a compact
/// window the composed form presents it inside a fullscreen sheet instead of a side pane, and
/// each home builds it fresh in its own scope.
pub struct Inspector<V: Binding<bool>> {
    visible: V,
    width: f64,
    scrollable: bool,
    edge: PaneEdge,
    half_sheet: bool,
    sheet_done: TextSource,
    content: AnyPiece,
    panel: Rc<dyn Fn() -> AnyPiece>,
}

/// Build an [`Inspector`]: `content` beside a trailing panel toggled by `visible`.
pub fn inspector<V: Binding<bool>, C: Piece, P: Piece>(
    visible: V,
    content: C,
    panel: impl Fn() -> P + 'static,
) -> Inspector<V> {
    Inspector {
        visible,
        width: INSPECTOR_WIDTH,
        scrollable: true,
        edge: PaneEdge::Trailing,
        half_sheet: false,
        // A language-neutral glyph, because day carries no "Done" in its own catalog; apps
        // localize with `.sheet_done(…)`.
        sheet_done: "✕".into_text(),
        content: AnyPiece::new(content),
        panel: Rc::new(move || AnyPiece::new(panel())),
    }
}

#[day_macros::builder(InspectorBuilder)]
impl<V: Binding<bool>> Inspector<V> {
    /// The panel's preferred width in points (default [`INSPECTOR_WIDTH`]). Where the native
    /// pane has a user-draggable divider this is the initial width, not a limit.
    pub fn width(mut self, width: f64) -> Self {
        self.width = width;
        self
    }

    /// Do not wrap the panel in a scroll view (it is wrapped by default): for a panel that owns
    /// a recycling list or its own scroller, so it receives a bounded viewport.
    pub fn not_scrollable(mut self) -> Self {
        self.scrollable = false;
        self
    }

    /// The label of the compact sheet's dismiss button (default `✕`). Pass a localized
    /// "Done"; the sheet is the one home where the panel needs its own way out.
    pub fn sheet_done<M>(mut self, t: impl IntoText<M>) -> Self {
        self.sheet_done = t.into_text();
        self
    }

    /// Put the pane on the leading side of the content, for a layer panel rather than a
    /// properties inspector (docs/tree.md). Default [`PaneEdge::Trailing`].
    pub fn edge(mut self, edge: PaneEdge) -> Self {
        self.edge = edge;
        self
    }

    /// On a compact window, present the panel as a half-height sheet rising from the bottom
    /// edge rather than a fullscreen one, so the content it describes stays on show (and, on
    /// iOS, interactive) while it is open: [`Cover::half_sheet`](crate::Cover::half_sheet).
    /// Default: the fullscreen sheet.
    pub fn half_sheet(mut self) -> Self {
        self.half_sheet = true;
        self
    }
}

impl<V: Binding<bool>> Piece for Inspector<V> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        if day_core::capability(Cap::Inspector) == Support::Native {
            build_native(self, cx)
        } else {
            build_composed(self, cx)
        }
    }
}

/// A tracked read of whether this window is compact. The un-reported case (`None`, a backend
/// with no window geometry) reads as not compact: those are desktop-shaped surfaces, and a
/// sheet that can never be resized away would strand the panel.
fn compact(window: RNode) -> bool {
    day_core::window_size_class(window).is_some_and(|c| c.width == day_spec::WidthClass::Compact)
}

// ---------------------------------------------------------------------------
// Native: the toolkit's own trailing-pane container (`Cap::Inspector == Native`)
// ---------------------------------------------------------------------------

fn panel_content(panel: AnyPiece, scrollable: bool) -> AnyPiece {
    if scrollable {
        scroll(panel).any()
    } else {
        panel
    }
}

fn build_native<V: Binding<bool>>(inspector: Inspector<V>, cx: &mut BuildCx) -> RNode {
    let Inspector {
        visible,
        width,
        scrollable,
        edge,
        content,
        panel,
        ..
    } = inspector;
    let initial = visible.peek();
    let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>> = Rc::default();
    let visible_cell = Rc::new(Cell::new(initial));
    let node = cx.native(
        kinds::INSPECTOR,
        &InspectorProps {
            visible: initial,
            width,
            edge,
        },
        Rc::new(InspectorLayout {
            sizes: sizes.clone(),
            visible: visible_cell.clone(),
            width,
        }),
        Flex {
            grow_w: true,
            grow_h: true,
            ..Default::default()
        },
        Boundary::Yes,
    );

    // The two panes: content, then the panel (`InspectorPaneProps::panel`). Frames are
    // native-owned, reported like nav pages.
    let content_pane = pane(node, false, &sizes);
    let mut ccx = BuildCx::new(content_pane);
    let _ = content.build(&mut ccx);
    let panel_pane = pane(node, true, &sizes);
    let mut pcx = BuildCx::new(panel_pane);
    let _ = panel_content(panel(), scrollable).build(&mut pcx);

    // Signal → native pane, as a targeted patch (no rebuild). The layout cell keeps the
    // pre-report fallback split in step.
    {
        let v = visible.clone();
        let cell = visible_cell;
        bind_seeded(
            initial,
            move || v.read(),
            move |show: &bool| {
                cell.set(*show);
                with_tree(|t| {
                    t.patch(node, Box::new(InspectorPatch::Visible(*show)), false);
                    t.mark_needs_measure(node);
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
            },
        );
    }
    // Native pane → signal: a dock close button, a divider dragged shut. The peek guard
    // keeps the patch→event→write loop from echoing.
    cx.on(node, move |ev| {
        if let Event::InspectorChanged(show) = ev
            && visible.peek() != *show
        {
            visible.write(*show);
        }
    });
    node
}

/// One native-owned pane container under the inspector host, with the same `FrameChanged`
/// wiring as a nav page: the backend reports each pane's real frame, and Day lays the pane's
/// content out inside it.
fn pane(
    host: RNode,
    panel: bool,
    sizes: &Rc<RefCell<std::collections::HashMap<RNode, Size>>>,
) -> RNode {
    let mut cx = BuildCx::new(host);
    let pane = cx.native(
        kinds::INSPECTOR_PANE,
        &InspectorPaneProps { panel },
        Rc::new(PassThrough),
        Flex::default(),
        Boundary::Yes,
    );
    let sizes = sizes.clone();
    cx.on(pane, move |ev| {
        if let Event::FrameChanged(sz) = ev {
            let changed = sizes.borrow().get(&pane) != Some(sz);
            if changed {
                sizes.borrow_mut().insert(pane, *sz);
                with_tree(|t| {
                    t.mark_needs_measure(pane);
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
            }
        }
    });
    pane
}

// ---------------------------------------------------------------------------
// Composed: plain containers + a compact-width sheet (every other backend)
// ---------------------------------------------------------------------------

/// The sheet's open signal, derived rather than stored: the panel is "presented as a sheet"
/// exactly while it is visible and the window is compact, so a window resized across the
/// breakpoint re-homes the panel with no extra state to reconcile. Dismissing the sheet
/// (system back) writes straight through to the app's own signal.
struct SheetOpen<V: Binding<bool>> {
    visible: V,
    window: RNode,
}

impl<V: Binding<bool>> Clone for SheetOpen<V> {
    fn clone(&self) -> Self {
        SheetOpen {
            visible: self.visible.clone(),
            window: self.window,
        }
    }
}

impl<V: Binding<bool>> Binding<Option<String>> for SheetOpen<V> {
    fn read(&self) -> Option<String> {
        (self.visible.read() && compact(self.window)).then(|| "inspector".to_string())
    }
    fn peek(&self) -> Option<String> {
        let visible = self.visible.peek();
        (visible && untrack(|| compact(self.window))).then(|| "inspector".to_string())
    }
    fn write(&self, v: Option<String>) {
        self.visible.write(v.is_some());
    }
}

/// The trailing pane's width for a split `total` points wide: the requested width, widened
/// to 320 at 1000 or more (a tablet in landscape beside a layers pane, a desktop window)
/// where an inspector has room to breathe, and never more than two fifths of the split, so
/// a narrow one keeps its content. Keynote-class inspectors sit in this range.
fn pane_width(requested: f64, total: f64) -> f64 {
    let w = if total >= 1000.0 {
        requested.max(320.0)
    } else {
        requested
    };
    w.min(total * 0.4).max(0.0)
}

/// The composed inspector's split: the content, the side pane (a container around the
/// `when`), and the compact-width sheet, placed by [`SplitLayout`] so the pane's width follows
/// the window rather than being fixed at build time. `shown` is the reactive condition shared
/// with the pane's `when`; it determines whether the layout reserves side-pane width.
fn split_row<C: PieceSeq>(
    width: f64,
    shown: impl Fn() -> bool + 'static,
    children: C,
) -> impl Piece {
    piece_fn(move |cx| {
        let initial = untrack(&shown);
        let pane_is_shown = Rc::new(Cell::new(initial));
        let node = cx.layout_only(
            Rc::new(SplitLayout {
                width,
                pane_is_shown: pane_is_shown.clone(),
            }),
            Flex {
                grow_w: true,
                grow_h: true,
                ..Default::default()
            },
            Boundary::No,
        );
        cx.under(node, |cx| children.build_each(cx));
        bind_seeded(initial, shown, move |show: &bool| {
            pane_is_shown.set(*show);
            with_tree(|tree| {
                tree.mark_needs_measure(node);
                tree.mark_layout_dirty();
            });
        });
        node
    })
}

struct SplitLayout {
    width: f64,
    pane_is_shown: Rc<Cell<bool>>,
}

impl day_core::Layout for SplitLayout {
    fn measure(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], p: Proposal) -> Size {
        // The split fills what it is offered; unconstrained, it is as big as its content.
        let content = children.first().copied();
        let natural = content
            .map(|c| cx.measure_child(c, p))
            .unwrap_or(Size::ZERO);
        Size::new(
            p.width.unwrap_or(natural.width),
            p.height.unwrap_or(natural.height),
        )
    }
    fn place(&self, cx: &mut dyn day_core::LayoutOps, children: &[RNode], bounds: Rect) {
        let (w, h) = (bounds.size.width, bounds.size.height);
        let pane = pane_width(self.width, w);
        // An empty growable container still measures to the proposed width. Visibility
        // comes from the binding and window size class, never from that measurement.
        let side_w = if self.pane_is_shown.get() { pane } else { 0.0 };
        if let Some(&c) = children.first() {
            cx.place_child(c, Rect::new(0.0, 0.0, (w - side_w).max(0.0), h));
        }
        if let Some(&s) = children.get(1) {
            cx.place_child(s, Rect::new(w - side_w, 0.0, side_w, h));
        }
        // The sheet (and anything after it) presents on its own; in the tree it takes only
        // what it measures to (nothing while it is not presented), the way it did as a row
        // child. Handing it the whole window would stack an empty host over the pane.
        for extra in children.iter().skip(2) {
            let m = cx.measure_child(*extra, Proposal::new(Some(w), Some(h)));
            cx.place_child(*extra, Rect::new(0.0, 0.0, m.width.min(w), m.height.min(h)));
        }
    }
}

fn build_composed<V: Binding<bool>>(inspector: Inspector<V>, cx: &mut BuildCx) -> RNode {
    let Inspector {
        visible,
        width,
        scrollable,
        edge: inspector_edge,
        half_sheet,
        sheet_done,
        content,
        panel,
    } = inspector;
    let window = day_core::window_being_built();
    // A leading pane is a utility surface (a layer panel, docs/tree.md): it stays a side
    // pane at every width rather than re-homing into the compact sheet; a phone shows a
    // narrow canvas beside it, and everything stays mounted in the window (no modal to
    // juggle around focus or scripting).
    if inspector_edge == PaneEdge::Leading {
        let lead_visible = visible;
        let lead_panel = panel;
        return row((
            when(
                move || lead_visible.read(),
                move || {
                    row((
                        panel_content(lead_panel(), scrollable).width(width),
                        divider(),
                    ))
                },
            ),
            content.grow(),
        ))
        .build(cx);
    }
    let pane_binding = visible.clone();
    let show_pane = move || pane_binding.read() && !compact(window);
    let side_panel = panel.clone();
    let sheet_panel = panel;
    let sheet_close = visible.clone();
    let done = sheet_done.initial();
    split_row(
        width,
        show_pane.clone(),
        (
            content.grow(),
            // The side pane: mounted only while visible on a non-compact window, so the compact
            // home (the sheet below) is never doubled. Its width is the split's to decide
            // (`pane_width`), so the row fills whatever it is proposed.
            // A hairline divider, then the panel filling the rest of the pane, both the
            // pane's full height.
            column((when(show_pane, move || {
                row((
                    divider().width(1.0).grow_h(),
                    panel_content(side_panel(), scrollable).grow(),
                ))
                .grow()
            }),))
            .grow(),
            // The compact home: a sheet, fullscreen or (`half_sheet`) half-height over the
            // content it describes. Unrouted, because the inspector is chrome, not a place
            // (`Cover::unrouted`), and carrying its own way out, since a modal has no divider
            // to drag shut.
            {
                let sheet = cover(SheetOpen { visible, window }, move |_: &String| {
                    let close = sheet_close.clone();
                    column((
                        row((
                            spacer(),
                            button(done.clone())
                                .action(move || close.write(false))
                                .id(day_core::id!(day_inspector_done)),
                        ))
                        .padding(Insets::symmetric(12.0, 8.0)),
                        panel_content(sheet_panel(), scrollable).grow(),
                    ))
                })
                .unrouted();
                if half_sheet {
                    sheet.half_sheet()
                } else {
                    sheet
                }
            },
        ),
    )
    .build(cx)
}

#[cfg(feature = "conformance")]
pub(crate) mod conformance {
    use std::rc::Rc;

    use day_core::conformance::{Case, Drive};
    use day_reactive::Signal;
    use day_spec::{Cap, Support, kinds};

    use crate::*;

    /// The panel follows its signal: hidden, shown, hidden again.
    #[day_macros::test(day_core)]
    fn inspector_shows_panel() -> Case {
        Case::new()
            .proves(kinds::INSPECTOR)
            .proves(kinds::INSPECTOR_PANE)
            .page(|| {
                let show = Signal::new(false);
                inspector(
                    show,
                    column((
                        label("Content").id(day_core::id!(content)),
                        button("Toggle")
                            .action(move || show.update(|v| *v = !*v))
                            .id(day_core::id!(toggle)),
                    )),
                    || label("Properties").id(day_core::id!(panel)),
                )
            })
            .drive(|d: Drive| async move {
                d.assert_text("content", "Content").await?;
                // A native pane collapses rather than going away, so hidden, not missing.
                d.assert_hidden("panel").await?;
                d.tap("toggle").await?;
                d.assert_text("panel", "Properties").await?;
                d.assert_visible("panel").await?;
                d.wait_idle().await?;
                d.tap("toggle").await?;
                d.assert_hidden("panel").await
            })
    }

    // The heights the half-sheet case compares: the page's, and the sheet panel's.
    thread_local! {
        static HALF_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
            (Rc::default(), Rc::default());
    }

    /// Puts the primary window's size class back when the drive ends, however it ends.
    pub(crate) struct RestoreSizeClass;

    impl Drop for RestoreSizeClass {
        fn drop(&mut self) {
            day_core::restore_reported_size_class();
        }
    }

    /// On a compact window a `half_sheet()` inspector presents its panel as a half sheet: the
    /// panel's content lays out at about half the page's height, the content stays mounted,
    /// and the signal closes it again.
    #[day_macros::test(day_core)]
    fn inspector_half_sheet_on_compact() -> Case {
        Case::new()
            .proves(kinds::COVER)
            // The sheet is the COMPOSED inspector's compact home; a toolkit with a native
            // trailing pane (`Cap::Inspector` = Native) collapses the pane instead and never
            // presents one, so the case does not apply there.
            .requires_support("composed inspector", || {
                if day_core::capability(Cap::Inspector) == Support::Native {
                    Support::Unsupported
                } else {
                    Support::Native
                }
            })
            .page(|| {
                let (page_h, panel_h) = HALF_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
                page_h.set(0.0);
                panel_h.set(0.0);
                let show = Signal::new(false);
                zstack((
                    crate::nav::conformance::height_probe(page_h),
                    inspector(
                        show,
                        column((
                            label("Content").id(day_core::id!(content)),
                            button("Toggle")
                                .action(move || show.update(|v| *v = !*v))
                                .id(day_core::id!(toggle)),
                        )),
                        move || {
                            column((
                                label("Properties").id(day_core::id!(panel)),
                                crate::nav::conformance::height_probe(panel_h.clone()),
                            ))
                        },
                    )
                    .not_scrollable()
                    .half_sheet(),
                ))
            })
            .drive(|d: Drive| async move {
                let _restore = RestoreSizeClass;
                day_core::override_size_class(day_spec::SizeClass {
                    width: day_spec::WidthClass::Compact,
                    height: day_spec::HeightClass::Medium,
                });
                d.wait_idle().await?;
                d.assert_missing("panel").await?;
                d.tap("toggle").await?;
                d.assert_text("panel", "Properties").await?;
                d.wait_idle().await?;
                let heights = HALF_HEIGHTS.with(|h| h.clone());
                crate::nav::conformance::check_half(&d, "inspector half sheet panel", &heights)
                    .await?;
                d.assert_text("content", "Content").await?;
                d.tap("toggle").await?;
                d.assert_missing("panel").await
            })
    }
}

#[cfg(test)]
mod pane_width_tests {
    use super::pane_width;

    #[test]
    fn the_pane_widens_on_a_wide_window_and_yields_on_a_narrow_one() {
        assert_eq!(
            pane_width(280.0, 1060.0),
            320.0,
            "a landscape tablet gets room"
        );
        assert_eq!(pane_width(360.0, 1280.0), 360.0, "a wider ask is kept");
        assert_eq!(
            pane_width(280.0, 960.0),
            280.0,
            "a desktop window keeps its ask"
        );
        assert_eq!(
            pane_width(280.0, 600.0),
            240.0,
            "never more than two fifths"
        );
    }
}