1use toml_edit::{InlineTable, Item, Value};
4
5use crate::{
6 composition::{
7 recipe::{
8 capture_fixed_panel, read_content, FixedOptions, SupplyContent, CONTENT_FIELDS,
9 FIXED_FIELDS,
10 },
11 DeclaredContent,
12 },
13 recipe::{
14 capture::Capture,
15 codec::{array_items, choice, field, invalid, table, Codec},
16 declaration::BindingRequirement,
17 resolve::Resolver,
18 CanvasRecipeScope,
19 },
20 Result,
21};
22
23use crate::recipe::schema::{self as grammar, Schema};
24
25use super::{
26 placement, Arc, AxisRef, Canvas, CanvasCategoryLabels, CanvasHeader, CanvasLegendPolicy,
27 LegendComposition, PanelPath, ReservedSlot, TextPanel, Theme,
28};
29
30choice!(CanvasCategoryLabels {EveryPlot=>"every_plot",FirstColumnPerRow=>"first_column_per_row"});
31choice!(CanvasLegendPolicy {PerPlot=>"per_plot",Shared=>"shared",Hidden=>"hidden"});
32
33const TEXT_PANEL_FIELDS: &[grammar::Field] = &[
34 grammar::mandatory::<crate::Text>("title"),
35 grammar::mandatory::<crate::Text>("body"),
36];
37
38impl Codec for TextPanel {
39 fn schema(ctx: &mut Schema) -> serde_json::Value {
40 grammar::record(ctx, TEXT_PANEL_FIELDS)
41 }
42
43 fn encode(&self) -> Value {
44 let mut fields = InlineTable::new();
45 fields.insert("title", self.title.encode());
46 fields.insert("body", self.body.encode());
47 fields.into()
48 }
49
50 fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
51 let fields = grammar::record_fields(item, TEXT_PANEL_FIELDS)?;
52 Self::new(
53 field::<crate::Text>(fields, "title", None)?,
54 field::<crate::Text>(fields, "body", None)?,
55 )
56 }
57}
58
59const HEADER_FIELDS: &[grammar::Field] = &[
60 grammar::mandatory::<usize>("start"),
61 grammar::optional::<usize>("span"),
62 grammar::mandatory::<crate::Text>("text"),
63];
64
65impl Codec for CanvasHeader {
66 fn schema(ctx: &mut Schema) -> serde_json::Value {
67 grammar::record(ctx, HEADER_FIELDS)
68 }
69
70 fn encode(&self) -> Value {
71 let mut fields = InlineTable::new();
72 fields.insert("start", self.start.encode());
73 fields.insert("span", self.span.encode());
74 fields.insert("text", self.text.encode());
75 fields.into()
76 }
77
78 fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
79 let fields = grammar::record_fields(item, HEADER_FIELDS)?;
80 Ok(Self {
81 start: field(fields, "start", None)?,
82 span: field(fields, "span", Some(1))?,
83 text: field(fields, "text", None)?,
84 })
85 }
86}
87
88struct PanelBuild {
89 footprint: placement::Footprint,
90 source: SupplyContent,
91 fixed: FixedOptions,
92 path: String,
93}
94
95pub(crate) struct Blueprint {
96 canvas: Canvas,
97 panels: Vec<PanelBuild>,
98 floating: Vec<crate::composition::recipe::SupplyPlacement>,
99}
100
101fn read_range_groups(item: &Item, canvas: &mut Canvas) -> Result<()> {
102 for item in array_items(item)? {
103 let fields = grammar::record_fields(item, RANGE_GROUP_FIELDS)?;
104 if field::<String>(fields, "axis", Some("x".to_owned()))? != "x"
105 || field::<String>(fields, "mode", Some("domain".to_owned()))? != "domain"
106 {
107 return Err(invalid(
108 "Canvas range groups currently require x and domain",
109 ));
110 }
111 let paths: Vec<PanelPath> = field(fields, "panels", None)?;
112 *canvas = canvas.clone().range_group(AxisRef::X, paths)?;
113 }
114 Ok(())
115}
116
117const FIELDS: &[grammar::Field] = &[
118 grammar::custom("scope", false, |_| grammar::choices(&["full", "layout"])),
119 grammar::mandatory::<usize>("rows"),
120 grammar::mandatory::<usize>("columns"),
121 grammar::optional::<crate::layout::RootRequest>("size"),
122 grammar::optional::<Option<Theme>>("theme"),
123 grammar::optional::<Option<Theme>>("default_theme"),
124 grammar::optional::<crate::Text>("title"),
125 grammar::optional::<crate::Text>("subtitle"),
126 grammar::optional::<crate::Text>("caption"),
127 grammar::optional::<CanvasLegendPolicy>("legend_policy"),
128 grammar::optional::<LegendComposition>("legend_composition"),
129 grammar::custom(
130 "labels",
131 false,
132 crate::builder::recipe::non_grid_labels_schema,
133 ),
134 grammar::optional::<CanvasCategoryLabels>("category_labels"),
135 grammar::optional::<Option<crate::text::TextAlignment>>("panel_title_alignment"),
136 grammar::optional::<Option<crate::text::TextAlignment>>("panel_subtitle_alignment"),
137 grammar::custom("guide_text_layouts", false, guide_layouts_schema),
138 grammar::optional::<Vec<CanvasHeader>>("row_headers"),
139 grammar::optional::<Vec<CanvasHeader>>("column_headers"),
140 grammar::optional::<Vec<CanvasHeader>>("row_titles"),
141 grammar::custom("range_groups", false, |ctx| {
142 grammar::array(grammar::record(ctx, RANGE_GROUP_FIELDS))
143 }),
144 grammar::custom("panels", false, |_| grammar::primitive("array")),
145];
146
147const RESERVE_FIELDS: &[grammar::Field] = &[
148 grammar::optional::<f64>("min_width"),
149 grammar::optional::<f64>("min_height"),
150];
151
152const PANEL_FIELDS: &[grammar::Field] = &[
153 grammar::optional::<Option<String>>("name"),
154 grammar::mandatory::<usize>("row"),
155 grammar::mandatory::<usize>("column"),
156 grammar::optional::<usize>("row_span"),
157 grammar::optional::<usize>("column_span"),
158 grammar::custom("reserve", false, |ctx| grammar::record(ctx, RESERVE_FIELDS)),
159 grammar::optional::<bool>("vacant"),
160];
161
162const RANGE_GROUP_FIELDS: &[grammar::Field] = &[
163 grammar::custom("axis", false, |_| grammar::literal("x")),
164 grammar::custom("mode", false, |_| grammar::literal("domain")),
165 grammar::mandatory::<Vec<PanelPath>>("panels"),
166];
167
168const GUIDE_LAYOUT_FIELDS: &[grammar::Field] = &[
169 grammar::optional::<Option<crate::text::TextLayout>>("title"),
170 grammar::optional::<Option<crate::text::TextLayout>>("entry"),
171 grammar::optional::<Option<crate::text::TextLayout>>("number"),
172];
173
174pub(crate) fn guide_layouts_schema(ctx: &mut Schema) -> serde_json::Value {
175 ctx.named("GuideTextLayouts", |ctx| {
176 grammar::record(ctx, GUIDE_LAYOUT_FIELDS)
177 })
178}
179
180const LAYOUT_REMOVED: &[&str] = &[
181 "title",
182 "subtitle",
183 "caption",
184 "labels",
185 "row_headers",
186 "column_headers",
187 "row_titles",
188];
189
190fn panel_schema(ctx: &mut Schema, layout: bool) -> serde_json::Value {
191 use crate::composition::recipe::{
192 content_names, content_properties, fixed_properties, placement_schema, FIXED_FIELDS,
193 };
194 let geometry = grammar::record(ctx, PANEL_FIELDS);
195 let reserved =
196 serde_json::json!({"required":["reserve","vacant"],"properties":{"vacant":{"const":true}}});
197 if layout {
198 return grammar::with(geometry, serde_json::json!({"not":reserved}));
199 }
200 let mut properties = PANEL_FIELDS
201 .iter()
202 .map(|field| (field.name, geometry["properties"][field.name].clone()))
203 .collect::<Vec<_>>();
204 properties.extend(content_properties(ctx, false));
205 properties.extend(fixed_properties(ctx, true));
206 let names = content_names(false);
207 let empty = serde_json::json!({"not":{"anyOf":names.iter().chain(FIXED_FIELDS).chain(std::iter::once(&"binding_map")).map(|name|grammar::required(&[name])).collect::<Vec<_>>() }});
208 let filled = serde_json::json!({"allOf":[
209 grammar::exclusive(&names),
210 {"not":{"required":["reserve"]}},
211 {"properties":{"vacant":{"const":false}}},
212 {"dependentRequired":{"binding_map":["use"]}},
213 {"if":{"anyOf":FIXED_FIELDS.iter().map(|name|grammar::required(&[name])).collect::<Vec<_>>()},
214 "then":{"anyOf":[{"required":["asset"]},{"required":["frozen"]},{"required":["use"]}]}}
215 ]});
216 let vacant = serde_json::json!({"required":["vacant"],"properties":{"vacant":{"const":true}},"not":{"required":["reserve"]}});
217 let solid = grammar::with(
218 grammar::object(properties, &["row", "column"]),
219 grammar::one_of([
220 filled,
221 serde_json::json!({"allOf":[empty.clone(),{"required":["reserve"],"properties":{"vacant":{"const":false}}}]}),
222 serde_json::json!({"allOf":[empty,vacant]}),
223 ]),
224 );
225 let floating = serde_json::json!({"allOf":[placement_schema(ctx),{
226 "oneOf":[{"required":["slot"]},{"required":["box"],"properties":{"box":crate::layout::recipe::slot_box_schema(ctx)}}],
227 "not":{"required":["at"]},
228 "properties":{"boundary":{"const":false}}
229 }]});
230 grammar::one_of([solid, floating])
231}
232
233pub(crate) fn schema(ctx: &mut Schema) -> serde_json::Value {
234 ctx.named("Canvas", |ctx| {
235 grammar::one_of([false, true].into_iter().map(|layout| {
236 let fields = FIELDS
237 .iter()
238 .copied()
239 .filter(|field| !layout || !LAYOUT_REMOVED.contains(&field.name))
240 .collect::<Vec<_>>();
241 let mut shape = grammar::record(ctx, &fields);
242 grammar::declare_property(
243 &mut shape,
244 "scope",
245 grammar::literal(if layout { "layout" } else { "full" }),
246 );
247 grammar::declare_property(
248 &mut shape,
249 "panels",
250 grammar::array(panel_schema(ctx, layout)),
251 );
252 if layout {
253 grammar::with(shape, grammar::required(&["scope"]))
254 } else {
255 shape
256 }
257 }))
258 })
259}
260
261impl Blueprint {
262 pub(crate) fn read(
263 item: &Item,
264 path: &str,
265 fallback: Option<&str>,
266 requirements: &mut Vec<BindingRequirement>,
267 ) -> Result<Self> {
268 let fields = grammar::record_fields(item, FIELDS)?;
269 let layout = match field::<String>(fields, "scope", Some("full".to_owned()))?.as_str() {
270 "full" => false,
271 "layout" => true,
272 _ => return Err(invalid("Canvas recipe requires full or layout scope")),
273 };
274 let mut canvas = Canvas::grid(
275 field(fields, "rows", None)?,
276 field(fields, "columns", None)?,
277 )?;
278 canvas.theme = field::<Option<Theme>>(fields, "theme", Some(None))?.map(Arc::new);
279 canvas.default_theme =
280 field::<Option<Theme>>(fields, "default_theme", Some(None))?.map(Arc::new);
281 canvas.root_size = field(fields, "size", Some(crate::layout::RootRequest::Natural))?;
282 read_configuration(&mut canvas, fields, path, fallback, requirements, layout)?;
283 let mut panels = Vec::new();
284 let mut floating = Vec::new();
285 if let Some(items) = fields.get("panels") {
286 for (index, item) in array_items(items)?.enumerate() {
287 crate::operation::check()?;
288 let panel_path = format!("{path}.panels[{index}]");
289 if item.get("slot").is_some()
290 || item.get("box").is_some()
291 || item.get("at").is_some()
292 {
293 if layout {
294 return Err(invalid(format!(
295 "{panel_path}: layout scope cannot contain floating content"
296 )));
297 }
298 floating.push(crate::composition::recipe::read_placement(
299 item,
300 &panel_path,
301 fallback,
302 requirements,
303 )?);
304 } else if let Some(panel) = read_panel(
305 item,
306 &mut canvas,
307 &panel_path,
308 fallback,
309 requirements,
310 layout,
311 )? {
312 panels.push(panel);
313 }
314 }
315 }
316 if let Some(groups) = fields.get("range_groups") {
317 read_range_groups(groups, &mut canvas)?;
318 }
319 for panel in &panels {
320 let index = panel.footprint.row * canvas.columns + panel.footprint.column;
321 let shared = canvas.category_labels == CanvasCategoryLabels::FirstColumnPerRow
322 || canvas
323 .x_range_groups
324 .iter()
325 .any(|group| group.contains(&index));
326 if shared && !panel.source.permits_plot() {
327 return Err(invalid(format!(
328 "{}: shared scientific axes require Plot content",
329 panel.path
330 )));
331 }
332 }
333 for placement in &floating {
334 let (row, column) = placement.slot_borrow()?;
335 if row >= canvas.rows
336 || column >= canvas.columns
337 || canvas
338 .placements
339 .reservation(row * canvas.columns + column)
340 .is_none()
341 {
342 return Err(invalid(format!("{path}: floating placement requires an actual reserved anchor ({row}, {column})")));
343 }
344 }
345 canvas.validate_recipe_topology()?;
347 Ok(Self {
348 canvas,
349 panels,
350 floating,
351 })
352 }
353
354 pub(crate) fn build(self, resolver: &mut Resolver<'_>) -> Result<Canvas> {
355 let mut canvas = self.canvas;
356 for panel in self.panels {
357 let source = panel.source.build(resolver)?;
358 let payload = match source.0 {
359 DeclaredContent::Plot(plot) => placement::Payload::Plot(*plot),
360 DeclaredContent::Text(text) => placement::Payload::Text(text),
361 DeclaredContent::Fixed(source) => {
362 placement::Payload::Fixed(panel.fixed.admit(source)?)
363 }
364 DeclaredContent::Canvas(_) => {
365 return Err(invalid(format!(
366 "{}: nested Canvas grid panels are not available",
367 panel.path
368 )))
369 }
370 };
371 let placements = Arc::make_mut(&mut canvas.placements);
372 placements.insert(panel.footprint, payload)?;
373 placements.set_content_origin(
374 panel.footprint.row * canvas.columns + panel.footprint.column,
375 source.1,
376 );
377 }
378 for placement in self.floating {
379 canvas.place_panel_placement(placement.build(resolver)?)?;
380 }
381 canvas.validate_recipe_topology()?;
382 Ok(canvas)
383 }
384}
385
386fn read_configuration(
387 canvas: &mut Canvas,
388 fields: &dyn toml_edit::TableLike,
389 path: &str,
390 fallback: Option<&str>,
391 requirements: &mut Vec<BindingRequirement>,
392 layout: bool,
393) -> Result<()> {
394 canvas.legend_policy = field(fields, "legend_policy", Some(CanvasLegendPolicy::PerPlot))?;
395 canvas.legend_composition = field(
396 fields,
397 "legend_composition",
398 Some(LegendComposition::Combined),
399 )?;
400 canvas.category_labels = field(
401 fields,
402 "category_labels",
403 Some(CanvasCategoryLabels::EveryPlot),
404 )?;
405 if layout && LAYOUT_REMOVED.iter().any(|key| fields.contains_key(key)) {
406 return Err(invalid(
407 "layout scope does not retain prose or authored data labels",
408 ));
409 }
410 canvas.title = field(fields, "title", Some(crate::Text::UNSET))?;
411 canvas.subtitle = field(fields, "subtitle", Some(crate::Text::UNSET))?;
412 canvas.caption = field(fields, "caption", Some(crate::Text::UNSET))?;
413 canvas.panel_title_alignment = field(fields, "panel_title_alignment", Some(None))?;
414 canvas.panel_subtitle_alignment = field(fields, "panel_subtitle_alignment", Some(None))?;
415 if let Some(labels) = fields.get("labels") {
416 canvas.labels = Some(
417 crate::builder::recipe::read_labels(labels, path, fallback, false, requirements)?.0,
418 );
419 }
420 if let Some(item) = fields.get("guide_text_layouts") {
421 let fields = grammar::record_fields(item, GUIDE_LAYOUT_FIELDS)?;
422 for (slot, role) in canvas
423 .guide_text_layouts
424 .iter_mut()
425 .zip(["title", "entry", "number"])
426 {
427 *slot = field(fields, role, Some(None))?;
428 }
429 }
430 for header in field::<Vec<CanvasHeader>>(fields, "column_headers", Some(Vec::new()))? {
431 *canvas = canvas
432 .clone()
433 .column_header(header.start, header.span, header.text)?;
434 }
435 for header in field::<Vec<CanvasHeader>>(fields, "row_headers", Some(Vec::new()))? {
436 *canvas = canvas
437 .clone()
438 .row_header(header.start, header.span, header.text)?;
439 }
440 for header in field::<Vec<CanvasHeader>>(fields, "row_titles", Some(Vec::new()))? {
441 if header.span != 1 {
442 return Err(invalid("row title spans exactly one row"));
443 }
444 *canvas = canvas.clone().row_title(header.start, header.text)?;
445 }
446 Ok(())
447}
448
449fn read_panel(
450 item: &Item,
451 canvas: &mut Canvas,
452 path: &str,
453 fallback: Option<&str>,
454 requirements: &mut Vec<BindingRequirement>,
455 layout: bool,
456) -> Result<Option<PanelBuild>> {
457 let mut allowed = grammar::names(PANEL_FIELDS);
458 allowed.extend(CONTENT_FIELDS);
459 allowed.extend(FIXED_FIELDS);
460 let fields = table(item, &allowed)?;
461 let footprint = placement::Footprint {
462 row: field(fields, "row", None)?,
463 column: field(fields, "column", None)?,
464 row_span: field(fields, "row_span", Some(1))?,
465 column_span: field(fields, "column_span", Some(1))?,
466 };
467 let name: Option<String> = field(fields, "name", Some(None))?;
468 let content = CONTENT_FIELDS.iter().any(|key| fields.contains_key(key));
469 let fixed = FIXED_FIELDS.iter().any(|key| fields.contains_key(key));
470 let vacant = field(fields, "vacant", Some(false))?;
471 let reserve = fields.get("reserve");
472 let location = format!(
473 "{path} {:?} ({}, {})",
474 name.as_deref(),
475 footprint.row,
476 footprint.column
477 );
478 let reservation = if let Some(item) = reserve {
479 let fields = grammar::record_fields(item, RESERVE_FIELDS)?;
480 let width = field(fields, "min_width", Some(0.))?;
481 let height = field(fields, "min_height", Some(0.))?;
482 ReservedSlot::at_least(width, height)?;
483 Some((width, height))
484 } else {
485 None
486 };
487 if (reservation.is_some() || layout || vacant) && (content || fixed)
488 || (vacant && reservation.is_some())
489 {
490 return Err(invalid(format!(
491 "{location}: a vacant or reserved slot cannot have content"
492 )));
493 }
494 if fixed && !(fields.contains_key("asset") || fields.contains_key("frozen")) {
495 return Err(invalid(format!(
496 "{location}: fixed-frame options require fixed content"
497 )));
498 }
499 if reservation.is_none() && !vacant && !layout && !content {
500 return Err(invalid(format!(
501 "{location}: a full panel requires content"
502 )));
503 }
504 let placements = Arc::make_mut(&mut canvas.placements);
505 placements
506 .insert(
507 footprint,
508 reservation.map_or(placement::Payload::Vacant, placement::Payload::Reserved),
509 )
510 .map_err(|error| error.with_prefix(&location))?;
511 if let Some(name) = name {
512 placements.name(footprint.row, footprint.column, &name)?;
513 }
514 if content {
515 Ok(Some(PanelBuild {
516 footprint,
517 source: read_content(fields, path, fallback, requirements, false)?,
518 fixed: FixedOptions::read(fields)?,
519 path: path.to_owned(),
520 }))
521 } else {
522 Ok(None)
523 }
524}
525
526impl Canvas {
527 fn validate_recipe_topology(&self) -> Result<()> {
528 self.root_size.validate()?;
529 if self.placements.slots().next().is_some() {
532 self.validate_structure()?;
533 }
534 Ok(())
535 }
536
537 pub(crate) fn capture_recipe(
538 &self,
539 context: &mut Capture,
540 path: &str,
541 scope: CanvasRecipeScope,
542 ) -> Result<Value> {
543 if scope == CanvasRecipeScope::Style {
544 return self.capture_style(true);
545 }
546 let layout = scope == CanvasRecipeScope::Layout;
547 let mut fields = self.capture_recipe_configuration(context, path, layout)?;
548 if layout {
549 fields.insert("scope", "layout".into());
550 }
551 let mut panels = toml_edit::Array::new();
552 for slot in self.placements.slots() {
553 crate::operation::check()?;
554 let index = slot.row() * self.columns + slot.column();
555 let prefix = slot.name().map_or_else(
556 || format!("panel_{}_{}", slot.row(), slot.column()),
557 str::to_owned,
558 );
559 let panel_path = format!("{path}.panels[{}]", panels.len());
560 let mut panel = InlineTable::new();
561 for (key, value) in [
562 ("row", slot.row()),
563 ("column", slot.column()),
564 ("row_span", slot.row_span()),
565 ("column_span", slot.column_span()),
566 ] {
567 panel.insert(key, value.encode());
568 }
569 if let Some(name) = slot.name() {
570 panel.insert("name", Value::from(name));
571 }
572 if let Some((width, height)) = slot.reservation() {
573 let mut reserved = InlineTable::new();
574 reserved.insert("min_width", width.encode());
575 reserved.insert("min_height", height.encode());
576 panel.insert("reserve", reserved.into());
577 } else if !layout {
578 context.owner(&prefix, |context| {
579 let origin = self.placements.content_origin(index);
580 match self.placements.payload(index).expect("actual panel owner") {
581 placement::Payload::Vacant => {
582 panel.insert("vacant", true.into());
583 }
584 placement::Payload::Plot(_) | placement::Payload::Text(_)
585 if origin.is_some() =>
586 {
587 panel.insert(
588 "native",
589 context.content_reference(
590 origin.expect("actual content binding"),
591 "native",
592 &format!("{panel_path}.native"),
593 )?,
594 );
595 }
596 placement::Payload::Plot(plot) => {
597 panel.insert(
598 "plot",
599 plot.capture_recipe(context, &format!("{panel_path}.plot"))?,
600 );
601 }
602 placement::Payload::Text(text) => {
603 panel.insert("text", text.encode());
604 }
605 placement::Payload::Fixed(fixed) => {
606 capture_fixed_panel(fixed, &mut panel, context, origin, &panel_path)?;
607 }
608 placement::Payload::Reserved(_) => unreachable!("actual reservation"),
609 }
610 Ok(())
611 })?;
612 }
613 panels.push(Value::from(panel));
614 }
615 if !layout {
616 for (index, placement) in self.slot_placements.iter().enumerate() {
617 let panel_path = format!("{path}.panels[{}]", panels.len());
618 let value = context.owner(&format!("placement_{index}"), |context| {
619 placement.capture_recipe(context, &panel_path)
620 })?;
621 panels.push(value);
622 }
623 }
624 fields.insert("panels", panels.into());
625 Ok(fields.into())
626 }
627
628 fn capture_recipe_configuration(
629 &self,
630 context: &mut Capture,
631 path: &str,
632 layout: bool,
633 ) -> Result<InlineTable> {
634 let mut fields = InlineTable::new();
635 fields.insert("rows", self.rows.encode());
636 fields.insert("columns", self.columns.encode());
637 fields.insert("size", self.root_size.encode());
638 if let Some(theme) = &self.theme {
639 fields.insert("theme", theme.encode());
640 }
641 if let Some(theme) = &self.default_theme {
642 fields.insert("default_theme", theme.encode());
643 }
644 fields.insert("legend_policy", self.legend_policy.encode());
645 fields.insert("legend_composition", self.legend_composition.encode());
646 fields.insert("category_labels", self.category_labels.encode());
647 if let Some(value) = self.panel_title_alignment {
648 fields.insert("panel_title_alignment", value.encode());
649 }
650 if let Some(value) = self.panel_subtitle_alignment {
651 fields.insert("panel_subtitle_alignment", value.encode());
652 }
653 let mut guides = InlineTable::new();
654 for (role, layout) in ["title", "entry", "number"]
655 .into_iter()
656 .zip(&self.guide_text_layouts)
657 {
658 if let Some(layout) = layout {
659 guides.insert(role, layout.encode());
660 }
661 }
662 if !guides.is_empty() {
663 fields.insert("guide_text_layouts", guides.into());
664 }
665 if !layout {
666 for (key, value) in [
667 ("title", &self.title),
668 ("subtitle", &self.subtitle),
669 ("caption", &self.caption),
670 ] {
671 if value != &crate::Text::UNSET {
672 fields.insert(key, value.encode());
673 }
674 }
675 if let Some(labels) = &self.labels {
676 fields.insert(
677 "labels",
678 crate::builder::recipe::encode_labels(labels, context, path)?,
679 );
680 }
681 for (key, headers) in [
682 ("column_headers", &self.column_headers),
683 ("row_headers", &self.row_headers),
684 ("row_titles", &self.row_titles),
685 ] {
686 if !headers.is_empty() {
687 fields.insert(key, headers.encode());
688 }
689 }
690 }
691 if !self.x_range_groups.is_empty() {
692 let groups: toml_edit::Array = self
693 .x_range_groups
694 .iter()
695 .map(|group| {
696 let mut fields = InlineTable::new();
697 fields.insert("axis", "x".into());
698 fields.insert("mode", "domain".into());
699 let paths = group
700 .iter()
701 .map(|&index| {
702 self.placements
703 .slot(index)
704 .and_then(|slot| slot.name().map(PanelPath::from))
705 .unwrap_or_else(|| {
706 PanelPath::from((index / self.columns, index % self.columns))
707 })
708 })
709 .collect::<Vec<_>>();
710 fields.insert("panels", paths.encode());
711 Value::from(fields)
712 })
713 .collect();
714 fields.insert("range_groups", groups.into());
715 }
716 Ok(fields)
717 }
718}
719impl Canvas {
720 pub fn get_recipe(&self) -> Result<crate::recipe::Recipe> {
722 self.get_recipe_with_operation(&crate::operation::OperationOptions::default())
723 }
724 pub fn get_recipe_with_operation(
726 &self,
727 options: &crate::operation::OperationOptions,
728 ) -> Result<crate::recipe::Recipe> {
729 self.get_recipe_with_scope_and_operation(CanvasRecipeScope::Full, options)
730 }
731 pub fn get_recipe_with_scope(&self, scope: CanvasRecipeScope) -> Result<crate::recipe::Recipe> {
733 self.get_recipe_with_scope_and_operation(
734 scope,
735 &crate::operation::OperationOptions::default(),
736 )
737 }
738 pub fn get_recipe_with_scope_and_operation(
740 &self,
741 scope: CanvasRecipeScope,
742 options: &crate::operation::OperationOptions,
743 ) -> Result<crate::recipe::Recipe> {
744 crate::operation::run(options, || {
745 let mut context = Capture::new();
746 let value = self.capture_recipe(&mut context, "canvas", scope)?;
747 crate::recipe::Recipe::from_capture("canvas", value, context)
748 })
749 }
750 pub fn recipe(&self, path: impl AsRef<std::path::Path>) -> Result<crate::recipe::Recipe> {
752 self.recipe_with_operation(path, &crate::operation::OperationOptions::default())
753 }
754 pub fn recipe_with_operation(
756 &self,
757 path: impl AsRef<std::path::Path>,
758 options: &crate::operation::OperationOptions,
759 ) -> Result<crate::recipe::Recipe> {
760 self.recipe_with_scope_and_operation(path, CanvasRecipeScope::Full, options)
761 }
762 pub fn recipe_with_scope(
764 &self,
765 path: impl AsRef<std::path::Path>,
766 scope: CanvasRecipeScope,
767 ) -> Result<crate::recipe::Recipe> {
768 self.recipe_with_scope_and_operation(
769 path,
770 scope,
771 &crate::operation::OperationOptions::default(),
772 )
773 }
774 pub fn recipe_with_scope_and_operation(
776 &self,
777 path: impl AsRef<std::path::Path>,
778 scope: CanvasRecipeScope,
779 options: &crate::operation::OperationOptions,
780 ) -> Result<crate::recipe::Recipe> {
781 crate::operation::run(options, || {
782 let mut context = Capture::new();
783 let value = self.capture_recipe(&mut context, "canvas", scope)?;
784 let recipe = crate::recipe::Recipe::from_capture("canvas", value, context)?;
785 recipe.write_document(path.as_ref())?;
786 Ok(recipe)
787 })
788 }
789}