typst_layout/
stack.rs

1use typst_library::diag::{bail, SourceResult};
2use typst_library::engine::Engine;
3use typst_library::foundations::{Content, Packed, Resolve, StyleChain, StyledElem};
4use typst_library::introspection::{Locator, SplitLocator};
5use typst_library::layout::{
6    Abs, AlignElem, Axes, Axis, Dir, FixedAlignment, Fr, Fragment, Frame, HElem, Point,
7    Regions, Size, Spacing, StackChild, StackElem, VElem,
8};
9use typst_syntax::Span;
10use typst_utils::{Get, Numeric};
11
12/// Layout the stack.
13#[typst_macros::time(span = elem.span())]
14pub fn layout_stack(
15    elem: &Packed<StackElem>,
16    engine: &mut Engine,
17    locator: Locator,
18    styles: StyleChain,
19    regions: Regions,
20) -> SourceResult<Fragment> {
21    let mut layouter =
22        StackLayouter::new(elem.span(), elem.dir(styles), locator, styles, regions);
23
24    let axis = layouter.dir.axis();
25
26    // Spacing to insert before the next block.
27    let spacing = elem.spacing(styles);
28    let mut deferred = None;
29
30    for child in &elem.children {
31        match child {
32            StackChild::Spacing(kind) => {
33                layouter.layout_spacing(*kind);
34                deferred = None;
35            }
36            StackChild::Block(block) => {
37                // Transparently handle `h`.
38                if let (Axis::X, Some(h)) = (axis, block.to_packed::<HElem>()) {
39                    layouter.layout_spacing(h.amount);
40                    deferred = None;
41                    continue;
42                }
43
44                // Transparently handle `v`.
45                if let (Axis::Y, Some(v)) = (axis, block.to_packed::<VElem>()) {
46                    layouter.layout_spacing(v.amount);
47                    deferred = None;
48                    continue;
49                }
50
51                if let Some(kind) = deferred {
52                    layouter.layout_spacing(kind);
53                }
54
55                layouter.layout_block(engine, block, styles)?;
56                deferred = spacing;
57            }
58        }
59    }
60
61    layouter.finish()
62}
63
64/// Performs stack layout.
65struct StackLayouter<'a> {
66    /// The span to raise errors at during layout.
67    span: Span,
68    /// The stacking direction.
69    dir: Dir,
70    /// The axis of the stacking direction.
71    axis: Axis,
72    /// Provides unique locations to the stack's children.
73    locator: SplitLocator<'a>,
74    /// The inherited styles.
75    styles: StyleChain<'a>,
76    /// The regions to layout children into.
77    regions: Regions<'a>,
78    /// Whether the stack itself should expand to fill the region.
79    expand: Axes<bool>,
80    /// The initial size of the current region before we started subtracting.
81    initial: Size,
82    /// The generic size used by the frames for the current region.
83    used: GenericSize<Abs>,
84    /// The sum of fractions in the current region.
85    fr: Fr,
86    /// Already layouted items whose exact positions are not yet known due to
87    /// fractional spacing.
88    items: Vec<StackItem>,
89    /// Finished frames for previous regions.
90    finished: Vec<Frame>,
91}
92
93/// A prepared item in a stack layout.
94enum StackItem {
95    /// Absolute spacing between other items.
96    Absolute(Abs),
97    /// Fractional spacing between other items.
98    Fractional(Fr),
99    /// A frame for a layouted block.
100    Frame(Frame, Axes<FixedAlignment>),
101}
102
103impl<'a> StackLayouter<'a> {
104    /// Create a new stack layouter.
105    fn new(
106        span: Span,
107        dir: Dir,
108        locator: Locator<'a>,
109        styles: StyleChain<'a>,
110        mut regions: Regions<'a>,
111    ) -> Self {
112        let axis = dir.axis();
113        let expand = regions.expand;
114
115        // Disable expansion along the block axis for children.
116        regions.expand.set(axis, false);
117
118        Self {
119            span,
120            dir,
121            axis,
122            locator: locator.split(),
123            styles,
124            regions,
125            expand,
126            initial: regions.size,
127            used: GenericSize::zero(),
128            fr: Fr::zero(),
129            items: vec![],
130            finished: vec![],
131        }
132    }
133
134    /// Add spacing along the spacing direction.
135    fn layout_spacing(&mut self, spacing: Spacing) {
136        match spacing {
137            Spacing::Rel(v) => {
138                // Resolve the spacing and limit it to the remaining space.
139                let resolved = v
140                    .resolve(self.styles)
141                    .relative_to(self.regions.base().get(self.axis));
142                let remaining = self.regions.size.get_mut(self.axis);
143                let limited = resolved.min(*remaining);
144                if self.dir.axis() == Axis::Y {
145                    *remaining -= limited;
146                }
147                self.used.main += limited;
148                self.items.push(StackItem::Absolute(resolved));
149            }
150            Spacing::Fr(v) => {
151                self.fr += v;
152                self.items.push(StackItem::Fractional(v));
153            }
154        }
155    }
156
157    /// Layout an arbitrary block.
158    fn layout_block(
159        &mut self,
160        engine: &mut Engine,
161        block: &Content,
162        styles: StyleChain,
163    ) -> SourceResult<()> {
164        if self.regions.is_full() {
165            self.finish_region()?;
166        }
167
168        // Block-axis alignment of the `AlignElem` is respected by stacks.
169        let align = if let Some(align) = block.to_packed::<AlignElem>() {
170            align.alignment(styles)
171        } else if let Some(styled) = block.to_packed::<StyledElem>() {
172            AlignElem::alignment_in(styles.chain(&styled.styles))
173        } else {
174            AlignElem::alignment_in(styles)
175        }
176        .resolve(styles);
177
178        let fragment = crate::layout_fragment(
179            engine,
180            block,
181            self.locator.next(&block.span()),
182            styles,
183            self.regions,
184        )?;
185
186        let len = fragment.len();
187        for (i, frame) in fragment.into_iter().enumerate() {
188            // Grow our size, shrink the region and save the frame for later.
189            let specific_size = frame.size();
190            if self.dir.axis() == Axis::Y {
191                self.regions.size.y -= specific_size.y;
192            }
193
194            let generic_size = match self.axis {
195                Axis::X => GenericSize::new(specific_size.y, specific_size.x),
196                Axis::Y => GenericSize::new(specific_size.x, specific_size.y),
197            };
198
199            self.used.main += generic_size.main;
200            self.used.cross.set_max(generic_size.cross);
201
202            self.items.push(StackItem::Frame(frame, align));
203
204            if i + 1 < len {
205                self.finish_region()?;
206            }
207        }
208
209        Ok(())
210    }
211
212    /// Advance to the next region.
213    fn finish_region(&mut self) -> SourceResult<()> {
214        // Determine the size of the stack in this region depending on whether
215        // the region expands.
216        let mut size = self
217            .expand
218            .select(self.initial, self.used.into_axes(self.axis))
219            .min(self.initial);
220
221        // Expand fully if there are fr spacings.
222        let full = self.initial.get(self.axis);
223        let remaining = full - self.used.main;
224        if self.fr.get() > 0.0 && full.is_finite() {
225            self.used.main = full;
226            size.set(self.axis, full);
227        }
228
229        if !size.is_finite() {
230            bail!(self.span, "stack spacing is infinite");
231        }
232
233        let mut output = Frame::hard(size);
234        let mut cursor = Abs::zero();
235        let mut ruler: FixedAlignment = self.dir.start().into();
236
237        // Place all frames.
238        for item in self.items.drain(..) {
239            match item {
240                StackItem::Absolute(v) => cursor += v,
241                StackItem::Fractional(v) => cursor += v.share(self.fr, remaining),
242                StackItem::Frame(frame, align) => {
243                    if self.dir.is_positive() {
244                        ruler = ruler.max(align.get(self.axis));
245                    } else {
246                        ruler = ruler.min(align.get(self.axis));
247                    }
248
249                    // Align along the main axis.
250                    let parent = size.get(self.axis);
251                    let child = frame.size().get(self.axis);
252                    let main = ruler.position(parent - self.used.main)
253                        + if self.dir.is_positive() {
254                            cursor
255                        } else {
256                            self.used.main - child - cursor
257                        };
258
259                    // Align along the cross axis.
260                    let other = self.axis.other();
261                    let cross = align
262                        .get(other)
263                        .position(size.get(other) - frame.size().get(other));
264
265                    let pos = GenericSize::new(cross, main).to_point(self.axis);
266                    cursor += child;
267                    output.push_frame(pos, frame);
268                }
269            }
270        }
271
272        // Advance to the next region.
273        self.regions.next();
274        self.initial = self.regions.size;
275        self.used = GenericSize::zero();
276        self.fr = Fr::zero();
277        self.finished.push(output);
278
279        Ok(())
280    }
281
282    /// Finish layouting and return the resulting frames.
283    fn finish(mut self) -> SourceResult<Fragment> {
284        self.finish_region()?;
285        Ok(Fragment::frames(self.finished))
286    }
287}
288
289/// A generic size with main and cross axes. The axes are generic, meaning the
290/// main axis could correspond to either the X or the Y axis.
291#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
292struct GenericSize<T> {
293    /// The cross component, along the axis perpendicular to the main.
294    pub cross: T,
295    /// The main component.
296    pub main: T,
297}
298
299impl<T> GenericSize<T> {
300    /// Create a new instance from the two components.
301    const fn new(cross: T, main: T) -> Self {
302        Self { cross, main }
303    }
304
305    /// Convert to the specific representation, given the current main axis.
306    fn into_axes(self, main: Axis) -> Axes<T> {
307        match main {
308            Axis::X => Axes::new(self.main, self.cross),
309            Axis::Y => Axes::new(self.cross, self.main),
310        }
311    }
312}
313
314impl GenericSize<Abs> {
315    /// The zero value.
316    fn zero() -> Self {
317        Self { cross: Abs::zero(), main: Abs::zero() }
318    }
319
320    /// Convert to a point.
321    fn to_point(self, main: Axis) -> Point {
322        self.into_axes(main).to_point()
323    }
324}