summaryrefslogtreecommitdiff
path: root/src/library/layout/place.rs
blob: e74776db4e3533eabe3e52633e676c3cb53597cc (plain) (blame)
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
use super::AlignNode;
use crate::library::prelude::*;

/// Place a node at an absolute position.
#[derive(Debug, Hash)]
pub struct PlaceNode(pub LayoutNode);

#[node]
impl PlaceNode {
    fn construct(_: &mut Context, args: &mut Args) -> TypResult<Content> {
        let aligns = args.find()?.unwrap_or(Spec::with_x(Some(RawAlign::Start)));
        let dx = args.named("dx")?.unwrap_or_default();
        let dy = args.named("dy")?.unwrap_or_default();
        let body: LayoutNode = args.expect("body")?;
        Ok(Content::block(Self(
            body.moved(Spec::new(dx, dy)).aligned(aligns),
        )))
    }
}

impl Layout for PlaceNode {
    fn layout(
        &self,
        ctx: &mut Context,
        regions: &Regions,
        styles: StyleChain,
    ) -> TypResult<Vec<Arc<Frame>>> {
        let out_of_flow = self.out_of_flow();

        // The pod is the base area of the region because for absolute
        // placement we don't really care about the already used area.
        let pod = {
            let finite = regions.base.map(Length::is_finite);
            let expand = finite & (regions.expand | out_of_flow);
            Regions::one(regions.base, regions.base, expand)
        };

        let mut frames = self.0.layout(ctx, &pod, styles)?;

        // If expansion is off, zero all sizes so that we don't take up any
        // space in our parent. Otherwise, respect the expand settings.
        let frame = &mut frames[0];
        let target = regions.expand.select(regions.first, Size::zero());
        Arc::make_mut(frame).resize(target, Align::LEFT_TOP);

        Ok(frames)
    }
}

impl PlaceNode {
    /// Whether this node wants to be placed relative to its its parent's base
    /// origin. Instead of relative to the parent's current flow/cursor
    /// position.
    pub fn out_of_flow(&self) -> bool {
        self.0
            .downcast::<AlignNode>()
            .map_or(false, |node| node.aligns.y.is_some())
    }
}