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 crate::layout::{AlignNode, GridLayouter, TrackSizings};
use crate::meta::LocalName;
use crate::prelude::*;
/// A table of items.
///
/// Tables are used to arrange content in cells. Cells can contain arbitrary
/// content, including multiple paragraphs and are specified in row-major order.
/// Because tables are just grids with configurable cell properties, refer to
/// the [grid documentation]($func/grid) for more information on how to size the
/// table tracks.
///
/// ## Example
/// ```example
/// #table(
/// columns: (1fr, auto, auto),
/// inset: 10pt,
/// align: horizon,
/// [], [*Area*], [*Parameters*],
/// image("cylinder.svg"),
/// $ pi h (D^2 - d^2) / 4 $,
/// [
/// $h$: height \
/// $D$: outer radius \
/// $d$: inner radius
/// ],
/// image("tetrahedron.svg"),
/// $ sqrt(2) / 12 a^3 $,
/// [$a$: edge length]
/// )
/// ```
///
/// Display: Table
/// Category: layout
#[node(Layout, LocalName)]
pub struct TableNode {
/// Defines the column sizes. See the [grid documentation]($func/grid) for
/// more information on track sizing.
pub columns: TrackSizings,
/// Defines the row sizes. See the [grid documentation]($func/grid) for more
/// information on track sizing.
pub rows: TrackSizings,
/// Defines the gaps between rows & columns. See the [grid
/// documentation]($func/grid) for more information on gutters.
#[external]
pub gutter: TrackSizings,
/// Defines the gaps between columns. Takes precedence over `gutter`. See
/// the [grid documentation]($func/grid) for more information on gutters.
#[parse(
let gutter = args.named("gutter")?;
args.named("column-gutter")?.or_else(|| gutter.clone())
)]
pub column_gutter: TrackSizings,
/// Defines the gaps between rows. Takes precedence over `gutter`. See the
/// [grid documentation]($func/grid) for more information on gutters.
#[parse(args.named("row-gutter")?.or_else(|| gutter.clone()))]
pub row_gutter: TrackSizings,
/// How to fill the cells.
///
/// This can be a color or a function that returns a color. The function is
/// passed the cell's column and row index, starting at zero. This can be
/// used to implement striped tables.
///
/// ```example
/// #table(
/// fill: (col, _) => if calc.odd(col) { luma(240) } else { white },
/// align: (col, row) =>
/// if row == 0 { center }
/// else if col == 0 { left }
/// else { right },
/// columns: 4,
/// [], [*Q1*], [*Q2*], [*Q3*],
/// [Revenue:], [1000 €], [2000 €], [3000 €],
/// [Expenses:], [500 €], [1000 €], [1500 €],
/// [Profit:], [500 €], [1000 €], [1500 €],
/// )
/// ```
pub fill: Celled<Option<Paint>>,
/// How to align the cell's content.
///
/// This can either be a single alignment or a function that returns an
/// alignment. The function is passed the cell's column and row index,
/// starting at zero. If set to `{auto}`, the outer alignment is used.
pub align: Celled<Smart<Axes<Option<GenAlign>>>>,
/// How to stroke the cells.
///
/// This can be a color, a stroke width, both, or `{none}` to disable
/// the stroke.
#[resolve]
#[fold]
#[default(Some(PartialStroke::default()))]
pub stroke: Option<PartialStroke>,
/// How much to pad the cells's content.
///
/// The default value is `{5pt}`.
#[default(Abs::pt(5.0).into())]
pub inset: Rel<Length>,
/// The contents of the table cells.
#[variadic]
pub children: Vec<Content>,
}
impl Layout for TableNode {
fn layout(
&self,
vt: &mut Vt,
styles: StyleChain,
regions: Regions,
) -> SourceResult<Fragment> {
let inset = self.inset(styles);
let align = self.align(styles);
let tracks = Axes::new(self.columns(styles).0, self.rows(styles).0);
let gutter = Axes::new(self.column_gutter(styles).0, self.row_gutter(styles).0);
let cols = tracks.x.len().max(1);
let cells: Vec<_> = self
.children()
.into_iter()
.enumerate()
.map(|(i, child)| {
let mut child = child.padded(Sides::splat(inset));
let x = i % cols;
let y = i / cols;
if let Smart::Custom(alignment) = align.resolve(vt, x, y)? {
child = child.styled(AlignNode::set_alignment(alignment));
}
Ok(child)
})
.collect::<SourceResult<_>>()?;
let fill = self.fill(styles);
let stroke = self.stroke(styles).map(PartialStroke::unwrap_or_default);
// Prepare grid layout by unifying content and gutter tracks.
let layouter = GridLayouter::new(
vt,
tracks.as_deref(),
gutter.as_deref(),
&cells,
regions,
styles,
);
// Measure the columns and layout the grid row-by-row.
let mut layout = layouter.layout()?;
// Add lines and backgrounds.
for (frame, rows) in layout.fragment.iter_mut().zip(&layout.rows) {
// Render table lines.
if let Some(stroke) = stroke {
let thickness = stroke.thickness;
let half = thickness / 2.0;
// Render horizontal lines.
for offset in points(rows.iter().map(|piece| piece.height)) {
let target = Point::with_x(frame.width() + thickness);
let hline = Geometry::Line(target).stroked(stroke);
frame.prepend(
Point::new(-half, offset),
Element::Shape(hline, self.span()),
);
}
// Render vertical lines.
for offset in points(layout.cols.iter().copied()) {
let target = Point::with_y(frame.height() + thickness);
let vline = Geometry::Line(target).stroked(stroke);
frame.prepend(
Point::new(offset, -half),
Element::Shape(vline, self.span()),
);
}
}
// Render cell backgrounds.
let mut dx = Abs::zero();
for (x, &col) in layout.cols.iter().enumerate() {
let mut dy = Abs::zero();
for row in rows {
if let Some(fill) = fill.resolve(vt, x, row.y)? {
let pos = Point::new(dx, dy);
let size = Size::new(col, row.height);
let rect = Geometry::Rect(size).filled(fill);
frame.prepend(pos, Element::Shape(rect, self.span()));
}
dy += row.height;
}
dx += col;
}
}
Ok(layout.fragment)
}
}
/// Turn an iterator extents into an iterator of offsets before, in between, and
/// after the extents, e.g. [10mm, 5mm] -> [0mm, 10mm, 15mm].
fn points(extents: impl IntoIterator<Item = Abs>) -> impl Iterator<Item = Abs> {
let mut offset = Abs::zero();
std::iter::once(Abs::zero())
.chain(extents.into_iter())
.map(move |extent| {
offset += extent;
offset
})
}
/// A value that can be configured per cell.
#[derive(Debug, Clone, PartialEq, Hash)]
pub enum Celled<T> {
/// A bare value, the same for all cells.
Value(T),
/// A closure mapping from cell coordinates to a value.
Func(Func),
}
impl<T: Cast + Clone> Celled<T> {
/// Resolve the value based on the cell position.
pub fn resolve(&self, vt: &Vt, x: usize, y: usize) -> SourceResult<T> {
Ok(match self {
Self::Value(value) => value.clone(),
Self::Func(func) => {
let args =
Args::new(func.span(), [Value::Int(x as i64), Value::Int(y as i64)]);
func.call_detached(vt.world, args)?.cast().at(func.span())?
}
})
}
}
impl<T: Default> Default for Celled<T> {
fn default() -> Self {
Self::Value(T::default())
}
}
impl<T: Cast> Cast for Celled<T> {
fn is(value: &Value) -> bool {
matches!(value, Value::Func(_)) || T::is(value)
}
fn cast(value: Value) -> StrResult<Self> {
match value {
Value::Func(v) => Ok(Self::Func(v)),
v if T::is(&v) => Ok(Self::Value(T::cast(v)?)),
v => <Self as Cast>::error(v),
}
}
fn describe() -> CastInfo {
T::describe() + CastInfo::Type("function")
}
}
impl<T: Into<Value>> From<Celled<T>> for Value {
fn from(celled: Celled<T>) -> Self {
match celled {
Celled::Value(value) => value.into(),
Celled::Func(func) => func.into(),
}
}
}
impl LocalName for TableNode {
fn local_name(&self, lang: Lang) -> &'static str {
match lang {
Lang::GERMAN => "Tabelle",
Lang::ENGLISH | _ => "Table",
}
}
}
|