Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/flow/lists.rs

8.4 KiB, 5 runs

created by r1870400018:63526, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-layout `lists.rs`, version 0.15.1).
3// Modified for Austenite: ported to Hematite's types, IR and error handling.
4// U6b owns this file: the layout routine of bullet and numbered lists.
5//
6// A port of Typst 0.15.1's `layout_list` and `layout_enum`: each item is a marker and a body laid out side
7// by side, the markers measured first so they align to the widest, the bodies measured too when the list may
8// not fill its region, and the items stacked by the stack layouter with the gutter between them. A marker
9// sits on the first baseline of its body, or against the body's first frame when its alignment says top,
10// horizon or bottom. The model's show (`eval::lib::model::list`) resolves the markers, numbers and bodies and
11// hands them over in the element's `laid` field.
12
13use crate::eval::content::{
14 Content,
15 ElemKind,
16};
17use crate::eval::locate::{
18 Locator,
19 Place,
20};
21use crate::eval::styles::StyleChain;
22use crate::eval::value::{
23 Direction,
24 Value,
25};
26use crate::eval::Engine;
27use crate::flow::block::{
28 abs_of,
29 field,
30 layout_fragment_in,
31 layout_frame_in,
32 rel_of,
33 rtl,
34 Frame,
35 Item,
36 Regions,
37 Rel,
38 Spacing,
39 Stacker,
40};
41
42use oxedyne_fe2o3_core::prelude::*;
43
44/// A marker and the body it leads, each realised at a place of its own under the list's, so that the several
45/// times an item is measured and laid out locate what is in it alike.
46struct Entry {
47 marker: Content,
48 body: Content,
49 marker_place: Option<Place>,
50 body_place: Option<Place>,
51}
52
53/// What every item of one list shares.
54struct Lister {
55 indent: f64, // from the text start to the marker
56 body_indent: f64, // between the marker and the body
57 baseline: bool, // the marker sits on the body's first baseline
58 rtl: bool,
59 marker_width: f64, // the widest marker, so they align to each other
60 body_width: Option<f64>, // the widest body, when the list may not fill its region
61}
62
63/// Lays a shown `list` or `enum` out into `regions`: one frame for each region it spans.
64pub fn layout(engine: &mut Engine, elem: &Content, styles: &StyleChain, regions: &Regions) -> Outcome<Vec<Frame>> {
65 let laid = match res!(field(elem, styles, "laid")) {
66 Some(Value::Dict(d)) => d,
67 _ => return Err(err!("A {} reached layout without being shown, so it has no items.",
68 elem.kind().map(|k| k.path()).unwrap_or("list"); Bug)),
69 };
70 let mut items = Vec::new();
71 let mut places = elem.place().map(Locator::new);
72 if let Some(Value::Array(rows)) = laid.get("items") {
73 for row in rows.iter() {
74 if let Value::Array(pair) = row {
75 if let (Some(Value::Content(m)), Some(Value::Content(b))) = (pair.get(0), pair.get(1)) {
76 let body_place = places.as_mut().map(|l| l.next(ElemKind::ListItem, b.shell()));
77 let marker_place = places.as_mut().map(|l| l.next(ElemKind::Align, m.shell()));
78 items.push(Entry { marker: m.clone(), body: b.clone(), marker_place, body_place });
79 }
80 }
81 }
82 }
83 let gutter = match laid.get("gutter").and_then(|g| rel_of(styles, g)) {
84 Some(r) => r,
85 None => Rel::zero(),
86 };
87 let length = |name: &str| -> Outcome<f64> {
88 Ok(match res!(field(elem, styles, name)) {
89 Some(Value::Length(l)) => abs_of(styles, l),
90 _ => 0.0,
91 })
92 };
93 let mut lister = Lister {
94 indent: res!(length("indent")),
95 body_indent: res!(length("body-indent")),
96 baseline: matches!(laid.get("baseline"), Some(Value::Bool(true))),
97 rtl: res!(rtl(styles)),
98 marker_width: 0.0,
99 body_width: None,
100 };
101 lister.marker_width = res!(measure_markers(engine, &lister, &items, styles, regions));
102 if !regions.w.is_finite() || !regions.expand_x {
103 lister.body_width = Some(res!(measure_bodies(engine, &lister, &items, styles, regions)));
104 }
105 let mut stack = Stacker::new(Direction::Ttb, regions.clone(), elem.span());
106 let mut first = true;
107 for entry in &items {
108 if !first {
109 stack.spacing(Spacing::Rel(gutter), styles);
110 }
111 first = false;
112 res!(stack.custom(engine, styles, |engine, regions| layout_item(engine, &lister, entry, styles, regions)));
113 }
114 stack.finish(engine)
115}
116
117/// The widest marker, so they may align horizontally to each other.
118fn measure_markers(
119 engine: &mut Engine,
120 lister: &Lister,
121 items: &[Entry],
122 styles: &StyleChain,
123 regions: &Regions,
124)
125 -> Outcome<f64>
126{
127 let avail = regions.w - lister.indent - lister.body_indent;
128 let mut width = 0.0f64;
129 for item in items {
130 let frame = res!(layout_frame_in(engine, item.marker_place, &item.marker, styles,
131 Regions::one(avail, f64::INFINITY, false, false)));
132 width = width.max(frame.w);
133 }
134 Ok(width.min(avail))
135}
136
137/// The widest body. A list of infinite width, or one that may not expand, could not align its bodies to the
138/// region's edge, so they align to each other instead. Marker and body together that exceed the width leave
139/// the marker what it asked for and the body the rest.
140fn measure_bodies(
141 engine: &mut Engine,
142 lister: &Lister,
143 items: &[Entry],
144 styles: &StyleChain,
145 regions: &Regions,
146)
147 -> Outcome<f64>
148{
149 let avail = regions.w - lister.indent - lister.body_indent;
150 let mut width = 0.0f64;
151 for item in items {
152 let frame = res!(layout_frame_in(engine, item.body_place, &item.body, styles,
153 Regions::one(avail, f64::INFINITY, false, false)));
154 width = width.max(frame.w);
155 }
156 Ok(width.min(avail - lister.marker_width))
157}
158
159/// Does the first frame hold nothing but tags, with a later one that holds more? That is a forced region
160/// break, which the marker ignores.
161fn skip_first(frames: &[Frame]) -> bool {
162 frames.len() > 1 && tags_only(&frames[0]) && frames.iter().skip(1).any(|f| !tags_only(f))
163}
164
165fn tags_only(frame: &Frame) -> bool {
166 frame.items.iter().all(|(_, _, i)| matches!(i, Item::Tag(_)))
167}
168
169/// One item: the marker laid out against the body, with vertical marker alignment.
170fn layout_item(
171 engine: &mut Engine,
172 lister: &Lister,
173 item: &Entry,
174 styles: &StyleChain,
175 regions: &Regions,
176)
177 -> Outcome<Vec<Frame>>
178{
179 let total = lister.indent + lister.marker_width + lister.body_indent;
180 // The body is restricted to the space the marker and indents leave.
181 let mut body_regions = regions.clone();
182 match lister.body_width {
183 Some(w) => {
184 body_regions.w = w;
185 body_regions.expand_x = true;
186 },
187 None => body_regions.w -= total,
188 }
189 let mut marker = res!(layout_frame_in(engine, item.marker_place, &item.marker, styles,
190 Regions::one(lister.marker_width, regions.base().1, true, false)));
191 let mut body = res!(layout_fragment_in(engine, item.body_place, &item.body, styles, body_regions.clone()));
192 // The first frame that is not only tags.
193 let mut first = if skip_first(&body) { 1 } else { 0 };
194 let (mut body_y, mut marker_y) = (0.0, 0.0);
195 if lister.baseline {
196 // A positive difference means the marker is above and moves down; a negative one means the body is
197 // above, so it is laid out again with that much less room and moved down.
198 let diff = match body.get(first) {
199 Some(f) if marker.has_baseline() && f.has_baseline() => f.baseline() - marker.baseline(),
200 _ => 0.0,
201 };
202 if diff >= 0.0 {
203 marker_y = diff;
204 } else {
205 let mut shorter = body_regions.clone();
206 shorter.h += diff;
207 body = res!(layout_fragment_in(engine, item.body_place, &item.body, styles, shorter));
208 if skip_first(&body) {
209 first = 1;
210 }
211 body_y = -diff;
212 }
213 } else {
214 // Explicit marker alignment: the marker is laid out again as tall as the body's first frame, so it
215 // aligns itself within it.
216 let height = match body.get(first) {
217 Some(f) => f.h.max(marker.h),
218 None => marker.h,
219 };
220 marker = res!(layout_frame_in(engine, item.marker_place, &item.marker, styles,
221 Regions::one(lister.marker_width, height, true, true)));
222 }
223 // The marker joins the first frame that is not only tags, and the whole body is indented after it.
224 let mut frames = Vec::with_capacity(body.len());
225 for (i, body_frame) in body.into_iter().enumerate() {
226 let width = total + body_frame.w;
227 let mut height = body_frame.h + body_y;
228 if i == first {
229 height = height.max(marker.h + marker_y);
230 }
231 let mut frame = Frame::new(width, height);
232 // In a right-to-left list the items expand to the left, so the body sits at the frame's left edge.
233 let body_x = if lister.rtl { 0.0 } else { total };
234 if i == first {
235 let marker_x = if lister.rtl { width - (lister.marker_width + lister.indent) } else { lister.indent };
236 frame.push_frame(marker_x, marker_y, marker.clone());
237 }
238 frame.push_frame(body_x, body_y, body_frame);
239 frames.push(frame);
240 }
241 Ok(frames)
242}