denise-ui 0.8.0

Scene graph, widgets and compositor for Denise.
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
//! A section that folds to its header, and the controller that makes several
//! of them an accordion.

use alloc::string::String;
use alloc::vec::Vec;

use denise::{ElementState, InputEvent, KeyCode, Point, Radius, Rect, Role, Theme};
use denise_render::Canvas;
use denise_text::TextStyle;

use crate::widget::{Event, EventCtx, Handled, PaintCtx, VisualState, Widget};
use crate::widgets::style::{Align, draw_aligned, focus_ring, interactive_pair};
use crate::{NodeId, Ui};

/// How long [`set_open`] takes to fold or unfold, unless the caller says.
pub const FOLD_MS: u64 = 200;

/// A section that folds to its header.
///
/// The widget is the **header** — title, chevron, the toggle — and the node it
/// sits on hosts the body as ordinary children below the header strip, the way
/// [`Panel`](super::Panel) hosts children. Collapsing is the node's *height*
/// animating between the header alone and the full section; the body needs no
/// hiding, because the node's own clip crops it, mid-animation included.
///
/// ```ignore
/// let section = ui.add(stack, Collapse::new("Nettverk", Msg::Network), rect)?;
/// // body children of `section`, placed below Collapse::header_height
/// // ...
/// Msg::Network(open) => widgets::set_open(&mut ui, section, open, FOLD_MS),
/// ```
///
/// The widget cannot animate its own node — `EventCtx` deliberately has no
/// tree access — so it emits `fn(bool) -> M` and the application answers with
/// [`set_open`], which flips the chevron and drives
/// [`Ui::animate_layout`](crate::Ui::animate_layout). Inside a
/// [`Ui::set_stack`](crate::Ui::set_stack) the siblings follow every frame,
/// which is the whole accordion mechanism; [`Accordion`] packages the
/// exclusivity.
///
/// # The expanded height is remembered, not configured
///
/// [`set_open`] notes the node's height at the moment of collapse, so opening
/// returns the section to wherever it really was — a section that grew a row
/// while open comes back at its grown height. The one case with nothing to
/// remember is a section *built* collapsed:
/// [`with_expanded_height`](Collapse::with_expanded_height) covers it.
#[derive(Clone, Debug)]
pub struct Collapse<M> {
    title: String,
    open: bool,
    /// Where opening returns to. Written by [`set_open`] on the way down, or
    /// by the builder for a section born collapsed.
    expanded: Option<i32>,
    message: Option<fn(bool) -> M>,
    role: Role,
    style: TextStyle,
}

impl<M> Collapse<M> {
    /// An open section titled `title`, reporting toggles through `message`.
    pub fn new(title: impl Into<String>, message: fn(bool) -> M) -> Self {
        Self {
            title: title.into(),
            open: true,
            expanded: None,
            message: Some(message),
            role: Role::Base200,
            style: TextStyle::built_in(16),
        }
    }

    /// Starts the section collapsed. Pair with
    /// [`with_expanded_height`](Collapse::with_expanded_height), since a
    /// section that has never been open has no height to remember.
    pub fn closed(mut self) -> Self {
        self.open = false;
        self
    }

    /// Sets where the first opening goes, for a section built collapsed.
    pub fn with_expanded_height(mut self, height: i32) -> Self {
        self.expanded = Some(height.max(0));
        self
    }

    /// Sets the header's colour role.
    pub fn with_role(mut self, role: Role) -> Self {
        self.role = role;
        self
    }

    /// Sets the title's font and size.
    pub fn with_style(mut self, style: TextStyle) -> Self {
        self.style = style;
        self
    }

    /// Whether the section is open (or opening).
    #[inline]
    pub const fn is_open(&self) -> bool {
        self.open
    }

    /// The header strip's height: the theme's field height.
    ///
    /// The strip the widget draws and the closed height [`set_open`] folds
    /// to — one definition, so they cannot drift.
    pub fn header_height(&self, theme: &Theme) -> i32 {
        theme.metrics.size_field.max(1)
    }

    /// Flips the open state **without emitting or animating** — [`set_open`]
    /// calls this; so can an application restoring saved state before first
    /// paint.
    pub fn set_open_silent(&mut self, open: bool) {
        self.open = open;
    }

    /// The remembered expanded height, if any.
    #[inline]
    pub const fn expanded_height(&self) -> Option<i32> {
        self.expanded
    }

    /// Remembers where opening should return to.
    pub fn set_expanded_height(&mut self, height: i32) {
        self.expanded = Some(height.max(0));
    }
}

/// Opens or folds the section at `id`, animated over `duration_ms`.
///
/// The application's whole answer to a [`Collapse`] message: flips the
/// widget's chevron, remembers the expanded height on the way down, and
/// drives [`Ui::animate_layout`] on the node's height. Does nothing if `id`
/// does not hold a [`Collapse`].
///
/// Opening a section that was built collapsed and never given an expanded
/// height unfolds to the header alone — visibly wrong rather than silently
/// absent, so the missing `with_expanded_height` is found in review.
pub fn set_open<M: 'static>(ui: &mut Ui<M>, id: NodeId, open: bool, duration_ms: u64) {
    let Some(layout) = ui.layout(id) else {
        return;
    };
    let theme = *ui.theme();
    let Some(collapse) = ui.widget_mut::<Collapse<M>>(id) else {
        return;
    };
    let header = collapse.header_height(&theme);
    let target = if open {
        collapse.expanded.unwrap_or(header)
    } else {
        // The height at the moment of folding is where opening returns to.
        collapse.set_expanded_height(layout.height);
        header
    };
    collapse.set_open_silent(open);
    ui.animate_layout(
        id,
        Rect::new(layout.x, layout.y, layout.width, target),
        duration_ms,
    );
}

/// Exclusivity over a run of [`Collapse`] sections: opening one closes the
/// open one.
///
/// A controller the application owns, not a widget — a widget cannot own
/// other nodes, and which sections belong together is application policy.
/// Like [`set_open`], it emits nothing: it *is* the answer to the messages.
///
/// ```ignore
/// let accordion = Accordion::new([network, screen, about]);
/// // ...
/// Msg::Section(index, _) => accordion.toggle(&mut ui, index),
/// ```
#[derive(Clone, Debug)]
pub struct Accordion {
    sections: Vec<NodeId>,
    open: Option<usize>,
    duration_ms: u64,
}

impl Accordion {
    /// An accordion over `sections`, all assumed open; the first `toggle`
    /// closes the rest. Call [`collapse_all`](Accordion::collapse_all) after
    /// building to start folded.
    pub fn new(sections: impl IntoIterator<Item = NodeId>) -> Self {
        Self {
            sections: sections.into_iter().collect(),
            open: None,
            duration_ms: FOLD_MS,
        }
    }

    /// Sets how long each fold takes.
    pub fn with_duration(mut self, duration_ms: u64) -> Self {
        self.duration_ms = duration_ms;
        self
    }

    /// The open section's index, if one is.
    #[inline]
    pub const fn open(&self) -> Option<usize> {
        self.open
    }

    /// Folds every section, leaving nothing open.
    pub fn collapse_all<M: 'static>(&mut self, ui: &mut Ui<M>) {
        for &section in &self.sections {
            set_open(ui, section, false, self.duration_ms);
        }
        self.open = None;
    }

    /// Opens section `index`, folding whichever was open — or folds `index`
    /// itself if it was the open one, leaving the accordion closed.
    ///
    /// Out of range does nothing.
    pub fn toggle<M: 'static>(&mut self, ui: &mut Ui<M>, index: usize) {
        if index >= self.sections.len() {
            return;
        }
        if self.open == Some(index) {
            set_open(ui, self.sections[index], false, self.duration_ms);
            self.open = None;
            return;
        }
        if let Some(current) = self.open {
            set_open(ui, self.sections[current], false, self.duration_ms);
        }
        set_open(ui, self.sections[index], true, self.duration_ms);
        self.open = Some(index);
    }
}

/// The chevron: a small `>` when closed, rotated to `v` when open, drawn as
/// two strokes since the built-in font has no glyph for it.
fn chevron(canvas: &mut Canvas<'_>, centre: Point, arm: i32, open: bool, color: denise::Color) {
    let a = arm.max(2);
    if open {
        // Pointing down: two arms meeting at the bottom.
        canvas.draw_line(
            Point::new(centre.x - a, centre.y - a / 2),
            Point::new(centre.x, centre.y + a / 2),
            color,
        );
        canvas.draw_line(
            Point::new(centre.x + a, centre.y - a / 2),
            Point::new(centre.x, centre.y + a / 2),
            color,
        );
    } else {
        // Pointing right: two arms meeting at the right.
        canvas.draw_line(
            Point::new(centre.x - a / 2, centre.y - a),
            Point::new(centre.x + a / 2, centre.y),
            color,
        );
        canvas.draw_line(
            Point::new(centre.x - a / 2, centre.y + a),
            Point::new(centre.x + a / 2, centre.y),
            color,
        );
    }
}

impl<M: 'static> Widget<M> for Collapse<M> {
    fn paint(&self, ctx: &mut PaintCtx<'_>, canvas: &mut Canvas<'_>) {
        let bounds = ctx.bounds;
        if bounds.is_empty() {
            return;
        }
        let header = Rect::new(
            bounds.x,
            bounds.y,
            bounds.width,
            self.header_height(ctx.theme).min(bounds.height),
        );
        let radius = ctx.theme.radius(Radius::Field);
        let (fill, content) = interactive_pair(ctx.theme, self.role, ctx.state);
        canvas.fill_rounded_rect(header, radius, fill);

        let pad = (self.style.size_px as i32 / 2).max(4);
        let arm = (header.height / 6).max(3);
        chevron(
            canvas,
            Point::new(header.x + pad + arm, header.y + header.height / 2),
            arm,
            self.open,
            content,
        );

        let title_box = Rect::new(
            header.x + pad * 2 + arm * 2,
            header.y,
            (header.width - pad * 3 - arm * 2).max(0),
            header.height,
        );
        if !title_box.is_empty() && !self.title.is_empty() {
            let mut clipped = canvas.with_clip(title_box);
            draw_aligned(
                &mut clipped,
                ctx.text,
                self.style,
                title_box,
                (Align::Start, Align::Center),
                &self.title,
                content,
            );
        }

        if ctx.state.contains(VisualState::FOCUSED) {
            focus_ring(ctx.theme, header, radius, canvas);
        }
    }

    fn on_event(&mut self, event: &Event<'_>, ctx: &mut EventCtx<'_, M>) -> Handled {
        let header = Rect::new(
            ctx.bounds.x,
            ctx.bounds.y,
            ctx.bounds.width,
            self.header_height(ctx.theme).min(ctx.bounds.height),
        );
        let toggle = match event {
            Event::Input(InputEvent::PointerButton {
                state: ElementState::Up,
                position,
                ..
            })
            | Event::Input(InputEvent::TouchUp {
                position,
                cancelled: false,
                ..
            }) => header.contains(*position),
            Event::Input(InputEvent::Key {
                code: KeyCode::Enter | KeyCode::NumpadEnter | KeyCode::Space,
                state: ElementState::Down,
                repeat,
                ..
            }) if ctx.state.contains(VisualState::FOCUSED) => {
                // Space held down must not fold and unfold per repeat, the
                // same guard Checkbox keeps.
                !repeat
            }
            _ => return Handled::No,
        };
        if !toggle {
            return Handled::No;
        }
        // The widget reports; the application animates. `open` flips here so
        // the chevron answers the press immediately, and `set_open` flips it
        // again to the same value — idempotent, not doubled.
        self.open = !self.open;
        if let Some(message) = self.message {
            ctx.emit(message(self.open));
        }
        Handled::Yes
    }

    fn accepts_pointer(&self) -> bool {
        true
    }

    fn focusable(&self) -> bool {
        self.message.is_some()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use denise::theme;

    #[test]
    fn the_header_height_is_the_folded_height() {
        let c: Collapse<usize> = Collapse::new("Nettverk", |open| open as usize);
        assert_eq!(
            c.header_height(&theme::DARK),
            theme::DARK.metrics.size_field
        );
        assert!(c.is_open());
        assert!(
            !Collapse::<usize>::new("x", |o| o as usize)
                .closed()
                .is_open()
        );
    }

    #[test]
    fn the_expanded_height_floor_is_zero() {
        let c: Collapse<usize> = Collapse::new("x", |o| o as usize).with_expanded_height(-40);
        assert_eq!(c.expanded_height(), Some(0));
    }

    #[test]
    fn a_collapse_without_a_listener_is_not_a_tab_stop() {
        let mut c: Collapse<usize> = Collapse::new("x", |o| o as usize);
        assert!(Widget::<usize>::focusable(&c));
        c.message = None;
        assert!(!Widget::<usize>::focusable(&c));
    }
}