//! The editor's markup for a note, the same as ProseMirror's `toDOM` for our schema. //! The server renders it to a string so the note shows before the editor loads, and //! the editor builds its DOM from the same specs. use loro::{LoroDoc, cursor::PosType}; use crate::flat::{self, Attrs, Kind, Wrap}; use crate::marks::Marks; use crate::write::{Block, Inline}; pub type HtmlAttrs = Vec<(&'static str, String)>; /// How a node renders: its element, attributes, and for `pre` the inner `code` /// element that holds the content. pub struct Spec { pub tag: &'static str, pub attrs: HtmlAttrs, pub inner: Option<&'static str>, } impl Spec { fn new(tag: &'static str) -> Self { Spec { tag, attrs: Vec::new(), inner: None } } } /// The class PM puts on the `
` that keeps an empty textblock (or a code block /// ending in a newline) one line tall. pub const TRAILING_BREAK: &str = "ProseMirror-trailingBreak"; /// The element of a leaf block. pub fn leaf_spec(kind: Kind, lang: Option<&str>) -> Spec { match kind { Kind::Para => Spec::new("p"), Kind::Heading(n) => Spec::new(["h1", "h2", "h3", "h4", "h5", "h6"][n.clamp(1, 6) as usize - 1]), Kind::Rule => Spec::new("hr"), Kind::Code => { let mut s = Spec::new("pre"); s.attrs.push(("spellcheck", "false".into())); if let Some(lang) = lang.filter(|l| !l.is_empty()) { s.attrs.push(("data-language", lang.to_owned())); } s.inner = Some("code"); s } } } pub fn block_spec(attrs: &Attrs) -> Spec { leaf_spec(attrs.kind, attrs.lang.as_deref()) } /// The element of a container: a quote, or a list with its first number. pub fn wrap_spec(wrap: Wrap, start: i64) -> Spec { match wrap { Wrap::Quote => Spec::new("blockquote"), Wrap::Bullet => Spec::new("ul"), Wrap::Ordered => { let mut s = Spec::new("ol"); if start != 1 { s.attrs.push(("start", start.to_string())); } s } } } pub fn item_spec() -> Spec { Spec::new("li") } /// What an image node shows as, by the file extension of its source. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Embed { Image, Audio, Video, } /// The embed of an image source, from its extension: `?query` and `#fragment` are /// ignored. A `data:image/` URI is an image. `None` for an unknown or missing extension. pub fn embed_of(src: &str) -> Option { let src = src.trim(); if src.get(..11).is_some_and(|p| p.eq_ignore_ascii_case("data:image/")) { return Some(Embed::Image); } let path = src.split(['?', '#']).next().unwrap_or(""); let name = path.rsplit('/').next().unwrap_or(""); let (_, ext) = name.rsplit_once('.')?; match ext.to_ascii_lowercase().as_str() { "mp3" | "m4a" | "wav" | "flac" | "aac" | "ogg" | "oga" | "opus" | "weba" => Some(Embed::Audio), "mp4" | "m4v" | "webm" | "mov" | "ogv" => Some(Embed::Video), "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "bmp" | "svg" => Some(Embed::Image), _ => None, } } pub fn image_spec(src: &str, alt: &str, title: Option<&str>) -> Spec { let media = match embed_of(src) { Some(Embed::Audio) => Some("audio"), Some(Embed::Video) => Some("video"), _ => None, }; let mut s = Spec::new(media.unwrap_or("img")); s.attrs.push(("src", src.to_owned())); match media { Some(_) => { s.attrs.push(("controls", String::new())); s.attrs.push(("preload", "metadata".to_owned())); s.attrs.push(("aria-label", alt.to_owned())); s.attrs.push(("class", "note-media".to_owned())); } None => s.attrs.push(("alt", alt.to_owned())), } if let Some(t) = title { s.attrs.push(("title", t.to_owned())); } s } pub fn is_void(tag: &str) -> bool { matches!(tag, "hr" | "br" | "img") } /// Mark wrappers of a run, outermost first (schema order: link, em, strong, code). pub fn mark_specs(m: &Marks) -> Vec { let mut out = Vec::new(); if let Some((href, title)) = &m.link { let mut s = Spec::new("a"); s.attrs.push(("href", href.clone())); if let Some(t) = title { s.attrs.push(("title", t.clone())); } out.push(s); } if m.em { out.push(Spec::new("em")); } if m.strong { out.push(Spec::new("strong")); } if m.code { out.push(Spec::new("code")); } out } /// The top of the note as the editor shows it before it starts: at most `blocks` /// blocks and about `chars` characters of text, in one page element. Reads only the /// head of the body. pub fn preview_html(doc: &LoroDoc, blocks: usize, chars: usize) -> String { let text = flat::body(doc); let n = text.len_unicode().min(chars + blocks + 1); let delta = text.slice_delta(0, n, PosType::Unicode).unwrap_or_default(); let mut flat = flat::read_delta(delta); flat.truncate(blocks); let mut out = String::from("
"); let mut budget = chars; blocks_html(&flat::nest(&flat), &mut out, &mut budget); out.push_str("
"); out } /// Blocks as the editor's markup, with at most `budget` characters of text. pub fn blocks_html(blocks: &[Block], out: &mut String, budget: &mut usize) { for b in blocks { if *budget == 0 { return; } block_html(b, out, budget); } } fn block_html(b: &Block, out: &mut String, budget: &mut usize) { let (spec, inl): (Spec, &[Inline]) = match b { Block::Paragraph(inl) => (leaf_spec(Kind::Para, None), inl), Block::Heading(n, inl) => (leaf_spec(Kind::Heading((*n).clamp(1, 6) as u8), None), inl), Block::Rule => { open(&leaf_spec(Kind::Rule, None), out); return; } Block::Code { lang, text } => { let spec = leaf_spec(Kind::Code, lang.as_deref()); open(&spec, out); out.push_str(""); let s = cut(text, budget); escape(s, out); if s.is_empty() || s.ends_with('\n') { trailing_break(out); } out.push_str(""); return; } Block::Quote(inner) => { open(&wrap_spec(Wrap::Quote, 1), out); blocks_html(inner, out, budget); close("blockquote", out); return; } Block::List { ordered, start, items } => { let spec = wrap_spec(if *ordered { Wrap::Ordered } else { Wrap::Bullet }, *start); open(&spec, out); for item in items { out.push_str("
  • "); blocks_html(item, out, budget); out.push_str("
  • "); } close(spec.tag, out); return; } }; open(&spec, out); inline_html(inl, out, budget); close(spec.tag, out); } /// A textblock's content. An empty one, or one ending in a break, gets a trailing /// `
    ` to show its last line. pub fn inline_html(inl: &[Inline], out: &mut String, budget: &mut usize) { let mut last_break = true; for i in inl { match i { Inline::Text(s, m) => { let s = cut(s, budget); if s.is_empty() { continue; } let wraps = mark_specs(m); for w in &wraps { open(w, out); } escape(s, out); for w in wraps.iter().rev() { close(w.tag, out); } last_break = false; } Inline::HardBreak => { out.push_str("
    "); last_break = true; } Inline::Image { src, alt, title } => { let spec = image_spec(src, alt, title.as_deref()); open(&spec, out); if !is_void(spec.tag) { close(spec.tag, out); } last_break = false; } } } if last_break { trailing_break(out); } } fn trailing_break(out: &mut String) { out.push_str("
    "); } /// The head of `s` that fits the budget, which it takes from. fn cut<'a>(s: &'a str, budget: &mut usize) -> &'a str { let s = match s.char_indices().nth(*budget) { Some((at, _)) => &s[..at], None => s, }; *budget -= s.chars().count().min(*budget); s } fn open(spec: &Spec, out: &mut String) { out.push('<'); out.push_str(spec.tag); for (k, v) in &spec.attrs { out.push(' '); out.push_str(k); out.push_str("=\""); escape(v, out); out.push('"'); } out.push('>'); } fn close(tag: &str, out: &mut String) { out.push_str("'); } pub fn escape(s: &str, out: &mut String) { for c in s.chars() { match c { '&' => out.push_str("&"), '<' => out.push_str("<"), '>' => out.push_str(">"), '"' => out.push_str("""), c => out.push(c), } } }