summaryrefslogtreecommitdiff
path: root/src/library/layout.rs
blob: f3f3f81e370078b67a3546be30ea7f47ff769baa (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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use super::*;
use crate::layout::{FixedNode, GridNode, PadNode, StackChild, StackNode, TrackSizing};
use crate::paper::{Paper, PaperClass};

/// `page`: Configure pages.
pub fn page(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let span = args.span;
    let paper = args.eat::<Spanned<EcoString>>().and_then(|name| {
        Paper::from_name(&name.v).or_else(|| {
            ctx.diag(error!(name.span, "invalid paper name"));
            None
        })
    });

    let width = args.named(ctx, "width");
    let height = args.named(ctx, "height");
    let margins = args.named(ctx, "margins");
    let left = args.named(ctx, "left");
    let top = args.named(ctx, "top");
    let right = args.named(ctx, "right");
    let bottom = args.named(ctx, "bottom");
    let flip = args.named(ctx, "flip");
    let body = args.expect::<Template>(ctx, "body").unwrap_or_default();

    Value::template(move |ctx| {
        let snapshot = ctx.state.clone();
        let state = ctx.state.page_mut();

        if let Some(paper) = paper {
            state.class = paper.class;
            state.size = paper.size();
        }

        if let Some(width) = width {
            state.class = PaperClass::Custom;
            state.size.width = width;
        }

        if let Some(height) = height {
            state.class = PaperClass::Custom;
            state.size.height = height;
        }

        if let Some(margins) = margins {
            state.margins = Sides::splat(Some(margins));
        }

        if let Some(left) = left {
            state.margins.left = Some(left);
        }

        if let Some(top) = top {
            state.margins.top = Some(top);
        }

        if let Some(right) = right {
            state.margins.right = Some(right);
        }

        if let Some(bottom) = bottom {
            state.margins.bottom = Some(bottom);
        }

        if flip.unwrap_or(false) {
            std::mem::swap(&mut state.size.width, &mut state.size.height);
        }

        ctx.pagebreak(false, true, span);
        body.exec(ctx);

        ctx.state = snapshot;
        ctx.pagebreak(true, false, span);
    })
}

/// `pagebreak`: Start a new page.
pub fn pagebreak(_: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let span = args.span;
    Value::template(move |ctx| {
        ctx.pagebreak(true, true, span);
    })
}

/// `h`: Horizontal spacing.
pub fn h(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    spacing_impl(ctx, args, GenAxis::Cross)
}

/// `v`: Vertical spacing.
pub fn v(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    spacing_impl(ctx, args, GenAxis::Main)
}

fn spacing_impl(ctx: &mut EvalContext, args: &mut FuncArgs, axis: GenAxis) -> Value {
    let spacing: Option<Linear> = args.expect(ctx, "spacing");
    Value::template(move |ctx| {
        if let Some(linear) = spacing {
            // TODO: Should this really always be font-size relative?
            let amount = linear.resolve(ctx.state.font.size);
            ctx.push_spacing(axis, amount);
        }
    })
}

/// `align`: Configure the alignment along the layouting axes.
pub fn align(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let first = args.eat::<Align>();
    let second = args.eat::<Align>();
    let mut horizontal = args.named(ctx, "horizontal");
    let mut vertical = args.named(ctx, "vertical");
    let body = args.expect::<Template>(ctx, "body").unwrap_or_default();

    for value in first.into_iter().chain(second) {
        match value.axis() {
            Some(SpecAxis::Horizontal) | None if horizontal.is_none() => {
                horizontal = Some(value);
            }
            Some(SpecAxis::Vertical) | None if vertical.is_none() => {
                vertical = Some(value);
            }
            _ => {}
        }
    }

    Value::template(move |ctx| {
        if let Some(horizontal) = horizontal {
            ctx.state.aligns.cross = horizontal;
        }

        if let Some(vertical) = vertical {
            ctx.state.aligns.main = vertical;
            ctx.parbreak();
        }

        body.exec(ctx);
    })
}

/// `box`: Place content in a rectangular box.
pub fn boxed(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let width = args.named(ctx, "width");
    let height = args.named(ctx, "height");
    let body = args.eat().unwrap_or_default();
    Value::template(move |ctx| {
        let child = ctx.exec_template_stack(&body).into();
        ctx.push_into_par(FixedNode { width, height, child });
    })
}

/// `block`: Place content in a block.
pub fn block(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let body = args.expect(ctx, "body").unwrap_or_default();
    Value::template(move |ctx| {
        let block = ctx.exec_template_stack(&body);
        ctx.push_into_stack(block);
    })
}

/// `pad`: Pad content at the sides.
pub fn pad(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let all = args.eat();
    let left = args.named(ctx, "left");
    let top = args.named(ctx, "top");
    let right = args.named(ctx, "right");
    let bottom = args.named(ctx, "bottom");
    let body = args.expect(ctx, "body").unwrap_or_default();

    let padding = Sides::new(
        left.or(all).unwrap_or_default(),
        top.or(all).unwrap_or_default(),
        right.or(all).unwrap_or_default(),
        bottom.or(all).unwrap_or_default(),
    );

    Value::template(move |ctx| {
        let child = ctx.exec_template_stack(&body).into();
        ctx.push_into_stack(PadNode { padding, child });
    })
}

/// `stack`: Stack children along an axis.
pub fn stack(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let dir = args.named(ctx, "dir");
    let children: Vec<_> = args.all().collect();

    Value::template(move |ctx| {
        let children = children
            .iter()
            .map(|child| {
                let child = ctx.exec_template_stack(child).into();
                StackChild::Any(child, ctx.state.aligns)
            })
            .collect();

        let mut dirs = Gen::new(None, dir).unwrap_or(ctx.state.dirs);

        // If the directions become aligned, fix up the cross direction since
        // that's the one that is not user-defined.
        if dirs.main.axis() == dirs.cross.axis() {
            dirs.cross = ctx.state.dirs.main;
        }

        ctx.push_into_stack(StackNode { dirs, aspect: None, children });
    })
}

/// `grid`: Arrange children into a grid.
pub fn grid(ctx: &mut EvalContext, args: &mut FuncArgs) -> Value {
    let columns = args.named(ctx, "columns").unwrap_or_default();
    let rows = args.named(ctx, "rows").unwrap_or_default();

    let gutter_columns = args.named(ctx, "gutter-columns");
    let gutter_rows = args.named(ctx, "gutter-rows");
    let default = args
        .named(ctx, "gutter")
        .map(|v| vec![TrackSizing::Linear(v)])
        .unwrap_or_default();

    let column_dir = args.named(ctx, "column-dir");
    let row_dir = args.named(ctx, "row-dir");

    let children: Vec<_> = args.all().collect();

    let tracks = Gen::new(columns, rows);
    let gutter = Gen::new(
        gutter_columns.unwrap_or_else(|| default.clone()),
        gutter_rows.unwrap_or(default),
    );

    Value::template(move |ctx| {
        let children = children
            .iter()
            .map(|child| ctx.exec_template_stack(child).into())
            .collect();

        let mut dirs = Gen::new(column_dir, row_dir).unwrap_or(ctx.state.dirs);

        // If the directions become aligned, try to fix up the direction which
        // is not user-defined.
        if dirs.main.axis() == dirs.cross.axis() {
            let target = if column_dir.is_some() {
                &mut dirs.main
            } else {
                &mut dirs.cross
            };

            *target = if target.axis() == ctx.state.dirs.cross.axis() {
                ctx.state.dirs.main
            } else {
                ctx.state.dirs.cross
            };
        }

        ctx.push_into_stack(GridNode {
            dirs,
            tracks: tracks.clone(),
            gutter: gutter.clone(),
            children,
        })
    })
}

/// Defines size of rows and columns in a grid.
type Tracks = Vec<TrackSizing>;

castable! {
    Tracks: "array of `auto`s, linears, and fractionals",
    Value::Int(count) => vec![TrackSizing::Auto; count.max(0) as usize],
    Value::Array(values) => values
        .into_iter()
        .filter_map(|v| v.cast().ok())
        .collect(),
}

castable! {
    TrackSizing: "`auto`, linear, or fractional",
    Value::Auto => TrackSizing::Auto,
    Value::Length(v) => TrackSizing::Linear(v.into()),
    Value::Relative(v) => TrackSizing::Linear(v.into()),
    Value::Linear(v) => TrackSizing::Linear(v),
    Value::Fractional(v) => TrackSizing::Fractional(v),
}