Skip to main content

lichtung_plot/layout/
position.rs

1use crate::{Error, Result};
2
3/// One physical object-position component, resolved in CSS pixels.
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub struct PositionComponent {
6    fraction: f64,
7    offset: f64,
8}
9
10impl PositionComponent {
11    /// A percentage of the difference between frame and object size.
12    pub fn percent(value: f64) -> Result<Self> {
13        Self::new(value / 100., 0.)
14    }
15
16    /// An offset from the leading edge, in CSS pixels.
17    pub fn px(value: f64) -> Result<Self> {
18        Self::new(0., value)
19    }
20
21    /// Combine a fractional alignment with a CSS-pixel offset.
22    pub fn new(fraction: f64, offset: f64) -> Result<Self> {
23        if !fraction.is_finite() || !offset.is_finite() {
24            return Err(Error::Data("object position must be finite".into()));
25        }
26        Ok(Self { fraction, offset })
27    }
28
29    pub(crate) const fn aligned(fraction: f64) -> Self {
30        Self {
31            fraction,
32            offset: 0.,
33        }
34    }
35
36    pub(crate) fn components(self) -> (f64, f64) {
37        (self.fraction, self.offset)
38    }
39
40    pub(crate) fn resolve(self, spare: f64) -> f64 {
41        self.fraction * spare + self.offset
42    }
43}