| 1 | //! Rendering a ProseMirror-shaped Y.XmlFragment to text and HTML. |
| 2 | //! |
| 3 | //! This is the only place on the Rust side that knows ProseMirror's |
| 4 | //! node vocabulary. It exists because the read view is server-rendered |
| 5 | //! (spec §6.2: reading a document works with no script), so the server |
| 6 | //! must be able to render what the browser's editor wrote. |
| 7 | //! |
| 8 | //! Unknown nodes render their children rather than disappearing. A |
| 9 | //! future editor build can introduce a node this binary has never |
| 10 | //! heard of, and a reader silently losing that text would be data |
| 11 | //! loss, not a degradation. |
| 12 | |
| 13 | use std::fmt::Write as _; |
| 14 | use yrs::types::xml::{XmlFragment, XmlOut, XmlTextRef}; |
| 15 | use yrs::{Doc, GetString, ReadTxn, Text, Transact, Xml, XmlElementRef, XmlFragmentRef}; |
| 16 | |
| 17 | /// The CRDT root name. y-prosemirror's default, and part of the wire |
| 18 | /// contract — changing it silently orphans every existing document. |
| 19 | pub const ROOT: &str = "prosemirror"; |
| 20 | |
| 21 | fn root(doc: &Doc) -> XmlFragmentRef { |
| 22 | doc.get_or_insert_xml_fragment(ROOT) |
| 23 | } |
| 24 | |
| 25 | fn escape(s: &str, out: &mut String) { |
| 26 | for c in s.chars() { |
| 27 | match c { |
| 28 | '&' => out.push_str("&"), |
| 29 | '<' => out.push_str("<"), |
| 30 | '>' => out.push_str(">"), |
| 31 | '"' => out.push_str("""), |
| 32 | '\'' => out.push_str("'"), |
| 33 | _ => out.push(c), |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// Marks this build knows, in a fixed order so output is deterministic: |
| 39 | /// `(mark name, opening markup, closing markup)`. A mark not listed here |
| 40 | /// contributes no wrapper but never suppresses its text. |
| 41 | /// |
| 42 | /// Every one of these is attribute-free on the CRDT side — the mark's |
| 43 | /// presence is the whole of its meaning — and the markup each one emits |
| 44 | /// is a compile-time constant chosen by lookup from this table. That is |
| 45 | /// what keeps `Store.HTML`'s `template.HTML` return honest |
| 46 | /// (`internal/docs/store.go`): `fragment_html` escapes every text run |
| 47 | /// AND puts no byte from a document into attribute position, so the |
| 48 | /// markup is safe to write out unescaped. A mark carrying a value — |
| 49 | /// `link`'s `href`, or a `fontFamily` naming its own face — would break |
| 50 | /// that, and `POST /d/{sqid}/updates` accepts arbitrary client-supplied |
| 51 | /// Yjs bytes that never went through ProseMirror's schema, so the value |
| 52 | /// would be genuinely arbitrary. Adding one is a real decision about |
| 53 | /// attribute escaping and (for `href`) a scheme allowlist, not a row in |
| 54 | /// this table. |
| 55 | /// |
| 56 | /// Images (Docs images spec §4.1) are the one place that decision was |
| 57 | /// made, and they are not a mark: `image_html` writes an image's id into |
| 58 | /// attribute position only after it has matched a fixed grammar exactly |
| 59 | /// (16 of `[0-9a-z]`, needing no escaping), under a base `View::parse` |
| 60 | /// has checked, and writes the alt text escaped. No other byte of an |
| 61 | /// image's attributes is written anywhere. |
| 62 | /// |
| 63 | /// Paragraph alignment (ALIGNMENTS below) is that same discipline |
| 64 | /// applied to a property that genuinely cannot be a mark: it belongs to |
| 65 | /// the block, so it arrives as an attribute WITH a value — and that |
| 66 | /// value is used only as a key into a table whose right-hand side is a |
| 67 | /// literal in this binary. |
| 68 | /// |
| 69 | /// The font and size marks are ordered ahead of the semantic ones so a |
| 70 | /// run carrying both nests as `<span class="…"><strong>…</strong></span>` |
| 71 | /// rather than the other way round. |
| 72 | /// |
| 73 | /// Every family has a mark; "normal" size still has none. The rule is |
| 74 | /// that the DEFAULT carries no mark — it is what a document is when |
| 75 | /// nobody has said otherwise, and spending a mark on it would put a span |
| 76 | /// around most of the text in most documents. What this table does NOT |
| 77 | /// do is decide which face that is: the default is internal/fonts/ |
| 78 | /// fonts.json's "default" (Carlito), and every family here has a row so |
| 79 | /// that moving it is a change to the manifest and not to this table. |
| 80 | /// `font_serif` and `font_sans` are why: each was once the absence of a |
| 81 | /// mark, and became unsayable the moment it stopped being the default. |
| 82 | pub(crate) const MARKS: &[(&str, &str, &str)] = &[ |
| 83 | // One row per family in internal/fonts/fonts.json, in its order, so |
| 84 | // the last font mark on a run is the innermost span and the one the |
| 85 | // cascade draws; internal/fonts' ForMarks and fixtures/fonts.mjs |
| 86 | // resolve a doubly-marked run the same way. tests/fragment.rs holds |
| 87 | // this list to the manifest. |
| 88 | ( |
| 89 | "font_carlito", |
| 90 | "<span class=\"docs-font-carlito\">", |
| 91 | "</span>", |
| 92 | ), |
| 93 | ( |
| 94 | "font_caladea", |
| 95 | "<span class=\"docs-font-caladea\">", |
| 96 | "</span>", |
| 97 | ), |
| 98 | ("font_inter", "<span class=\"docs-font-inter\">", "</span>"), |
| 99 | ( |
| 100 | "font_sourcesans", |
| 101 | "<span class=\"docs-font-sourcesans\">", |
| 102 | "</span>", |
| 103 | ), |
| 104 | ( |
| 105 | "font_plexsans", |
| 106 | "<span class=\"docs-font-plexsans\">", |
| 107 | "</span>", |
| 108 | ), |
| 109 | ( |
| 110 | "font_sourceserif", |
| 111 | "<span class=\"docs-font-sourceserif\">", |
| 112 | "</span>", |
| 113 | ), |
| 114 | ( |
| 115 | "font_literata", |
| 116 | "<span class=\"docs-font-literata\">", |
| 117 | "</span>", |
| 118 | ), |
| 119 | ( |
| 120 | "font_garamond", |
| 121 | "<span class=\"docs-font-garamond\">", |
| 122 | "</span>", |
| 123 | ), |
| 124 | ("font_sans", "<span class=\"docs-font-sans\">", "</span>"), |
| 125 | ("font_serif", "<span class=\"docs-font-serif\">", "</span>"), |
| 126 | ("font_mono", "<span class=\"docs-font-mono\">", "</span>"), |
| 127 | ( |
| 128 | "font_notosans", |
| 129 | "<span class=\"docs-font-notosans\">", |
| 130 | "</span>", |
| 131 | ), |
| 132 | ("font_zilla", "<span class=\"docs-font-zilla\">", "</span>"), |
| 133 | ( |
| 134 | "font_jetbrains", |
| 135 | "<span class=\"docs-font-jetbrains\">", |
| 136 | "</span>", |
| 137 | ), |
| 138 | ( |
| 139 | "font_playfair", |
| 140 | "<span class=\"docs-font-playfair\">", |
| 141 | "</span>", |
| 142 | ), |
| 143 | ( |
| 144 | "font_caveat", |
| 145 | "<span class=\"docs-font-caveat\">", |
| 146 | "</span>", |
| 147 | ), |
| 148 | // The point ladder. Eleven rows rather than one mark carrying a |
| 149 | // number, and that is the whole of this table's discipline applied |
| 150 | // to the feature people most expect to be a value: a mark spelling |
| 151 | // "14pt" would put a document's own byte into attribute position, |
| 152 | // which is exactly what the comment above forbids. Eleven |
| 153 | // attribute-free marks spend no new safety property at all. |
| 154 | // |
| 155 | // 12pt is absent because it is the default, and the default carries |
| 156 | // no mark — the same rule that keeps "normal" and the default face |
| 157 | // out of this table. |
| 158 | ("size_8", "<span class=\"docs-size-8\">", "</span>"), |
| 159 | ("size_9", "<span class=\"docs-size-9\">", "</span>"), |
| 160 | ("size_10", "<span class=\"docs-size-10\">", "</span>"), |
| 161 | ("size_11", "<span class=\"docs-size-11\">", "</span>"), |
| 162 | ("size_14", "<span class=\"docs-size-14\">", "</span>"), |
| 163 | ("size_18", "<span class=\"docs-size-18\">", "</span>"), |
| 164 | ("size_24", "<span class=\"docs-size-24\">", "</span>"), |
| 165 | ("size_36", "<span class=\"docs-size-36\">", "</span>"), |
| 166 | ("size_48", "<span class=\"docs-size-48\">", "</span>"), |
| 167 | ("size_72", "<span class=\"docs-size-72\">", "</span>"), |
| 168 | // The four-step scale the ladder replaced. These stay here |
| 169 | // PERMANENTLY, and not out of politeness: documents in the wild |
| 170 | // carry them, and a mark this table stops rendering is a mark whose |
| 171 | // text silently loses its size for every reader without JavaScript |
| 172 | // — the module comment's own "silence here is data loss". They are |
| 173 | // simply no longer offered by the control, and the stylesheet maps |
| 174 | // each to its nearest ladder step so one document does not read at |
| 175 | // two sizes depending on which renderer looked at it. |
| 176 | ("size_sm", "<span class=\"docs-size-sm\">", "</span>"), |
| 177 | ("size_lg", "<span class=\"docs-size-lg\">", "</span>"), |
| 178 | ("size_xl", "<span class=\"docs-size-xl\">", "</span>"), |
| 179 | ("strong", "<strong>", "</strong>"), |
| 180 | ("em", "<em>", "</em>"), |
| 181 | ("code", "<code>", "</code>"), |
| 182 | ]; |
| 183 | |
| 184 | /// Paragraph alignments this build knows: `(attribute value, class |
| 185 | /// name)`. The first block-level formatting, and the first thing in |
| 186 | /// this file that reads a document attribute whose value is not a |
| 187 | /// number. |
| 188 | /// |
| 189 | /// That is why it is a table and not an interpolation. Alignment cannot |
| 190 | /// be a mark — it belongs to the block, not the run — but it has to |
| 191 | /// keep the property the MARKS table above exists to protect: nothing |
| 192 | /// from a document may reach attribute position in `fragment_html`, |
| 193 | /// whose output `internal/docs/store.go` returns as `template.HTML` and |
| 194 | /// `views/show.html` writes into the page unescaped. So the value is |
| 195 | /// only ever a key looked up here, and what gets emitted is the |
| 196 | /// right-hand side, which is a literal in this binary. |
| 197 | /// |
| 198 | /// Closed, therefore, in the strong sense: a value that is not in this |
| 199 | /// table — a typo, a hand-crafted update through |
| 200 | /// `POST /d/{sqid}/updates`, or a future version's `justify` — is |
| 201 | /// dropped entirely. Never escaped and emitted, never passed through. |
| 202 | /// Adding `justify` here later is one row plus one CSS rule plus the |
| 203 | /// arithmetic in `internal/export/pdf.go`; letting an unknown value |
| 204 | /// through would be a decision about attribute escaping, which is the |
| 205 | /// decision this shape refuses to have to make. |
| 206 | /// |
| 207 | /// `left` is deliberately absent. It is what a paragraph is when nobody |
| 208 | /// has said otherwise, so it spends no class and no `attrs` — the same |
| 209 | /// reasoning that keeps "normal" out of MARKS, and what makes |
| 210 | /// a document written before alignment existed render byte-identically |
| 211 | /// to one whose author chose left on purpose. |
| 212 | const ALIGNMENTS: &[(&str, &str)] = &[ |
| 213 | ("center", "docs-align-center"), |
| 214 | ("right", "docs-align-right"), |
| 215 | ]; |
| 216 | |
| 217 | /// The alignment value, if this build knows it. `None` for left, for an |
| 218 | /// absent attribute, and for anything unrecognised — the three cases |
| 219 | /// that all render the same way. |
| 220 | fn alignment<T: ReadTxn>(txn: &T, e: &XmlElementRef) -> Option<&'static str> { |
| 221 | let value = e.get_attribute(txn, "align")?; |
| 222 | ALIGNMENTS |
| 223 | .iter() |
| 224 | .find(|(name, _)| *name == value) |
| 225 | .map(|(name, _)| *name) |
| 226 | } |
| 227 | |
| 228 | /// The deepest indent this build renders. Past eight half-inch steps a |
| 229 | /// paragraph on US Letter has no measure left, and `fixtures/indent.mjs` |
| 230 | /// states the same limit for the editor. |
| 231 | const MAX_INDENT: u8 = 8; |
| 232 | |
| 233 | /// The indent level, if this block has one: a whole number from 1 to |
| 234 | /// `MAX_INDENT`, or `None` for 0, for an absent attribute, and for |
| 235 | /// anything that does not parse. |
| 236 | /// |
| 237 | /// A NUMBER, where `alignment` above handles a string, and that is the |
| 238 | /// whole reason this is a separate function rather than another closed |
| 239 | /// table. Alignment's values are strings, so the only safe thing to do |
| 240 | /// with one is look it up and emit the table's own right-hand side. |
| 241 | /// Indent's value is an integer, so it is handled the way `heading`'s |
| 242 | /// level already is: parsed, then clamped. Both reach the property this |
| 243 | /// module exists to hold — no byte from a document reaches attribute |
| 244 | /// position — by different routes, and using the EXISTING route rather |
| 245 | /// than inventing a third one is the point. A `u8` that has been through |
| 246 | /// `clamp(1, 8)` can only be one of eight values, so interpolating it |
| 247 | /// into a class name below is not the injection that interpolating an |
| 248 | /// arbitrary attribute would be. |
| 249 | /// |
| 250 | /// Clamped rather than rejected, matching `heading`'s level: a document |
| 251 | /// arriving through `POST /d/{sqid}/updates` with `indent` 400 renders |
| 252 | /// at 8, and so does one with 4000000. Anything that is not a run of |
| 253 | /// digits — `"420; drop"`, `" 3"`, `"3.0"`, an empty string — is `None` |
| 254 | /// and renders flush left. `fixtures/indent.mjs`'s `normaliseIndent` |
| 255 | /// applies the same two rules, deliberately, so the two agree on every |
| 256 | /// input rather than only on the ones a real editor produces. |
| 257 | /// |
| 258 | /// (`heading`'s own level below still parses as `u8` and so still |
| 259 | /// rejects 400 where it clamps 99. That is the shape this function had |
| 260 | /// and stopped having; it is left alone here because changing it would |
| 261 | /// change what existing documents render as, but it is not the model to |
| 262 | /// copy.) |
| 263 | fn indent_level<T: ReadTxn>(txn: &T, e: &XmlElementRef) -> Option<u8> { |
| 264 | let raw = e.get_attribute(txn, "indent")?; |
| 265 | // DIGITS ONLY, then parse wide, then clamp — and each of those |
| 266 | // three is answering a disagreement with the editor rather than |
| 267 | // being careful for its own sake. |
| 268 | // |
| 269 | // This parsed as `u8` for one review cycle, and the doc comment |
| 270 | // above claimed "indent 400 renders at 8". It did not: 400 |
| 271 | // overflows a u8, so the parse failed and the block rendered flush |
| 272 | // left — while `fixtures/indent.mjs` used `Number()` and rendered |
| 273 | // it at 8. The same split existed for " 3", "3.0", "1e1" and "0x3", |
| 274 | // all of which JavaScript accepts and Rust rejected. No safety |
| 275 | // property was ever spent (nothing here emits the byte either way), |
| 276 | // but the claim that a document cannot indent one distance on |
| 277 | // screen and another on paper was false for every one of them. |
| 278 | // |
| 279 | // Parsing as u32 makes "400" a number rather than an error, so it |
| 280 | // clamps like every other too-large value; requiring digits makes |
| 281 | // " 3" and "3.0" fail on BOTH sides, which is what indent.mjs's |
| 282 | // matching strictness now guarantees. |
| 283 | if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) { |
| 284 | return None; |
| 285 | } |
| 286 | // unwrap_or(u32::MAX), not `.ok()?`. A string that passed the |
| 287 | // digits-only check above and still fails to parse can only have |
| 288 | // failed by being too large — so treating it as "as large as |
| 289 | // possible" clamps it, where propagating the error would render it |
| 290 | // flush left. That is the last corner where this and |
| 291 | // fixtures/indent.mjs disagreed: JavaScript's Number() turns a |
| 292 | // twenty-digit run into a float far above the maximum and clamps to |
| 293 | // 8, and now so does this. |
| 294 | let level = raw |
| 295 | .parse::<u32>() |
| 296 | .unwrap_or(u32::MAX) |
| 297 | .min(MAX_INDENT as u32) as u8; |
| 298 | if level == 0 { |
| 299 | None |
| 300 | } else { |
| 301 | Some(level) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | /// The class `fragment_html` puts on an indented block. `None` when the |
| 306 | /// block is not indented, so an un-indented paragraph emits exactly the |
| 307 | /// markup it did before this existed. |
| 308 | fn indent_class<T: ReadTxn>(txn: &T, e: &XmlElementRef) -> Option<String> { |
| 309 | indent_level(txn, e).map(|n| format!("docs-indent-{n}")) |
| 310 | } |
| 311 | |
| 312 | /// The whole `class` attribute for a block, or `None` when it needs |
| 313 | /// none. `extra` is whatever the caller already worked out (the |
| 314 | /// alignment class, for a paragraph); the indent class is added here. |
| 315 | /// |
| 316 | /// One function rather than each call site joining its own, because |
| 317 | /// the two classes have to be separated by exactly one space and a |
| 318 | /// block with only one of them must emit no stray space — the sort of |
| 319 | /// thing that is obviously right in each of two places and wrong in |
| 320 | /// the one where they meet. |
| 321 | fn block_class<T: ReadTxn>( |
| 322 | txn: &T, |
| 323 | e: &XmlElementRef, |
| 324 | extra: Option<&'static str>, |
| 325 | ) -> Option<String> { |
| 326 | match (extra, indent_class(txn, e)) { |
| 327 | (Some(a), Some(i)) => Some(format!("{a} {i}")), |
| 328 | (Some(a), None) => Some(a.to_string()), |
| 329 | (None, Some(i)) => Some(i), |
| 330 | (None, None) => None, |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | /// The class `fragment_html` puts on an aligned paragraph, from the |
| 335 | /// same table. |
| 336 | fn align_class<T: ReadTxn>(txn: &T, e: &XmlElementRef) -> Option<&'static str> { |
| 337 | let value = e.get_attribute(txn, "align")?; |
| 338 | ALIGNMENTS |
| 339 | .iter() |
| 340 | .find(|(name, _)| *name == value) |
| 341 | .map(|(_, class)| *class) |
| 342 | } |
| 343 | |
| 344 | fn text_html<T: ReadTxn>(txn: &T, t: &XmlTextRef, out: &mut String) { |
| 345 | // Diff gives runs with their attributes, which is where marks live. |
| 346 | for chunk in t.diff(txn, yrs::types::text::YChange::identity) { |
| 347 | let mut open = Vec::new(); |
| 348 | if let Some(attrs) = &chunk.attributes { |
| 349 | for (name, o, c) in MARKS { |
| 350 | if attrs.contains_key(*name) { |
| 351 | open.push((*o, *c)); |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | for (o, _) in &open { |
| 356 | out.push_str(o); |
| 357 | } |
| 358 | if let yrs::Out::Any(yrs::Any::String(s)) = &chunk.insert { |
| 359 | escape(s, out); |
| 360 | } |
| 361 | for (_, c) in open.iter().rev() { |
| 362 | out.push_str(c); |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | /// Where a rendering will be read (Docs images spec §4.1): the document's |
| 368 | /// own sqid, and the base an image's address is drawn under — `/d/{sqid}` |
| 369 | /// for a signed-in reader, `/p/{token}` for a link holder. The default |
| 370 | /// view has neither, and draws every image as missing: a rendering with |
| 371 | /// no document to answer for cannot name one of its images. |
| 372 | /// |
| 373 | /// Both halves are checked against their grammars here, whatever the host |
| 374 | /// already checked, because what this module writes into attribute |
| 375 | /// position is `base` itself. |
| 376 | #[derive(Clone, Debug, Default, PartialEq, Eq)] |
| 377 | pub struct View { |
| 378 | sqid: String, |
| 379 | base: String, |
| 380 | } |
| 381 | |
| 382 | /// store.go's sqidAlphabet. |
| 383 | const SQID_ALPHABET: &[u8] = b"23456789abcdefghjkmnpqrstuvwxyz"; |
| 384 | /// An image's public id: exactly this many of `[0-9a-z]` (spec §1 |
| 385 | /// decision 2). Go's `imagePublicID` and the editor's `IMAGE_ID` agree. |
| 386 | pub const IMAGE_ID_LEN: usize = 16; |
| 387 | |
| 388 | fn is_sqid(s: &str) -> bool { |
| 389 | !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| SQID_ALPHABET.contains(&b)) |
| 390 | } |
| 391 | |
| 392 | /// links.go's tokens: base64url, no padding. 16 bytes is 22 characters; |
| 393 | /// the bound leaves room without admitting anything but the alphabet. |
| 394 | fn is_token(s: &str) -> bool { |
| 395 | !s.is_empty() |
| 396 | && s.len() <= 64 |
| 397 | && s.bytes() |
| 398 | .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') |
| 399 | } |
| 400 | |
| 401 | fn is_image_id(s: &str) -> bool { |
| 402 | s.len() == IMAGE_ID_LEN |
| 403 | && s.bytes() |
| 404 | .all(|b| b.is_ascii_digit() || b.is_ascii_lowercase()) |
| 405 | } |
| 406 | |
| 407 | impl View { |
| 408 | /// `"{sqid}\n{base}"`, or the empty string for the default view. Any |
| 409 | /// other shape is `None`, and the host's read refuses. |
| 410 | pub fn parse(raw: &str) -> Option<View> { |
| 411 | if raw.is_empty() { |
| 412 | return Some(View::default()); |
| 413 | } |
| 414 | let (sqid, base) = raw.split_once('\n')?; |
| 415 | if !is_sqid(sqid) { |
| 416 | return None; |
| 417 | } |
| 418 | let ok = match base.strip_prefix("/d/") { |
| 419 | Some(own) => own == sqid, |
| 420 | None => base.strip_prefix("/p/").is_some_and(is_token), |
| 421 | }; |
| 422 | ok.then(|| View { |
| 423 | sqid: sqid.to_string(), |
| 424 | base: base.to_string(), |
| 425 | }) |
| 426 | } |
| 427 | |
| 428 | /// The image id `src` names, when `src` is exactly this document's own |
| 429 | /// address, `/d/{own sqid}/images/{id}`. Everything else — another |
| 430 | /// document's address, the absolute form, `data:`, a remote URL, a |
| 431 | /// trailing path, a look-alike — is `None`, and draws as missing. |
| 432 | fn image_id<'a>(&self, src: &'a str) -> Option<&'a str> { |
| 433 | if self.sqid.is_empty() { |
| 434 | return None; |
| 435 | } |
| 436 | let rest = src.strip_prefix("/d/")?.strip_prefix(self.sqid.as_str())?; |
| 437 | let id = rest.strip_prefix("/images/")?; |
| 438 | is_image_id(id).then_some(id) |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | /// An image's `width` or `height` (spec §1 decision 5): 1 to 5 digits, |
| 443 | /// clamped to 10,000; 0, junk, and a missing value are `None`. y-prosemirror |
| 444 | /// never runs the schema's `validate` on what it reads, so a value can |
| 445 | /// arrive as a number (yrs prints an integral number as its digits) or as |
| 446 | /// anything at all. |
| 447 | fn dimension<T: ReadTxn>(txn: &T, e: &XmlElementRef, name: &str) -> Option<u32> { |
| 448 | let raw = e.get_attribute(txn, name)?; |
| 449 | if raw.is_empty() || raw.len() > 5 || !raw.bytes().all(|b| b.is_ascii_digit()) { |
| 450 | return None; |
| 451 | } |
| 452 | match raw.parse::<u32>().ok()? { |
| 453 | 0 => None, |
| 454 | n => Some(n.min(10_000)), |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | /// An image node's parts, checked: its id (when it is this document's |
| 459 | /// own), its alt text, and its size when both sides are present. |
| 460 | struct ImageParts { |
| 461 | id: Option<String>, |
| 462 | alt: String, |
| 463 | size: Option<(u32, u32)>, |
| 464 | } |
| 465 | |
| 466 | fn image_parts<T: ReadTxn>(txn: &T, e: &XmlElementRef, view: &View) -> ImageParts { |
| 467 | let src = e.get_attribute(txn, "src").unwrap_or_default(); |
| 468 | let id = view.image_id(&src).map(str::to_string); |
| 469 | let alt = e.get_attribute(txn, "alt").unwrap_or_default(); |
| 470 | let size = match (dimension(txn, e, "width"), dimension(txn, e, "height")) { |
| 471 | (Some(w), Some(h)) => Some((w, h)), |
| 472 | _ => None, |
| 473 | }; |
| 474 | ImageParts { id, alt, size } |
| 475 | } |
| 476 | |
| 477 | /// An image in the read view. This is the one place a byte from a |
| 478 | /// document reaches attribute position, and only these do: the `id`, |
| 479 | /// after it has matched the grammar exactly (so it is 16 of `[0-9a-z]` |
| 480 | /// and needs no escaping), and the alt text, escaped. `base` is the |
| 481 | /// view's, checked by `View::parse`; the sizes are numbers this function |
| 482 | /// formats. Anything that is not this document's own image is a fixed |
| 483 | /// box holding its alt text: no request, no URL from the document. |
| 484 | fn image_html<T: ReadTxn>(txn: &T, e: &XmlElementRef, view: &View, out: &mut String) { |
| 485 | let parts = image_parts(txn, e, view); |
| 486 | match parts.id { |
| 487 | Some(id) => { |
| 488 | let _ = write!(out, "<img src=\"{}/images/{}\" alt=\"", view.base, id); |
| 489 | escape(&parts.alt, out); |
| 490 | out.push('"'); |
| 491 | if let Some((w, h)) = parts.size { |
| 492 | let _ = write!(out, " width=\"{w}\" height=\"{h}\""); |
| 493 | } |
| 494 | out.push_str(" loading=\"lazy\" decoding=\"async\">"); |
| 495 | } |
| 496 | None => { |
| 497 | out.push_str("<span class=\"docs-image-missing\">"); |
| 498 | escape(&parts.alt, out); |
| 499 | out.push_str("</span>"); |
| 500 | } |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | fn node_html<T: ReadTxn>(txn: &T, node: &XmlOut, view: &View, out: &mut String) { |
| 505 | match node { |
| 506 | XmlOut::Text(t) => text_html(txn, t, out), |
| 507 | XmlOut::Element(e) => { |
| 508 | let name = e.tag().to_string(); |
| 509 | if name == "image" { |
| 510 | image_html(txn, e, view, out); |
| 511 | // An image has no children; a client posting raw Yjs |
| 512 | // bytes could give it some, and they render after it |
| 513 | // rather than vanishing (the module comment). |
| 514 | for child in e.children(txn) { |
| 515 | node_html(txn, &child, view, out); |
| 516 | } |
| 517 | return; |
| 518 | } |
| 519 | let (open, close) = match name.as_str() { |
| 520 | // A paragraph can be aligned, indented, both, or |
| 521 | // neither. Both classes are literals this binary builds |
| 522 | // — one from the ALIGNMENTS table, one from a u8 that |
| 523 | // has already been clamped to 1..=8 — so the joined |
| 524 | // value can only be one of a small closed set of |
| 525 | // strings, and nothing from the document reaches |
| 526 | // attribute position. |
| 527 | "paragraph" => match block_class(txn, e, align_class(txn, e)) { |
| 528 | Some(class) => (format!("<p class=\"{class}\">"), "</p>".to_string()), |
| 529 | None => ("<p>".to_string(), "</p>".to_string()), |
| 530 | }, |
| 531 | "heading" => { |
| 532 | // Clamp: a corrupt or hostile level must not emit |
| 533 | // <h0> or <h99>. |
| 534 | let level = e |
| 535 | .get_attribute(txn, "level") |
| 536 | .and_then(|v| v.parse::<u8>().ok()) |
| 537 | .unwrap_or(1) |
| 538 | .clamp(1, 6); |
| 539 | // Headings indent too — every word processor lets |
| 540 | // them — but they do not align: alignment is on the |
| 541 | // paragraph spec alone, here and in the editor's |
| 542 | // schema, and adding it is a change to both. |
| 543 | match block_class(txn, e, None) { |
| 544 | Some(class) => ( |
| 545 | format!("<h{level} class=\"{class}\">"), |
| 546 | format!("</h{level}>"), |
| 547 | ), |
| 548 | None => (format!("<h{level}>"), format!("</h{level}>")), |
| 549 | } |
| 550 | } |
| 551 | "bullet_list" => ("<ul>".to_string(), "</ul>".to_string()), |
| 552 | "ordered_list" => ("<ol>".to_string(), "</ol>".to_string()), |
| 553 | "list_item" => ("<li>".to_string(), "</li>".to_string()), |
| 554 | "blockquote" => ("<blockquote>".to_string(), "</blockquote>".to_string()), |
| 555 | // prosemirror-schema-basic's code block, which a paste of |
| 556 | // <pre> makes: the same <pre><code> the editor draws, so |
| 557 | // a reader sees it in the code face before and after the |
| 558 | // editor mounts (branch review 5), not in the body face |
| 559 | // until then. |
| 560 | "code_block" => ("<pre><code>".to_string(), "</code></pre>".to_string()), |
| 561 | // Shift+Enter's node (prosemirror-schema-basic's own |
| 562 | // `hard_break`; the tag is the node's name because |
| 563 | // y-prosemirror builds every non-text node as an |
| 564 | // XmlElement named after its type). `<br>` is void, so |
| 565 | // it has an opening and no closing markup — the loop |
| 566 | // below still walks its children, which a real editor |
| 567 | // never gives it and a client posting raw Yjs bytes |
| 568 | // could, and they render after the break rather than |
| 569 | // vanishing, per the module comment. |
| 570 | "hard_break" => ("<br>".to_string(), String::new()), |
| 571 | // Unknown: render children with no wrapper. See the |
| 572 | // module comment — silence here is data loss. |
| 573 | _ => (String::new(), String::new()), |
| 574 | }; |
| 575 | out.push_str(&open); |
| 576 | for child in e.children(txn) { |
| 577 | node_html(txn, &child, view, out); |
| 578 | } |
| 579 | out.push_str(&close); |
| 580 | } |
| 581 | XmlOut::Fragment(f) => { |
| 582 | for child in f.children(txn) { |
| 583 | node_html(txn, &child, view, out); |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | /// The document rendered as HTML, escaped and ready to place inside the |
| 590 | /// page container, with every image drawn as missing (the default view). |
| 591 | pub fn fragment_html(doc: &Doc) -> String { |
| 592 | fragment_html_in(doc, &View::default()) |
| 593 | } |
| 594 | |
| 595 | /// The document rendered as HTML for one view (Docs images spec §4.1). |
| 596 | pub fn fragment_html_in(doc: &Doc, view: &View) -> String { |
| 597 | let f = root(doc); |
| 598 | let txn = doc.transact(); |
| 599 | let mut out = String::new(); |
| 600 | for child in f.children(&txn) { |
| 601 | node_html(&txn, &child, view, &mut out); |
| 602 | } |
| 603 | out |
| 604 | } |
| 605 | |
| 606 | fn node_text<T: ReadTxn>(txn: &T, node: &XmlOut, blocks: &mut Vec<String>, cur: &mut String) { |
| 607 | match node { |
| 608 | XmlOut::Text(t) => cur.push_str(&t.get_string(txn)), |
| 609 | XmlOut::Element(e) => { |
| 610 | let name = e.tag().to_string(); |
| 611 | // A hard break ends the current line and the block carries |
| 612 | // on: one newline, where the block boundary below is a |
| 613 | // blank line. It is deliberately NOT in the is_block set — |
| 614 | // treating it as a block would turn one paragraph into two |
| 615 | // wherever a person pressed Shift+Enter. |
| 616 | if name == "hard_break" { |
| 617 | cur.push('\n'); |
| 618 | return; |
| 619 | } |
| 620 | let is_block = matches!( |
| 621 | name.as_str(), |
| 622 | "paragraph" | "heading" | "list_item" | "blockquote" |
| 623 | ); |
| 624 | // A text sibling that precedes this block with no block of |
| 625 | // its own (unreachable through ProseMirror's own schema, |
| 626 | // but reachable the moment a client posts arbitrary Yjs |
| 627 | // bytes — see fragment_text's own doc comment) must not |
| 628 | // run straight into this block's text with no separator: |
| 629 | // flush whatever is already pending as its own segment |
| 630 | // before this block contributes anything. |
| 631 | if is_block && !cur.is_empty() { |
| 632 | blocks.push(std::mem::take(cur)); |
| 633 | } |
| 634 | let mut had_children = false; |
| 635 | for child in e.children(txn) { |
| 636 | had_children = true; |
| 637 | node_text(txn, &child, blocks, cur); |
| 638 | } |
| 639 | if is_block { |
| 640 | if !cur.is_empty() { |
| 641 | blocks.push(std::mem::take(cur)); |
| 642 | } else if !had_children { |
| 643 | // A structurally empty block (`<p></p>`) still |
| 644 | // renders as a blank paragraph in fragment_html; |
| 645 | // mirror that here rather than silently dropping |
| 646 | // it, which would make the two renderers disagree |
| 647 | // about how many paragraphs a document has. A |
| 648 | // block whose children already flushed their own |
| 649 | // text (had_children but cur now empty, e.g. a |
| 650 | // list_item wrapping a paragraph) must not get a |
| 651 | // second, spurious empty entry — that is exactly |
| 652 | // what had_children distinguishes. |
| 653 | blocks.push(String::new()); |
| 654 | } |
| 655 | } |
| 656 | } |
| 657 | XmlOut::Fragment(f) => { |
| 658 | for child in f.children(txn) { |
| 659 | node_text(txn, &child, blocks, cur); |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | /// The document as plain text, one blank line between blocks. Used by |
| 666 | /// the list's preview and by anything that wants the words without the |
| 667 | /// markup. |
| 668 | /// |
| 669 | /// Neither ProseMirror's own schema nor its `y-prosemirror` binding can |
| 670 | /// produce a fragment with a bare text node preceding a block, or a |
| 671 | /// structurally empty block — so, until this task, node_text's two |
| 672 | /// edge cases here were unreachable in practice: a text sibling ahead |
| 673 | /// of a block used to run straight into that block's own text with no |
| 674 | /// separator (`"orphanactual"` for `[text("orphan"), paragraph(text("actual"))]`), |
| 675 | /// and an empty `<p></p>` that fragment_html preserves used to vanish |
| 676 | /// here instead of leaving a blank line. `POST /d/{sqid}/updates` |
| 677 | /// (Task 5) is what makes them reachable: it accepts arbitrary |
| 678 | /// client-supplied Yjs bytes, not only what a real ProseMirror editor |
| 679 | /// would ever emit. Both are fixed in node_text above and covered by |
| 680 | /// core/tests/fragment.rs. |
| 681 | pub fn fragment_text(doc: &Doc) -> String { |
| 682 | let f = root(doc); |
| 683 | let txn = doc.transact(); |
| 684 | let mut blocks = Vec::new(); |
| 685 | let mut cur = String::new(); |
| 686 | for child in f.children(&txn) { |
| 687 | node_text(&txn, &child, &mut blocks, &mut cur); |
| 688 | } |
| 689 | if !cur.is_empty() { |
| 690 | blocks.push(cur); |
| 691 | } |
| 692 | blocks.join("\n\n") |
| 693 | } |
| 694 | |
| 695 | // --- the structured renderer --- |
| 696 | // |
| 697 | // `fragment_html` above answers "what does this document look like"; |
| 698 | // `fragment_json` below answers "what is this document made of". The |
| 699 | // export paths (`internal/export`, `internal/pdf`) need the second |
| 700 | // question answered: where a list ends, which run is bold, which |
| 701 | // paragraph is a heading. Re-deriving that in Go by parsing the markup |
| 702 | // this file emits would mean a parser to keep honest against an |
| 703 | // emitter, and Go's standard library has no HTML parser to do it with. |
| 704 | // |
| 705 | // The shape is ProseMirror's own JSON — `{"type":..,"attrs":..,"content":[..]}`, |
| 706 | // text as `{"type":"text","text":..,"marks":[..]}` — because that is the |
| 707 | // vocabulary the editor on the other side of the wire already speaks, |
| 708 | // so a Go consumer and a future JS one describe the same document the |
| 709 | // same way. Written by hand rather than through serde: the crate has |
| 710 | // no serialisation dependency outside dev-dependencies, and this is |
| 711 | // one escape function and three walks. |
| 712 | |
| 713 | /// JSON string escaping, per RFC 8259: the two mandatory escapes, the |
| 714 | /// three shorthands, and `\u00XX` for everything else below U+0020. |
| 715 | /// Everything at or above U+0020 other than `"` and `\` goes through |
| 716 | /// as-is — the output is UTF-8 and JSON says that is legal. |
| 717 | fn escape_json(s: &str, out: &mut String) { |
| 718 | for c in s.chars() { |
| 719 | match c { |
| 720 | '"' => out.push_str("\\\""), |
| 721 | '\\' => out.push_str("\\\\"), |
| 722 | '\n' => out.push_str("\\n"), |
| 723 | '\r' => out.push_str("\\r"), |
| 724 | '\t' => out.push_str("\\t"), |
| 725 | c if (c as u32) < 0x20 => { |
| 726 | let _ = write!(out, "\\u{:04x}", c as u32); |
| 727 | } |
| 728 | c => out.push(c), |
| 729 | } |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | /// The mark names on one text run: the ones this build knows in `MARKS` |
| 734 | /// order, then any it does not, sorted. |
| 735 | /// |
| 736 | /// The sort is not cosmetic. `Attrs` is a `HashMap`, so iterating it |
| 737 | /// yields an order that varies between runs of the same binary on the |
| 738 | /// same document — an unsorted tail would make this renderer's output |
| 739 | /// nondeterministic, which would make every golden-file test on the Go |
| 740 | /// side flake rather than fail. Unknown marks are carried through |
| 741 | /// rather than dropped for the same reason unknown *nodes* render their |
| 742 | /// children (see the module comment): a consumer that ignores a mark it |
| 743 | /// does not recognise still has the text, and one that grows to |
| 744 | /// understand it needs it to have been there. |
| 745 | /// WHOEVER ADDS THE FIRST VALUED MARK: THIS FUNCTION IS WHERE THE |
| 746 | /// ALLOWLIST GOES, AND IT MUST NOT ASSUME ONLY THAT MARK HAS A VALUE. |
| 747 | /// |
| 748 | /// This returns NAMES. Every mark's value — including an unknown mark's |
| 749 | /// — is dropped here and reaches no consumer, which is why an unknown |
| 750 | /// mark carried through by name is safe today: `fragment_html` finds no |
| 751 | /// MARKS row and emits no wrapper, and `text_json` writes the name |
| 752 | /// through `escape_json`. |
| 753 | /// |
| 754 | /// A valued mark changes that. The moment one value is allowed past |
| 755 | /// this point, the shape of the question becomes "which marks may carry |
| 756 | /// a value, and what may that value be" — and the tempting answer, that |
| 757 | /// `link` is the one with an `href`, is wrong on arrival. This function |
| 758 | /// collects marks it has never heard of, straight off the wire, and |
| 759 | /// `POST /d/{sqid}/updates` accepts bytes that never went through |
| 760 | /// ProseMirror's schema. So an unknown mark can carry an arbitrary |
| 761 | /// value too, and an allowlist written around the known one would let |
| 762 | /// it past. |
| 763 | /// |
| 764 | /// It is also the right place, and that is the other half of the note: |
| 765 | /// this is the single point the HTML renderer and every JSON consumer |
| 766 | /// agree on what marks a run carries, so a check here cannot be |
| 767 | /// re-implemented differently by `markdown.go` and `pdf.go` the way one |
| 768 | /// in `node_html` would have to be. Plan 7's D1 names it. |
| 769 | /// |
| 770 | /// (Found by the session that owns Plan 7, reading this file after the |
| 771 | /// point-ladder work restructured around it — recorded here rather than |
| 772 | /// only in that plan, because the plan may land long after someone else |
| 773 | /// touches this function.) |
| 774 | fn mark_names(attrs: &yrs::types::Attrs) -> Vec<String> { |
| 775 | let mut names: Vec<String> = MARKS |
| 776 | .iter() |
| 777 | .filter(|(name, _, _)| attrs.contains_key(*name)) |
| 778 | .map(|(name, _, _)| (*name).to_string()) |
| 779 | .collect(); |
| 780 | let mut unknown: Vec<String> = attrs |
| 781 | .keys() |
| 782 | .map(|k| k.to_string()) |
| 783 | .filter(|k| !MARKS.iter().any(|(name, _, _)| *name == k.as_str())) |
| 784 | .collect(); |
| 785 | unknown.sort(); |
| 786 | names.append(&mut unknown); |
| 787 | names |
| 788 | } |
| 789 | |
| 790 | fn text_json<T: ReadTxn>(txn: &T, t: &XmlTextRef, out: &mut String, first: &mut bool) { |
| 791 | for chunk in t.diff(txn, yrs::types::text::YChange::identity) { |
| 792 | let yrs::Out::Any(yrs::Any::String(s)) = &chunk.insert else { |
| 793 | // A non-string insert is an embed. `fragment_html` renders |
| 794 | // nothing for one today, and inventing a JSON shape for |
| 795 | // something with no renderer would be guessing at a schema |
| 796 | // rather than reporting one. |
| 797 | continue; |
| 798 | }; |
| 799 | if s.is_empty() { |
| 800 | continue; |
| 801 | } |
| 802 | if !*first { |
| 803 | out.push(','); |
| 804 | } |
| 805 | *first = false; |
| 806 | out.push_str("{\"type\":\"text\",\"text\":\""); |
| 807 | escape_json(s, out); |
| 808 | out.push('"'); |
| 809 | if let Some(attrs) = &chunk.attributes { |
| 810 | let names = mark_names(attrs); |
| 811 | if !names.is_empty() { |
| 812 | out.push_str(",\"marks\":["); |
| 813 | for (i, name) in names.iter().enumerate() { |
| 814 | if i > 0 { |
| 815 | out.push(','); |
| 816 | } |
| 817 | out.push_str("{\"type\":\""); |
| 818 | escape_json(name, out); |
| 819 | out.push_str("\"}"); |
| 820 | } |
| 821 | out.push(']'); |
| 822 | } |
| 823 | } |
| 824 | out.push('}'); |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | // Unlike the two renderers above, this one needs no case of its own |
| 829 | // for `hard_break`: an element with no children already comes out as |
| 830 | // `{"type":"hard_break","content":[]}`, which names the node and is |
| 831 | // what internal/export reads. The empty `content` is how this renderer |
| 832 | // spells every childless element (an empty paragraph included), so a |
| 833 | // leaf is not a special shape here. |
| 834 | /// An image's JSON (Docs images spec §4.2), after `{"type":"image"`. The |
| 835 | /// rule above holds — no unchecked document byte reaches JSON: the id has |
| 836 | /// matched its grammar, the sizes are numbers, and the alt text goes |
| 837 | /// through `escape_json`. Anything not this document's own image is the |
| 838 | /// missing form, so a 12 MB `data:` source or a remote URL never reaches |
| 839 | /// an export, a preview, an import read or an agent. Children are not |
| 840 | /// written: an image has none, and the exporters draw it as a unit. |
| 841 | fn image_json<T: ReadTxn>(txn: &T, e: &XmlElementRef, view: &View, out: &mut String) { |
| 842 | let parts = image_parts(txn, e, view); |
| 843 | out.push_str(",\"attrs\":{"); |
| 844 | match &parts.id { |
| 845 | Some(id) => { |
| 846 | let _ = write!(out, "\"id\":\"{id}\""); |
| 847 | } |
| 848 | None => out.push_str("\"missing\":true"), |
| 849 | } |
| 850 | out.push_str(",\"alt\":\""); |
| 851 | escape_json(&parts.alt, out); |
| 852 | out.push('"'); |
| 853 | if let (Some(_), Some((w, h))) = (&parts.id, parts.size) { |
| 854 | let _ = write!(out, ",\"width\":{w},\"height\":{h}"); |
| 855 | } |
| 856 | out.push_str("},\"content\":[]}"); |
| 857 | } |
| 858 | |
| 859 | fn node_json<T: ReadTxn>(txn: &T, node: &XmlOut, view: &View, out: &mut String, first: &mut bool) { |
| 860 | match node { |
| 861 | XmlOut::Text(t) => text_json(txn, t, out, first), |
| 862 | XmlOut::Element(e) => { |
| 863 | let name = e.tag().to_string(); |
| 864 | if !*first { |
| 865 | out.push(','); |
| 866 | } |
| 867 | *first = false; |
| 868 | out.push_str("{\"type\":\""); |
| 869 | escape_json(&name, out); |
| 870 | out.push('"'); |
| 871 | if name == "image" { |
| 872 | image_json(txn, e, view, out); |
| 873 | return; |
| 874 | } |
| 875 | // Attributes are collected and written ONCE, as a single |
| 876 | // object. |
| 877 | // |
| 878 | // This used to be two independent `if name == …` arms, each |
| 879 | // writing a complete `,"attrs":{…}`. That was correct only |
| 880 | // for as long as no node could carry two attributes: a |
| 881 | // heading has a level and a paragraph has an alignment, and |
| 882 | // never both. Indent broke that — a paragraph can be |
| 883 | // centred AND indented, and a heading can be indented too — |
| 884 | // and the old shape would have emitted `"attrs"` twice in |
| 885 | // one object. Every JSON parser accepts that and they do not |
| 886 | // agree on which wins, so it would not have failed loudly; |
| 887 | // internal/export would have quietly lost one of the two. |
| 888 | // |
| 889 | // Each value below is a number or a literal from a closed |
| 890 | // table in this binary, never a byte from the document, so |
| 891 | // nothing here needs escaping — the same property |
| 892 | // `fragment_html` depends on, held for the same reason. |
| 893 | let mut attrs: Vec<String> = Vec::new(); |
| 894 | if name == "heading" { |
| 895 | // Clamped exactly as `node_html` clamps it, and for the |
| 896 | // same reason: a corrupt or hostile level must not reach |
| 897 | // a consumer as `h0` or `h99`. Both renderers clamping |
| 898 | // independently is deliberate — a document must not |
| 899 | // paginate as one level on screen and export as another. |
| 900 | let level = e |
| 901 | .get_attribute(txn, "level") |
| 902 | .and_then(|v| v.parse::<u8>().ok()) |
| 903 | .unwrap_or(1) |
| 904 | .clamp(1, 6); |
| 905 | attrs.push(format!("\"level\":{level}")); |
| 906 | } |
| 907 | if name == "paragraph" { |
| 908 | // Same allowlist, same drop, and — like the heading |
| 909 | // clamp above — arrived at independently in both |
| 910 | // renderers, so a paragraph cannot read as centred on |
| 911 | // screen and export flush left. `align` is the |
| 912 | // allowlist's own key, a literal in this binary, so |
| 913 | // nothing here needs escaping and nothing from the |
| 914 | // document can appear. |
| 915 | if let Some(align) = alignment(txn, e) { |
| 916 | attrs.push(format!("\"align\":\"{align}\"")); |
| 917 | } |
| 918 | } |
| 919 | if name == "paragraph" || name == "heading" { |
| 920 | if let Some(indent) = indent_level(txn, e) { |
| 921 | attrs.push(format!("\"indent\":{indent}")); |
| 922 | } |
| 923 | } |
| 924 | if !attrs.is_empty() { |
| 925 | let _ = write!(out, ",\"attrs\":{{{}}}", attrs.join(",")); |
| 926 | } |
| 927 | out.push_str(",\"content\":["); |
| 928 | let mut inner = true; |
| 929 | for child in e.children(txn) { |
| 930 | node_json(txn, &child, view, out, &mut inner); |
| 931 | } |
| 932 | out.push_str("]}"); |
| 933 | } |
| 934 | XmlOut::Fragment(f) => { |
| 935 | // Flattened into the parent's content, exactly as |
| 936 | // `node_html` renders a nested fragment's children with no |
| 937 | // wrapper of its own. |
| 938 | for child in f.children(txn) { |
| 939 | node_json(txn, &child, view, out, first); |
| 940 | } |
| 941 | } |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | /// The document as ProseMirror-shaped JSON: `{"type":"doc","content":[..]}`. |
| 946 | /// |
| 947 | /// Deterministic for a given document state — see `mark_names` for the |
| 948 | /// one place that took work — so a Go consumer's golden files are |
| 949 | /// stable. |
| 950 | pub fn fragment_json(doc: &Doc) -> String { |
| 951 | fragment_json_in(doc, &View::default()) |
| 952 | } |
| 953 | |
| 954 | /// `fragment_json` for one view (Docs images spec §4.2): an image is its |
| 955 | /// checked parts or the missing form, never its raw `src`. |
| 956 | pub fn fragment_json_in(doc: &Doc, view: &View) -> String { |
| 957 | let f = root(doc); |
| 958 | let txn = doc.transact(); |
| 959 | let mut out = String::from("{\"type\":\"doc\",\"content\":["); |
| 960 | let mut first = true; |
| 961 | for child in f.children(&txn) { |
| 962 | node_json(&txn, &child, view, &mut out, &mut first); |
| 963 | } |
| 964 | out.push_str("]}"); |
| 965 | out |
| 966 | } |
| 967 | |