plushie-core 0.4.0

Extension SDK for Plushie
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
//! Custom overlay widget: renders first child as anchor, second child as an
//! overlay positioned relative to the anchor bounds.
//!
//! Modelled after iced's tooltip widget but without hover delay or container
//! styling -- the overlay is always visible and the caller controls content.

use crate::message::Message;

use iced::advanced::Shell;
use iced::advanced::layout::{self, Layout};
use iced::advanced::overlay;
use iced::advanced::renderer;
use iced::advanced::widget::{self, Widget};
use iced::{Element, Event, Length, Point, Rectangle, Size, Vector};

/// Overlay position relative to the anchor widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Position {
    Below,
    Above,
    Left,
    Right,
}

/// Cross-axis alignment of the overlay content relative to the anchor.
///
/// For `Below`/`Above` positions, this controls horizontal alignment.
/// For `Left`/`Right` positions, this controls vertical alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum Align {
    /// Align to the start edge (left for Below/Above, top for Left/Right).
    Start,
    /// Center on the cross-axis (default).
    #[default]
    Center,
    /// Align to the end edge (right for Below/Above, bottom for Left/Right).
    End,
}

/// A widget that renders its anchor child normally and displays its overlay
/// child as an iced overlay positioned relative to the anchor.
///
/// # Focus and accessibility
///
/// Both the anchor and content children participate in `operate()` so
/// that focus cycling (Tab/Shift+Tab) can reach widgets inside the
/// overlay content and the accessibility tree includes both subtrees.
///
/// When `a11y.modal = true` is set on the overlay node, the host is
/// responsible for focus trapping (restricting Tab navigation to the
/// overlay content). plushie does not implement iced-level focus
/// interception, so modal overlays rely on the host SDK to manage
/// focus boundaries -- typically by intercepting focus_next/focus_previous
/// events and redirecting focus back into the overlay.
pub(crate) struct OverlayWrapper<'a> {
    anchor: Element<'a, Message>,
    content: Element<'a, Message>,
    position: Position,
    gap: f32,
    offset_x: f32,
    offset_y: f32,
    /// When true, auto-flip the position (Below<->Above, Left<->Right)
    /// when the content would overflow the viewport in the primary axis.
    flip: bool,
    /// Cross-axis alignment of the content relative to the anchor.
    align: Align,
}

impl<'a> OverlayWrapper<'a> {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        anchor: Element<'a, Message>,
        content: Element<'a, Message>,
        position: Position,
        gap: f32,
        offset_x: f32,
        offset_y: f32,
        flip: bool,
        align: Align,
    ) -> Self {
        Self {
            anchor,
            content,
            position,
            gap,
            offset_x,
            offset_y,
            flip,
            align,
        }
    }
}

impl Widget<Message, iced::Theme, iced::Renderer> for OverlayWrapper<'_> {
    fn children(&self) -> Vec<widget::Tree> {
        vec![
            widget::Tree::new(&self.anchor),
            widget::Tree::new(&self.content),
        ]
    }

    fn diff(&self, tree: &mut widget::Tree) {
        tree.diff_children(&[self.anchor.as_widget(), self.content.as_widget()]);
    }

    fn size(&self) -> Size<Length> {
        self.anchor.as_widget().size()
    }

    fn size_hint(&self) -> Size<Length> {
        self.anchor.as_widget().size_hint()
    }

    fn layout(
        &mut self,
        tree: &mut widget::Tree,
        renderer: &iced::Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        self.anchor
            .as_widget_mut()
            .layout(&mut tree.children[0], renderer, limits)
    }

    fn draw(
        &self,
        tree: &widget::Tree,
        renderer: &mut iced::Renderer,
        theme: &iced::Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: iced::mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.anchor.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            style,
            layout,
            cursor,
            viewport,
        );
    }

    fn update(
        &mut self,
        tree: &mut widget::Tree,
        event: &Event,
        layout: Layout<'_>,
        cursor: iced::mouse::Cursor,
        renderer: &iced::Renderer,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) {
        self.anchor.as_widget_mut().update(
            &mut tree.children[0],
            event,
            layout,
            cursor,
            renderer,
            shell,
            viewport,
        );
    }

    fn mouse_interaction(
        &self,
        tree: &widget::Tree,
        layout: Layout<'_>,
        cursor: iced::mouse::Cursor,
        viewport: &Rectangle,
        renderer: &iced::Renderer,
    ) -> iced::mouse::Interaction {
        self.anchor.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor,
            viewport,
            renderer,
        )
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut widget::Tree,
        layout: Layout<'b>,
        renderer: &iced::Renderer,
        viewport: &Rectangle,
        translation: Vector,
    ) -> Option<overlay::Element<'b, Message, iced::Theme, iced::Renderer>> {
        let mut children = tree.children.iter_mut();
        let anchor_tree = children
            .next()
            .expect("OverlayWrapper must have anchor tree child");
        let content_tree = children
            .next()
            .expect("OverlayWrapper must have content tree child");

        // Collect any overlay from the anchor child itself.
        let anchor_overlay = self.anchor.as_widget_mut().overlay(
            anchor_tree,
            layout,
            renderer,
            viewport,
            translation,
        );

        let content_overlay = overlay::Element::new(Box::new(OverlayContent {
            content: &mut self.content,
            tree: content_tree,
            position: self.position,
            gap: self.gap,
            offset_x: self.offset_x,
            offset_y: self.offset_y,
            flip: self.flip,
            align: self.align,
            anchor_bounds: layout.bounds(),
            translation,
        }));

        // If the anchor also produces overlays, group them together.
        Some(
            overlay::Group::with_children(
                anchor_overlay
                    .into_iter()
                    .chain(Some(content_overlay))
                    .collect(),
            )
            .overlay(),
        )
    }

    fn operate(
        &mut self,
        tree: &mut widget::Tree,
        layout: Layout<'_>,
        renderer: &iced::Renderer,
        operation: &mut dyn widget::Operation,
    ) {
        // Forward to the anchor child (the widget the overlay is attached to).
        self.anchor
            .as_widget_mut()
            .operate(&mut tree.children[0], layout, renderer, operation);

        // Forward to the content child so overlay widgets participate in
        // focus cycling and the accessibility tree. The content child uses
        // the anchor layout as a stand-in here; its true position is
        // determined by the overlay system during rendering. This ensures
        // that operations like focus_next and accessible tree traversal
        // include widgets inside the overlay content.
        self.content
            .as_widget_mut()
            .operate(&mut tree.children[1], layout, renderer, operation);
    }
}

impl<'a> From<OverlayWrapper<'a>> for Element<'a, Message> {
    fn from(wrapper: OverlayWrapper<'a>) -> Self {
        Element::new(wrapper)
    }
}

// ---------------------------------------------------------------------------
// Overlay content (the piece that floats above everything)
// ---------------------------------------------------------------------------

/// The floating overlay piece. Positioned relative to the anchor bounds
/// and clamped to the viewport edges.
struct OverlayContent<'a, 'b> {
    content: &'b mut Element<'a, Message>,
    tree: &'b mut widget::Tree,
    position: Position,
    gap: f32,
    offset_x: f32,
    offset_y: f32,
    flip: bool,
    align: Align,
    anchor_bounds: Rectangle,
    translation: Vector,
}

/// Extract the single child layout from an overlay layout node.
fn content_layout<'a>(layout: Layout<'a>) -> Layout<'a> {
    layout
        .children()
        .next()
        .expect("overlay content must have a child layout")
}

impl overlay::Overlay<Message, iced::Theme, iced::Renderer> for OverlayContent<'_, '_> {
    fn layout(&mut self, renderer: &iced::Renderer, bounds: Size) -> layout::Node {
        let limits = layout::Limits::new(Size::ZERO, bounds);
        let content_layout = self
            .content
            .as_widget_mut()
            .layout(self.tree, renderer, &limits);
        let content_size = content_layout.bounds().size();

        // Anchor position in absolute coordinates (accounting for translation).
        let anchor = Rectangle {
            x: self.anchor_bounds.x + self.translation.x,
            y: self.anchor_bounds.y + self.translation.y,
            width: self.anchor_bounds.width,
            height: self.anchor_bounds.height,
        };

        // Determine effective position (may flip if content overflows).
        let position = if self.flip {
            match self.position {
                Position::Below => {
                    let below_y = anchor.y + anchor.height + self.gap;
                    if below_y + content_size.height > bounds.height {
                        let above_y = anchor.y - content_size.height - self.gap;
                        if above_y >= 0.0 {
                            Position::Above
                        } else {
                            Position::Below // neither fits, keep original
                        }
                    } else {
                        Position::Below
                    }
                }
                Position::Above => {
                    let above_y = anchor.y - content_size.height - self.gap;
                    if above_y < 0.0 {
                        let below_y = anchor.y + anchor.height + self.gap;
                        if below_y + content_size.height <= bounds.height {
                            Position::Below
                        } else {
                            Position::Above
                        }
                    } else {
                        Position::Above
                    }
                }
                Position::Left => {
                    let left_x = anchor.x - content_size.width - self.gap;
                    if left_x < 0.0 {
                        let right_x = anchor.x + anchor.width + self.gap;
                        if right_x + content_size.width <= bounds.width {
                            Position::Right
                        } else {
                            Position::Left
                        }
                    } else {
                        Position::Left
                    }
                }
                Position::Right => {
                    let right_x = anchor.x + anchor.width + self.gap;
                    if right_x + content_size.width > bounds.width {
                        let left_x = anchor.x - content_size.width - self.gap;
                        if left_x >= 0.0 {
                            Position::Left
                        } else {
                            Position::Right
                        }
                    } else {
                        Position::Right
                    }
                }
            }
        } else {
            self.position
        };

        // Cross-axis alignment.
        let cross_h = match self.align {
            Align::Start => anchor.x,
            Align::Center => anchor.x + (anchor.width - content_size.width) / 2.0,
            Align::End => anchor.x + anchor.width - content_size.width,
        };
        let cross_v = match self.align {
            Align::Start => anchor.y,
            Align::Center => anchor.y + (anchor.height - content_size.height) / 2.0,
            Align::End => anchor.y + anchor.height - content_size.height,
        };

        let (x, y) = match position {
            Position::Below => (cross_h, anchor.y + anchor.height + self.gap),
            Position::Above => (cross_h, anchor.y - content_size.height - self.gap),
            Position::Left => (anchor.x - content_size.width - self.gap, cross_v),
            Position::Right => (anchor.x + anchor.width + self.gap, cross_v),
        };

        // Viewport clamping (last resort after flip + align + offsets).
        let final_x = (x + self.offset_x).clamp(0.0, (bounds.width - content_size.width).max(0.0));
        let final_y =
            (y + self.offset_y).clamp(0.0, (bounds.height - content_size.height).max(0.0));

        layout::Node::with_children(content_size, vec![content_layout])
            .move_to(Point::new(final_x, final_y))
    }

    fn draw(
        &self,
        renderer: &mut iced::Renderer,
        theme: &iced::Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor: iced::mouse::Cursor,
    ) {
        let content_layout = content_layout(layout);
        self.content.as_widget().draw(
            self.tree,
            renderer,
            theme,
            style,
            content_layout,
            cursor,
            &Rectangle::with_size(Size::INFINITE),
        );
    }

    fn update(
        &mut self,
        event: &Event,
        layout: Layout<'_>,
        cursor: iced::mouse::Cursor,
        renderer: &iced::Renderer,
        shell: &mut Shell<'_, Message>,
    ) {
        let content_layout = content_layout(layout);
        self.content.as_widget_mut().update(
            self.tree,
            event,
            content_layout,
            cursor,
            renderer,
            shell,
            &Rectangle::with_size(Size::INFINITE),
        );
    }

    fn mouse_interaction(
        &self,
        layout: Layout<'_>,
        cursor: iced::mouse::Cursor,
        renderer: &iced::Renderer,
    ) -> iced::mouse::Interaction {
        let viewport = Rectangle::with_size(Size::INFINITE);
        let content_layout = content_layout(layout);
        self.content.as_widget().mouse_interaction(
            self.tree,
            content_layout,
            cursor,
            &viewport,
            renderer,
        )
    }

    fn operate(
        &mut self,
        layout: Layout<'_>,
        renderer: &iced::Renderer,
        operation: &mut dyn widget::Operation,
    ) {
        let content_layout = content_layout(layout);
        self.content
            .as_widget_mut()
            .operate(self.tree, content_layout, renderer, operation);
    }

    fn overlay<'c>(
        &'c mut self,
        layout: Layout<'c>,
        renderer: &iced::Renderer,
    ) -> Option<overlay::Element<'c, Message, iced::Theme, iced::Renderer>> {
        let content_layout = content_layout(layout);
        self.content.as_widget_mut().overlay(
            self.tree,
            content_layout,
            renderer,
            &layout.bounds(),
            Vector::ZERO,
        )
    }
}

#[cfg(test)]
mod tests {
    /// Mirrors the clamping logic in OverlayContent::layout().
    fn clamp_position(
        x: f32,
        y: f32,
        content_w: f32,
        content_h: f32,
        viewport_w: f32,
        viewport_h: f32,
    ) -> (f32, f32) {
        let final_x = x.clamp(0.0, (viewport_w - content_w).max(0.0));
        let final_y = y.clamp(0.0, (viewport_h - content_h).max(0.0));
        (final_x, final_y)
    }

    #[test]
    fn clamp_within_viewport() {
        let (x, y) = clamp_position(100.0, 100.0, 50.0, 50.0, 800.0, 600.0);
        assert_eq!((x, y), (100.0, 100.0));
    }

    #[test]
    fn clamp_right_edge() {
        // Content at x=780 with width=50 would extend to 830, beyond viewport 800.
        let (x, _) = clamp_position(780.0, 100.0, 50.0, 50.0, 800.0, 600.0);
        assert_eq!(x, 750.0);
    }

    #[test]
    fn clamp_bottom_edge() {
        // Content at y=580 with height=50 would extend to 630, beyond viewport 600.
        let (_, y) = clamp_position(100.0, 580.0, 50.0, 50.0, 800.0, 600.0);
        assert_eq!(y, 550.0);
    }

    #[test]
    fn clamp_negative() {
        let (x, y) = clamp_position(-10.0, -20.0, 50.0, 50.0, 800.0, 600.0);
        assert_eq!((x, y), (0.0, 0.0));
    }

    #[test]
    fn clamp_content_larger_than_viewport() {
        // Content bigger than viewport -- best we can do is pin to origin.
        let (x, y) = clamp_position(100.0, 100.0, 900.0, 700.0, 800.0, 600.0);
        assert_eq!((x, y), (0.0, 0.0));
    }

    #[test]
    fn clamp_exact_fit() {
        // Content exactly fills viewport -- only valid position is (0, 0).
        let (x, y) = clamp_position(50.0, 50.0, 800.0, 600.0, 800.0, 600.0);
        assert_eq!((x, y), (0.0, 0.0));
    }

    #[test]
    fn clamp_zero_size_content() {
        // Zero-size content can go anywhere within the viewport.
        let (x, y) = clamp_position(400.0, 300.0, 0.0, 0.0, 800.0, 600.0);
        assert_eq!((x, y), (400.0, 300.0));
    }
}