summaryrefslogtreecommitdiff
path: root/src/library/structure/list.rs
blob: ac705156e590bf4d4beb8de4e058176c0f88976f (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::fmt::Write;

use unscanny::Scanner;

use crate::library::layout::{GridNode, TrackSizing};
use crate::library::prelude::*;
use crate::library::text::ParNode;
use crate::library::utility::Numbering;

/// An unordered (bulleted) or ordered (numbered) list.
#[derive(Debug, Hash)]
pub struct ListNode<const L: ListKind = UNORDERED> {
    /// Where the list starts.
    pub start: usize,
    /// If false, there is paragraph spacing between the items, if true
    /// there is list spacing between the items.
    pub tight: bool,
    /// The individual bulleted or numbered items.
    pub items: StyleVec<ListItem>,
}

/// An item in a list.
#[derive(Clone, PartialEq, Hash)]
pub struct ListItem {
    /// The kind of item.
    pub kind: ListKind,
    /// The number of the item.
    pub number: Option<usize>,
    /// The node that produces the item's body.
    pub body: Box<Content>,
}

/// An ordered list.
pub type EnumNode = ListNode<ORDERED>;

#[node(showable)]
impl<const L: ListKind> ListNode<L> {
    /// How the list is labelled.
    #[property(referenced)]
    pub const LABEL: Label = Label::Default;

    /// The spacing between the list items of a non-wide list.
    #[property(resolve)]
    pub const SPACING: RawLength = RawLength::zero();
    /// The indentation of each item's label.
    #[property(resolve)]
    pub const INDENT: RawLength = RawLength::zero();
    /// The space between the label and the body of each item.
    #[property(resolve)]
    pub const BODY_INDENT: RawLength = Em::new(0.5).into();

    /// The extra padding above the list.
    #[property(resolve)]
    pub const ABOVE: RawLength = RawLength::zero();
    /// The extra padding below the list.
    #[property(resolve)]
    pub const BELOW: RawLength = RawLength::zero();

    fn construct(_: &mut Context, args: &mut Args) -> TypResult<Content> {
        Ok(Content::show(Self {
            start: args.named("start")?.unwrap_or(1),
            tight: args.named("tight")?.unwrap_or(true),
            items: args
                .all()?
                .into_iter()
                .map(|body| ListItem {
                    kind: L,
                    number: None,
                    body: Box::new(body),
                })
                .collect(),
        }))
    }
}

impl<const L: ListKind> Show for ListNode<L> {
    fn encode(&self) -> Dict {
        dict! {
            "start" => Value::Int(self.start as i64),
            "tight" => Value::Bool(self.tight),
            "items" => Value::Array(
                self.items
                    .items()
                    .map(|item| Value::Content((*item.body).clone()))
                    .collect()
            ),
        }
    }

    fn realize(&self, ctx: &mut Context, styles: StyleChain) -> TypResult<Content> {
        let mut cells = vec![];
        let mut number = self.start;

        let label = styles.get(Self::LABEL);

        for (item, map) in self.items.iter() {
            number = item.number.unwrap_or(number);
            cells.push(LayoutNode::default());
            cells
                .push(label.resolve(ctx, L, number)?.styled_with_map(map.clone()).pack());
            cells.push(LayoutNode::default());
            cells.push((*item.body).clone().styled_with_map(map.clone()).pack());
            number += 1;
        }

        let leading = styles.get(ParNode::LEADING);
        let spacing = if self.tight {
            styles.get(Self::SPACING)
        } else {
            styles.get(ParNode::SPACING)
        };

        let gutter = leading + spacing;
        let indent = styles.get(Self::INDENT);
        let body_indent = styles.get(Self::BODY_INDENT);

        Ok(Content::block(GridNode {
            tracks: Spec::with_x(vec![
                TrackSizing::Relative(indent.into()),
                TrackSizing::Auto,
                TrackSizing::Relative(body_indent.into()),
                TrackSizing::Auto,
            ]),
            gutter: Spec::with_y(vec![TrackSizing::Relative(gutter.into())]),
            cells,
        }))
    }

    fn finalize(
        &self,
        _: &mut Context,
        styles: StyleChain,
        realized: Content,
    ) -> TypResult<Content> {
        Ok(realized.spaced(styles.get(Self::ABOVE), styles.get(Self::BELOW)))
    }
}

impl Debug for ListItem {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        if self.kind == UNORDERED {
            f.write_char('-')?;
        } else {
            if let Some(number) = self.number {
                write!(f, "{}", number)?;
            }
            f.write_char('.')?;
        }
        f.write_char(' ')?;
        self.body.fmt(f)
    }
}

/// How to label a list.
pub type ListKind = usize;

/// Unordered list labelling style.
pub const UNORDERED: ListKind = 0;

/// Ordered list labelling style.
pub const ORDERED: ListKind = 1;

/// How to label a list or enumeration.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Label {
    /// The default labelling.
    Default,
    /// A pattern with prefix, numbering, lower / upper case and suffix.
    Pattern(EcoString, Numbering, bool, EcoString),
    /// Bare content.
    Content(Content),
    /// A closure mapping from an item number to a value.
    Func(Func, Span),
}

impl Label {
    /// Resolve the value based on the level.
    pub fn resolve(
        &self,
        ctx: &mut Context,
        kind: ListKind,
        number: usize,
    ) -> TypResult<Content> {
        Ok(match self {
            Self::Default => match kind {
                UNORDERED => Content::Text('•'.into()),
                ORDERED | _ => Content::Text(format_eco!("{}.", number)),
            },
            Self::Pattern(prefix, numbering, upper, suffix) => {
                let fmt = numbering.apply(number);
                let mid = if *upper { fmt.to_uppercase() } else { fmt.to_lowercase() };
                Content::Text(format_eco!("{}{}{}", prefix, mid, suffix))
            }
            Self::Content(content) => content.clone(),
            Self::Func(func, span) => {
                let args = Args::from_values(*span, [Value::Int(number as i64)]);
                func.call(ctx, args)?.cast().at(*span)?
            }
        })
    }
}

impl Cast<Spanned<Value>> for Label {
    fn is(value: &Spanned<Value>) -> bool {
        matches!(&value.v, Value::Content(_) | Value::Func(_))
    }

    fn cast(value: Spanned<Value>) -> StrResult<Self> {
        match value.v {
            Value::Str(pattern) => {
                let mut s = Scanner::new(&pattern);
                let mut prefix;
                let numbering = loop {
                    prefix = s.before();
                    match s.eat().map(|c| c.to_ascii_lowercase()) {
                        Some('1') => break Numbering::Arabic,
                        Some('a') => break Numbering::Letter,
                        Some('i') => break Numbering::Roman,
                        Some('*') => break Numbering::Symbol,
                        Some(_) => {}
                        None => Err("invalid pattern")?,
                    }
                };
                let upper = s.scout(-1).map_or(false, char::is_uppercase);
                let suffix = s.after().into();
                Ok(Self::Pattern(prefix.into(), numbering, upper, suffix))
            }
            Value::Content(v) => Ok(Self::Content(v)),
            Value::Func(v) => Ok(Self::Func(v, value.span)),
            _ => Err("expected pattern, content or function")?,
        }
    }
}