burin 0.1.2

A Rust GUI framework built on the auralis reactive signal kernel
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
use std::rc::Rc;

use auralis_signal::Signal;

use crate::animation::Animation;
use crate::core::config::EventHandler;
use crate::core::context::MountContext;
use crate::core::element::ElementId;
use crate::core::widget::Widget;
use crate::ecs::components;
use crate::event::action::{ActionKind, ActionOutcome};
use crate::style::styled::{StyleRefinement, Styled};
use crate::style::Rect;
use crate::theme::m3::roles::{ComponentRole, DisplayRole, ResolvedComponentStyle};
use crate::widgets::shared::{mount_portal_popup, PortalPopupConfig};

// ── Positioning types ─────────────────────────────────────────────

/// Preferred position of a popover relative to its anchor.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum PopoverPosition {
    #[default]
    Bottom,
    Top,
    Left,
    Right,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CrossAxisAlignment {
    Start,
    Center,
    End,
}

impl CrossAxisAlignment {
    fn offset(&self, anchor_start: f32, anchor_size: f32, popover_size: f32) -> f32 {
        match self {
            Self::Start => anchor_start,
            Self::Center => anchor_start + (anchor_size - popover_size) * 0.5,
            Self::End => anchor_start + anchor_size - popover_size,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FlipAxes {
    Both,
    VerticalOnly,
    HorizontalOnly,
}

/// Configuration for popover positioning and auto-flip.
#[derive(Clone, Copy, Debug)]
pub struct PopoverPlacement {
    pub preferred_position: PopoverPosition,
    pub alignment: CrossAxisAlignment,
    pub gap: f32,
    pub viewport_margin: f32,
    pub auto_flip: bool,
    pub flip_axes: FlipAxes,
    pub min_width: Option<f32>,
    pub max_width: Option<f32>,
}

impl Default for PopoverPlacement {
    fn default() -> Self {
        Self {
            preferred_position: PopoverPosition::Bottom,
            alignment: CrossAxisAlignment::Start,
            gap: 4.0,
            viewport_margin: 8.0,
            auto_flip: true,
            flip_axes: FlipAxes::Both,
            min_width: None,
            max_width: None,
        }
    }
}

/// Computed screen-space position and size of a popover.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PopoverGeometry {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub actual_position: PopoverPosition,
}

// ── Positioning engine ────────────────────────────────────────────

fn fits_viewport(bounds: Rect, viewport: Rect, margin: f32) -> bool {
    bounds.x >= viewport.x + margin
        && bounds.y >= viewport.y + margin
        && bounds.x + bounds.width <= viewport.x + viewport.width - margin
        && bounds.y + bounds.height <= viewport.y + viewport.height - margin
}

fn candidate_geometry(
    pos: PopoverPosition,
    anchor: Rect,
    content_w: f32,
    content_h: f32,
    placement: &PopoverPlacement,
) -> PopoverGeometry {
    let w = content_w.max(placement.min_width.unwrap_or(0.0));
    let w = if let Some(max_w) = placement.max_width {
        w.min(max_w)
    } else {
        w
    };
    let h = content_h;

    match pos {
        PopoverPosition::Bottom => {
            let x = placement.alignment.offset(anchor.x, anchor.width, w);
            let y = anchor.y + anchor.height + placement.gap;
            PopoverGeometry {
                x,
                y,
                width: w,
                height: h,
                actual_position: PopoverPosition::Bottom,
            }
        }
        PopoverPosition::Top => {
            let x = placement.alignment.offset(anchor.x, anchor.width, w);
            let y = anchor.y - h - placement.gap;
            PopoverGeometry {
                x,
                y,
                width: w,
                height: h,
                actual_position: PopoverPosition::Top,
            }
        }
        PopoverPosition::Right => {
            let x = anchor.x + anchor.width + placement.gap;
            let y = placement.alignment.offset(anchor.y, anchor.height, h);
            PopoverGeometry {
                x,
                y,
                width: w,
                height: h,
                actual_position: PopoverPosition::Right,
            }
        }
        PopoverPosition::Left => {
            let x = anchor.x - w - placement.gap;
            let y = placement.alignment.offset(anchor.y, anchor.height, h);
            PopoverGeometry {
                x,
                y,
                width: w,
                height: h,
                actual_position: PopoverPosition::Left,
            }
        }
    }
}

fn priority_order(preferred: PopoverPosition, flip_axes: FlipAxes) -> Vec<PopoverPosition> {
    match flip_axes {
        FlipAxes::Both => match preferred {
            PopoverPosition::Bottom => vec![
                PopoverPosition::Bottom,
                PopoverPosition::Top,
                PopoverPosition::Right,
                PopoverPosition::Left,
            ],
            PopoverPosition::Top => vec![
                PopoverPosition::Top,
                PopoverPosition::Bottom,
                PopoverPosition::Right,
                PopoverPosition::Left,
            ],
            PopoverPosition::Right => vec![
                PopoverPosition::Right,
                PopoverPosition::Left,
                PopoverPosition::Bottom,
                PopoverPosition::Top,
            ],
            PopoverPosition::Left => vec![
                PopoverPosition::Left,
                PopoverPosition::Right,
                PopoverPosition::Bottom,
                PopoverPosition::Top,
            ],
        },
        FlipAxes::VerticalOnly => match preferred {
            PopoverPosition::Bottom => vec![PopoverPosition::Bottom, PopoverPosition::Top],
            PopoverPosition::Top => vec![PopoverPosition::Top, PopoverPosition::Bottom],
            _ => vec![preferred],
        },
        FlipAxes::HorizontalOnly => match preferred {
            PopoverPosition::Right => vec![PopoverPosition::Right, PopoverPosition::Left],
            PopoverPosition::Left => vec![PopoverPosition::Left, PopoverPosition::Right],
            _ => vec![preferred],
        },
    }
}

fn clamp_to_viewport(geo: PopoverGeometry, viewport: Rect, margin: f32) -> PopoverGeometry {
    let mut g = geo;
    let min_x = viewport.x + margin;
    let max_x = viewport.x + viewport.width - margin;
    let min_y = viewport.y + margin;
    let max_y = viewport.y + viewport.height - margin;
    if g.x < min_x {
        g.x = min_x;
    }
    if g.y < min_y {
        g.y = min_y;
    }
    if g.x + g.width > max_x {
        g.x = (max_x - g.width).max(min_x);
    }
    if g.y + g.height > max_y {
        g.y = (max_y - g.height).max(min_y);
    }
    g
}

pub fn compute_popover_geometry(
    anchor: Rect,
    viewport: Rect,
    content_w: f32,
    content_h: f32,
    placement: PopoverPlacement,
) -> PopoverGeometry {
    let order = if placement.auto_flip {
        priority_order(placement.preferred_position, placement.flip_axes)
    } else {
        vec![placement.preferred_position]
    };

    for &pos in &order {
        let geo = candidate_geometry(pos, anchor, content_w, content_h, &placement);
        let bounds = Rect::new(geo.x, geo.y, geo.width, geo.height);
        if fits_viewport(bounds, viewport, placement.viewport_margin) {
            return geo;
        }
    }

    let fallback = candidate_geometry(
        placement.preferred_position,
        anchor,
        content_w,
        content_h,
        &placement,
    );
    clamp_to_viewport(fallback, viewport, placement.viewport_margin)
}

// ── Popover widget ────────────────────────────────────────────────

const DEFAULT_POPOVER_WIDTH: f32 = 220.0;
const DEFAULT_MAX_WIDTH: f32 = 400.0;
const DEFAULT_CONTENT_HEIGHT: f32 = 0.0;

/// An anchored popup overlay driven by an open signal.
pub struct Popover {
    child: Option<Box<dyn Widget>>,
    content: Option<Box<dyn Widget>>,
    is_open: Signal<bool>,
    placement: PopoverPlacement,
    close_on_outside: bool,
    animate: Option<Animation>,
    on_dismiss: Option<Rc<dyn Fn()>>,
    style: StyleRefinement,
}

impl Popover {
    pub fn new(
        is_open: Signal<bool>,
        child: impl Widget + 'static,
        content: impl Widget + 'static,
    ) -> Self {
        Self {
            child: Some(Box::new(child)),
            content: Some(Box::new(content)),
            is_open,
            placement: PopoverPlacement {
                min_width: Some(DEFAULT_POPOVER_WIDTH),
                max_width: Some(DEFAULT_MAX_WIDTH),
                ..PopoverPlacement::default()
            },
            close_on_outside: true,
            animate: None,
            on_dismiss: None,
            style: StyleRefinement::default(),
        }
    }

    pub fn position(mut self, pos: PopoverPosition) -> Self {
        self.placement.preferred_position = pos;
        self
    }

    pub fn placement(mut self, placement: PopoverPlacement) -> Self {
        self.placement = placement;
        self
    }

    pub fn alignment(mut self, align: CrossAxisAlignment) -> Self {
        self.placement.alignment = align;
        self
    }

    pub fn gap(mut self, px: f32) -> Self {
        self.placement.gap = px;
        self
    }

    pub fn min_width(mut self, px: f32) -> Self {
        self.placement.min_width = Some(px);
        self
    }

    pub fn max_width(mut self, px: f32) -> Self {
        self.placement.max_width = Some(px);
        self
    }

    pub fn close_on_outside_click(mut self, v: bool) -> Self {
        self.close_on_outside = v;
        self
    }

    pub fn animation(mut self, anim: Animation) -> Self {
        self.animate = Some(anim);
        self
    }

    pub fn on_dismiss(mut self, f: impl Fn() + 'static) -> Self {
        self.on_dismiss = Some(Rc::new(f));
        self
    }
}

impl Styled for Popover {
    fn style_refinement(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl Widget for Popover {
    fn mount_box(mut self: Box<Self>, ctx: &mut MountContext<'_>) -> ElementId {
        let theme = ctx.theme;
        let _placement = self.placement;

        let popover_role = ComponentRole::Display(DisplayRole::Popover);
        let popover_resolved = theme.resolve_component(&popover_role);
        let ps = match &popover_resolved {
            ResolvedComponentStyle::Popover(s) => s.clone(),
            _ => unreachable!(),
        };

        // ── Root container ──
        let id = ctx.arena.allocate();
        ctx.preallocate(
            id,
            components::STYLE | components::LAYOUT | components::LIFECYCLE,
        );
        {
            let Some(el) = ctx.arena.get_mut(id) else {
                return id;
            };
            el.set_layout_direction(crate::core::LayoutDirection::Vertical);
        }

        // ── Mount anchor (child widget) ──
        let anchor_id = self
            .child
            .take()
            .unwrap()
            .mount_box(&mut ctx.child_with_events(id));
        ctx.arena.add_child(id, anchor_id);
        {
            let Some(el) = ctx.arena.get_mut(anchor_id) else {
                return id;
            };
            el.set_flex_shrink(0.0);
        }

        // ── Portals overlay ──
        let content_id = mount_portal_popup(
            &mut ctx.child_with_events(id),
            PortalPopupConfig {
                open: self.is_open.clone(),
                anchor_id,
                placement: self.placement,
                z_index: theme.z_index.dropdown,
                modal: true,
                dismiss_on_outside: self.close_on_outside,
                visible_height: DEFAULT_CONTENT_HEIGHT,
                animate: self.animate,
                on_open: None,
                on_close: self.on_dismiss.clone(),
                background: None,
                border_color: None,
                border_width: None,
                corner_radius: None,
                shadow: None,
                padding: None,
            },
            StyledPortalContent {
                inner: self.content.take(),
                bg: ps.background,
                border_color: ps.border_color,
                corner_radii: ps.corner_radius,
                shadow: ps.shadow,
                padding: crate::style::Padding::all(8.0),
            },
        );

        // ── Autofocus first focusable child ──
        if let Some(content_child) = ctx
            .arena
            .get(content_id)
            .and_then(|el| el.children.first().copied())
        {
            let children = ctx
                .arena
                .get(content_child)
                .map(|el| el.children.clone())
                .unwrap_or_default();
            for &child_id in &children {
                if ctx.arena.get(child_id).is_some_and(|el| el.is_focusable()) {
                    if let Some(reg) = ctx.event_registry.as_mut() {
                        reg.request_autofocus(child_id);
                    }
                    break;
                }
            }
        }

        // ── Keyboard: Escape dismiss ──
        {
            let vis_cancel = self.is_open.clone();
            let events = EventHandler::new().on_action(move |action| {
                if action.kind == ActionKind::Cancel {
                    vis_cancel.set(false);
                    ActionOutcome::Consumed
                } else {
                    ActionOutcome::Unhandled
                }
            });
            if let Some(reg) = ctx.event_registry.as_mut() {
                events.register_all(reg, content_id);
            }
        }

        id
    }
}

struct StyledPortalContent {
    inner: Option<Box<dyn Widget>>,
    bg: crate::style::Color,
    border_color: crate::style::Color,
    corner_radii: crate::style::CornerRadii,
    shadow: Option<crate::style::styled::Shadow>,
    padding: crate::style::Padding,
}

impl Widget for StyledPortalContent {
    fn mount_box(mut self: Box<Self>, ctx: &mut MountContext<'_>) -> ElementId {
        let id = ctx.arena.allocate();
        ctx.preallocate(id, components::STYLE | components::LAYOUT);
        {
            let Some(el) = ctx.arena.get_mut(id) else {
                return id;
            };
            el.set_background(self.bg);
            el.set_border_width(1.0);
            el.set_border_color(self.border_color);
            el.set_corner_radii(self.corner_radii);
            if let Some(ref s) = self.shadow {
                el.set_shadow(Some(*s));
            }
            el.set_padding(self.padding);
            el.set_flex_shrink(0.0);
            el.set_layout_direction(crate::core::LayoutDirection::Vertical);
        }
        let inner_id = self
            .inner
            .take()
            .unwrap()
            .mount_box(&mut ctx.child_with_events(id));
        ctx.arena.add_child(id, inner_id);
        id
    }
}

impl std::fmt::Debug for Popover {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Popover")
            .field("placement", &self.placement)
            .finish_non_exhaustive()
    }
}