oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1//! The JSON view of a deck: what `GET /api/v1/decks/{sqid}` returns and
2//! what the renderer, the thumbnailer and the PDF exporter read. Its
3//! shape is the contract in the task brief, verbatim:
4//!
5//! ```json
6//! {"meta":{"title":"","theme":"paper","accent":null,"fonts":null,"aspect":"16:9"},
7//! "slides":[{"id":"…","layout":"flow","template":"title",
8//! "background":{"kind":"theme","value":""},
9//! "phone":"inherit","transition":"none",
10//! "notes":[[{"t":"Say hello"}]],
11//! "blocks":[{"id":"…","type":"heading","props":{"level":1},
12//! "region":"heading","box":null,"z":0,"phone":{},
13//! "text":[[{"t":"Hello","b":true}]]}]}],
14//! "assets":{"id":{"ref":"…","name":"","width":0,"height":0,"alt":""}}}
15//! ```
16//!
17//! A clip's video asset also has `poster` (its first frame's ref) and
18//! `duration` (whole milliseconds), each omitted when absent.
19//!
20//! A deck with scenes also has `"scenes": {id: {name, author, code,
21//! states: [{id, name, description}], words, data, stills}}` (scene.rs);
22//! a deck without has no `scenes` key at all.
23//!
24//! `blocks` is in reading order — the `order` key sorted, array index
25//! for ties — and the key itself is not in the view: one sequence for
26//! every reader (schema.rs, "block order").
27//!
28//! Text is an array of paragraphs, a paragraph an array of runs
29//! `{t, b?, i?, c?, h?, href?}` with false and absent marks omitted. A
30//! block's `text` key is present for text-bearing types (any block that
31//! carries a `text` fragment) and absent otherwise; a `table`'s cells
32//! appear as `props.cells`, a row-major array of texts.
33//!
34//! Four keys are omitted when absent rather than defaulted, because
35//! their absence is itself the meaning: a block's `step` (a number
36//! above 0, the press it arrives on) and `items` (`together` or `each`,
37//! on a list), a slide's `talk` (`full` or `parked`) and the meta's
38//! `arrive` (`appear`, `fade` or `rise`). A value outside those reads as
39//! absent.
40//!
41//! Every key has a default so a deck a peer left half-written still
42//! renders as something rather than failing to serialise: an absent
43//! `layout` is `flow`, an absent `template` is `blank`, an absent `z`
44//! is 0. Key order within `props`, `assets` and other free-form objects
45//! is sorted (serde_json's default map), so the output is deterministic
46//! and two documents with the same content render byte-identically —
47//! which is what the update round-trip tests compare.
48
49use crate::scene;
50use crate::schema::{self, Paragraph};
51use serde::Serialize;
52use serde_json::Value;
53use std::collections::BTreeMap;
54use yrs::{Array, Doc, Map, ReadTxn, Transact};
55
56#[derive(Serialize)]
57struct View {
58 meta: Meta,
59 slides: Vec<Slide>,
60 assets: BTreeMap<String, Value>,
61 /// Omitted when the deck has none, so a deck without scenes views
62 /// exactly as it did before there were any.
63 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
64 scenes: BTreeMap<String, Value>,
65}
66
67#[derive(Serialize)]
68struct Meta {
69 title: String,
70 theme: String,
71 accent: Option<String>,
72 fonts: Option<Value>,
73 #[serde(rename = "fontFiles", skip_serializing_if = "Option::is_none")]
74 font_files: Option<Value>,
75 aspect: String,
76 #[serde(skip_serializing_if = "Option::is_none")]
77 arrive: Option<String>,
78}
79
80#[derive(Serialize)]
81struct Slide {
82 id: String,
83 layout: String,
84 template: String,
85 background: Value,
86 phone: String,
87 transition: String,
88 notes: Vec<Paragraph>,
89 blocks: Vec<Block>,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 talk: Option<String>,
92}
93
94#[derive(Serialize)]
95struct Block {
96 id: String,
97 #[serde(rename = "type")]
98 kind: String,
99 props: Value,
100 region: Option<String>,
101 #[serde(rename = "box")]
102 bx: Option<Value>,
103 z: Value,
104 phone: Value,
105 #[serde(skip_serializing_if = "Option::is_none")]
106 text: Option<Vec<Paragraph>>,
107 #[serde(skip_serializing_if = "Option::is_none")]
108 step: Option<Value>,
109 #[serde(skip_serializing_if = "Option::is_none")]
110 items: Option<String>,
111}
112
113fn empty_object() -> Value {
114 Value::Object(serde_json::Map::new())
115}
116
117// --- typed leaves ---
118//
119// The host reads this view through typed structs (internal/slides/deck),
120// and a browser peer can put any shape at any key: `box.x = "a"`,
121// `background.kind = 5`, `fonts.body = []`, an asset that is a string.
122// Passed through untyped, any one of those fails the host's parse of the
123// WHOLE deck and every surface that opens it. So each leaf with a fixed
124// shape is rebuilt here from the fields that have the right type, and a
125// shape that cannot be made is omitted (null, the default, a skipped
126// entry) rather than emitted. `fixtures/view.mjs` applies the same
127// rules, key for key, because the vectors compare the two.
128
129type Object = serde_json::Map<String, Value>;
130
131fn as_object(v: Option<Value>) -> Option<Object> {
132 match v {
133 Some(Value::Object(o)) => Some(o),
134 _ => None,
135 }
136}
137
138/// A present string field, or None. `Err` is a present field of the
139/// wrong type — the case that disqualifies a fixed-shape object.
140fn string_field(o: &Object, key: &str) -> Result<Option<String>, ()> {
141 match o.get(key) {
142 None | Some(Value::Null) => Ok(None),
143 Some(Value::String(s)) => Ok(Some(s.clone())),
144 Some(_) => Err(()),
145 }
146}
147
148fn number_field(o: &Object, key: &str) -> Result<Option<f64>, ()> {
149 match o.get(key) {
150 None | Some(Value::Null) => Ok(None),
151 Some(Value::Number(n)) => Ok(n.as_f64()),
152 Some(_) => Err(()),
153 }
154}
155
156/// `{x, y, w, h}`, all four numbers, or None.
157fn box_value(v: Option<Value>) -> Option<Value> {
158 let o = as_object(v)?;
159 let mut out = Object::new();
160 for key in ["x", "y", "w", "h"] {
161 let n = number_field(&o, key).ok()??;
162 out.insert(key.into(), schema::number_json(n));
163 }
164 Some(Value::Object(out))
165}
166
167/// `{kind, value}` with kind a string, else the theme default.
168fn background_value(v: Option<Value>) -> Value {
169 let fallback = || serde_json::json!({"kind": "theme", "value": ""});
170 let Some(o) = as_object(v) else {
171 return fallback();
172 };
173 let (Ok(Some(kind)), Ok(value)) = (string_field(&o, "kind"), string_field(&o, "value")) else {
174 return fallback();
175 };
176 serde_json::json!({"kind": kind, "value": value.unwrap_or_default()})
177}
178
179/// `{heading, body}`, both strings when present, else None.
180fn fonts_value(v: Option<Value>) -> Option<Value> {
181 let o = as_object(v)?;
182 let heading = string_field(&o, "heading").ok()?;
183 let body = string_field(&o, "body").ok()?;
184 Some(serde_json::json!({
185 "heading": heading.unwrap_or_default(),
186 "body": body.unwrap_or_default(),
187 }))
188}
189
190/// `meta.fontFiles` when the whole list is well formed (schema::font_files),
191/// else None: a list with one bad face is not half trusted.
192fn font_files_value<T: yrs::ReadTxn>(txn: &T, meta: &yrs::MapRef) -> Option<Value> {
193 match yrs::Map::get(meta, txn, "fontFiles")? {
194 yrs::Out::Any(a) => schema::font_files(&schema::any_to_json(&a)).ok(),
195 _ => None,
196 }
197}
198
199/// The §2.5 overrides that have the right type, field by field: the
200/// layer is additions to the desktop layout, so a bad `hidden` should
201/// not cost a good `order`. `order` is a whole number to the host.
202fn phone_value(v: Option<Value>) -> Value {
203 let Some(o) = as_object(v) else {
204 return empty_object();
205 };
206 let mut out = Object::new();
207 if let Some(Value::Bool(b)) = o.get("hidden") {
208 out.insert("hidden".into(), Value::Bool(*b));
209 }
210 if let Ok(Some(n)) = number_field(&o, "order") {
211 out.insert("order".into(), schema::number_json(n.trunc()));
212 }
213 if let Ok(Some(s)) = string_field(&o, "size") {
214 out.insert("size".into(), Value::String(s));
215 }
216 if let Some(b) = box_value(o.get("box").cloned()) {
217 out.insert("box".into(), b);
218 }
219 Value::Object(out)
220}
221
222/// `{ref, name, width, height, alt}` for an entry with a string `ref`;
223/// None for anything else. The other four take their defaults when
224/// absent or mistyped: the picture is the ref, and losing it over a
225/// bad alt would be the wrong trade.
226fn asset_value(v: Value) -> Option<Value> {
227 let o = as_object(Some(v))?;
228 let r = string_field(&o, "ref").ok()??;
229 let text = |key: &str| string_field(&o, key).ok().flatten().unwrap_or_default();
230 let whole = |key: &str| {
231 number_field(&o, key)
232 .ok()
233 .flatten()
234 .map(|n| schema::number_json(n.trunc()))
235 .unwrap_or(Value::from(0))
236 };
237 let mut out = serde_json::json!({
238 "ref": r,
239 "name": text("name"),
240 "width": whole("width"),
241 "height": whole("height"),
242 "alt": text("alt"),
243 });
244 // A clip's video (scenes and clips spec §2): its poster's ref and its
245 // length in whole milliseconds, each only when there is one, so a
246 // picture's record is what it always was.
247 if let Some(p) = string_field(&o, "poster")
248 .ok()
249 .flatten()
250 .filter(|p| !p.is_empty())
251 {
252 out["poster"] = Value::from(p);
253 }
254 if let Some(n) = number_field(&o, "duration")
255 .ok()
256 .flatten()
257 .filter(|n| n.is_finite() && n.trunc() > 0.0)
258 {
259 out["duration"] = schema::number_json(n.trunc());
260 }
261 Some(out)
262}
263
264/// A string key whose value is one of `vocab`, or None: a mistyped or
265/// unknown value reads as no key, which is what each of these keys'
266/// absence already means (`talk`, `items`, `arrive`).
267fn vocab_string<T: ReadTxn>(txn: &T, m: &yrs::MapRef, key: &str, vocab: &[&str]) -> Option<String> {
268 schema::get_string(txn, m, key).filter(|s| vocab.contains(&s.as_str()))
269}
270
271/// A block's `step`: a finite number above 0, or None. Anything else a
272/// peer wrote there reads as no step, the box arriving with its slide.
273fn step_value<T: ReadTxn>(txn: &T, m: &yrs::MapRef) -> Option<Value> {
274 schema::get_number(txn, m, "step")
275 .filter(|n| n.is_finite() && *n > 0.0)
276 .map(schema::number_json)
277}
278
279fn block_view<T: ReadTxn>(txn: &T, m: &yrs::MapRef) -> Block {
280 let mut props = schema::get_object(txn, m, "props").unwrap_or_else(empty_object);
281 if let Some(cells) = schema::get_array(txn, m, "cells") {
282 let texts: Vec<Value> = cells
283 .iter(txn)
284 .map(|c| match c {
285 yrs::Out::YXmlFragment(f) => {
286 serde_json::to_value(schema::read_text(txn, &f)).unwrap_or_default()
287 }
288 other => schema::out_to_json(txn, &other),
289 })
290 .collect();
291 if let Value::Object(p) = &mut props {
292 p.insert("cells".into(), Value::Array(texts));
293 }
294 }
295 Block {
296 id: schema::get_string(txn, m, "id").unwrap_or_default(),
297 kind: schema::get_string(txn, m, "type").unwrap_or_default(),
298 props,
299 region: schema::get_string(txn, m, "region"),
300 bx: box_value(schema::get_object(txn, m, "box")),
301 z: schema::number_json(schema::get_number(txn, m, "z").unwrap_or(0.0)),
302 phone: phone_value(schema::get_object(txn, m, "phone")),
303 text: schema::get_fragment(txn, m, "text").map(|f| schema::read_text(txn, &f)),
304 step: step_value(txn, m),
305 items: vocab_string(txn, m, "items", schema::ITEMS),
306 }
307}
308
309fn slide_view<T: ReadTxn>(txn: &T, m: &yrs::MapRef) -> Slide {
310 // Blocks in reading order (schema::ordered_maps), so every
311 // reader of the view — the renderer, the layout engine, the API —
312 // sees one sequence and none of them knows there is an `order` key.
313 let blocks = schema::get_array(txn, m, "blocks")
314 .map(|a| {
315 schema::ordered_maps(txn, &a)
316 .iter()
317 .map(|(_, b)| block_view(txn, b))
318 .collect()
319 })
320 .unwrap_or_default();
321 Slide {
322 id: schema::get_string(txn, m, "id").unwrap_or_default(),
323 layout: schema::get_string(txn, m, "layout").unwrap_or_else(|| "flow".into()),
324 template: schema::get_string(txn, m, "template")
325 .unwrap_or_else(|| schema::DEFAULT_TEMPLATE.into()),
326 background: background_value(schema::get_object(txn, m, "background")),
327 phone: schema::get_string(txn, m, "phone").unwrap_or_else(|| "inherit".into()),
328 transition: schema::get_string(txn, m, "transition").unwrap_or_else(|| "none".into()),
329 notes: schema::get_fragment(txn, m, "notes")
330 .map(|f| schema::read_text(txn, &f))
331 .unwrap_or_default(),
332 blocks,
333 talk: vocab_string(txn, m, "talk", schema::TALKS),
334 }
335}
336
337/// The deck as JSON. Never empty: an untouched document renders as the
338/// defaults with no slides and no assets.
339pub fn view_json(doc: &Doc) -> String {
340 let roots = schema::roots(doc);
341 let txn = doc.transact();
342 let meta = Meta {
343 title: schema::get_string(&txn, &roots.meta, "title").unwrap_or_default(),
344 theme: schema::get_string(&txn, &roots.meta, "theme")
345 .unwrap_or_else(|| schema::DEFAULT_THEME.into()),
346 accent: schema::get_string(&txn, &roots.meta, "accent"),
347 fonts: fonts_value(schema::get_object(&txn, &roots.meta, "fonts")),
348 font_files: font_files_value(&txn, &roots.meta),
349 aspect: schema::get_string(&txn, &roots.meta, "aspect")
350 .unwrap_or_else(|| schema::DEFAULT_ASPECT.into()),
351 arrive: vocab_string(&txn, &roots.meta, "arrive", schema::ARRIVALS),
352 };
353 // Slides in reading order (schema::ordered_maps), the same way the
354 // blocks of one are: the `order` key never reaches the view, so no
355 // reader of it knows there is one.
356 let slides = schema::ordered_maps(&txn, &roots.slides)
357 .iter()
358 .map(|(_, m)| slide_view(&txn, m))
359 .collect();
360 let assets = roots
361 .assets
362 .iter(&txn)
363 .filter_map(|(k, v)| asset_value(schema::out_to_json(&txn, &v)).map(|a| (k.to_string(), a)))
364 .collect();
365 let scenes = roots
366 .scenes
367 .iter(&txn)
368 .filter_map(|(k, v)| {
369 scene::scene_view(schema::out_to_json(&txn, &v)).map(|s| (k.to_string(), s))
370 })
371 .collect();
372 let view = View {
373 meta,
374 slides,
375 assets,
376 scenes,
377 };
378 // Serialising a struct of strings, numbers and already-built Values
379 // cannot fail; the fallback is belt and braces, not a path.
380 serde_json::to_string(&view).unwrap_or_else(|_| String::from("{}"))
381}
382
383#[cfg(test)]
384mod tests {
385 //! The view has to be readable by the host's typed `deck.Parse` for
386 //! ANY document the CRDT can hold, not only ones this crate's ops
387 //! wrote — a browser peer can put any shape at any key. These build
388 //! the malformed shapes directly with yrs and require the view to
389 //! omit or default them rather than pass them through untyped.
390 //! `fixtures/view.test.mjs` is the JS twin.
391 use super::*;
392 use crate::new_doc;
393 use yrs::{In, MapPrelim};
394
395 fn any(v: serde_json::Value) -> In {
396 In::Any(schema::json_to_any(&v))
397 }
398
399 fn poisoned() -> Value {
400 let doc = new_doc("poison", 7);
401 let roots = schema::roots(&doc);
402 {
403 let mut txn = doc.transact_mut();
404 roots.meta.insert(
405 &mut txn,
406 "fonts",
407 any(serde_json::json!({"heading": "Serif", "body": []})),
408 );
409 let phone: MapPrelim = [
410 ("hidden", any(serde_json::json!("yes"))),
411 ("order", any(serde_json::json!(2.7))),
412 ("size", any(serde_json::json!(7))),
413 (
414 "box",
415 any(serde_json::json!({"x": 0, "y": 0, "w": 1, "h": 0.5})),
416 ),
417 ]
418 .into_iter()
419 .collect();
420 let block: MapPrelim = [
421 ("id", any(serde_json::json!("blk"))),
422 ("type", any(serde_json::json!("text"))),
423 (
424 "box",
425 any(serde_json::json!({"x": "a", "y": 0, "w": 1, "h": 1})),
426 ),
427 ("z", any(serde_json::json!(1))),
428 ("phone", In::Map(phone)),
429 ]
430 .into_iter()
431 .collect();
432 let background: MapPrelim = [
433 ("kind", any(serde_json::json!(5))),
434 ("value", any(serde_json::json!(""))),
435 ]
436 .into_iter()
437 .collect();
438 let blocks: yrs::ArrayPrelim = [In::Map(block)].into_iter().collect();
439 let slide: MapPrelim = [
440 ("id", any(serde_json::json!("sld"))),
441 ("layout", any(serde_json::json!("canvas"))),
442 ("background", In::Map(background)),
443 ("blocks", In::Array(blocks)),
444 ]
445 .into_iter()
446 .collect();
447 roots.slides.push_back(&mut txn, slide);
448 roots
449 .assets
450 .insert(&mut txn, "str", any(serde_json::json!("not a map")));
451 roots
452 .assets
453 .insert(&mut txn, "noref", any(serde_json::json!({"name": "x.png"})));
454 roots.assets.insert(
455 &mut txn,
456 "badfields",
457 any(serde_json::json!({
458 "ref": "abc", "name": 3, "width": "w", "height": 9.9, "alt": null
459 })),
460 );
461 roots.assets.insert(
462 &mut txn,
463 "good",
464 any(serde_json::json!({
465 "ref": "def", "name": "p.png", "width": 10, "height": 20, "alt": "A"
466 })),
467 );
468 }
469 serde_json::from_str(&view_json(&doc)).expect("view is JSON")
470 }
471
472 /// `step`, `items`, `talk` and `arrive` with values no op writes: a
473 /// string step, a step of 0 or below, a numeric items, an unknown
474 /// items, talk and arrive.
475 fn off_vocabulary() -> Value {
476 let doc = new_doc("steps", 7);
477 let roots = schema::roots(&doc);
478 {
479 let mut txn = doc.transact_mut();
480 roots
481 .meta
482 .insert(&mut txn, "arrive", any(serde_json::json!("zoom")));
483 let block = |id: &str, step: Value, items: Value| -> In {
484 let m: MapPrelim = [
485 ("id", any(serde_json::json!(id))),
486 ("type", any(serde_json::json!("list"))),
487 ("step", any(step)),
488 ("items", any(items)),
489 ]
490 .into_iter()
491 .collect();
492 In::Map(m)
493 };
494 let blocks: yrs::ArrayPrelim = [
495 block("b1", serde_json::json!("2"), serde_json::json!(5)),
496 block("b2", serde_json::json!(-1), serde_json::json!("bogus")),
497 block("b3", serde_json::json!(0), serde_json::json!(true)),
498 block("b4", serde_json::json!(0.25), serde_json::json!("each")),
499 ]
500 .into_iter()
501 .collect();
502 let slide: MapPrelim = [
503 ("id", any(serde_json::json!("sld"))),
504 ("talk", any(serde_json::json!("maybe"))),
505 ("blocks", In::Array(blocks)),
506 ]
507 .into_iter()
508 .collect();
509 roots.slides.push_back(&mut txn, slide);
510 }
511 serde_json::from_str(&view_json(&doc)).expect("view is JSON")
512 }
513
514 #[test]
515 fn step_items_talk_and_arrive_outside_their_vocabularies_are_absent() {
516 let v = off_vocabulary();
517 assert!(v["meta"].get("arrive").is_none(), "{}", v["meta"]);
518 assert!(v["slides"][0].get("talk").is_none(), "{}", v["slides"][0]);
519 let blocks = v["slides"][0]["blocks"].as_array().unwrap();
520 for b in &blocks[..3] {
521 assert!(b.get("step").is_none() && b.get("items").is_none(), "{b}");
522 }
523 assert_eq!(blocks[3]["step"].as_f64(), Some(0.25));
524 assert_eq!(blocks[3]["items"], "each");
525 }
526
527 #[test]
528 fn a_malformed_font_files_list_is_absent() {
529 let r = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
530 let face = |w: serde_json::Value| serde_json::json!({"ref": r, "format": "ttf", "weight": w, "italic": false, "pictures": true});
531 let list = |w: serde_json::Value| serde_json::json!([{"family": "F", "css": "F", "faces": [face(w)], "extra": 1}]);
532 let with = |v: serde_json::Value| {
533 let doc = new_doc("fontfiles", 7);
534 let roots = schema::roots(&doc);
535 {
536 let mut txn = doc.transact_mut();
537 roots.meta.insert(&mut txn, "fontFiles", any(v));
538 }
539 let v: Value = serde_json::from_str(&view_json(&doc)).unwrap();
540 v
541 };
542 let good = with(list(serde_json::json!([400, 700])));
543 assert_eq!(
544 good["meta"]["fontFiles"],
545 serde_json::json!([{"family": "F", "css": "F", "faces": [face(serde_json::json!([400, 700]))]}]),
546 "rebuilt from the known fields"
547 );
548 for bad in [
549 list(serde_json::json!([700, 400])),
550 list(serde_json::json!(["a", 1])),
551 serde_json::json!("nope"),
552 serde_json::json!({"family": "F"}),
553 ] {
554 let v = with(bad.clone());
555 assert!(v["meta"].get("fontFiles").is_none(), "{bad}");
556 }
557 }
558
559 #[test]
560 fn scenes_keep_only_their_typed_fields() {
561 // fixtures/view.test.mjs builds the same document.
562 let code = "0123456789abcdef".repeat(4);
563 let doc = new_doc("scenes", 1);
564 let scenes = doc.get_or_insert_map("scenes");
565 {
566 let mut txn = doc.transact_mut();
567 scenes.insert(&mut txn, "str", any(serde_json::json!("not a map")));
568 let words: MapPrelim = [
569 ("k", any(serde_json::json!("v"))),
570 ("n", any(serde_json::json!(4))),
571 ]
572 .into_iter()
573 .collect();
574 let m: MapPrelim = [
575 ("name", any(serde_json::json!(3))),
576 ("code", any(serde_json::json!(code))),
577 ("author", any(serde_json::json!(["x"]))),
578 (
579 "states",
580 any(serde_json::json!([
581 {"id": "a", "name": 5}, "b", {"name": "no id"},
582 {"id": "a", "name": "twice"}, {"id": "c", "description": "C"}
583 ])),
584 ),
585 ("words", In::Map(words)),
586 ("data", any(serde_json::json!({"deep": [1, {"x": "y"}]}))),
587 (
588 "stills",
589 any(serde_json::json!({
590 "a": {"ref": code, "made": code}, "b": {"ref": 3, "made": code}, "c": "x"
591 })),
592 ),
593 ]
594 .into_iter()
595 .collect();
596 scenes.insert(&mut txn, "w", m);
597 }
598 let v: Value = serde_json::from_str(&view_json(&doc)).unwrap();
599 assert_eq!(
600 v["scenes"],
601 serde_json::json!({"w": {
602 "name": "", "author": "", "code": code,
603 "states": [{"id": "a", "name": "", "description": ""}, {"id": "c", "name": "", "description": "C"}],
604 "words": {"k": "v"},
605 "data": {"deep": [1, {"x": "y"}]},
606 "stills": {"a": {"ref": code, "made": code}}
607 }})
608 );
609 }
610
611 #[test]
612 fn malformed_fonts_are_null() {
613 assert_eq!(poisoned()["meta"]["fonts"], Value::Null);
614 }
615
616 #[test]
617 fn malformed_background_is_the_default() {
618 assert_eq!(
619 poisoned()["slides"][0]["background"],
620 serde_json::json!({"kind": "theme", "value": ""})
621 );
622 }
623
624 #[test]
625 fn malformed_box_is_null_and_phone_keeps_only_typed_fields() {
626 let v = poisoned();
627 let block = &v["slides"][0]["blocks"][0];
628 assert_eq!(block["box"], Value::Null);
629 assert_eq!(
630 block["phone"],
631 serde_json::json!({"order": 2, "box": {"x": 0, "y": 0, "w": 1, "h": 0.5}})
632 );
633 }
634
635 #[test]
636 fn assets_are_typed_or_skipped() {
637 let v = poisoned();
638 assert_eq!(
639 v["assets"],
640 serde_json::json!({
641 "badfields": {"ref": "abc", "name": "", "width": 0, "height": 9, "alt": ""},
642 "good": {"ref": "def", "name": "p.png", "width": 10, "height": 20, "alt": "A"}
643 })
644 );
645 }
646}
647