Skip to main content

glory_render/
anchor.rs

1use crate::{Error, Rect};
2
3/// Physical viewport side; independent of document writing direction.
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum AnchorSide {
6    Top,
7    #[default]
8    Bottom,
9    Left,
10    Right,
11}
12impl AnchorSide {
13    pub fn as_str(self) -> &'static str {
14        match self {
15            Self::Top => "top",
16            Self::Bottom => "bottom",
17            Self::Left => "left",
18            Self::Right => "right",
19        }
20    }
21    fn opposite(self) -> Self {
22        match self {
23            Self::Top => Self::Bottom,
24            Self::Bottom => Self::Top,
25            Self::Left => Self::Right,
26            Self::Right => Self::Left,
27        }
28    }
29}
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum AnchorAlign {
32    #[default]
33    Start,
34    Center,
35    End,
36}
37/// Finite arrow placement within the resolved panel edge.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub enum AnchorArrowPosition {
40    /// Point at the physical center of the live anchor, clamped inside the panel.
41    #[default]
42    Center,
43    /// Keep a fixed inset from the aligned panel edge.
44    Side,
45}
46
47/// Host-rendered anchored-layer arrow, in viewport CSS pixels.
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct AnchorArrow {
50    pub size: f64,
51    pub radius: f64,
52    pub offset: f64,
53    pub position: AnchorArrowPosition,
54}
55impl Default for AnchorArrow {
56    fn default() -> Self {
57        Self {
58            size: 8.0,
59            radius: 1.0,
60            offset: 10.0,
61            position: AnchorArrowPosition::Center,
62        }
63    }
64}
65impl AnchorArrow {
66    pub fn validate(self) -> Result<(), Error> {
67        if [self.size, self.radius, self.offset]
68            .iter()
69            .any(|value| !value.is_finite() || !(0.0..=4096.0).contains(value))
70            || self.size == 0.0
71            || self.radius > self.size / 2.0
72        {
73            return Err(Error::InvalidProps(
74                "anchor arrow size, radius and offset must be finite; size must be positive and radius no greater than half the size",
75            ));
76        }
77        Ok(())
78    }
79}
80impl AnchorAlign {
81    pub fn as_str(self) -> &'static str {
82        match self {
83            Self::Start => "start",
84            Self::Center => "center",
85            Self::End => "end",
86        }
87    }
88}
89/// Finite anchored-layer policy, in viewport CSS pixels. Flip compares the
90/// requested and opposite side; shift clamps both axes to viewport padding.
91/// Neither policy changes the declared side or the logical anchor relation.
92#[derive(Clone, Copy, Debug, PartialEq)]
93pub struct AnchorPlacement {
94    pub side: AnchorSide,
95    pub align: AnchorAlign,
96    pub gap: f64,
97    pub viewport_padding: f64,
98    pub flip: bool,
99    pub shift: bool,
100    /// Size the panel border box to the live anchor width before placement.
101    pub match_width: bool,
102    /// Render a host-owned arrow using the collision-resolved side.
103    pub arrow: Option<AnchorArrow>,
104}
105impl Default for AnchorPlacement {
106    fn default() -> Self {
107        Self::new(AnchorSide::Bottom, AnchorAlign::Start)
108    }
109}
110impl AnchorPlacement {
111    pub const fn new(side: AnchorSide, align: AnchorAlign) -> Self {
112        Self {
113            side,
114            align,
115            gap: 6.0,
116            viewport_padding: 8.0,
117            flip: true,
118            shift: true,
119            match_width: false,
120            arrow: None,
121        }
122    }
123    pub const fn gap(mut self, value: f64) -> Self {
124        self.gap = value;
125        self
126    }
127    pub fn validate(self) -> Result<(), Error> {
128        if [self.gap, self.viewport_padding]
129            .iter()
130            .any(|v| !v.is_finite() || !(0.0..=4096.0).contains(v))
131        {
132            return Err(Error::InvalidProps(
133                "anchor gap and viewport padding must be finite and within 4096 CSS pixels",
134            ));
135        }
136        if let Some(arrow) = self.arrow {
137            arrow.validate()?;
138        }
139        Ok(())
140    }
141    /// Pure finite geometry. `panel` contributes dimensions only. The host
142    /// supplies the current anchor, including any pending ancestor-layer delta.
143    pub fn resolve(
144        self,
145        anchor: Rect,
146        panel: Rect,
147        viewport: Rect,
148    ) -> Result<AnchorPosition, Error> {
149        self.validate()?;
150        for rect in [anchor, panel, viewport] {
151            if ![
152                rect.x,
153                rect.y,
154                rect.width,
155                rect.height,
156                rect.x + rect.width,
157                rect.y + rect.height,
158            ]
159            .iter()
160            .all(|v| v.is_finite())
161                || rect.width < 0.0
162                || rect.height < 0.0
163            {
164                return Err(Error::InvalidProps(
165                    "anchor geometry must be finite with nonnegative dimensions",
166                ));
167            }
168        }
169        let candidate = |side| {
170            let vertical = matches!(side, AnchorSide::Top | AnchorSide::Bottom);
171            let (start, extent, size) = if vertical {
172                (anchor.x, anchor.width, panel.width)
173            } else {
174                (anchor.y, anchor.height, panel.height)
175            };
176            let cross = match self.align {
177                AnchorAlign::Start => start,
178                AnchorAlign::Center => start + (extent - size) / 2.0,
179                AnchorAlign::End => start + extent - size,
180            };
181            let (x, y) = match side {
182                AnchorSide::Top => (cross, anchor.y - panel.height - self.gap),
183                AnchorSide::Bottom => (cross, anchor.y + anchor.height + self.gap),
184                AnchorSide::Left => (anchor.x - panel.width - self.gap, cross),
185                AnchorSide::Right => (anchor.x + anchor.width + self.gap, cross),
186            };
187            AnchorPosition { x, y, side }
188        };
189        let min_x = viewport.x + self.viewport_padding;
190        let min_y = viewport.y + self.viewport_padding;
191        let max_x = viewport.x + viewport.width - self.viewport_padding;
192        let max_y = viewport.y + viewport.height - self.viewport_padding;
193        let overflow = |p: AnchorPosition| {
194            (min_x - p.x).max(0.0)
195                + (p.x + panel.width - max_x).max(0.0)
196                + (min_y - p.y).max(0.0)
197                + (p.y + panel.height - max_y).max(0.0)
198        };
199        let mut result = candidate(self.side);
200        let opposite = candidate(self.side.opposite());
201        if ![
202            result.x,
203            result.y,
204            opposite.x,
205            opposite.y,
206            min_x,
207            min_y,
208            max_x,
209            max_y,
210            overflow(result),
211            overflow(opposite),
212        ]
213        .iter()
214        .all(|v| v.is_finite())
215        {
216            return Err(Error::InvalidProps("anchor geometry arithmetic overflow"));
217        }
218        if self.flip && overflow(opposite) < overflow(result) {
219            result = opposite;
220        }
221        if self.shift {
222            result.x = result.x.clamp(min_x, (max_x - panel.width).max(min_x));
223            result.y = result.y.clamp(min_y, (max_y - panel.height).max(min_y));
224        }
225        Ok(result)
226    }
227}
228#[derive(Clone, Copy, Debug, PartialEq)]
229pub struct AnchorPosition {
230    pub x: f64,
231    pub y: f64,
232    pub side: AnchorSide,
233}