Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/model/list.rs

18.2 KiB, 10 runs

created by r1870400018:63266, 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-library `model/{list,enum,terms}.rs`, version 0.15.1).
3// Modified for Austenite: the element's fields, defaults and default show, ported to Hematite's types, IR and error handling.
4// U5 owns this file: list, enum and terms, and their items. Realisation groups consecutive items into
5// the list element; the list's show lays its items out.
6//
7// A bullet or numbered list is shown as a grid of four columns -- the indent, the markers (as wide as the
8// widest), the body indent and the bodies -- with the item spacing as its row gutter. Typst 0.15 lays
9// lists out with a dedicated layouter over the same geometry, which differs in two respects the grid
10// cannot express: a marker is aligned to its body's first baseline rather than to the row's top (they
11// coincide unless the body opens larger than the marker), and a list inside a container of automatic
12// width sizes its bodies to the widest one. A term list is Typst's own realisation: a stack of padded
13// blocks.
14//
15// Nesting is carried by style-only fields Typst keeps internal: `list.depth` picks the marker,
16// `enum.parents` holds the enclosing numbers for `full` numbering, and `terms.within` marks a term list.
17// Each is set to its absolute value for the items' bodies.
18
19use crate::eval::args::Args;
20use crate::eval::content::{
21 Content,
22 ElemKind,
23 FieldDefault,
24 FieldSpec,
25 FieldType,
26};
27use crate::eval::lib::model::common::{
28 self,
29 expect,
30 expect_cast,
31 natural,
32 to_content,
33 CastErr,
34 K,
35};
36use crate::eval::lib::numbering;
37use crate::eval::styles::StyleChain;
38use crate::eval::value::{
39 Alignment,
40 Dict,
41 HAlign,
42 Type,
43 Value,
44};
45use crate::eval::Engine;
46use crate::syntax::Span;
47
48use oxedyne_fe2o3_core::prelude::*;
49
50const ANY: FieldType = FieldType::Any;
51const BOOL: FieldType = FieldType::Of(Type::Bool);
52const LENGTH: FieldType = FieldType::Of(Type::Length);
53
54static LIST: [FieldSpec; 9] = [
55 FieldSpec::named("tight", BOOL, FieldDefault::Bool(true)),
56 FieldSpec::named("marker", ANY, FieldDefault::Computed),
57 FieldSpec::named("indent", LENGTH, FieldDefault::Pt(0.0)),
58 FieldSpec::named("body-indent", LENGTH, FieldDefault::Em(0.5)),
59 FieldSpec::named("spacing", FieldType::OneOf(&[Type::Length, Type::Auto]), FieldDefault::Auto),
60 FieldSpec::named("marker-align", ANY, FieldDefault::Computed),
61 FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
62 FieldSpec::named("depth", ANY, FieldDefault::Int(0)).internal(),
63 FieldSpec::named("laid", ANY, FieldDefault::None).internal(),
64];
65
66static LIST_ITEM: [FieldSpec; 1] = [
67 FieldSpec::required("body", ANY),
68];
69
70static ENUM: [FieldSpec; 12] = [
71 FieldSpec::named("tight", BOOL, FieldDefault::Bool(true)),
72 FieldSpec::named("numbering", ANY, FieldDefault::Str("1.")),
73 FieldSpec::named("start", ANY, FieldDefault::Auto),
74 FieldSpec::named("full", BOOL, FieldDefault::Bool(false)),
75 FieldSpec::named("reversed", BOOL, FieldDefault::Bool(false)),
76 FieldSpec::named("indent", LENGTH, FieldDefault::Pt(0.0)),
77 FieldSpec::named("body-indent", LENGTH, FieldDefault::Em(0.5)),
78 FieldSpec::named("spacing", FieldType::OneOf(&[Type::Length, Type::Auto]), FieldDefault::Auto),
79 FieldSpec::named("number-align", ANY, FieldDefault::Computed),
80 FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
81 FieldSpec::named("parents", ANY, FieldDefault::EmptyArray).internal(),
82 FieldSpec::named("laid", ANY, FieldDefault::None).internal(),
83];
84
85static ENUM_ITEM: [FieldSpec; 2] = [
86 FieldSpec::named("number", ANY, FieldDefault::Auto).positional(),
87 FieldSpec::required("body", ANY),
88];
89
90static TERMS: [FieldSpec; 7] = [
91 FieldSpec::named("tight", BOOL, FieldDefault::Bool(true)),
92 FieldSpec::named("separator", ANY, FieldDefault::Computed),
93 FieldSpec::named("indent", LENGTH, FieldDefault::Pt(0.0)),
94 FieldSpec::named("hanging-indent", LENGTH, FieldDefault::Em(2.0)),
95 FieldSpec::named("spacing", FieldType::OneOf(&[Type::Length, Type::Auto]), FieldDefault::Auto),
96 FieldSpec::named("children", ANY, FieldDefault::EmptyArray).variadic().unsettable(),
97 FieldSpec::named("within", ANY, FieldDefault::Bool(false)).internal(),
98];
99
100static TERM_ITEM: [FieldSpec; 2] = [
101 FieldSpec::required("term", ANY),
102 FieldSpec::required("description", ANY),
103];
104
105pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
106 match kind {
107 ElemKind::List => &LIST,
108 ElemKind::ListItem => &LIST_ITEM,
109 ElemKind::Enum => &ENUM,
110 ElemKind::EnumItem => &ENUM_ITEM,
111 ElemKind::Terms => &TERMS,
112 ElemKind::TermItem => &TERM_ITEM,
113 _ => &[],
114 }
115}
116
117pub fn default_value(kind: ElemKind, name: &str) -> Option<Value> {
118 let end = Value::Alignment(Alignment { x: Some(HAlign::End), y: None });
119 match (kind, name) {
120 (ElemKind::List, "marker") => Some(Value::array(vec![
121 Value::Content(common::text("\u{2022}")), // bullet
122 Value::Content(common::text("\u{2023}")), // triangular bullet
123 Value::Content(common::text("\u{2013}")), // en dash
124 ])),
125 (ElemKind::List, "marker-align") => Some(end),
126 (ElemKind::Enum, "number-align") => Some(end),
127 (ElemKind::Terms, "separator") => {
128 // `h(0.6em, weak: true)`, with whichever of those fields `h`'s schema has.
129 let h = ElemKind::H;
130 let mut fields = Vec::new();
131 if let Some(a) = h.field_id("amount") {
132 fields.push((a, common::em(0.6)));
133 }
134 if let Some(w) = h.field_id("weak") {
135 fields.push((w, Value::Bool(true)));
136 }
137 Some(Value::Content(Content::new(h, fields, Span::detached())))
138 }
139 _ => None,
140 }
141}
142
143pub fn cast(kind: ElemKind, name: &str, v: Value) -> Result<Value, CastErr> {
144 match (kind, name) {
145 (_, "tight") | (ElemKind::Enum, "full") | (ElemKind::Enum, "reversed")
146 => expect(&v, &[K::Bool]).map(|_| v),
147 (_, "indent") | (_, "body-indent") | (ElemKind::Terms, "hanging-indent")
148 => expect(&v, &[K::Length]).map(|_| v),
149 (_, "spacing") => expect(&v, &[K::Length, K::Auto]).map(|_| v),
150 (ElemKind::List, "marker") => marker(v),
151 (ElemKind::List, "marker-align") | (ElemKind::Enum, "number-align")
152 => expect(&v, &[K::Alignment]).map(|_| v),
153 (ElemKind::Enum, "numbering") => expect_cast(v, &[K::Str, K::Func]),
154 (ElemKind::Enum, "start") | (ElemKind::EnumItem, "number") => match v {
155 Value::Auto => Ok(v),
156 Value::Int(_) => natural(&v, true).map(|_| v),
157 other => Err(CastErr::Type(common::mismatch("integer or auto", &other))),
158 },
159 (ElemKind::Terms, "separator") => expect(&v, &[K::Content]).map(|_| to_content(v)),
160 (ElemKind::List, "children") => list_child(v),
161 (ElemKind::Enum, "children") => enum_child(v),
162 (ElemKind::Terms, "children") => term_child(v),
163 (_, "body") | (_, "term") | (_, "description")
164 => expect(&v, &[K::Content]).map(|_| to_content(v)),
165 _ => Ok(v),
166 }
167}
168
169fn marker(v: Value) -> Result<Value, CastErr> {
170 match v {
171 Value::Func(_) => Ok(v),
172 Value::Array(a) => {
173 if a.is_empty() {
174 return Err(CastErr::Value("array must contain at least one marker".to_string()));
175 }
176 Ok(Value::array(a.iter().map(|x| Value::Content(common::display(x.clone()))).collect()))
177 }
178 other => expect(&other, &[K::Content, K::Array, K::Func]).map(|_| to_content(other)),
179 }
180}
181
182fn list_child(v: Value) -> Result<Value, CastErr> {
183 ok!(expect(&v, &[K::Content]));
184 match to_content(v) {
185 Value::Content(c) if c.is(ElemKind::ListItem) => Ok(Value::Content(c)),
186 Value::Content(c) => item(ElemKind::ListItem, vec![("body", Value::Content(c))]),
187 other => Ok(other),
188 }
189}
190
191fn enum_child(v: Value) -> Result<Value, CastErr> {
192 if let Value::Array(a) = &v {
193 if a.len() != 2 {
194 return Err(CastErr::Value("array must contain exactly two entries".to_string()));
195 }
196 let number = a[0].clone();
197 match &number {
198 Value::Auto => (),
199 Value::Int(_) => ok!(natural(&number, true)),
200 other => return Err(CastErr::Value(common::mismatch("integer or auto", other))),
201 }
202 ok!(expect(&a[1], &[K::Content]));
203 return item(ElemKind::EnumItem, vec![("number", number), ("body", to_content(a[1].clone()))]);
204 }
205 ok!(expect(&v, &[K::Content, K::Array]));
206 match to_content(v) {
207 Value::Content(c) if c.is(ElemKind::EnumItem) => Ok(Value::Content(c)),
208 Value::Content(c) => item(ElemKind::EnumItem, vec![("body", Value::Content(c))]),
209 other => Ok(other),
210 }
211}
212
213fn term_child(v: Value) -> Result<Value, CastErr> {
214 if let Value::Array(a) = &v {
215 if a.len() != 2 {
216 return Err(CastErr::Value("array must contain exactly two entries".to_string()));
217 }
218 ok!(expect(&a[0], &[K::Content]));
219 ok!(expect(&a[1], &[K::Content]));
220 return item(ElemKind::TermItem, vec![
221 ("term", to_content(a[0].clone())),
222 ("description", to_content(a[1].clone())),
223 ]);
224 }
225 ok!(expect(&v, &[K::Content, K::Array]));
226 match v {
227 Value::Content(c) if c.is(ElemKind::TermItem) => Ok(Value::Content(c)),
228 _ => Err(CastErr::Value("expected term item or array".to_string())),
229 }
230}
231
232fn item(kind: ElemKind, fields: Vec<(&str, Value)>) -> Result<Value, CastErr> {
233 match common::raw_elem(kind, Span::detached(), fields) {
234 Ok(c) => Ok(Value::Content(c)),
235 Err(e) => Err(CastErr::Value(e.to_string())),
236 }
237}
238
239/// Is flow inside a list, an enumeration or a term list? A paragraph's first-line indent reads this.
240pub fn in_list(styles: &StyleChain) -> bool {
241 let depth = matches!(common::style_or(styles, ElemKind::List, "depth", Value::Int(0)), Value::Int(d) if d > 0);
242 let parents = matches!(common::style_or(styles, ElemKind::Enum, "parents", Value::array(Vec::new())),
243 Value::Array(a) if !a.is_empty());
244 let within = matches!(common::style_or(styles, ElemKind::Terms, "within", Value::Bool(false)), Value::Bool(true));
245 depth || parents || within
246}
247
248pub fn show(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> {
249 match elem.kind() {
250 // Shown already: flow lays it out with the routine of `flow::lists`.
251 Some(ElemKind::List | ElemKind::Enum) if elem.field("laid").is_some() => Ok(None),
252 Some(ElemKind::List) => show_list(engine, elem, styles).map(Some),
253 Some(ElemKind::Enum) => show_enum(engine, elem, styles).map(Some),
254 Some(ElemKind::Terms) => show_terms(engine, elem, styles).map(Some),
255 // An item has no show of its own: realisation groups it into its list first.
256 _ => Ok(None),
257 }
258}
259
260fn children(elem: &Content) -> Vec<Content> {
261 match elem.field("children") {
262 Some(Value::Array(a)) => a.iter().filter_map(|v| match v {
263 Value::Content(c) => Some(c.clone()),
264 _ => None,
265 }).collect(),
266 _ => Vec::new(),
267 }
268}
269
270/// The gap between items: `spacing` when set, else the paragraph leading for a tight list and the
271/// paragraph spacing for a wide one.
272fn gutter(elem: &Content, styles: &StyleChain, tight: bool) -> Outcome<Value> {
273 match res!(common::get(elem, styles, "spacing")) {
274 Value::Auto => Ok(if tight {
275 res!(common::style(styles, ElemKind::Par, "leading"))
276 } else {
277 res!(common::style(styles, ElemKind::Par, "spacing"))
278 }),
279 v => Ok(v),
280 }
281}
282
283/// A tight list keeps to the paragraph before it: weak spacing of the gutter, attached to it.
284fn attach_tight(engine: &mut Engine, spacing: Value, realised: Content, span: Span) -> Outcome<Content> {
285 let v = res!(common::build(engine, ElemKind::V, span, vec![spacing], vec![
286 ("weak", Value::Bool(true)),
287 ("attach", Value::Bool(true)),
288 ]));
289 Ok(common::seq(vec![v, realised]))
290}
291
292/// The list as its layout routine takes it (`flow::lists`): the element itself, marked laid by a `laid`
293/// field that holds each item's marker and body, the gutter between items and whether the marker aligns to
294/// the body's first baseline. The element then reaches flow as a block with a layout routine of its own, as
295/// Typst's `BlockElem::multi_layouter` makes it.
296fn laid(
297 elem: &Content,
298 rows: Vec<(Content, Content)>,
299 gutter: Value,
300 baseline: bool,
301)
302 -> Outcome<Content>
303{
304 let kind = match elem.kind() {
305 Some(k) => k,
306 None => return Err(err!("a list was asked of content that is not an element"; Bug)),
307 };
308 let id = res!(common::fid(kind, "laid"));
309 let items = rows.into_iter().map(|(m, b)| Value::array(vec![Value::Content(m), Value::Content(b)])).collect();
310 let mut d = Dict::new();
311 d.insert("items", Value::array(items));
312 d.insert("gutter", gutter);
313 d.insert("baseline", Value::Bool(baseline));
314 let mut out = elem.clone();
315 out.set(id, Value::dict(d));
316 Ok(out)
317}
318
319fn show_list(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> {
320 let span = elem.span();
321 let tight = matches!(res!(common::get(elem, styles, "tight")), Value::Bool(true));
322 let gutter = res!(gutter(elem, styles, tight));
323 let depth = match common::style_or(styles, ElemKind::List, "depth", Value::Int(0)) {
324 Value::Int(d) => d.max(0),
325 _ => 0,
326 };
327 let align = res!(common::get(elem, styles, "marker-align"));
328 let baseline = matches!(&align, Value::Alignment(a) if a.y.is_none());
329 let marker = match res!(common::get(elem, styles, "marker")) {
330 Value::Array(a) => match a.get(depth as usize % a.len().max(1)) {
331 Some(m) => common::display(m.clone()),
332 None => Content::empty(),
333 },
334 Value::Func(f) => {
335 let mut args = Args::new(span);
336 args.push(span, Value::Int(depth));
337 let saved = std::mem::replace(&mut engine.context, crate::eval::Context {
338 location: None,
339 styles: Some(styles.clone()),
340 });
341 let out = engine.call_func(&f, args);
342 engine.context = saved;
343 res!(common::shown(engine, res!(out), span))
344 }
345 v => common::display(v),
346 };
347 let marker = res!(common::build(engine, ElemKind::Align, span, vec![align, Value::Content(marker)], Vec::new()));
348 let mut rows = Vec::new();
349 for item in children(elem) {
350 let mut body = common::body(&item, "body");
351 if !tight {
352 body = common::seq(vec![body, Content::marker(ElemKind::Parbreak, Span::detached())]);
353 }
354 let body = res!(common::set(body, ElemKind::List, "depth", Value::Int(depth + 1)));
355 rows.push((marker.clone(), body));
356 }
357 let realised = res!(laid(elem, rows, gutter.clone(), baseline));
358 if tight {
359 return attach_tight(engine, gutter, realised, span);
360 }
361 Ok(realised)
362}
363
364fn show_enum(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> {
365 let span = elem.span();
366 let tight = matches!(res!(common::get(elem, styles, "tight")), Value::Bool(true));
367 let gutter = res!(gutter(elem, styles, tight));
368 let numbering = res!(common::get(elem, styles, "numbering"));
369 let reversed = matches!(res!(common::get(elem, styles, "reversed")), Value::Bool(true));
370 let full = matches!(res!(common::get(elem, styles, "full")), Value::Bool(true));
371 let align = res!(common::get(elem, styles, "number-align"));
372 let baseline = matches!(&align, Value::Alignment(a) if a.y.is_none());
373 let items = children(elem);
374 let mut number: u64 = match res!(common::get(elem, styles, "start")) {
375 Value::Int(n) => n.max(0) as u64,
376 _ => if reversed { items.len() as u64 } else { 1 },
377 };
378 let parents: Vec<u64> = match common::style_or(styles, ElemKind::Enum, "parents", Value::array(Vec::new())) {
379 Value::Array(a) => a.iter().filter_map(|v| match v {
380 Value::Int(i) => Some(*i as u64),
381 _ => None,
382 }).collect(),
383 _ => Vec::new(),
384 };
385 let mut rows = Vec::new();
386 for item in items {
387 if let Some(Value::Int(n)) = item.field("number") {
388 number = (*n).max(0) as u64;
389 }
390 let resolved = if full {
391 let mut all = parents.clone();
392 all.push(number);
393 let v = res!(numbering::apply(engine, &numbering, &all));
394 res!(common::shown(engine, v, item.span()))
395 } else {
396 // A pattern gives the piece for the item's depth; a function gets the number alone.
397 let v = res!(numbering::apply_kth(engine, &numbering, parents.len(), number));
398 res!(common::shown(engine, v, item.span()))
399 };
400 let resolved = res!(common::set(resolved, ElemKind::Text, "overhang", Value::Bool(false)));
401 let resolved = res!(common::build(engine, ElemKind::Align, span,
402 vec![align.clone(), Value::Content(resolved)], Vec::new()));
403 let mut body = common::body(&item, "body");
404 if !tight {
405 body = common::seq(vec![body, Content::marker(ElemKind::Parbreak, Span::detached())]);
406 }
407 let mut inner = parents.iter().map(|p| Value::Int(*p as i64)).collect::<Vec<_>>();
408 inner.push(Value::Int(number as i64));
409 let body = res!(common::set(body, ElemKind::Enum, "parents", Value::array(inner)));
410 rows.push((resolved, body));
411 number = if reversed { number.saturating_sub(1) } else { number.saturating_add(1) };
412 }
413 let realised = res!(laid(elem, rows, gutter.clone(), baseline));
414 if tight {
415 return attach_tight(engine, gutter, realised, span);
416 }
417 Ok(realised)
418}
419
420fn show_terms(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> {
421 let span = elem.span();
422 let tight = matches!(res!(common::get(elem, styles, "tight")), Value::Bool(true));
423 let separator = common::display(res!(common::get(elem, styles, "separator")));
424 let indent = res!(common::get(elem, styles, "indent"));
425 let hanging = res!(common::get(elem, styles, "hanging-indent"));
426 let gutter = res!(gutter(elem, styles, tight));
427 let pad = common::pt(common::resolve_pt(styles, &hanging) + common::resolve_pt(styles, &indent));
428 let unpad = if common::resolve_pt(styles, &hanging) != 0.0 {
429 Some(res!(common::h(engine, common::neg(&hanging), false)))
430 } else {
431 None
432 };
433 let mut stack_children = Vec::new();
434 for child in children(elem) {
435 let mut parts = Vec::new();
436 if let Some(u) = &unpad {
437 parts.push(u.clone());
438 }
439 let term = res!(common::raw_elem(ElemKind::Strong, child.span(),
440 vec![("body", Value::Content(common::body(&child, "term")))]));
441 parts.push(term);
442 parts.push(separator.clone());
443 parts.push(common::body(&child, "description"));
444 // Text in a wide term list is always set as paragraphs.
445 if !tight {
446 parts.push(Content::marker(ElemKind::Parbreak, Span::detached()));
447 }
448 // The item is the stack's own child, not a `block` of it: a block shrinks its inline lines to the longest,
449 // where the stack hands them its full width, as Typst's `StackChild::Block` of the bare sequence does.
450 let item = common::spanned(common::seq(parts), child.span());
451 stack_children.push(Value::Content(item));
452 }
453 let stack = res!(common::build(engine, ElemKind::Stack, span, stack_children, vec![("spacing", gutter.clone())]));
454 let side = if common::is_rtl(styles) { "right" } else { "left" };
455 let padded = res!(common::build(engine, ElemKind::Pad, span, vec![Value::Content(stack)], vec![(side, pad)]));
456 let realised = res!(common::set(padded, ElemKind::Terms, "within", Value::Bool(true)));
457 if tight {
458 return attach_tight(engine, gutter, realised, span);
459 }
460 Ok(realised)
461}