oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1//! The operations the drive surface applies (spec §7.2), as one batch in
2//! one transaction.
3//!
4//! # Atomicity
5//!
6//! A yrs `TransactionMut` cannot be rolled back — dropping it commits
7//! whatever was written. So "a failure applies nothing" has to be true
8//! before the first write, and it is arranged in two passes:
9//!
10//! 1. Every op is parsed (shape, vocabularies, required fields) and then
11//! checked against a *model* of the deck — just the slide ids, their
12//! block ids and types, and the asset ids — that each op updates as
13//! it is checked, so a reference that only becomes wrong halfway
14//! through the batch (`remove_block` on a block an earlier op removed)
15//! is caught here too.
16//! 2. Only then does the transaction open and the ops apply. By the
17//! model's construction every lookup in this pass succeeds; the
18//! `Err`s it can still return exist so a bug here surfaces as a
19//! message rather than a trap, not because they are expected.
20//!
21//! # Ids
22//!
23//! The core never draws entropy (`lib.rs`). Every new slide or block id
24//! arrives in the op (`id`, `new_id`, `new_block_ids`) from the Go host,
25//! and an op that needs one and lacks it is a parse error.
26//!
27//! # The update
28//!
29//! The batch's update is the transaction's own `encode_update_v1()`,
30//! taken after an explicit `commit()` (which squashes the delete set and
31//! fires observers) and before the guard drops. yrs 0.23.5's
32//! `TransactionMut::encode_update` reads `before_state`, the store and
33//! the transaction's delete set, all of which are intact after commit —
34//! so no observer, no captured buffer, and nothing that could see a
35//! different transaction's changes.
36
37use crate::layout;
38use crate::markdown;
39use crate::scene::{self, SceneRef};
40use crate::schema::{self, Paragraph, Roots};
41use crate::CoreError;
42use serde::{Deserialize, Deserializer};
43use serde_json::{Map as JsonMap, Value};
44use std::collections::{HashMap, HashSet};
45use std::sync::Arc;
46use yrs::types::xml::XmlFragmentPrelim;
47use yrs::types::AsPrelim;
48use yrs::{
49 Any, Array, ArrayRef, Doc, In, Map, MapRef, Out, ReadTxn, StateVector, Transact, TransactionMut,
50};
51
52type Props = JsonMap<String, Value>;
53
54/// `Option<Option<T>>` so an absent key (`None`) and an explicit `null`
55/// (`Some(None)`) can mean different things — `after` absent appends,
56/// `after: null` puts first; `accent: null` clears.
57fn nullable<'de, D, T>(d: D) -> Result<Option<Option<T>>, D::Error>
58where
59 D: Deserializer<'de>,
60 T: Deserialize<'de>,
61{
62 Option::<T>::deserialize(d).map(Some)
63}
64
65#[derive(Deserialize)]
66struct Fonts {
67 heading: String,
68 body: String,
69}
70
71#[derive(Deserialize, Clone, Copy)]
72struct BoxSpec {
73 x: f64,
74 y: f64,
75 w: f64,
76 h: f64,
77}
78
79impl BoxSpec {
80 fn json(&self) -> Value {
81 schema::box_json(self.x, self.y, self.w, self.h)
82 }
83}
84
85#[derive(Deserialize)]
86struct Background {
87 kind: String,
88 #[serde(default)]
89 value: String,
90}
91
92#[derive(Deserialize)]
93#[serde(deny_unknown_fields)]
94struct PhoneOverride {
95 hidden: Option<bool>,
96 order: Option<i64>,
97 size: Option<String>,
98 #[serde(rename = "box")]
99 bx: Option<BoxSpec>,
100}
101
102#[derive(Deserialize)]
103#[serde(tag = "op", rename_all = "snake_case")]
104enum Op {
105 SetMeta {
106 title: Option<String>,
107 theme: Option<String>,
108 #[serde(default, deserialize_with = "nullable")]
109 accent: Option<Option<String>>,
110 #[serde(default, deserialize_with = "nullable")]
111 fonts: Option<Option<Fonts>>,
112 #[serde(default, rename = "fontFiles", deserialize_with = "nullable")]
113 font_files: Option<Option<Value>>,
114 #[serde(default, deserialize_with = "nullable")]
115 arrive: Option<Option<String>>,
116 },
117 AddSlide {
118 id: String,
119 #[serde(default, deserialize_with = "nullable")]
120 after: Option<Option<String>>,
121 layout: String,
122 template: Option<String>,
123 },
124 RemoveSlide {
125 id: String,
126 },
127 MoveSlide {
128 id: String,
129 after: Option<String>,
130 },
131 DuplicateSlide {
132 id: String,
133 new_id: String,
134 new_block_ids: Vec<String>,
135 },
136 SetSlide {
137 id: String,
138 layout: Option<String>,
139 template: Option<String>,
140 background: Option<Background>,
141 phone: Option<String>,
142 transition: Option<String>,
143 #[serde(default, deserialize_with = "nullable")]
144 talk: Option<Option<String>>,
145 },
146 SetNotes {
147 id: String,
148 markdown: String,
149 },
150 AddBlock {
151 slide: String,
152 id: String,
153 #[serde(rename = "type")]
154 kind: String,
155 #[serde(default)]
156 props: Props,
157 region: Option<String>,
158 #[serde(rename = "box")]
159 bx: Option<BoxSpec>,
160 z: Option<f64>,
161 #[serde(default, deserialize_with = "nullable")]
162 after: Option<Option<String>>,
163 markdown: Option<String>,
164 },
165 RemoveBlock {
166 slide: String,
167 id: String,
168 },
169 MoveBlock {
170 slide: String,
171 id: String,
172 after: Option<String>,
173 },
174 SetBlock {
175 slide: String,
176 id: String,
177 props: Option<Props>,
178 #[serde(default, deserialize_with = "nullable")]
179 region: Option<Option<String>>,
180 #[serde(default, deserialize_with = "nullable", rename = "box")]
181 bx: Option<Option<BoxSpec>>,
182 z: Option<f64>,
183 #[serde(default, deserialize_with = "nullable")]
184 step: Option<Option<f64>>,
185 #[serde(default, deserialize_with = "nullable")]
186 items: Option<Option<String>>,
187 },
188 SetText {
189 slide: String,
190 id: String,
191 markdown: String,
192 },
193 SetPhone {
194 slide: String,
195 id: String,
196 phone: PhoneOverride,
197 },
198 RegisterAsset {
199 id: String,
200 #[serde(rename = "ref")]
201 reference: String,
202 #[serde(default)]
203 name: String,
204 #[serde(default)]
205 width: i64,
206 #[serde(default)]
207 height: i64,
208 #[serde(default)]
209 alt: String,
210 /// A clip's video (scenes and clips spec §2): the ref of the
211 /// picture of its first frame, and its length in whole
212 /// milliseconds. Neither is written for a picture.
213 #[serde(default)]
214 poster: String,
215 #[serde(default)]
216 duration: i64,
217 },
218 RemoveAsset {
219 id: String,
220 },
221 /// A scene (scene.rs). `author` is whoever the server says wrote the
222 /// code: the Go host sets it on every op that carries `code`, and
223 /// drops any other.
224 AddScene {
225 id: String,
226 name: String,
227 code: String,
228 states: Value,
229 words: Option<Value>,
230 data: Option<Value>,
231 author: Option<String>,
232 },
233 /// Patches a scene: `words` and `stills` key by key (null removes
234 /// one), `data` replaced whole (null is a value), the rest replaced.
235 SetScene {
236 id: String,
237 name: Option<String>,
238 code: Option<String>,
239 states: Option<Value>,
240 words: Option<Value>,
241 #[serde(default, deserialize_with = "nullable")]
242 data: Option<Option<Value>>,
243 stills: Option<Value>,
244 author: Option<String>,
245 },
246 RemoveScene {
247 id: String,
248 },
249}
250
251fn fail<T>(msg: impl Into<String>) -> Result<T, CoreError> {
252 Err(CoreError::Ops(msg.into()))
253}
254
255fn in_vocab(what: &str, value: &str, vocab: &[&str]) -> Result<(), CoreError> {
256 if vocab.contains(&value) {
257 Ok(())
258 } else {
259 fail(format!(
260 "{what} {value:?} is not one of {}",
261 vocab.join(", ")
262 ))
263 }
264}
265
266fn non_empty(what: &str, value: &str) -> Result<(), CoreError> {
267 if value.is_empty() {
268 fail(format!("{what} is empty"))
269 } else {
270 Ok(())
271 }
272}
273
274/// A `qr` block's `url` from props when present: a follow link
275/// (`schema::is_follow_url`), or `null`, which clears it.
276fn qr_url(props: &Props) -> Result<(), CoreError> {
277 match props.get("url") {
278 None | Some(Value::Null) => Ok(()),
279 Some(Value::String(s)) if schema::is_follow_url(s) => Ok(()),
280 Some(_) => fail(schema::QR_URL_MESSAGE),
281 }
282}
283
284/// `rows`/`cols` from props when present: whole numbers within
285/// `1..=MAX_TABLE_SIDE`.
286fn table_side(props: &Props, key: &str) -> Result<Option<i64>, CoreError> {
287 let Some(v) = props.get(key) else {
288 return Ok(None);
289 };
290 match v.as_i64() {
291 Some(n) if (1..=schema::MAX_TABLE_SIDE).contains(&n) => Ok(Some(n)),
292 _ => fail(format!(
293 "table {key} must be a whole number from 1 to {}",
294 schema::MAX_TABLE_SIDE
295 )),
296 }
297}
298
299// --- the model, and the checking pass ---
300
301struct BlockModel {
302 id: String,
303 kind: String,
304 /// `Some(children)` for a `columns` block: the block ids its
305 /// `props.children` currently names, kept in step through the batch
306 /// so `remove_block` can drop a removed id from it and a later
307 /// `set_block` on the same columns block sees the drop (spec §2.4).
308 /// `None` for every other kind.
309 children: Option<Vec<String>>,
310 /// `Some` for a `scene` block: what its props point at, kept in
311 /// step so a `set_block` that changes one of them is checked with
312 /// the other two.
313 scene: Option<SceneRef>,
314}
315
316struct SlideModel {
317 id: String,
318 blocks: Vec<BlockModel>,
319}
320
321struct Model {
322 slides: Vec<SlideModel>,
323 assets: HashSet<String>,
324 /// Each scene's state ids, in order, as the view shows them.
325 scenes: HashMap<String, Vec<String>>,
326}
327
328impl Model {
329 fn read<T: ReadTxn>(txn: &T, roots: &Roots) -> Model {
330 // Reading order at both levels (schema::ordered_maps): `after`
331 // is positional, and the position that means anything is the
332 // one a reader of the view sees.
333 let slides = schema::ordered_maps(txn, &roots.slides)
334 .into_iter()
335 .map(|(_, m)| {
336 let blocks = schema::get_array(txn, &m, "blocks")
337 .map(|a| {
338 schema::ordered_maps(txn, &a)
339 .into_iter()
340 .map(|(_, b)| {
341 let kind = schema::get_string(txn, &b, "type").unwrap_or_default();
342 let children = (kind == "columns").then(|| {
343 schema::get_object(txn, &b, "props")
344 .and_then(|p| p.get("children").cloned())
345 .and_then(|v| v.as_array().cloned())
346 .map(|arr| {
347 arr.iter()
348 .filter_map(|c| c.as_str().map(str::to_string))
349 .collect()
350 })
351 .unwrap_or_default()
352 });
353 let scene = (kind == "scene").then(|| {
354 SceneRef::of(
355 &schema::get_object(txn, &b, "props").unwrap_or_default(),
356 )
357 });
358 BlockModel {
359 id: schema::get_string(txn, &b, "id").unwrap_or_default(),
360 kind,
361 children,
362 scene,
363 }
364 })
365 .collect()
366 })
367 .unwrap_or_default();
368 SlideModel {
369 id: schema::get_string(txn, &m, "id").unwrap_or_default(),
370 blocks,
371 }
372 })
373 .collect();
374 let assets = roots.assets.keys(txn).map(|k| k.to_string()).collect();
375 // Only what the view shows as a scene is one (scene::scene_view):
376 // a map. Its `states` alone is read — not its data, which can be
377 // large.
378 let scenes = roots
379 .scenes
380 .iter(txn)
381 .filter_map(|(k, v)| {
382 let states = match &v {
383 Out::YMap(m) => m.get(txn, "states").map(|s| schema::out_to_json(txn, &s)),
384 Out::Any(Any::Map(m)) => m.get("states").map(schema::any_to_json),
385 _ => return None,
386 };
387 Some((k.to_string(), scene::state_ids(states.as_ref())))
388 })
389 .collect();
390 Model {
391 slides,
392 assets,
393 scenes,
394 }
395 }
396
397 /// The state ids of a scene the deck has.
398 fn states_of(&self, scene: &str) -> Option<&[String]> {
399 self.scenes.get(scene).map(Vec::as_slice)
400 }
401
402 fn slide_index(&self, id: &str) -> Result<usize, CoreError> {
403 self.slides
404 .iter()
405 .position(|s| s.id == id)
406 .ok_or_else(|| CoreError::Ops(format!("no slide {id:?}")))
407 }
408
409 fn slide_mut(&mut self, id: &str) -> Result<&mut SlideModel, CoreError> {
410 let i = self.slide_index(id)?;
411 Ok(&mut self.slides[i])
412 }
413
414 fn check(&mut self, op: &Op) -> Result<(), CoreError> {
415 match op {
416 Op::SetMeta {
417 arrive, font_files, ..
418 } => {
419 if let Some(Some(a)) = arrive {
420 in_vocab("arrive", a, schema::ARRIVALS)?;
421 }
422 if let Some(Some(f)) = font_files {
423 schema::font_files(f).or_else(fail)?;
424 }
425 Ok(())
426 }
427 Op::AddSlide {
428 id,
429 after,
430 layout,
431 template,
432 } => {
433 non_empty("id", id)?;
434 if self.slide_index(id).is_ok() {
435 return fail(format!("slide {id:?} already exists"));
436 }
437 in_vocab("layout", layout, schema::LAYOUTS)?;
438 if let Some(t) = template {
439 in_vocab("template", t, schema::TEMPLATES)?;
440 }
441 let at = match after {
442 None => self.slides.len(),
443 Some(None) => 0,
444 Some(Some(a)) => self.slide_index(a)? + 1,
445 };
446 self.slides.insert(
447 at,
448 SlideModel {
449 id: id.clone(),
450 blocks: Vec::new(),
451 },
452 );
453 Ok(())
454 }
455 Op::RemoveSlide { id } => {
456 let i = self.slide_index(id)?;
457 self.slides.remove(i);
458 Ok(())
459 }
460 Op::MoveSlide { id, after } => {
461 self.slide_index(id)?;
462 if let Some(a) = after {
463 if a == id {
464 return fail("move_slide: after is the slide itself");
465 }
466 self.slide_index(a)?;
467 }
468 let i = self.slide_index(id)?;
469 let s = self.slides.remove(i);
470 let at = match after {
471 None => 0,
472 Some(a) => self.slide_index(a)? + 1,
473 };
474 self.slides.insert(at, s);
475 Ok(())
476 }
477 Op::DuplicateSlide {
478 id,
479 new_id,
480 new_block_ids,
481 } => {
482 non_empty("new_id", new_id)?;
483 let i = self.slide_index(id)?;
484 if self.slide_index(new_id).is_ok() {
485 return fail(format!("slide {new_id:?} already exists"));
486 }
487 let n = self.slides[i].blocks.len();
488 if new_block_ids.len() != n {
489 return fail(format!(
490 "duplicate_slide: {n} blocks but {} new_block_ids",
491 new_block_ids.len()
492 ));
493 }
494 let distinct: HashSet<&String> = new_block_ids.iter().collect();
495 if distinct.len() != n || new_block_ids.iter().any(String::is_empty) {
496 return fail("duplicate_slide: new_block_ids must be distinct and non-empty");
497 }
498 // Old block id -> new, so a duplicated `columns` block's
499 // children (already validated to name blocks on this
500 // slide) follow the copy exactly like `rewrite_ids`
501 // remaps them at apply time.
502 let id_map: HashMap<&str, &str> = self.slides[i]
503 .blocks
504 .iter()
505 .map(|b| b.id.as_str())
506 .zip(new_block_ids.iter().map(String::as_str))
507 .collect();
508 let blocks = self.slides[i]
509 .blocks
510 .iter()
511 .zip(new_block_ids)
512 .map(|(b, nid)| BlockModel {
513 id: nid.clone(),
514 kind: b.kind.clone(),
515 scene: b.scene.clone(),
516 children: b.children.as_ref().map(|cs| {
517 cs.iter()
518 .map(|c| {
519 id_map
520 .get(c.as_str())
521 .map(|n| n.to_string())
522 .unwrap_or_else(|| c.clone())
523 })
524 .collect()
525 }),
526 })
527 .collect();
528 self.slides.insert(
529 i + 1,
530 SlideModel {
531 id: new_id.clone(),
532 blocks,
533 },
534 );
535 Ok(())
536 }
537 Op::SetSlide {
538 id,
539 layout,
540 template,
541 background,
542 phone,
543 transition,
544 talk,
545 } => {
546 self.slide_index(id)?;
547 if let Some(l) = layout {
548 in_vocab("layout", l, schema::LAYOUTS)?;
549 }
550 if let Some(t) = template {
551 in_vocab("template", t, schema::TEMPLATES)?;
552 }
553 if let Some(b) = background {
554 in_vocab("background.kind", &b.kind, schema::BACKGROUND_KINDS)?;
555 }
556 if let Some(p) = phone {
557 in_vocab("phone", p, schema::SLIDE_PHONES)?;
558 }
559 if let Some(t) = transition {
560 in_vocab("transition", t, schema::TRANSITIONS)?;
561 }
562 if let Some(Some(t)) = talk {
563 in_vocab("talk", t, schema::TALKS)?;
564 }
565 Ok(())
566 }
567 Op::SetNotes { id, .. } => self.slide_index(id).map(|_| ()),
568 Op::AddBlock {
569 slide,
570 id,
571 kind,
572 props,
573 region,
574 after,
575 ..
576 } => {
577 non_empty("id", id)?;
578 in_vocab("type", kind, schema::BLOCK_TYPES)?;
579 if let Some(r) = region {
580 in_vocab("region", r, schema::REGIONS)?;
581 }
582 if kind == "table" {
583 table_side(props, "rows")?;
584 table_side(props, "cols")?;
585 }
586 if kind == "qr" {
587 qr_url(props)?;
588 }
589 if kind == "clip" {
590 scene::clip_props(props).or_else(fail)?;
591 }
592 let scene = if kind == "scene" {
593 let mut r = SceneRef::default();
594 if r.patch(props).or_else(fail)? {
595 r.check(|s| self.states_of(s)).or_else(fail)?;
596 }
597 Some(r)
598 } else {
599 None
600 };
601 let s = self.slide_mut(slide)?;
602 if s.blocks.iter().any(|b| &b.id == id) {
603 return fail(format!("block {id:?} already exists in slide {slide:?}"));
604 }
605 let children = if kind == "columns" {
606 Some(match props.get("children") {
607 Some(v) => validate_children(s, id, v)?,
608 None => Vec::new(),
609 })
610 } else {
611 None
612 };
613 let at = match after {
614 None => s.blocks.len(),
615 Some(None) => 0,
616 Some(Some(a)) => block_index(s, a)? + 1,
617 };
618 s.blocks.insert(
619 at,
620 BlockModel {
621 id: id.clone(),
622 kind: kind.clone(),
623 children,
624 scene,
625 },
626 );
627 Ok(())
628 }
629 Op::RemoveBlock { slide, id } => {
630 let s = self.slide_mut(slide)?;
631 let i = block_index(s, id)?;
632 s.blocks.remove(i);
633 // Spec §2.4: a `columns` block's children may not name a
634 // block that no longer exists — drop it rather than
635 // reject the removal.
636 for b in s.blocks.iter_mut() {
637 if let Some(children) = &mut b.children {
638 children.retain(|c| c != id);
639 }
640 }
641 Ok(())
642 }
643 Op::MoveBlock { slide, id, after } => {
644 let s = self.slide_mut(slide)?;
645 let i = block_index(s, id)?;
646 if let Some(a) = after {
647 if a == id {
648 return fail("move_block: after is the block itself");
649 }
650 block_index(s, a)?;
651 }
652 let b = s.blocks.remove(i);
653 let at = match after {
654 None => 0,
655 Some(a) => block_index(s, a)? + 1,
656 };
657 s.blocks.insert(at, b);
658 Ok(())
659 }
660 Op::SetBlock {
661 slide,
662 id,
663 props,
664 region,
665 step,
666 items,
667 ..
668 } => {
669 let si = self.slide_index(slide)?;
670 let bi = block_index(&self.slides[si], id)?;
671 if let Some(p) = props {
672 if self.slides[si].blocks[bi].kind == "clip" {
673 scene::clip_props(p).or_else(fail)?;
674 }
675 if let Some(mut r) = self.slides[si].blocks[bi].scene.clone() {
676 if r.patch(p).or_else(fail)? {
677 r.check(|s| self.states_of(s)).or_else(fail)?;
678 }
679 self.slides[si].blocks[bi].scene = Some(r);
680 }
681 }
682 let s = &mut self.slides[si];
683 let i = bi;
684 if let Some(Some(r)) = region {
685 in_vocab("region", r, schema::REGIONS)?;
686 }
687 if let Some(Some(n)) = step {
688 if !(n.is_finite() && *n > 0.0) {
689 return fail("step must be a number above 0");
690 }
691 }
692 if let Some(Some(it)) = items {
693 in_vocab("items", it, schema::ITEMS)?;
694 if s.blocks[i].kind != "list" {
695 return fail(format!(
696 "block {id:?} is a {}; items is for lists only",
697 s.blocks[i].kind
698 ));
699 }
700 }
701 if s.blocks[i].kind == "table" {
702 if let Some(p) = props {
703 table_side(p, "rows")?;
704 table_side(p, "cols")?;
705 }
706 }
707 if s.blocks[i].kind == "qr" {
708 if let Some(p) = props {
709 qr_url(p)?;
710 }
711 }
712 if s.blocks[i].kind == "columns" {
713 if let Some(children_value) = props.as_ref().and_then(|p| p.get("children")) {
714 let children = validate_children(s, id, children_value)?;
715 s.blocks[i].children = Some(children);
716 }
717 }
718 Ok(())
719 }
720 Op::SetText { slide, id, .. } => {
721 let s = self.slide_mut(slide)?;
722 let i = block_index(s, id)?;
723 if !schema::is_text_type(&s.blocks[i].kind) {
724 return fail(format!(
725 "block {id:?} is a {} and carries no text",
726 s.blocks[i].kind
727 ));
728 }
729 Ok(())
730 }
731 Op::SetPhone { slide, id, phone } => {
732 let s = self.slide_mut(slide)?;
733 block_index(s, id)?;
734 if let Some(size) = &phone.size {
735 in_vocab("phone.size", size, schema::SIZES)?;
736 }
737 Ok(())
738 }
739 Op::RegisterAsset {
740 id,
741 reference,
742 duration,
743 ..
744 } => {
745 non_empty("id", id)?;
746 non_empty("ref", reference)?;
747 if *duration < 0 {
748 return fail("duration is below 0");
749 }
750 if !self.assets.insert(id.clone()) {
751 return fail(format!("asset {id:?} is already registered"));
752 }
753 Ok(())
754 }
755 Op::RemoveAsset { id } => {
756 if !self.assets.remove(id) {
757 return fail(format!("no asset {id:?}"));
758 }
759 Ok(())
760 }
761 Op::AddScene {
762 id,
763 code,
764 states,
765 words,
766 data,
767 ..
768 } => {
769 if !scene::scene_id(id) {
770 return fail(format!(
771 "scene id {id:?} is not 12 lowercase base32 characters"
772 ));
773 }
774 if self.scenes.contains_key(id) {
775 return fail(format!("scene {id:?} already exists"));
776 }
777 check_code(code)?;
778 let (_, ids) = scene::states(states).or_else(fail)?;
779 if let Some(w) = words {
780 scene::words(w, false).or_else(fail)?;
781 }
782 if let Some(d) = data {
783 scene::data(d).or_else(fail)?;
784 }
785 self.scenes.insert(id.clone(), ids);
786 Ok(())
787 }
788 Op::SetScene {
789 id,
790 code,
791 states,
792 words,
793 data,
794 stills,
795 ..
796 } => {
797 if !self.scenes.contains_key(id) {
798 return fail(format!("no scene {id:?}"));
799 }
800 if let Some(c) = code {
801 check_code(c)?;
802 }
803 if let Some(s) = states {
804 let (_, ids) = scene::states(s).or_else(fail)?;
805 self.scenes.insert(id.clone(), ids);
806 }
807 if let Some(w) = words {
808 scene::words(w, true).or_else(fail)?;
809 }
810 if let Some(Some(d)) = data {
811 scene::data(d).or_else(fail)?;
812 }
813 if let Some(s) = stills {
814 scene::stills(s, id, &self.scenes[id]).or_else(fail)?;
815 }
816 Ok(())
817 }
818 Op::RemoveScene { id } => {
819 // The blocks that show it stay as they are (scenes and
820 // clips Review Focus 3): they draw a placeholder.
821 if self.scenes.remove(id).is_none() {
822 return fail(format!("no scene {id:?}"));
823 }
824 Ok(())
825 }
826 }
827 }
828}
829
830/// A scene's `code`: the ref of its stored bundle.
831fn check_code(code: &str) -> Result<(), CoreError> {
832 if scene::hex64(code) {
833 Ok(())
834 } else {
835 fail("code is not 64 lowercase hex digits")
836 }
837}
838
839fn block_index(s: &SlideModel, id: &str) -> Result<usize, CoreError> {
840 s.blocks
841 .iter()
842 .position(|b| b.id == id)
843 .ok_or_else(|| CoreError::Ops(format!("no block {id:?} in slide {:?}", s.id)))
844}
845
846/// A `columns` block's `props.children` (spec §2.4): an array of block
847/// ids, each naming a block on `s` other than `self_id`, each named
848/// once, none of them already a child of another columns block on the
849/// slide, and none of them holding `self_id` underneath it — the
850/// children of a slide are a forest, every block with at most one
851/// parent and no way back up (codex 7). `null` clears (an
852/// absent-props-key removal), so it validates to no children.
853///
854/// The messages are word for word the ones fixtures/ops-model.mjs
855/// throws, so the inspector and the drive API say the same thing.
856fn validate_children(
857 s: &SlideModel,
858 self_id: &str,
859 value: &Value,
860) -> Result<Vec<String>, CoreError> {
861 if value.is_null() {
862 return Ok(Vec::new());
863 }
864 let items = value
865 .as_array()
866 .ok_or_else(|| CoreError::Ops("columns children must be an array of block ids".into()))?;
867 let mut out: Vec<String> = Vec::with_capacity(items.len());
868 for item in items {
869 let cid = item.as_str().ok_or_else(|| {
870 CoreError::Ops("columns children must be an array of block ids".into())
871 })?;
872 if cid == self_id {
873 return fail(format!(
874 "columns {self_id:?} cannot name itself in children"
875 ));
876 }
877 if !s.blocks.iter().any(|b| b.id == cid) {
878 return fail(format!(
879 "columns children names {cid:?}, not a block on slide {:?}",
880 s.id
881 ));
882 }
883 if out.iter().any(|c| c == cid) {
884 return fail(format!("columns children names {cid:?} twice"));
885 }
886 if let Some(other) = s.blocks.iter().find(|b| {
887 b.id != self_id
888 && b.children
889 .as_ref()
890 .is_some_and(|cs| cs.iter().any(|c| c == cid))
891 }) {
892 return fail(format!(
893 "columns children names {cid:?}, already a child of columns {:?}",
894 other.id
895 ));
896 }
897 if contains(s, cid, self_id) {
898 return fail(format!(
899 "columns children names {cid:?}, which would put columns {self_id:?} inside itself"
900 ));
901 }
902 out.push(cid.to_string());
903 }
904 Ok(out)
905}
906
907/// Whether `target` is `root` or sits anywhere under it, following the
908/// slide's columns children as the model holds them now. Every block
909/// has at most one parent by construction, so the walk is a tree walk;
910/// the visited set is there so a document a peer put a cycle into by
911/// hand still terminates.
912fn contains(s: &SlideModel, root: &str, target: &str) -> bool {
913 let mut stack = vec![root];
914 let mut seen: HashSet<&str> = HashSet::new();
915 while let Some(id) = stack.pop() {
916 if id == target {
917 return true;
918 }
919 if !seen.insert(id) {
920 continue;
921 }
922 if let Some(b) = s.blocks.iter().find(|b| b.id == id) {
923 if let Some(cs) = &b.children {
924 stack.extend(cs.iter().map(String::as_str));
925 }
926 }
927 }
928 false
929}
930
931// --- the applying pass ---
932
933fn slide_map(txn: &TransactionMut, roots: &Roots, id: &str) -> Result<(u32, MapRef), CoreError> {
934 schema::find_by_id(txn, &roots.slides, id)
935 .ok_or_else(|| CoreError::Ops(format!("no slide {id:?}")))
936}
937
938/// The slide's block array, created if a peer wrote a slide without one.
939pub(crate) fn blocks_of(txn: &mut TransactionMut, slide: &MapRef) -> ArrayRef {
940 match schema::get_array(txn, slide, "blocks") {
941 Some(a) => a,
942 None => slide.insert(txn, "blocks", yrs::ArrayPrelim::default()),
943 }
944}
945
946fn block_map(
947 txn: &TransactionMut,
948 blocks: &ArrayRef,
949 id: &str,
950) -> Result<(u32, MapRef), CoreError> {
951 schema::find_by_id(txn, blocks, id).ok_or_else(|| CoreError::Ops(format!("no block {id:?}")))
952}
953
954/// Drops `removed_id` from every `columns` block's `props.children` in
955/// `blocks` (spec §2.4: children may not name a block that no longer
956/// exists — `remove_block` prunes rather than rejects).
957fn remove_from_columns_children(txn: &mut TransactionMut, blocks: &ArrayRef, removed_id: &str) {
958 for (_, m) in schema::maps_of(txn, blocks) {
959 if schema::get_string(txn, &m, "type").as_deref() != Some("columns") {
960 continue;
961 }
962 let Some(pm) = schema::get_map(txn, &m, "props") else {
963 continue;
964 };
965 let Some(Value::Array(children)) = schema::map_to_json(txn, &pm).get("children").cloned()
966 else {
967 continue;
968 };
969 if !children.iter().any(|c| c.as_str() == Some(removed_id)) {
970 continue;
971 }
972 let filtered: Vec<Value> = children
973 .into_iter()
974 .filter(|c| c.as_str() != Some(removed_id))
975 .collect();
976 pm.insert(
977 txn,
978 "children",
979 schema::json_to_any(&Value::Array(filtered)),
980 );
981 }
982}
983
984fn fragment_of(txn: &mut TransactionMut, map: &MapRef, key: &str) -> yrs::XmlFragmentRef {
985 match schema::get_fragment(txn, map, key) {
986 Some(f) => f,
987 None => map.insert(txn, key, XmlFragmentPrelim::default()),
988 }
989}
990
991fn map_of(txn: &mut TransactionMut, map: &MapRef, key: &str) -> MapRef {
992 match schema::get_map(txn, map, key) {
993 Some(m) => m,
994 None => map.insert(txn, key, yrs::MapPrelim::default()),
995 }
996}
997
998/// Where an `after` puts a new entry: absent appends, null goes first,
999/// an id goes right after it.
1000fn insert_index(
1001 txn: &TransactionMut,
1002 array: &ArrayRef,
1003 after: &Option<Option<String>>,
1004) -> Result<u32, CoreError> {
1005 Ok(match after {
1006 None => array.len(txn),
1007 Some(None) => 0,
1008 Some(Some(a)) => {
1009 schema::find_by_id(txn, array, a)
1010 .ok_or_else(|| CoreError::Ops(format!("no entry {a:?}")))?
1011 .0
1012 + 1
1013 }
1014 })
1015}
1016
1017/// Puts the entry `id` of an ordered array — a slide of the deck, a
1018/// block of a slide — at the reading position `after` asks for: absent
1019/// means first, an id means right after it. It does that by renumbering
1020/// `order` on every entry (schema.rs, "reading order"). The array is
1021/// not touched: the maps stay the shared types they are, so a peer's
1022/// edit in flight against any of them still lands (codex 4).
1023fn place_entry(
1024 txn: &mut TransactionMut,
1025 array: &ArrayRef,
1026 what: &str,
1027 id: &str,
1028 after: &Option<String>,
1029) -> Result<(), CoreError> {
1030 let mut ordered: Vec<(String, MapRef)> = schema::ordered_maps(txn, array)
1031 .into_iter()
1032 .map(|(_, m)| (schema::get_string(txn, &m, "id").unwrap_or_default(), m))
1033 .collect();
1034 let i = ordered
1035 .iter()
1036 .position(|(bid, _)| bid == id)
1037 .ok_or_else(|| CoreError::Ops(format!("no {what} {id:?}")))?;
1038 let moved = ordered.remove(i);
1039 let at = match after {
1040 None => 0,
1041 Some(a) => {
1042 ordered
1043 .iter()
1044 .position(|(bid, _)| bid == a)
1045 .ok_or_else(|| CoreError::Ops(format!("no entry {a:?}")))?
1046 + 1
1047 }
1048 };
1049 ordered.insert(at, moved);
1050 let maps: Vec<MapRef> = ordered.into_iter().map(|(_, m)| m).collect();
1051 schema::renumber(txn, &maps);
1052 Ok(())
1053}
1054
1055/// `place_entry` for an entry that was just inserted, whose `after` is
1056/// the three-valued kind (absent appends, `null` first, an id after it).
1057/// Only called when the array already carries explicit `order` keys.
1058fn place_new(
1059 txn: &mut TransactionMut,
1060 array: &ArrayRef,
1061 what: &str,
1062 id: &str,
1063 after: &Option<Option<String>>,
1064) -> Result<(), CoreError> {
1065 let after_id = match after {
1066 None => schema::ordered_maps(txn, array)
1067 .iter()
1068 .map(|(_, m)| schema::get_string(txn, m, "id").unwrap_or_default())
1069 .rev()
1070 .find(|other| other != id),
1071 Some(None) => None,
1072 Some(Some(a)) => Some(a.clone()),
1073 };
1074 place_entry(txn, array, what, id, &after_id)
1075}
1076
1077/// Text for a block of `kind` from its Markdown: `code` is plain lines,
1078/// everything else the subset.
1079fn text_for(kind: &str, markdown: &str) -> Vec<Paragraph> {
1080 if kind == "code" {
1081 markdown::parse_lines(markdown)
1082 } else {
1083 markdown::parse(markdown)
1084 }
1085}
1086
1087// --- duplicate ---
1088
1089/// Gives a copied slide its new ids: the slide's own, each block's, and
1090/// any `columns.children` list that named the old block ids.
1091///
1092/// `reading` is the source slide's block ids in reading order, and the
1093/// k-th new id goes to the k-th block in THAT order — the order the
1094/// model paired them in — whatever position the block has in the
1095/// array. The copied `order` keys come along untouched, so the copy
1096/// reads in the order the original did.
1097fn rewrite_ids(
1098 copy: &mut yrs::MapPrelim,
1099 new_id: &str,
1100 new_block_ids: &[String],
1101 reading: &[String],
1102) {
1103 copy.insert(Arc::from("id"), schema::string_in(new_id));
1104 let Some(In::Array(blocks)) = copy.get_mut("blocks") else {
1105 return;
1106 };
1107 let mut mapping: HashMap<String, String> = HashMap::new();
1108 for b in blocks.iter_mut() {
1109 let In::Map(bm) = b else { continue };
1110 let Some(In::Any(Any::String(old))) = bm.get("id") else {
1111 continue;
1112 };
1113 let Some(nid) = reading
1114 .iter()
1115 .position(|r| r.as_str() == old.as_ref())
1116 .and_then(|k| new_block_ids.get(k))
1117 else {
1118 continue;
1119 };
1120 mapping.insert(old.to_string(), nid.clone());
1121 bm.insert(Arc::from("id"), schema::string_in(nid));
1122 }
1123 for b in blocks.iter_mut() {
1124 let In::Map(bm) = b else { continue };
1125 let Some(In::Map(props)) = bm.get_mut("props") else {
1126 continue;
1127 };
1128 let Some(In::Any(Any::Array(children))) = props.get("children") else {
1129 continue;
1130 };
1131 let remapped: Vec<Any> = children
1132 .iter()
1133 .map(|c| match c {
1134 Any::String(s) => match mapping.get(s.as_ref()) {
1135 Some(n) => Any::from(n.as_str()),
1136 None => c.clone(),
1137 },
1138 other => other.clone(),
1139 })
1140 .collect();
1141 props.insert(Arc::from("children"), In::Any(Any::Array(remapped.into())));
1142 }
1143}
1144
1145// --- apply ---
1146
1147/// A nullable key's write: absent leaves `key` alone, `null` removes it,
1148/// a value sets it.
1149fn set_or_clear(txn: &mut TransactionMut, map: &MapRef, key: &str, value: Option<Option<Any>>) {
1150 match value {
1151 None => {}
1152 Some(None) => {
1153 map.remove(txn, key);
1154 }
1155 Some(Some(v)) => {
1156 map.insert(txn, key, v);
1157 }
1158 }
1159}
1160
1161fn apply_one(txn: &mut TransactionMut, roots: &Roots, op: &Op) -> Result<(), CoreError> {
1162 match op {
1163 Op::SetMeta {
1164 title,
1165 theme,
1166 accent,
1167 fonts,
1168 font_files,
1169 arrive,
1170 } => {
1171 if let Some(t) = title {
1172 roots.meta.insert(txn, "title", Any::from(t.as_str()));
1173 }
1174 if let Some(t) = theme {
1175 roots.meta.insert(txn, "theme", Any::from(t.as_str()));
1176 }
1177 match accent {
1178 None => {}
1179 Some(None) => {
1180 roots.meta.remove(txn, "accent");
1181 }
1182 Some(Some(a)) => {
1183 roots.meta.insert(txn, "accent", Any::from(a.as_str()));
1184 }
1185 }
1186 match fonts {
1187 None => {}
1188 Some(None) => {
1189 roots.meta.remove(txn, "fonts");
1190 }
1191 Some(Some(f)) => {
1192 let v = serde_json::json!({"heading": f.heading, "body": f.body});
1193 roots.meta.insert(txn, "fonts", schema::json_to_any(&v));
1194 }
1195 }
1196 match font_files {
1197 None => {}
1198 Some(None) => {
1199 roots.meta.remove(txn, "fontFiles");
1200 }
1201 Some(Some(f)) => {
1202 // checked already; rebuilt from the known fields
1203 if let Ok(v) = schema::font_files(f) {
1204 roots.meta.insert(txn, "fontFiles", schema::json_to_any(&v));
1205 }
1206 }
1207 }
1208 set_or_clear(
1209 txn,
1210 &roots.meta,
1211 "arrive",
1212 arrive.as_ref().map(|a| a.as_deref().map(Any::from)),
1213 );
1214 }
1215 Op::AddSlide {
1216 id,
1217 after,
1218 layout,
1219 template,
1220 } => {
1221 let at = insert_index(txn, &roots.slides, after)?;
1222 let template = template.as_deref().unwrap_or(schema::DEFAULT_TEMPLATE);
1223 let explicit = schema::has_explicit_order(txn, &roots.slides);
1224 roots
1225 .slides
1226 .insert(txn, at, schema::slide_prelim(id, layout, template));
1227 // On a deck nobody has reordered the array IS the reading
1228 // order and the insert above already put the slide where
1229 // `after` asked. Once the deck carries `order` keys the
1230 // array position means nothing, so the new slide is placed
1231 // by renumbering instead (schema.rs, "reading order").
1232 if explicit {
1233 place_new(txn, &roots.slides, "slide", id, after)?;
1234 }
1235 }
1236 Op::RemoveSlide { id } => {
1237 let (i, _) = slide_map(txn, roots, id)?;
1238 roots.slides.remove(txn, i);
1239 }
1240 Op::MoveSlide { id, after } => {
1241 slide_map(txn, roots, id)?;
1242 place_entry(txn, &roots.slides, "slide", id, after)?;
1243 }
1244 Op::DuplicateSlide {
1245 id,
1246 new_id,
1247 new_block_ids,
1248 } => {
1249 let (i, m) = slide_map(txn, roots, id)?;
1250 let reading: Vec<String> = schema::get_array(txn, &m, "blocks")
1251 .map(|a| {
1252 schema::ordered_maps(txn, &a)
1253 .iter()
1254 .map(|(_, b)| schema::get_string(txn, b, "id").unwrap_or_default())
1255 .collect()
1256 })
1257 .unwrap_or_default();
1258 let mut copy = m.as_prelim(txn);
1259 rewrite_ids(&mut copy, new_id, new_block_ids, &reading);
1260 let explicit = schema::has_explicit_order(txn, &roots.slides);
1261 roots.slides.insert(txn, i + 1, copy);
1262 // The copy carries the original's `order` too, so on a
1263 // reordered deck it would tie with it; renumber so the
1264 // duplicate is unambiguously the next slide.
1265 if explicit {
1266 place_entry(txn, &roots.slides, "slide", new_id, &Some(id.clone()))?;
1267 }
1268 }
1269 Op::SetSlide {
1270 id,
1271 layout,
1272 template,
1273 background,
1274 phone,
1275 transition,
1276 talk,
1277 } => {
1278 let (_, m) = slide_map(txn, roots, id)?;
1279 if let Some(l) = layout {
1280 let current =
1281 schema::get_string(txn, &m, "layout").unwrap_or_else(|| "flow".into());
1282 if *l != current {
1283 match l.as_str() {
1284 "canvas" => layout::to_canvas(txn, &m),
1285 _ => layout::to_flow(txn, &m),
1286 }
1287 m.insert(txn, "layout", Any::from(l.as_str()));
1288 }
1289 }
1290 if let Some(t) = template {
1291 m.insert(txn, "template", Any::from(t.as_str()));
1292 }
1293 if let Some(b) = background {
1294 m.insert(
1295 txn,
1296 "background",
1297 schema::background_prelim(&b.kind, &b.value),
1298 );
1299 }
1300 if let Some(p) = phone {
1301 m.insert(txn, "phone", Any::from(p.as_str()));
1302 }
1303 if let Some(t) = transition {
1304 m.insert(txn, "transition", Any::from(t.as_str()));
1305 }
1306 set_or_clear(
1307 txn,
1308 &m,
1309 "talk",
1310 talk.as_ref().map(|t| t.as_deref().map(Any::from)),
1311 );
1312 }
1313 Op::SetNotes { id, markdown } => {
1314 let (_, m) = slide_map(txn, roots, id)?;
1315 let notes = fragment_of(txn, &m, "notes");
1316 schema::replace_text(txn, &notes, &markdown::parse(markdown));
1317 }
1318 Op::AddBlock {
1319 slide,
1320 id,
1321 kind,
1322 props,
1323 region,
1324 bx,
1325 z,
1326 after,
1327 markdown,
1328 } => {
1329 let (_, s) = slide_map(txn, roots, slide)?;
1330 let blocks = blocks_of(txn, &s);
1331 let at = insert_index(txn, &blocks, after)?;
1332 let canvas = schema::get_string(txn, &s, "layout").as_deref() == Some("canvas");
1333 let mut props = props.clone();
1334 let cells = if kind == "table" {
1335 let rows = table_side(&props, "rows")?.unwrap_or(schema::DEFAULT_TABLE_ROWS);
1336 let cols = table_side(&props, "cols")?.unwrap_or(schema::DEFAULT_TABLE_COLS);
1337 props.insert("rows".into(), Value::from(rows));
1338 props.insert("cols".into(), Value::from(cols));
1339 Some((rows * cols) as usize)
1340 } else {
1341 None
1342 };
1343 let text: Option<Vec<Paragraph>> = if schema::is_text_type(kind) {
1344 Some(
1345 markdown
1346 .as_deref()
1347 .map(|md| text_for(kind, md))
1348 .unwrap_or_default(),
1349 )
1350 } else {
1351 None
1352 };
1353 let region = region
1354 .as_deref()
1355 .unwrap_or_else(|| layout::default_region(kind));
1356 let (region_key, box_value, z_value) = if canvas {
1357 let bx = bx.map(|b| b.json()).unwrap_or_else(|| {
1358 let (x, y, w, h) = layout::region_rect(region, false);
1359 schema::box_json(x, y, w, h)
1360 });
1361 (None, Some(bx), Some(z.unwrap_or(at as f64)))
1362 } else {
1363 (Some(region), None, None)
1364 };
1365 let prelim = schema::block_prelim(
1366 id,
1367 kind,
1368 &props,
1369 region_key,
1370 box_value.as_ref(),
1371 z_value,
1372 text.as_deref(),
1373 cells,
1374 );
1375 let explicit = schema::has_explicit_order(txn, &blocks);
1376 blocks.insert(txn, at, prelim);
1377 // On a slide nobody has reordered the array IS the reading
1378 // order and the insert above already put the block where
1379 // `after` asked. Once the slide carries `order` keys the
1380 // array position means nothing, so the new block is placed
1381 // by renumbering instead (schema.rs, "reading order").
1382 if explicit {
1383 place_new(txn, &blocks, "block", id, after)?;
1384 }
1385 }
1386 Op::RemoveBlock { slide, id } => {
1387 let (_, s) = slide_map(txn, roots, slide)?;
1388 let blocks = blocks_of(txn, &s);
1389 let (i, _) = block_map(txn, &blocks, id)?;
1390 blocks.remove(txn, i);
1391 remove_from_columns_children(txn, &blocks, id);
1392 }
1393 Op::MoveBlock { slide, id, after } => {
1394 let (_, s) = slide_map(txn, roots, slide)?;
1395 let blocks = blocks_of(txn, &s);
1396 block_map(txn, &blocks, id)?;
1397 place_entry(txn, &blocks, "block", id, after)?;
1398 }
1399 Op::SetBlock {
1400 slide,
1401 id,
1402 props,
1403 region,
1404 bx,
1405 z,
1406 step,
1407 items,
1408 } => {
1409 let (_, s) = slide_map(txn, roots, slide)?;
1410 let blocks = blocks_of(txn, &s);
1411 let (_, m) = block_map(txn, &blocks, id)?;
1412 if let Some(p) = props {
1413 let pm = map_of(txn, &m, "props");
1414 for (k, v) in p {
1415 if v.is_null() {
1416 pm.remove(txn, k);
1417 } else {
1418 pm.insert(txn, k.as_str(), schema::json_to_any(v));
1419 }
1420 }
1421 let is_table = schema::get_string(txn, &m, "type").as_deref() == Some("table");
1422 // `cells` is row-major and flat, so growing/shrinking
1423 // only appends to or truncates the end of it -- a
1424 // cols-only change (rows unchanged) reflows every row's
1425 // cells rather than inserting/removing per row, which
1426 // shuffles existing cell text across the grid. Spec
1427 // §2.4 sanctions this as a v1 limitation; a person
1428 // resizing columns should expect to recheck cell
1429 // contents.
1430 if is_table && (p.contains_key("rows") || p.contains_key("cols")) {
1431 let rows = schema::get_number(txn, &pm, "rows")
1432 .unwrap_or(schema::DEFAULT_TABLE_ROWS as f64)
1433 as i64;
1434 let cols = schema::get_number(txn, &pm, "cols")
1435 .unwrap_or(schema::DEFAULT_TABLE_COLS as f64)
1436 as i64;
1437 let want = (rows.max(1) * cols.max(1)) as u32;
1438 let cells = match schema::get_array(txn, &m, "cells") {
1439 Some(c) => c,
1440 None => m.insert(txn, "cells", yrs::ArrayPrelim::default()),
1441 };
1442 let have = cells.len(txn);
1443 if have > want {
1444 cells.remove_range(txn, want, have - want);
1445 }
1446 for _ in have..want {
1447 cells.push_back(txn, XmlFragmentPrelim::default());
1448 }
1449 }
1450 }
1451 match region {
1452 None => {}
1453 Some(None) => {
1454 m.remove(txn, "region");
1455 }
1456 Some(Some(r)) => {
1457 m.insert(txn, "region", Any::from(r.as_str()));
1458 }
1459 }
1460 match bx {
1461 None => {}
1462 Some(None) => {
1463 m.remove(txn, "box");
1464 }
1465 Some(Some(b)) => {
1466 m.insert(txn, "box", schema::json_to_any(&b.json()));
1467 }
1468 }
1469 if let Some(z) = z {
1470 m.insert(txn, "z", Any::Number(*z));
1471 }
1472 set_or_clear(txn, &m, "step", step.map(|n| n.map(Any::Number)));
1473 set_or_clear(
1474 txn,
1475 &m,
1476 "items",
1477 items.as_ref().map(|it| it.as_deref().map(Any::from)),
1478 );
1479 }
1480 Op::SetText {
1481 slide,
1482 id,
1483 markdown,
1484 } => {
1485 let (_, s) = slide_map(txn, roots, slide)?;
1486 let blocks = blocks_of(txn, &s);
1487 let (_, m) = block_map(txn, &blocks, id)?;
1488 let kind = schema::get_string(txn, &m, "type").unwrap_or_default();
1489 let text = fragment_of(txn, &m, "text");
1490 schema::replace_text(txn, &text, &text_for(&kind, markdown));
1491 }
1492 Op::SetPhone { slide, id, phone } => {
1493 let (_, s) = slide_map(txn, roots, slide)?;
1494 let blocks = blocks_of(txn, &s);
1495 let (_, m) = block_map(txn, &blocks, id)?;
1496 let pm = map_of(txn, &m, "phone");
1497 pm.clear(txn);
1498 if let Some(h) = phone.hidden {
1499 pm.insert(txn, "hidden", Any::Bool(h));
1500 }
1501 if let Some(o) = phone.order {
1502 pm.insert(txn, "order", Any::Number(o as f64));
1503 }
1504 if let Some(sz) = &phone.size {
1505 pm.insert(txn, "size", Any::from(sz.as_str()));
1506 }
1507 if let Some(b) = &phone.bx {
1508 pm.insert(txn, "box", schema::json_to_any(&b.json()));
1509 }
1510 }
1511 Op::RegisterAsset {
1512 id,
1513 reference,
1514 name,
1515 width,
1516 height,
1517 alt,
1518 poster,
1519 duration,
1520 } => {
1521 let mut v = serde_json::json!({
1522 "ref": reference,
1523 "name": name,
1524 "width": width,
1525 "height": height,
1526 "alt": alt,
1527 });
1528 if !poster.is_empty() {
1529 v["poster"] = Value::from(poster.as_str());
1530 }
1531 if *duration > 0 {
1532 v["duration"] = Value::from(*duration);
1533 }
1534 roots
1535 .assets
1536 .insert(txn, id.as_str(), schema::json_to_any(&v));
1537 }
1538 Op::RemoveAsset { id } => {
1539 roots.assets.remove(txn, id);
1540 }
1541 Op::AddScene {
1542 id,
1543 name,
1544 code,
1545 states,
1546 words,
1547 data,
1548 author,
1549 } => {
1550 let (states, _) = scene::states(states).map_err(CoreError::Ops)?;
1551 let words = words
1552 .as_ref()
1553 .and_then(Value::as_object)
1554 .cloned()
1555 .unwrap_or_default();
1556 let mut m: yrs::MapPrelim = [
1557 ("name", schema::string_in(name)),
1558 ("code", schema::string_in(code)),
1559 ("states", In::Any(schema::json_to_any(&states))),
1560 ("words", In::Map(schema::plain_map_prelim(&words))),
1561 (
1562 "data",
1563 In::Any(schema::json_to_any(data.as_ref().unwrap_or(&Value::Null))),
1564 ),
1565 ("stills", In::Map(yrs::MapPrelim::default())),
1566 ]
1567 .into_iter()
1568 .collect();
1569 if let Some(a) = author {
1570 m.insert(Arc::from("author"), schema::string_in(a));
1571 }
1572 roots.scenes.insert(txn, id.as_str(), m);
1573 }
1574 Op::SetScene {
1575 id,
1576 name,
1577 code,
1578 states,
1579 words,
1580 data,
1581 stills,
1582 author,
1583 } => {
1584 let m = scene_map(txn, roots, id)?;
1585 for (key, value) in [("name", name), ("code", code), ("author", author)] {
1586 if let Some(v) = value {
1587 m.insert(txn, key, Any::from(v.as_str()));
1588 }
1589 }
1590 if let Some(s) = states {
1591 let (states, _) = scene::states(s).map_err(CoreError::Ops)?;
1592 m.insert(txn, "states", schema::json_to_any(&states));
1593 }
1594 if let Some(Value::Object(w)) = words {
1595 patch_map(txn, &m, "words", w, schema::json_to_any);
1596 }
1597 if let Some(d) = data {
1598 let d = d.as_ref().unwrap_or(&Value::Null);
1599 m.insert(txn, "data", schema::json_to_any(d));
1600 }
1601 if let Some(Value::Object(s)) = stills {
1602 patch_map(txn, &m, "stills", s, |v| {
1603 schema::json_to_any(&scene::still(v))
1604 });
1605 }
1606 }
1607 Op::RemoveScene { id } => {
1608 roots.scenes.remove(txn, id);
1609 }
1610 }
1611 Ok(())
1612}
1613
1614/// The Y.Map of scene `id`. A scene a peer wrote as one plain map is
1615/// turned into a Y.Map of the same fields first, so it can be patched
1616/// a key at a time from here on.
1617fn scene_map(txn: &mut TransactionMut, roots: &Roots, id: &str) -> Result<MapRef, CoreError> {
1618 match roots.scenes.get(txn, id) {
1619 Some(Out::YMap(m)) => Ok(m),
1620 Some(Out::Any(Any::Map(fields))) => {
1621 let prelim: yrs::MapPrelim = fields
1622 .iter()
1623 .map(|(k, v)| (k.as_str(), In::Any(v.clone())))
1624 .collect();
1625 Ok(roots.scenes.insert(txn, id, prelim))
1626 }
1627 _ => fail(format!("no scene {id:?}")),
1628 }
1629}
1630
1631/// Patches the Y.Map at `key` of `m` key by key: null removes, anything
1632/// else is written as `value` makes it. A plain map a peer left there is
1633/// turned into a Y.Map of its entries first.
1634fn patch_map(
1635 txn: &mut TransactionMut,
1636 m: &MapRef,
1637 key: &str,
1638 patch: &JsonMap<String, Value>,
1639 value: impl Fn(&Value) -> Any,
1640) {
1641 let target = match m.get(txn, key) {
1642 Some(Out::YMap(x)) => x,
1643 other => {
1644 let prelim: yrs::MapPrelim = match other {
1645 Some(Out::Any(Any::Map(entries))) => entries
1646 .iter()
1647 .map(|(k, v)| (k.as_str(), In::Any(v.clone())))
1648 .collect(),
1649 _ => yrs::MapPrelim::default(),
1650 };
1651 m.insert(txn, key, prelim)
1652 }
1653 };
1654 for (k, v) in patch {
1655 if v.is_null() {
1656 target.remove(txn, k);
1657 } else {
1658 target.insert(txn, k.as_str(), value(v));
1659 }
1660 }
1661}
1662
1663/// Applies `ops` (a JSON array of operations) to `doc` in one
1664/// transaction with origin `"ops"`, returning the v1 update that
1665/// transaction produced. On `Err` nothing was written — see the module
1666/// comment for how that is arranged.
1667pub fn apply_ops(doc: &Doc, ops: &str) -> Result<Vec<u8>, CoreError> {
1668 let raw: Vec<Value> = serde_json::from_str(ops)
1669 .map_err(|e| CoreError::Ops(format!("ops must be a JSON array: {e}")))?;
1670 let mut parsed = Vec::with_capacity(raw.len());
1671 for (i, v) in raw.into_iter().enumerate() {
1672 let op: Op =
1673 serde_json::from_value(v).map_err(|e| CoreError::Ops(format!("op {i}: {e}")))?;
1674 parsed.push(op);
1675 }
1676
1677 // Roots first: get_or_insert_* takes its own write transaction.
1678 let roots = schema::roots(doc);
1679 {
1680 let txn = doc.transact();
1681 let mut model = Model::read(&txn, &roots);
1682 for (i, op) in parsed.iter().enumerate() {
1683 model.check(op).map_err(|e| match e {
1684 CoreError::Ops(m) => CoreError::Ops(format!("op {i}: {m}")),
1685 other => other,
1686 })?;
1687 }
1688 }
1689
1690 // A batch with a scene op is applied to a copy first and refused when
1691 // its update would not fit one live update (scene::MAX_UPDATE_BYTES):
1692 // data within its 960 KiB of JSON can still encode past it.
1693 // fixtures/ops.mjs does the same, message for message.
1694 let scene = parsed.iter().enumerate().find_map(|(i, op)| match op {
1695 Op::AddScene { id, .. } | Op::SetScene { id, .. } => Some((i, id)),
1696 _ => None,
1697 });
1698 if let Some((i, id)) = scene {
1699 if update_size(doc, &parsed)? > scene::MAX_UPDATE_BYTES {
1700 return fail(format!(
1701 "op {i}: scene {id:?} would make an update larger than 1 MiB, the most one live update may carry (number-heavy data encodes larger than its JSON)"
1702 ));
1703 }
1704 }
1705
1706 let mut txn = doc.transact_mut_with("ops");
1707 for (i, op) in parsed.iter().enumerate() {
1708 apply_one(&mut txn, &roots, op).map_err(|e| match e {
1709 CoreError::Ops(m) => CoreError::Ops(format!("op {i} (applying): {m}")),
1710 other => other,
1711 })?;
1712 }
1713 txn.commit();
1714 Ok(txn.encode_update_v1())
1715}
1716
1717/// The size of the update `parsed` makes on a copy of `doc`, as the same
1718/// client.
1719fn update_size(doc: &Doc, parsed: &[Op]) -> Result<usize, CoreError> {
1720 let state = doc
1721 .transact()
1722 .encode_state_as_update_v1(&StateVector::default());
1723 let copy = crate::new_doc(&doc.guid(), doc.client_id());
1724 crate::apply_update(&copy, &state)?;
1725 let roots = schema::roots(&copy);
1726 let mut txn = copy.transact_mut_with("ops");
1727 for op in parsed {
1728 apply_one(&mut txn, &roots, op)?;
1729 }
1730 txn.commit();
1731 Ok(txn.encode_update_v1().len())
1732}
1733