nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
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
//! Zero-allocation pure-Rust anchored overlay collision-flipping, viewport clamping,
//! auto-sizing, arrow center tracking, and submenu safe-polygon hover corridor solver.
//!
//! Shared across `nativeview-layout` (Skia / native top-layer reconciliation), `nativeview-backend-web`
//! (CSS Anchor Positioning fallback), and `nativeview-ui` (`nativeview_ui::positioning`).

pub use nativeview_tables::tables::{Alignment, OverlayPlacement as Placement, Side};

const EPS: f32 = 1e-4;

/// 2D point in logical viewport coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Point {
    pub x: f32,
    pub y: f32,
}

impl Point {
    #[inline]
    pub const fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }

    #[inline]
    pub fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite()
    }
}

/// Axis-aligned rectangle in logical viewport coordinates.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Rect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
}

impl Rect {
    #[inline]
    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    #[inline]
    pub fn right(self) -> f32 {
        self.x + self.width
    }

    #[inline]
    pub fn bottom(self) -> f32 {
        self.y + self.height
    }

    #[inline]
    pub fn center_x(self) -> f32 {
        self.x + self.width * 0.5
    }

    #[inline]
    pub fn center_y(self) -> f32 {
        self.y + self.height * 0.5
    }

    #[inline]
    pub fn is_valid(self) -> bool {
        self.x.is_finite()
            && self.y.is_finite()
            && self.width.is_finite()
            && self.height.is_finite()
            && self.width >= 0.0
            && self.height >= 0.0
    }

    #[inline]
    pub fn contains_point(self, p: Point) -> bool {
        self.is_valid()
            && p.is_finite()
            && p.x >= self.x
            && p.x <= self.right()
            && p.y >= self.y
            && p.y <= self.bottom()
    }
}

/// Logical dimensions of an overlay panel.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Size {
    pub width: f32,
    pub height: f32,
}

impl Size {
    #[inline]
    pub const fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }
}

/// Logical viewport dimensions (`[0, width] × [0, height]`).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Viewport {
    pub width: f32,
    pub height: f32,
}

impl Viewport {
    #[inline]
    pub const fn new(width: f32, height: f32) -> Self {
        Self { width, height }
    }
}

/// Configuration for [`compute_overlay_position`].
#[derive(Debug, Clone, PartialEq)]
pub struct PositionOptions {
    pub placement: Placement,
    pub offset: f32,
    pub viewport_padding: f32,
    pub flip: bool,
    pub shift: bool,
    pub auto_size: bool,
    pub fallback_placements: Vec<Placement>,
}

impl Default for PositionOptions {
    fn default() -> Self {
        Self {
            placement: Placement::Bottom,
            offset: 8.0,
            viewport_padding: 8.0,
            flip: true,
            shift: true,
            auto_size: false,
            fallback_placements: Vec::new(),
        }
    }
}

impl PositionOptions {
    pub fn new(placement: Placement) -> Self {
        Self {
            placement,
            ..Self::default()
        }
    }

    pub fn with_offset(mut self, offset: f32) -> Self {
        self.offset = offset;
        self
    }

    pub fn with_viewport_padding(mut self, padding: f32) -> Self {
        self.viewport_padding = padding;
        self
    }

    pub fn with_flip(mut self, flip: bool) -> Self {
        self.flip = flip;
        self
    }

    pub fn with_shift(mut self, shift: bool) -> Self {
        self.shift = shift;
        self
    }

    pub fn with_auto_size(mut self, auto_size: bool) -> Self {
        self.auto_size = auto_size;
        self
    }

    pub fn with_fallbacks(mut self, fallbacks: Vec<Placement>) -> Self {
        self.fallback_placements = fallbacks;
        self
    }
}

/// Resolved overlay coordinates, placement, arrow offset, and size constraints.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ComputedPosition {
    pub x: f32,
    pub y: f32,
    pub placement: Placement,
    pub arrow_x: Option<f32>,
    pub arrow_y: Option<f32>,
    pub max_width: Option<f32>,
    pub max_height: Option<f32>,
    pub flipped: bool,
    pub shifted: bool,
}

#[inline]
fn sanitize_non_neg(v: f32) -> f32 {
    if v.is_finite() { v.max(0.0) } else { 0.0 }
}

#[inline]
fn sanitize_finite(v: f32) -> f32 {
    if v.is_finite() { v } else { 0.0 }
}

#[inline]
fn push_unique_arr<const N: usize>(buf: &mut [Placement; N], len: &mut usize, p: Placement) {
    if *len < N && !buf[..*len].contains(&p) {
        buf[*len] = p;
        *len += 1;
    }
}

#[derive(Clone, Copy)]
struct SolverCtx {
    anchor: Rect,
    overlay: Size,
    offset: f32,
    vp_w: f32,
    vp_h: f32,
    pad_x: f32,
    pad_y: f32,
}

impl SolverCtx {
    fn raw_coords(self, size: Size, placement: Placement) -> (f32, f32) {
        let x = match placement.side() {
            Side::Left => self.anchor.x - self.offset - size.width,
            Side::Right => self.anchor.right() + self.offset,
            Side::Top | Side::Bottom => match placement.alignment() {
                Alignment::Start => self.anchor.x,
                Alignment::Center => self.anchor.x + (self.anchor.width - size.width) * 0.5,
                Alignment::End => self.anchor.right() - size.width,
            },
        };
        let y = match placement.side() {
            Side::Top => self.anchor.y - self.offset - size.height,
            Side::Bottom => self.anchor.bottom() + self.offset,
            Side::Left | Side::Right => match placement.alignment() {
                Alignment::Start => self.anchor.y,
                Alignment::Center => self.anchor.y + (self.anchor.height - size.height) * 0.5,
                Alignment::End => self.anchor.bottom() - size.height,
            },
        };
        (x, y)
    }

    fn available_main_space(self, side: Side) -> f32 {
        let usable_w = (self.vp_w - 2.0 * self.pad_x).max(0.0);
        let usable_h = (self.vp_h - 2.0 * self.pad_y).max(0.0);
        match side {
            Side::Top => (self.anchor.y - self.offset - self.pad_y).clamp(0.0, usable_h),
            Side::Bottom => ((self.vp_h - self.pad_y) - (self.anchor.bottom() + self.offset))
                .clamp(0.0, usable_h),
            Side::Left => (self.anchor.x - self.offset - self.pad_x).clamp(0.0, usable_w),
            Side::Right => ((self.vp_w - self.pad_x) - (self.anchor.right() + self.offset))
                .clamp(0.0, usable_w),
        }
    }

    fn overflows(self, placement: Placement) -> (f32, f32) {
        let (x, y) = self.raw_coords(self.overlay, placement);
        let left_ov = (self.pad_x - x).max(0.0);
        let right_ov = ((x + self.overlay.width) - (self.vp_w - self.pad_x)).max(0.0);
        let top_ov = (self.pad_y - y).max(0.0);
        let bottom_ov = ((y + self.overlay.height) - (self.vp_h - self.pad_y)).max(0.0);
        let main_ov = if placement.side().is_vertical() {
            top_ov + bottom_ov
        } else {
            left_ov + right_ov
        };
        let cross_ov = if placement.side().is_vertical() {
            left_ov + right_ov
        } else {
            top_ov + bottom_ov
        };
        (main_ov, cross_ov)
    }

    fn select_placement(self, primary: &[Placement], cross: &[Placement], shift: bool) -> Placement {
        // 1. Exact fit in primary tier (normal fit, single-axis flip, or corner double-flip).
        for &c in primary {
            let (m, x) = self.overflows(c);
            if m <= EPS && x <= EPS {
                return c;
            }
        }
        // 2. Main-axis fit in primary tier when cross-axis shifting is enabled.
        if shift {
            for &c in primary {
                if self.overflows(c).0 <= EPS {
                    return c;
                }
            }
        }
        // 3. Cross-axis tier: exact fit, then main-axis fit when shifting is enabled.
        for &c in cross {
            let (m, x) = self.overflows(c);
            if m <= EPS && x <= EPS {
                return c;
            }
        }
        if shift {
            for &c in cross {
                if self.overflows(c).0 <= EPS {
                    return c;
                }
            }
        }
        // 4. Tiny viewport fallback: pick candidate with maximum available main-axis space.
        let mut best = primary[0];
        let mut best_space = self.available_main_space(best.side());
        let mut best_cross = self.overflows(best).1;
        for &c in primary.iter().chain(cross.iter()).skip(1) {
            let space = self.available_main_space(c.side());
            let cross_ov = self.overflows(c).1;
            if space > best_space + EPS
                || ((space - best_space).abs() <= EPS && cross_ov + EPS < best_cross)
            {
                best = c;
                best_space = space;
                best_cross = cross_ov;
            }
        }
        best
    }

    /// Zero-allocation candidate selection using fixed stack arrays (`[Placement; 12]`).
    fn pick_placement(self, options: &PositionOptions) -> Placement {
        let req = options.placement;
        if !options.flip {
            return req;
        }
        if !options.fallback_placements.is_empty() {
            let mut candidates = [req; 12];
            let mut len = 0usize;
            push_unique_arr(&mut candidates, &mut len, req);
            for &fb in &options.fallback_placements {
                push_unique_arr(&mut candidates, &mut len, fb);
            }
            return self.select_placement(&candidates[..len], &[], options.shift);
        }
        let mut primary = [req; 12];
        let mut primary_len = 0usize;
        push_unique_arr(&mut primary, &mut primary_len, req);
        push_unique_arr(&mut primary, &mut primary_len, req.opposite());
        push_unique_arr(&mut primary, &mut primary_len, req.flip_alignment());
        push_unique_arr(&mut primary, &mut primary_len, req.opposite().flip_alignment());

        let cross_sides = if req.side().is_vertical() {
            [Side::Right, Side::Left]
        } else {
            [Side::Bottom, Side::Top]
        };
        let mut cross = [req; 12];
        let mut cross_len = 0usize;
        for side in cross_sides {
            push_unique_arr(
                &mut cross,
                &mut cross_len,
                Placement::from_side_align(side, req.alignment()),
            );
            push_unique_arr(
                &mut cross,
                &mut cross_len,
                Placement::from_side_align(side, req.alignment().opposite()),
            );
        }
        self.select_placement(&primary[..primary_len], &cross[..cross_len], options.shift)
    }
}

/// Computes the collision-flipped, viewport-clamped, optionally auto-sized position and arrow
/// offset for an overlay anchored to `anchor` within `viewport` with **0 heap allocations**.
pub fn compute_overlay_position(
    anchor: Rect,
    overlay: Size,
    viewport: Viewport,
    options: &PositionOptions,
) -> ComputedPosition {
    let vp_w = sanitize_non_neg(viewport.width);
    let vp_h = sanitize_non_neg(viewport.height);
    let raw_pad = sanitize_non_neg(options.viewport_padding);
    let ctx = SolverCtx {
        anchor: Rect::new(
            sanitize_finite(anchor.x),
            sanitize_finite(anchor.y),
            sanitize_non_neg(anchor.width),
            sanitize_non_neg(anchor.height),
        ),
        overlay: Size::new(
            sanitize_non_neg(overlay.width),
            sanitize_non_neg(overlay.height),
        ),
        offset: sanitize_finite(options.offset),
        vp_w,
        vp_h,
        pad_x: raw_pad.min(vp_w * 0.5),
        pad_y: raw_pad.min(vp_h * 0.5),
    };

    let chosen = ctx.pick_placement(options);
    let flipped = chosen != options.placement;

    let (max_width, max_height, eff_size) = if options.auto_size {
        let avail_main = ctx.available_main_space(chosen.side());
        let avail_w = if chosen.side().is_vertical() {
            (ctx.vp_w - 2.0 * ctx.pad_x).max(0.0)
        } else {
            avail_main
        };
        let avail_h = if chosen.side().is_vertical() {
            avail_main
        } else {
            (ctx.vp_h - 2.0 * ctx.pad_y).max(0.0)
        };
        (
            Some(avail_w),
            Some(avail_h),
            Size::new(ctx.overlay.width.min(avail_w), ctx.overlay.height.min(avail_h)),
        )
    } else {
        (None, None, ctx.overlay)
    };

    let (mut x, mut y) = ctx.raw_coords(eff_size, chosen);
    let mut shifted = false;

    if options.shift {
        let max_x = (ctx.vp_w - ctx.pad_x - eff_size.width).max(ctx.pad_x);
        let clamped_x = x.clamp(ctx.pad_x, max_x);
        if (clamped_x - x).abs() > EPS {
            x = clamped_x;
            shifted = true;
        }
        let max_y = (ctx.vp_h - ctx.pad_y - eff_size.height).max(ctx.pad_y);
        let clamped_y = y.clamp(ctx.pad_y, max_y);
        if (clamped_y - y).abs() > EPS {
            y = clamped_y;
            shifted = true;
        }
    }

    let (arrow_x, arrow_y) = if chosen.side().is_vertical() {
        (Some((ctx.anchor.center_x() - x).clamp(0.0, eff_size.width)), None)
    } else {
        (None, Some((ctx.anchor.center_y() - y).clamp(0.0, eff_size.height)))
    };

    ComputedPosition {
        x,
        y,
        placement: chosen,
        arrow_x,
        arrow_y,
        max_width,
        max_height,
        flipped,
        shifted,
    }
}

#[inline]
fn cross_2d(a: Point, b: Point, p: Point) -> f32 {
    (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
}

#[inline]
fn point_in_triangle(p: Point, a: Point, b: Point, c: Point) -> bool {
    let (d1, d2, d3) = (cross_2d(a, b, p), cross_2d(b, c, p), cross_2d(c, a, p));
    !((d1 < -EPS || d2 < -EPS || d3 < -EPS) && (d1 > EPS || d2 > EPS || d3 > EPS))
}

/// Safe-triangle hover corridor test for cascading submenus.
pub fn point_in_safe_polygon(cursor: Point, prev_cursor: Point, submenu_rect: Rect) -> bool {
    if !submenu_rect.is_valid() || !cursor.is_finite() || !prev_cursor.is_finite() {
        return false;
    }
    if submenu_rect.contains_point(cursor) {
        return true;
    }
    if submenu_rect.contains_point(prev_cursor) {
        return false;
    }

    let tl = Point::new(submenu_rect.x, submenu_rect.y);
    let tr = Point::new(submenu_rect.right(), submenu_rect.y);
    let br = Point::new(submenu_rect.right(), submenu_rect.bottom());
    let bl = Point::new(submenu_rect.x, submenu_rect.bottom());

    let (c1, c2) = if prev_cursor.x < submenu_rect.x {
        if prev_cursor.y < submenu_rect.y {
            (tr, bl)
        } else if prev_cursor.y > submenu_rect.bottom() {
            (tl, br)
        } else {
            (tl, bl)
        }
    } else if prev_cursor.x > submenu_rect.right() {
        if prev_cursor.y < submenu_rect.y {
            (tl, br)
        } else if prev_cursor.y > submenu_rect.bottom() {
            (tr, bl)
        } else {
            (tr, br)
        }
    } else if prev_cursor.y < submenu_rect.y {
        (tl, tr)
    } else {
        (bl, br)
    };

    point_in_triangle(cursor, prev_cursor, c1, c2)
}