| 1 | //! The deck's shape over yrs: root names, key names, the vocabularies the |
| 2 | //! spec closes, the text schema, and the small set of constructors and |
| 3 | //! accessors `ops` and `view` share. Spec §2 in code. |
| 4 | //! |
| 5 | //! What lives where (§2.1, §2.2, §2.4): |
| 6 | //! |
| 7 | //! - `meta` (Y.Map): `title`, `theme`, `accent`, `fonts`, `aspect` and an |
| 8 | //! optional `arrive` as plain values (`fonts` is one `{heading, body}` |
| 9 | //! object). |
| 10 | //! - `slides` (Y.Array of Y.Map): the SET of the deck's slides; their |
| 11 | //! order is the `order` key on each (see "reading order" below). Each |
| 12 | //! slide map holds `id`, `layout`, |
| 13 | //! `template`, `phone`, `transition` and an optional `talk` as strings, |
| 14 | //! `background` as a Y.Map `{kind, value}`, `notes` as a |
| 15 | //! Y.XmlFragment, an optional `order` (number), and `blocks` as a |
| 16 | //! Y.Array of block Y.Maps — the set of blocks; their reading order |
| 17 | //! is the `order` key on each, the same way. |
| 18 | //! - a block map holds `id`, `type`, `props` (Y.Map of plain values — |
| 19 | //! `columns.children` is a plain array inside it), `phone` (Y.Map of |
| 20 | //! the §2.5 overrides), an optional `order` (number), an optional |
| 21 | //! `step` (a number above 0: the press it arrives on), on a list an |
| 22 | //! optional `items` (string), and then either |
| 23 | //! `region` (flow) or `box` + |
| 24 | //! `z` (canvas). `box` is one plain `{x, y, w, h}` value — the four |
| 25 | //! numbers move together, and merging two peers' drags coordinate by |
| 26 | //! coordinate would produce a box neither of them made. Text-bearing |
| 27 | //! types carry `text` (Y.XmlFragment); a `table` carries `cells` |
| 28 | //! (Y.Array of Y.XmlFragment, row-major, `rows * cols` long) as a key |
| 29 | //! of its own on the block map, which the view folds into |
| 30 | //! `props.cells`. |
| 31 | //! - `assets` (Y.Map): id to one plain `{ref, name, width, height, alt}` |
| 32 | //! value — an asset is registered once and never edited in place. |
| 33 | //! - `scenes` (Y.Map): scene id to one Y.Map per scene; `scene.rs` says |
| 34 | //! what is in it. A `scene` block's props are `{scene, from, to}`, a |
| 35 | //! `clip` block's `{asset, play}`. |
| 36 | //! |
| 37 | //! The text schema (§2.6): an XmlFragment of `<paragraph>` elements, each |
| 38 | //! holding one XmlText. Marks are formatting attributes on the text's |
| 39 | //! runs: `b`, `i`, `c`, `h` (value `true`) and `href` (the one-key map |
| 40 | //! `{"href": url}`). The map is y-prosemirror's shape: it maps a mark to |
| 41 | //! the attribute `<mark name> = <mark attrs object>`, so the mark `href` |
| 42 | //! with attrs `{href}` is the attribute `href` with that object as its |
| 43 | //! value, and a plain string there would throw in `schema.mark` (which |
| 44 | //! makes y-prosemirror delete the text). The reader is more tolerant |
| 45 | //! than the writer — `href` reads as either the map or a plain string |
| 46 | //! (documents written before this shape), any truthy value counts as a |
| 47 | //! set mark (y-prosemirror writes `{}` for the attr-less marks), |
| 48 | //! several texts in one paragraph concatenate, and a bare text at |
| 49 | //! fragment level is its own paragraph — because updates reach the |
| 50 | //! server from browsers as well. |
| 51 | |
| 52 | use serde::Serialize; |
| 53 | use std::collections::HashMap; |
| 54 | use std::sync::Arc; |
| 55 | use yrs::types::text::YChange; |
| 56 | use yrs::types::xml::{XmlDeltaPrelim, XmlElementPrelim, XmlFragmentPrelim, XmlIn, XmlOut}; |
| 57 | use yrs::types::{Attrs, Delta}; |
| 58 | use yrs::{ |
| 59 | Any, Array, ArrayRef, Doc, GetString, In, Map, MapRef, Out, ReadTxn, Text, TransactionMut, |
| 60 | XmlFragment, XmlFragmentRef, |
| 61 | }; |
| 62 | |
| 63 | pub const ROOT_META: &str = "meta"; |
| 64 | pub const ROOT_SLIDES: &str = "slides"; |
| 65 | pub const ROOT_ASSETS: &str = "assets"; |
| 66 | pub const ROOT_SCENES: &str = "scenes"; |
| 67 | |
| 68 | pub const LAYOUTS: &[&str] = &["flow", "canvas"]; |
| 69 | pub const TEMPLATES: &[&str] = &[ |
| 70 | "title", |
| 71 | "title-body", |
| 72 | "two-column", |
| 73 | "section", |
| 74 | "image-full", |
| 75 | "quote", |
| 76 | "blank", |
| 77 | ]; |
| 78 | pub const REGIONS: &[&str] = &["heading", "body", "aside", "media"]; |
| 79 | pub const BACKGROUND_KINDS: &[&str] = &["theme", "color", "image"]; |
| 80 | pub const SLIDE_PHONES: &[&str] = &["inherit", "reflow"]; |
| 81 | pub const TRANSITIONS: &[&str] = &["none", "fade"]; |
| 82 | pub const BLOCK_TYPES: &[&str] = &[ |
| 83 | "heading", "text", "list", "quote", "image", "columns", "code", "shape", "table", "divider", |
| 84 | "spacer", "scene", "clip", "qr", |
| 85 | ]; |
| 86 | /// Types that carry a `text` fragment (§2.4's "Text: yes" column, plus |
| 87 | /// `shape`'s optional label). |
| 88 | pub const TEXT_TYPES: &[&str] = &["heading", "text", "list", "quote", "code", "shape"]; |
| 89 | pub const SIZES: &[&str] = &["s", "m", "l"]; |
| 90 | /// A list block's `items`: arriving with the box (`together`, also the |
| 91 | /// meaning of no key) or one press each. |
| 92 | pub const ITEMS: &[&str] = &["together", "each"]; |
| 93 | /// A slide's `talk`: only in the full version, or parked out of the |
| 94 | /// talk. No key means in the talk. |
| 95 | pub const TALKS: &[&str] = &["full", "parked"]; |
| 96 | /// The deck's `arrive`: how a box waiting for its press comes in. |
| 97 | /// No key means `appear`. |
| 98 | pub const ARRIVALS: &[&str] = &["appear", "fade", "rise"]; |
| 99 | |
| 100 | pub const DEFAULT_THEME: &str = "paper"; |
| 101 | pub const DEFAULT_ASPECT: &str = "16:9"; |
| 102 | pub const DEFAULT_TEMPLATE: &str = "blank"; |
| 103 | pub const DEFAULT_TABLE_ROWS: i64 = 2; |
| 104 | pub const DEFAULT_TABLE_COLS: i64 = 2; |
| 105 | /// The most cells one table can hold. Not a product limit — a guard on |
| 106 | /// `set_block {props: {rows: 1000000}}` allocating a million fragments |
| 107 | /// inside one request. |
| 108 | pub const MAX_TABLE_SIDE: i64 = 100; |
| 109 | |
| 110 | /// The refusal for a `qr` block's `props.url` that is not a follow |
| 111 | /// link. Word for word fixtures/ops-model.mjs's. |
| 112 | pub const QR_URL_MESSAGE: &str = |
| 113 | "qr url must be a follow link: http(s)://<host>/s/<token>?follow=1"; |
| 114 | |
| 115 | /// Whether `url` is shaped like the follow address of a share link: |
| 116 | /// `http://` or `https://`, a host (letters, digits, dots, hyphens, a |
| 117 | /// port's colon, an IPv6 literal's brackets; no user info), then |
| 118 | /// exactly `/s/<token>?follow=1` with a token of 16 to 128 base64url |
| 119 | /// characters. A follow-along code (the `qr` block) stores the address |
| 120 | /// it was made with, because the server keeps only the token's hash. |
| 121 | /// Which host is the server's to say: it mints the address |
| 122 | /// (internal/slides/qrlink.go). internal/slides/deck's FollowAddress |
| 123 | /// and fixtures/ops-model.mjs's isFollowURL are the same rule. |
| 124 | pub fn is_follow_url(url: &str) -> bool { |
| 125 | let rest = match url |
| 126 | .strip_prefix("https://") |
| 127 | .or_else(|| url.strip_prefix("http://")) |
| 128 | { |
| 129 | Some(r) => r, |
| 130 | None => return false, |
| 131 | }; |
| 132 | let Some(slash) = rest.find('/') else { |
| 133 | return false; |
| 134 | }; |
| 135 | let (host, path) = rest.split_at(slash); |
| 136 | if host.is_empty() |
| 137 | || host.len() > 253 |
| 138 | || !host |
| 139 | .chars() |
| 140 | .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')) |
| 141 | { |
| 142 | return false; |
| 143 | } |
| 144 | let Some(token) = path |
| 145 | .strip_prefix("/s/") |
| 146 | .and_then(|p| p.strip_suffix("?follow=1")) |
| 147 | else { |
| 148 | return false; |
| 149 | }; |
| 150 | (16..=128).contains(&token.len()) |
| 151 | && token |
| 152 | .chars() |
| 153 | .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') |
| 154 | } |
| 155 | |
| 156 | pub fn is_text_type(kind: &str) -> bool { |
| 157 | TEXT_TYPES.contains(&kind) |
| 158 | } |
| 159 | |
| 160 | // --- text --- |
| 161 | |
| 162 | /// One formatted run of a paragraph. Serialises as `{t, b?, i?, c?, h?, |
| 163 | /// href?}` with false and absent marks omitted, which is the view's run |
| 164 | /// shape verbatim. |
| 165 | #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize)] |
| 166 | pub struct Run { |
| 167 | pub t: String, |
| 168 | #[serde(skip_serializing_if = "std::ops::Not::not")] |
| 169 | pub b: bool, |
| 170 | #[serde(skip_serializing_if = "std::ops::Not::not")] |
| 171 | pub i: bool, |
| 172 | #[serde(skip_serializing_if = "std::ops::Not::not")] |
| 173 | pub c: bool, |
| 174 | #[serde(skip_serializing_if = "std::ops::Not::not")] |
| 175 | pub h: bool, |
| 176 | #[serde(skip_serializing_if = "Option::is_none")] |
| 177 | pub href: Option<String>, |
| 178 | } |
| 179 | |
| 180 | impl Run { |
| 181 | pub fn same_marks(&self, other: &Run) -> bool { |
| 182 | self.b == other.b |
| 183 | && self.i == other.i |
| 184 | && self.c == other.c |
| 185 | && self.h == other.h |
| 186 | && self.href == other.href |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | pub type Paragraph = Vec<Run>; |
| 191 | |
| 192 | const MARK_KEYS: [&str; 4] = ["b", "i", "c", "h"]; |
| 193 | |
| 194 | fn run_attrs(run: &Run) -> Attrs { |
| 195 | let mut attrs = Attrs::new(); |
| 196 | for (key, on) in MARK_KEYS.iter().zip([run.b, run.i, run.c, run.h]) { |
| 197 | if on { |
| 198 | attrs.insert(Arc::from(*key), Any::Bool(true)); |
| 199 | } |
| 200 | } |
| 201 | if let Some(href) = &run.href { |
| 202 | attrs.insert(Arc::from("href"), href_any(href)); |
| 203 | } |
| 204 | attrs |
| 205 | } |
| 206 | |
| 207 | /// The `href` attribute's value: y-prosemirror's one-key map for the mark |
| 208 | /// `href` with attrs `{href}`. |
| 209 | fn href_any(href: &str) -> Any { |
| 210 | Any::Map(Arc::new(HashMap::from([( |
| 211 | "href".to_string(), |
| 212 | Any::from(href), |
| 213 | )]))) |
| 214 | } |
| 215 | |
| 216 | /// The URL an `href` attribute carries: the `{"href": url}` map this |
| 217 | /// module writes, or the plain string documents written before it carry. |
| 218 | fn href_of(v: &Any) -> Option<String> { |
| 219 | match v { |
| 220 | Any::String(s) => Some(s.to_string()), |
| 221 | Any::Map(m) => match m.get("href") { |
| 222 | Some(Any::String(s)) => Some(s.to_string()), |
| 223 | _ => None, |
| 224 | }, |
| 225 | _ => None, |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | fn paragraph_prelim(paragraph: &[Run]) -> XmlElementPrelim { |
| 230 | let delta: Vec<Delta<In>> = paragraph |
| 231 | .iter() |
| 232 | .filter(|run| !run.t.is_empty()) |
| 233 | .map(|run| { |
| 234 | let attrs = run_attrs(run); |
| 235 | let attrs = if attrs.is_empty() { |
| 236 | None |
| 237 | } else { |
| 238 | Some(Box::new(attrs)) |
| 239 | }; |
| 240 | Delta::Inserted(In::Any(Any::from(run.t.as_str())), attrs) |
| 241 | }) |
| 242 | .collect(); |
| 243 | let text = XmlDeltaPrelim { |
| 244 | attributes: HashMap::default(), |
| 245 | delta, |
| 246 | }; |
| 247 | XmlElementPrelim::new("paragraph", [XmlIn::Text(text)]) |
| 248 | } |
| 249 | |
| 250 | /// A fragment holding `text` in the §2.6 schema, ready to insert. |
| 251 | pub fn text_prelim(text: &[Paragraph]) -> XmlFragmentPrelim { |
| 252 | XmlFragmentPrelim::new::<_, ()>(text.iter().map(|p| XmlIn::Element(paragraph_prelim(p)))) |
| 253 | } |
| 254 | |
| 255 | /// Replaces the whole content of `frag` with `text`. |
| 256 | pub fn replace_text(txn: &mut TransactionMut, frag: &XmlFragmentRef, text: &[Paragraph]) { |
| 257 | let len = frag.len(txn); |
| 258 | if len > 0 { |
| 259 | frag.remove_range(txn, 0, len); |
| 260 | } |
| 261 | for p in text { |
| 262 | frag.push_back(txn, paragraph_prelim(p)); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn truthy(v: &Any) -> bool { |
| 267 | !matches!(v, Any::Null | Any::Undefined | Any::Bool(false)) |
| 268 | } |
| 269 | |
| 270 | fn push_runs<T: ReadTxn>(txn: &T, text: &yrs::XmlTextRef, out: &mut Paragraph) { |
| 271 | for chunk in text.diff(txn, YChange::identity) { |
| 272 | let Out::Any(Any::String(s)) = &chunk.insert else { |
| 273 | continue; // an embed: nothing in this schema, nothing to show |
| 274 | }; |
| 275 | if s.is_empty() { |
| 276 | continue; |
| 277 | } |
| 278 | let mut run = Run { |
| 279 | t: s.to_string(), |
| 280 | ..Run::default() |
| 281 | }; |
| 282 | if let Some(attrs) = &chunk.attributes { |
| 283 | run.b = attrs.get("b").is_some_and(truthy); |
| 284 | run.i = attrs.get("i").is_some_and(truthy); |
| 285 | run.c = attrs.get("c").is_some_and(truthy); |
| 286 | run.h = attrs.get("h").is_some_and(truthy); |
| 287 | run.href = attrs.get("href").and_then(href_of); |
| 288 | } |
| 289 | match out.last_mut() { |
| 290 | Some(last) if last.same_marks(&run) => last.t.push_str(&run.t), |
| 291 | _ => out.push(run), |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// The paragraphs of a text fragment. |
| 297 | pub fn read_text<T: ReadTxn>(txn: &T, frag: &XmlFragmentRef) -> Vec<Paragraph> { |
| 298 | let mut paragraphs = Vec::new(); |
| 299 | for child in frag.children(txn) { |
| 300 | match child { |
| 301 | XmlOut::Element(e) => { |
| 302 | let mut p = Paragraph::new(); |
| 303 | for inner in e.children(txn) { |
| 304 | match inner { |
| 305 | XmlOut::Text(t) => push_runs(txn, &t, &mut p), |
| 306 | // An element inside a paragraph is outside this |
| 307 | // schema; keep its plain text rather than lose it. |
| 308 | other => { |
| 309 | let s = other_string(txn, &other); |
| 310 | if !s.is_empty() { |
| 311 | p.push(Run { |
| 312 | t: s, |
| 313 | ..Run::default() |
| 314 | }); |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | paragraphs.push(p); |
| 320 | } |
| 321 | XmlOut::Text(t) => { |
| 322 | let mut p = Paragraph::new(); |
| 323 | push_runs(txn, &t, &mut p); |
| 324 | paragraphs.push(p); |
| 325 | } |
| 326 | XmlOut::Fragment(f) => paragraphs.extend(read_text(txn, &f)), |
| 327 | } |
| 328 | } |
| 329 | paragraphs |
| 330 | } |
| 331 | |
| 332 | fn other_string<T: ReadTxn>(txn: &T, node: &XmlOut) -> String { |
| 333 | match node { |
| 334 | XmlOut::Element(e) => e.get_string(txn), |
| 335 | XmlOut::Fragment(f) => f.get_string(txn), |
| 336 | XmlOut::Text(t) => t.get_string(txn), |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | // --- roots and lookups --- |
| 341 | |
| 342 | pub struct Roots { |
| 343 | pub meta: MapRef, |
| 344 | pub slides: ArrayRef, |
| 345 | pub assets: MapRef, |
| 346 | pub scenes: MapRef, |
| 347 | } |
| 348 | |
| 349 | /// The four root types. `get_or_insert_*` takes a write transaction of |
| 350 | /// its own internally, so this must run BEFORE any transaction the caller |
| 351 | /// opens (Docs' `snapshot.rs` records the self-deadlock otherwise). |
| 352 | pub fn roots(doc: &Doc) -> Roots { |
| 353 | Roots { |
| 354 | meta: doc.get_or_insert_map(ROOT_META), |
| 355 | slides: doc.get_or_insert_array(ROOT_SLIDES), |
| 356 | assets: doc.get_or_insert_map(ROOT_ASSETS), |
| 357 | scenes: doc.get_or_insert_map(ROOT_SCENES), |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | pub fn get_string<T: ReadTxn>(txn: &T, map: &MapRef, key: &str) -> Option<String> { |
| 362 | match map.get(txn, key)? { |
| 363 | Out::Any(Any::String(s)) => Some(s.to_string()), |
| 364 | _ => None, |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | pub fn get_number<T: ReadTxn>(txn: &T, map: &MapRef, key: &str) -> Option<f64> { |
| 369 | match map.get(txn, key)? { |
| 370 | Out::Any(Any::Number(n)) => Some(n), |
| 371 | Out::Any(Any::BigInt(n)) => Some(n as f64), |
| 372 | _ => None, |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | pub fn get_map<T: ReadTxn>(txn: &T, map: &MapRef, key: &str) -> Option<MapRef> { |
| 377 | match map.get(txn, key)? { |
| 378 | Out::YMap(m) => Some(m), |
| 379 | _ => None, |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | pub fn get_array<T: ReadTxn>(txn: &T, map: &MapRef, key: &str) -> Option<ArrayRef> { |
| 384 | match map.get(txn, key)? { |
| 385 | Out::YArray(a) => Some(a), |
| 386 | _ => None, |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | pub fn get_fragment<T: ReadTxn>(txn: &T, map: &MapRef, key: &str) -> Option<XmlFragmentRef> { |
| 391 | match map.get(txn, key)? { |
| 392 | Out::YXmlFragment(f) => Some(f), |
| 393 | _ => None, |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// The maps of an array of maps, in order, with their indices. Entries |
| 398 | /// that are not maps (nothing this crate writes, but an update from a |
| 399 | /// browser could) are skipped rather than trapped on. |
| 400 | pub fn maps_of<T: ReadTxn>(txn: &T, array: &ArrayRef) -> Vec<(u32, MapRef)> { |
| 401 | array |
| 402 | .iter(txn) |
| 403 | .enumerate() |
| 404 | .filter_map(|(i, out)| match out { |
| 405 | Out::YMap(m) => Some((i as u32, m)), |
| 406 | _ => None, |
| 407 | }) |
| 408 | .collect() |
| 409 | } |
| 410 | |
| 411 | /// The map in `array` whose `id` is `id`, with its index. |
| 412 | pub fn find_by_id<T: ReadTxn>(txn: &T, array: &ArrayRef, id: &str) -> Option<(u32, MapRef)> { |
| 413 | maps_of(txn, array) |
| 414 | .into_iter() |
| 415 | .find(|(_, m)| get_string(txn, m, "id").as_deref() == Some(id)) |
| 416 | } |
| 417 | |
| 418 | // --- reading order --- |
| 419 | // |
| 420 | // Both of the document's ordered arrays — the deck's `slides` and a |
| 421 | // slide's `blocks` — are SETS, and the order is a key, `order`, on each |
| 422 | // map in them (spec §2.2, §2.3, rulings 18 and 21). The array's own |
| 423 | // order is only the tie-break. The reason is what a reorder costs under |
| 424 | // concurrency: moving an entry in a Y.Array means deleting the map and |
| 425 | // inserting a copy, and every edit another peer made to the original — |
| 426 | // a sentence typed into its text — then addresses a deleted type and is |
| 427 | // lost on merge. Writing a number onto the map it already is leaves the |
| 428 | // map, and the edits in flight against it, alone. That is codex 4, and |
| 429 | // it is the same finding at both levels, so it has one answer. |
| 430 | // |
| 431 | // Absent `order` ranks as the array index, so a document written |
| 432 | // before the key existed reads exactly as it did, and a slide nobody |
| 433 | // has reordered carries no `order` at all. An op that changes the |
| 434 | // order of a slide's blocks (move_block, canvas-to-flow) or of the |
| 435 | // deck's slides (move_slide) writes a dense 0..n-1 onto every entry; |
| 436 | // add_block / add_slide / duplicate_slide on an array that already |
| 437 | // carries explicit orders renumbers so the new entry lands where |
| 438 | // `after` asked. |
| 439 | |
| 440 | /// The rank an entry sorts by: its `order` when that is a finite |
| 441 | /// number, else its array index. |
| 442 | fn rank<T: ReadTxn>(txn: &T, index: u32, m: &MapRef) -> f64 { |
| 443 | match get_number(txn, m, "order") { |
| 444 | Some(n) if n.is_finite() => n, |
| 445 | _ => index as f64, |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | /// The maps of an ordered array (the deck's `slides`, a slide's |
| 450 | /// `blocks`) in reading order: by `order`, then by array index for ties |
| 451 | /// and for entries that carry none. The returned index is each map's |
| 452 | /// array index, not its rank. |
| 453 | pub fn ordered_maps<T: ReadTxn>(txn: &T, array: &ArrayRef) -> Vec<(u32, MapRef)> { |
| 454 | let mut maps = maps_of(txn, array); |
| 455 | maps.sort_by(|a, b| { |
| 456 | rank(txn, a.0, &a.1) |
| 457 | .partial_cmp(&rank(txn, b.0, &b.1)) |
| 458 | .unwrap_or(std::cmp::Ordering::Equal) |
| 459 | .then(a.0.cmp(&b.0)) |
| 460 | }); |
| 461 | maps |
| 462 | } |
| 463 | |
| 464 | /// Whether any entry in `array` carries an explicit `order`. |
| 465 | pub fn has_explicit_order<T: ReadTxn>(txn: &T, array: &ArrayRef) -> bool { |
| 466 | maps_of(txn, array) |
| 467 | .iter() |
| 468 | .any(|(_, m)| get_number(txn, m, "order").is_some_and(f64::is_finite)) |
| 469 | } |
| 470 | |
| 471 | /// Writes `order` 0..n-1 onto `maps` in the order given. |
| 472 | pub fn renumber(txn: &mut TransactionMut, maps: &[MapRef]) { |
| 473 | for (k, m) in maps.iter().enumerate() { |
| 474 | m.insert(txn, "order", Any::Number(k as f64)); |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | // --- JSON <-> yrs values --- |
| 479 | |
| 480 | /// A plain JSON value as a yrs `Any`. Objects and arrays become plain |
| 481 | /// nested values, never shared types: this is for the leaves of the |
| 482 | /// schema (`props` entries, `box`, `fonts`, an asset), which are edited |
| 483 | /// whole. |
| 484 | pub fn json_to_any(v: &serde_json::Value) -> Any { |
| 485 | match v { |
| 486 | serde_json::Value::Null => Any::Null, |
| 487 | serde_json::Value::Bool(b) => Any::Bool(*b), |
| 488 | serde_json::Value::Number(n) => { |
| 489 | if let Some(i) = n.as_i64() { |
| 490 | if i.unsigned_abs() < (1u64 << 53) { |
| 491 | Any::Number(i as f64) |
| 492 | } else { |
| 493 | Any::BigInt(i) |
| 494 | } |
| 495 | } else { |
| 496 | Any::Number(n.as_f64().unwrap_or(0.0)) |
| 497 | } |
| 498 | } |
| 499 | serde_json::Value::String(s) => Any::from(s.as_str()), |
| 500 | serde_json::Value::Array(items) => { |
| 501 | Any::Array(items.iter().map(json_to_any).collect::<Vec<_>>().into()) |
| 502 | } |
| 503 | serde_json::Value::Object(entries) => Any::Map(Arc::new( |
| 504 | entries |
| 505 | .iter() |
| 506 | .map(|(k, v)| (k.clone(), json_to_any(v))) |
| 507 | .collect(), |
| 508 | )), |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | /// A JSON number for `f`: an integer when it is one (so `level: 1` reads |
| 513 | /// back as `1`, not `1.0`), a float otherwise, null for NaN/inf. |
| 514 | pub fn number_json(f: f64) -> serde_json::Value { |
| 515 | if f.fract() == 0.0 && f.abs() < (1u64 << 53) as f64 { |
| 516 | serde_json::Value::from(f as i64) |
| 517 | } else { |
| 518 | serde_json::Number::from_f64(f) |
| 519 | .map(serde_json::Value::Number) |
| 520 | .unwrap_or(serde_json::Value::Null) |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | pub fn any_to_json(v: &Any) -> serde_json::Value { |
| 525 | match v { |
| 526 | Any::Null | Any::Undefined => serde_json::Value::Null, |
| 527 | Any::Bool(b) => serde_json::Value::Bool(*b), |
| 528 | Any::Number(n) => number_json(*n), |
| 529 | Any::BigInt(n) => serde_json::Value::from(*n), |
| 530 | Any::String(s) => serde_json::Value::String(s.to_string()), |
| 531 | Any::Buffer(b) => { |
| 532 | serde_json::Value::Array(b.iter().map(|x| serde_json::Value::from(*x)).collect()) |
| 533 | } |
| 534 | Any::Array(items) => serde_json::Value::Array(items.iter().map(any_to_json).collect()), |
| 535 | Any::Map(entries) => serde_json::Value::Object( |
| 536 | entries |
| 537 | .iter() |
| 538 | .map(|(k, v)| (k.clone(), any_to_json(v))) |
| 539 | .collect(), |
| 540 | ), |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | /// Any value the document holds, as JSON. Shared types are rendered by |
| 545 | /// content — a map as an object, an array as an array, a text fragment |
| 546 | /// as its paragraphs — so the view need not know which of a key's |
| 547 | /// possible representations a peer chose. |
| 548 | pub fn out_to_json<T: ReadTxn>(txn: &T, out: &Out) -> serde_json::Value { |
| 549 | match out { |
| 550 | Out::Any(a) => any_to_json(a), |
| 551 | Out::YMap(m) => map_to_json(txn, m), |
| 552 | Out::YArray(a) => { |
| 553 | serde_json::Value::Array(a.iter(txn).map(|item| out_to_json(txn, &item)).collect()) |
| 554 | } |
| 555 | Out::YXmlFragment(f) => serde_json::to_value(read_text(txn, f)).unwrap_or_default(), |
| 556 | Out::YText(t) => serde_json::Value::String(t.get_string(txn)), |
| 557 | Out::YXmlText(t) => serde_json::Value::String(t.get_string(txn)), |
| 558 | Out::YXmlElement(e) => serde_json::Value::String(e.get_string(txn)), |
| 559 | _ => serde_json::Value::Null, |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | pub fn map_to_json<T: ReadTxn>(txn: &T, map: &MapRef) -> serde_json::Value { |
| 564 | serde_json::Value::Object( |
| 565 | map.iter(txn) |
| 566 | .map(|(k, v)| (k.to_string(), out_to_json(txn, &v))) |
| 567 | .collect(), |
| 568 | ) |
| 569 | } |
| 570 | |
| 571 | /// `Some(json)` when the value is a map (shared or plain), else `None`. |
| 572 | pub fn get_object<T: ReadTxn>(txn: &T, map: &MapRef, key: &str) -> Option<serde_json::Value> { |
| 573 | match map.get(txn, key)? { |
| 574 | Out::YMap(m) => Some(map_to_json(txn, &m)), |
| 575 | Out::Any(a @ Any::Map(_)) => Some(any_to_json(&a)), |
| 576 | _ => None, |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | // --- constructors --- |
| 581 | |
| 582 | pub fn string_in(s: &str) -> In { |
| 583 | In::Any(Any::from(s)) |
| 584 | } |
| 585 | |
| 586 | pub fn number_in(n: f64) -> In { |
| 587 | In::Any(Any::Number(n)) |
| 588 | } |
| 589 | |
| 590 | /// A Y.Map prelim whose entries are plain values from a JSON object. |
| 591 | pub fn plain_map_prelim(entries: &serde_json::Map<String, serde_json::Value>) -> yrs::MapPrelim { |
| 592 | entries |
| 593 | .iter() |
| 594 | .map(|(k, v)| (k.as_str(), In::Any(json_to_any(v)))) |
| 595 | .collect() |
| 596 | } |
| 597 | |
| 598 | /// A `{kind, value}` background as a Y.Map prelim. |
| 599 | pub fn background_prelim(kind: &str, value: &str) -> yrs::MapPrelim { |
| 600 | [("kind", string_in(kind)), ("value", string_in(value))] |
| 601 | .into_iter() |
| 602 | .collect() |
| 603 | } |
| 604 | |
| 605 | /// An array of `n` empty text fragments — a table's cells. |
| 606 | pub fn cells_prelim(n: usize) -> yrs::ArrayPrelim { |
| 607 | (0..n) |
| 608 | .map(|_| In::XmlFragment(XmlFragmentPrelim::default())) |
| 609 | .collect() |
| 610 | } |
| 611 | |
| 612 | /// A block map prelim. `text` is written for text-bearing types only, |
| 613 | /// `cells` for tables only; flow blocks get `region`, canvas blocks |
| 614 | /// `box` and `z` — the caller has already decided which. |
| 615 | #[allow(clippy::too_many_arguments)] |
| 616 | pub fn block_prelim( |
| 617 | id: &str, |
| 618 | kind: &str, |
| 619 | props: &serde_json::Map<String, serde_json::Value>, |
| 620 | region: Option<&str>, |
| 621 | r#box: Option<&serde_json::Value>, |
| 622 | z: Option<f64>, |
| 623 | text: Option<&[Paragraph]>, |
| 624 | cells: Option<usize>, |
| 625 | ) -> yrs::MapPrelim { |
| 626 | let mut m: yrs::MapPrelim = [ |
| 627 | ("id", string_in(id)), |
| 628 | ("type", string_in(kind)), |
| 629 | ("props", In::Map(plain_map_prelim(props))), |
| 630 | ("phone", In::Map(yrs::MapPrelim::default())), |
| 631 | ] |
| 632 | .into_iter() |
| 633 | .collect(); |
| 634 | if let Some(r) = region { |
| 635 | m.insert(Arc::from("region"), string_in(r)); |
| 636 | } |
| 637 | if let Some(b) = r#box { |
| 638 | m.insert(Arc::from("box"), In::Any(json_to_any(b))); |
| 639 | } |
| 640 | if let Some(z) = z { |
| 641 | m.insert(Arc::from("z"), number_in(z)); |
| 642 | } |
| 643 | if let Some(t) = text { |
| 644 | m.insert(Arc::from("text"), In::XmlFragment(text_prelim(t))); |
| 645 | } |
| 646 | if let Some(n) = cells { |
| 647 | m.insert(Arc::from("cells"), In::Array(cells_prelim(n))); |
| 648 | } |
| 649 | m |
| 650 | } |
| 651 | |
| 652 | /// A slide map prelim with no blocks and empty notes. |
| 653 | pub fn slide_prelim(id: &str, layout: &str, template: &str) -> yrs::MapPrelim { |
| 654 | [ |
| 655 | ("id", string_in(id)), |
| 656 | ("layout", string_in(layout)), |
| 657 | ("template", string_in(template)), |
| 658 | ("phone", string_in("inherit")), |
| 659 | ("transition", string_in("none")), |
| 660 | ("background", In::Map(background_prelim("theme", ""))), |
| 661 | ("notes", In::XmlFragment(XmlFragmentPrelim::default())), |
| 662 | ("blocks", In::Array(yrs::ArrayPrelim::default())), |
| 663 | ] |
| 664 | .into_iter() |
| 665 | .collect() |
| 666 | } |
| 667 | |
| 668 | /// Rounds a box coordinate to the four decimals §2.3 specifies. |
| 669 | pub fn round4(f: f64) -> f64 { |
| 670 | (f * 10_000.0).round() / 10_000.0 |
| 671 | } |
| 672 | |
| 673 | pub fn box_json(x: f64, y: f64, w: f64, h: f64) -> serde_json::Value { |
| 674 | serde_json::json!({ |
| 675 | "x": round4(x), |
| 676 | "y": round4(y), |
| 677 | "w": round4(w), |
| 678 | "h": round4(h), |
| 679 | }) |
| 680 | } |
| 681 | |
| 682 | // --- meta.fontFiles --- |
| 683 | |
| 684 | pub const FONT_FORMATS: &[&str] = &["ttf", "otf", "woff", "woff2"]; |
| 685 | pub const MAX_FONT_FAMILIES: usize = 32; |
| 686 | pub const MAX_FONT_FACES: usize = 16; |
| 687 | pub const MAX_FONT_NAME: usize = 200; |
| 688 | |
| 689 | /// CSS names an uploaded family may not take, lowercase: the catalog's |
| 690 | /// families, which it would join in document.fonts, and CSS's generic |
| 691 | /// family keywords. internal/slides/library.go's reservedFontName and |
| 692 | /// fixtures/font-files.mjs say the same. |
| 693 | pub const RESERVED_FONT_NAMES: &[&str] = &[ |
| 694 | "liberation sans", |
| 695 | "liberation serif", |
| 696 | "liberation mono", |
| 697 | "serif", |
| 698 | "sans-serif", |
| 699 | "monospace", |
| 700 | "cursive", |
| 701 | "fantasy", |
| 702 | "system-ui", |
| 703 | "ui-serif", |
| 704 | "ui-sans-serif", |
| 705 | "ui-monospace", |
| 706 | "ui-rounded", |
| 707 | "math", |
| 708 | "emoji", |
| 709 | "fangsong", |
| 710 | ]; |
| 711 | |
| 712 | /// The one pattern for an uploaded family's CSS name, shared with the |
| 713 | /// library and layout (internal/slides/deck's FontCSSName): |
| 714 | /// ^[A-Za-z0-9][A-Za-z0-9 ._-]{0,199}$. No comma or quote: the name is |
| 715 | /// written into a quoted font-family as it is. |
| 716 | fn font_css_ok(s: &str) -> bool { |
| 717 | s.len() <= MAX_FONT_NAME |
| 718 | && s.bytes().next().is_some_and(|b| b.is_ascii_alphanumeric()) |
| 719 | && s.bytes() |
| 720 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b' ' | b'.' | b'_' | b'-')) |
| 721 | } |
| 722 | |
| 723 | fn font_ref_ok(s: &str) -> bool { |
| 724 | s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) |
| 725 | } |
| 726 | |
| 727 | /// A whole number from 1 to 1000, read from a JSON number. |
| 728 | fn font_weight(v: &serde_json::Value) -> Option<i64> { |
| 729 | let n = v.as_f64()?; |
| 730 | (n.fract() == 0.0 && (1.0..=1000.0).contains(&n)).then_some(n as i64) |
| 731 | } |
| 732 | |
| 733 | /// `meta.fontFiles` checked and rebuilt from its known fields: the list |
| 734 | /// of `{family, css, faces: [{ref, format, weight: [min, max], italic, |
| 735 | /// pictures}]}`, or the first thing wrong with it. The ops refuse on the |
| 736 | /// message; the view drops the whole value. fixtures/ops-model.mjs |
| 737 | /// (fontFilesValue) says the same, word for word. |
| 738 | pub fn font_files(v: &serde_json::Value) -> Result<serde_json::Value, String> { |
| 739 | use serde_json::{json, Value}; |
| 740 | let list = v.as_array().ok_or("fontFiles must be a list")?; |
| 741 | if list.len() > MAX_FONT_FAMILIES { |
| 742 | return Err(format!( |
| 743 | "fontFiles has more than {MAX_FONT_FAMILIES} families" |
| 744 | )); |
| 745 | } |
| 746 | let mut seen = std::collections::HashSet::new(); |
| 747 | let mut out = Vec::new(); |
| 748 | for (i, fam) in list.iter().enumerate() { |
| 749 | let at = format!("fontFiles[{i}]"); |
| 750 | let fam = fam.as_object().ok_or(format!("{at} must be a map"))?; |
| 751 | let family = fam |
| 752 | .get("family") |
| 753 | .and_then(Value::as_str) |
| 754 | .ok_or(format!("{at}.family must be a string"))?; |
| 755 | if family.chars().count() > MAX_FONT_NAME { |
| 756 | return Err(format!( |
| 757 | "{at}.family is longer than {MAX_FONT_NAME} characters" |
| 758 | )); |
| 759 | } |
| 760 | let css = fam |
| 761 | .get("css") |
| 762 | .and_then(Value::as_str) |
| 763 | .ok_or(format!("{at}.css must be a string"))?; |
| 764 | if !font_css_ok(css) { |
| 765 | return Err(format!("{at}.css is not a font family name")); |
| 766 | } |
| 767 | if RESERVED_FONT_NAMES.contains(&css.to_ascii_lowercase().as_str()) { |
| 768 | return Err(format!("{at}.css {css:?} is a name stacks already use")); |
| 769 | } |
| 770 | // A browser matches family names without regard to case. |
| 771 | if !seen.insert(css.to_ascii_lowercase()) { |
| 772 | return Err(format!("{at}.css {css:?} is used twice")); |
| 773 | } |
| 774 | let faces = fam |
| 775 | .get("faces") |
| 776 | .and_then(Value::as_array) |
| 777 | .ok_or(format!("{at}.faces must be a list"))?; |
| 778 | if faces.len() > MAX_FONT_FACES { |
| 779 | return Err(format!("{at}.faces has more than {MAX_FONT_FACES} faces")); |
| 780 | } |
| 781 | let mut fs = Vec::new(); |
| 782 | for (j, face) in faces.iter().enumerate() { |
| 783 | let at = format!("{at}.faces[{j}]"); |
| 784 | let face = face.as_object().ok_or(format!("{at} must be a map"))?; |
| 785 | let reference = face |
| 786 | .get("ref") |
| 787 | .and_then(Value::as_str) |
| 788 | .ok_or(format!("{at}.ref must be a string"))?; |
| 789 | if !font_ref_ok(reference) { |
| 790 | return Err(format!("{at}.ref is not 64 lowercase hex digits")); |
| 791 | } |
| 792 | let format_ = face |
| 793 | .get("format") |
| 794 | .and_then(Value::as_str) |
| 795 | .ok_or(format!("{at}.format must be a string"))?; |
| 796 | if !FONT_FORMATS.contains(&format_) { |
| 797 | return Err(format!( |
| 798 | "{at}.format {format_:?} is not one of {}", |
| 799 | FONT_FORMATS.join(", ") |
| 800 | )); |
| 801 | } |
| 802 | let w = face |
| 803 | .get("weight") |
| 804 | .and_then(Value::as_array) |
| 805 | .filter(|w| w.len() == 2) |
| 806 | .ok_or(format!("{at}.weight must be [min, max]"))?; |
| 807 | let (Some(min), Some(max)) = (font_weight(&w[0]), font_weight(&w[1])) else { |
| 808 | return Err(format!("{at}.weight must be whole numbers from 1 to 1000")); |
| 809 | }; |
| 810 | if min > max { |
| 811 | return Err(format!("{at}.weight min is above max")); |
| 812 | } |
| 813 | let italic = face |
| 814 | .get("italic") |
| 815 | .and_then(Value::as_bool) |
| 816 | .ok_or(format!("{at}.italic must be true or false"))?; |
| 817 | let pictures = face |
| 818 | .get("pictures") |
| 819 | .and_then(Value::as_bool) |
| 820 | .ok_or(format!("{at}.pictures must be true or false"))?; |
| 821 | fs.push( |
| 822 | json!({"ref": reference, "format": format_, "weight": [min, max], |
| 823 | "italic": italic, "pictures": pictures}), |
| 824 | ); |
| 825 | } |
| 826 | out.push(json!({"family": family, "css": css, "faces": fs})); |
| 827 | } |
| 828 | Ok(Value::Array(out)) |
| 829 | } |
| 830 | |
| 831 | #[cfg(test)] |
| 832 | mod tests { |
| 833 | use super::*; |
| 834 | use crate::new_doc; |
| 835 | use yrs::Transact; |
| 836 | |
| 837 | fn linked(t: &str, href: &str) -> Run { |
| 838 | Run { |
| 839 | t: t.to_string(), |
| 840 | href: Some(href.to_string()), |
| 841 | ..Run::default() |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | /// Writes one paragraph holding one XmlText formatted with `attrs`, |
| 846 | /// then reads the fragment back the way the view does. |
| 847 | fn read_back_written_attrs(attrs: Attrs) -> Vec<Paragraph> { |
| 848 | let doc = new_doc("test-href", 1); |
| 849 | let frag = doc.get_or_insert_xml_fragment("t"); |
| 850 | let mut txn = doc.transact_mut(); |
| 851 | let el = frag.push_back(&mut txn, XmlElementPrelim::empty("paragraph")); |
| 852 | let text = el.push_back(&mut txn, yrs::XmlTextPrelim::new("")); |
| 853 | text.insert_with_attributes(&mut txn, 0, "x", attrs); |
| 854 | read_text(&txn, &frag) |
| 855 | } |
| 856 | |
| 857 | #[test] |
| 858 | fn href_is_written_as_a_one_key_map_and_reads_back() { |
| 859 | let doc = new_doc("test-href", 1); |
| 860 | let frag = doc.get_or_insert_xml_fragment("t"); |
| 861 | let mut txn = doc.transact_mut(); |
| 862 | replace_text(&mut txn, &frag, &[vec![linked("t", "https://x")]]); |
| 863 | |
| 864 | // The stored attribute is y-prosemirror's shape, not a bare string. |
| 865 | let Some(XmlOut::Element(el)) = frag.get(&txn, 0) else { |
| 866 | panic!("the paragraph is an element"); |
| 867 | }; |
| 868 | let Some(XmlOut::Text(text)) = el.get(&txn, 0) else { |
| 869 | panic!("the paragraph holds a text"); |
| 870 | }; |
| 871 | let chunks = text.diff(&txn, YChange::identity); |
| 872 | let attrs = chunks[0].attributes.as_ref().expect("attributes"); |
| 873 | assert_eq!(attrs.get("href"), Some(&href_any("https://x"))); |
| 874 | |
| 875 | assert_eq!(read_text(&txn, &frag), vec![vec![linked("t", "https://x")]]); |
| 876 | } |
| 877 | |
| 878 | #[test] |
| 879 | fn href_written_as_a_plain_string_still_reads_back() { |
| 880 | // What documents written before the map shape carry. |
| 881 | let attrs = Attrs::from([(Arc::from("href"), Any::from("https://old"))]); |
| 882 | assert_eq!( |
| 883 | read_back_written_attrs(attrs), |
| 884 | vec![vec![linked("x", "https://old")]] |
| 885 | ); |
| 886 | } |
| 887 | |
| 888 | #[test] |
| 889 | fn an_empty_map_reads_as_a_set_mark() { |
| 890 | // y-prosemirror writes `{}` for a mark with no attributes. |
| 891 | let attrs = Attrs::from([(Arc::from("b"), Any::Map(Arc::new(HashMap::new())))]); |
| 892 | assert_eq!( |
| 893 | read_back_written_attrs(attrs), |
| 894 | vec![vec![Run { |
| 895 | t: "x".to_string(), |
| 896 | b: true, |
| 897 | ..Run::default() |
| 898 | }]] |
| 899 | ); |
| 900 | } |
| 901 | |
| 902 | #[test] |
| 903 | fn an_href_map_without_a_string_url_reads_as_no_link() { |
| 904 | let inner = HashMap::from([("href".to_string(), Any::Null)]); |
| 905 | let attrs = Attrs::from([(Arc::from("href"), Any::Map(Arc::new(inner)))]); |
| 906 | assert_eq!( |
| 907 | read_back_written_attrs(attrs), |
| 908 | vec![vec![Run { |
| 909 | t: "x".to_string(), |
| 910 | ..Run::default() |
| 911 | }]] |
| 912 | ); |
| 913 | } |
| 914 | } |
| 915 | |