forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

render.rs302 lines, 9.2 KiBHistoryRawDownload
1//! The editor's markup for a note, the same as ProseMirror's `toDOM` for our schema.
2//! The server renders it to a string so the note shows before the editor loads, and
3//! the editor builds its DOM from the same specs.
4
5use loro::{LoroDoc, cursor::PosType};
6
7use crate::flat::{self, Attrs, Kind, Wrap};
8use crate::marks::Marks;
9use crate::write::{Block, Inline};
10
11pub type HtmlAttrs = Vec<(&'static str, String)>;
12
13/// How a node renders: its element, attributes, and for `pre` the inner `code`
14/// element that holds the content.
15pub struct Spec {
16 pub tag: &'static str,
17 pub attrs: HtmlAttrs,
18 pub inner: Option<&'static str>,
19}
20
21impl Spec {
22 fn new(tag: &'static str) -> Self {
23 Spec { tag, attrs: Vec::new(), inner: None }
24 }
25}
26
27/// The class PM puts on the `<br>` that keeps an empty textblock (or a code block
28/// ending in a newline) one line tall.
29pub const TRAILING_BREAK: &str = "ProseMirror-trailingBreak";
30
31/// The element of a leaf block.
32pub fn leaf_spec(kind: Kind, lang: Option<&str>) -> Spec {
33 match kind {
34 Kind::Para => Spec::new("p"),
35 Kind::Heading(n) => Spec::new(["h1", "h2", "h3", "h4", "h5", "h6"][n.clamp(1, 6) as usize - 1]),
36 Kind::Rule => Spec::new("hr"),
37 Kind::Code => {
38 let mut s = Spec::new("pre");
39 s.attrs.push(("spellcheck", "false".into()));
40 if let Some(lang) = lang.filter(|l| !l.is_empty()) {
41 s.attrs.push(("data-language", lang.to_owned()));
42 }
43 s.inner = Some("code");
44 s
45 }
46 }
47}
48
49pub fn block_spec(attrs: &Attrs) -> Spec {
50 leaf_spec(attrs.kind, attrs.lang.as_deref())
51}
52
53/// The element of a container: a quote, or a list with its first number.
54pub fn wrap_spec(wrap: Wrap, start: i64) -> Spec {
55 match wrap {
56 Wrap::Quote => Spec::new("blockquote"),
57 Wrap::Bullet => Spec::new("ul"),
58 Wrap::Ordered => {
59 let mut s = Spec::new("ol");
60 if start != 1 {
61 s.attrs.push(("start", start.to_string()));
62 }
63 s
64 }
65 }
66}
67
68pub fn item_spec() -> Spec {
69 Spec::new("li")
70}
71
72/// What an image node shows as, by the file extension of its source.
73#[derive(Clone, Copy, PartialEq, Eq, Debug)]
74pub enum Embed {
75 Image,
76 Audio,
77 Video,
78}
79
80/// The embed of an image source, from its extension: `?query` and `#fragment` are
81/// ignored. A `data:image/` URI is an image. `None` for an unknown or missing extension.
82pub fn embed_of(src: &str) -> Option<Embed> {
83 let src = src.trim();
84 if src.get(..11).is_some_and(|p| p.eq_ignore_ascii_case("data:image/")) {
85 return Some(Embed::Image);
86 }
87 let path = src.split(['?', '#']).next().unwrap_or("");
88 let name = path.rsplit('/').next().unwrap_or("");
89 let (_, ext) = name.rsplit_once('.')?;
90 match ext.to_ascii_lowercase().as_str() {
91 "mp3" | "m4a" | "wav" | "flac" | "aac" | "ogg" | "oga" | "opus" | "weba" => Some(Embed::Audio),
92 "mp4" | "m4v" | "webm" | "mov" | "ogv" => Some(Embed::Video),
93 "png" | "jpg" | "jpeg" | "gif" | "webp" | "avif" | "bmp" | "svg" => Some(Embed::Image),
94 _ => None,
95 }
96}
97
98pub fn image_spec(src: &str, alt: &str, title: Option<&str>) -> Spec {
99 let media = match embed_of(src) {
100 Some(Embed::Audio) => Some("audio"),
101 Some(Embed::Video) => Some("video"),
102 _ => None,
103 };
104 let mut s = Spec::new(media.unwrap_or("img"));
105 s.attrs.push(("src", src.to_owned()));
106 match media {
107 Some(_) => {
108 s.attrs.push(("controls", String::new()));
109 s.attrs.push(("preload", "metadata".to_owned()));
110 s.attrs.push(("aria-label", alt.to_owned()));
111 s.attrs.push(("class", "note-media".to_owned()));
112 }
113 None => s.attrs.push(("alt", alt.to_owned())),
114 }
115 if let Some(t) = title {
116 s.attrs.push(("title", t.to_owned()));
117 }
118 s
119}
120
121pub fn is_void(tag: &str) -> bool {
122 matches!(tag, "hr" | "br" | "img")
123}
124
125/// Mark wrappers of a run, outermost first (schema order: link, em, strong, code).
126pub fn mark_specs(m: &Marks) -> Vec<Spec> {
127 let mut out = Vec::new();
128 if let Some((href, title)) = &m.link {
129 let mut s = Spec::new("a");
130 s.attrs.push(("href", href.clone()));
131 if let Some(t) = title {
132 s.attrs.push(("title", t.clone()));
133 }
134 out.push(s);
135 }
136 if m.em {
137 out.push(Spec::new("em"));
138 }
139 if m.strong {
140 out.push(Spec::new("strong"));
141 }
142 if m.code {
143 out.push(Spec::new("code"));
144 }
145 out
146}
147
148/// The top of the note as the editor shows it before it starts: at most `blocks`
149/// blocks and about `chars` characters of text, in one page element. Reads only the
150/// head of the body.
151pub fn preview_html(doc: &LoroDoc, blocks: usize, chars: usize) -> String {
152 let text = flat::body(doc);
153 let n = text.len_unicode().min(chars + blocks + 1);
154 let delta = text.slice_delta(0, n, PosType::Unicode).unwrap_or_default();
155 let mut flat = flat::read_delta(delta);
156 flat.truncate(blocks);
157 let mut out = String::from("<div class=\"pm-page\">");
158 let mut budget = chars;
159 blocks_html(&flat::nest(&flat), &mut out, &mut budget);
160 out.push_str("</div>");
161 out
162}
163
164/// Blocks as the editor's markup, with at most `budget` characters of text.
165pub fn blocks_html(blocks: &[Block], out: &mut String, budget: &mut usize) {
166 for b in blocks {
167 if *budget == 0 {
168 return;
169 }
170 block_html(b, out, budget);
171 }
172}
173
174fn block_html(b: &Block, out: &mut String, budget: &mut usize) {
175 let (spec, inl): (Spec, &[Inline]) = match b {
176 Block::Paragraph(inl) => (leaf_spec(Kind::Para, None), inl),
177 Block::Heading(n, inl) => (leaf_spec(Kind::Heading((*n).clamp(1, 6) as u8), None), inl),
178 Block::Rule => {
179 open(&leaf_spec(Kind::Rule, None), out);
180 return;
181 }
182 Block::Code { lang, text } => {
183 let spec = leaf_spec(Kind::Code, lang.as_deref());
184 open(&spec, out);
185 out.push_str("<code>");
186 let s = cut(text, budget);
187 escape(s, out);
188 if s.is_empty() || s.ends_with('\n') {
189 trailing_break(out);
190 }
191 out.push_str("</code></pre>");
192 return;
193 }
194 Block::Quote(inner) => {
195 open(&wrap_spec(Wrap::Quote, 1), out);
196 blocks_html(inner, out, budget);
197 close("blockquote", out);
198 return;
199 }
200 Block::List { ordered, start, items } => {
201 let spec = wrap_spec(if *ordered { Wrap::Ordered } else { Wrap::Bullet }, *start);
202 open(&spec, out);
203 for item in items {
204 out.push_str("<li>");
205 blocks_html(item, out, budget);
206 out.push_str("</li>");
207 }
208 close(spec.tag, out);
209 return;
210 }
211 };
212 open(&spec, out);
213 inline_html(inl, out, budget);
214 close(spec.tag, out);
215}
216
217/// A textblock's content. An empty one, or one ending in a break, gets a trailing
218/// `<br>` to show its last line.
219pub fn inline_html(inl: &[Inline], out: &mut String, budget: &mut usize) {
220 let mut last_break = true;
221 for i in inl {
222 match i {
223 Inline::Text(s, m) => {
224 let s = cut(s, budget);
225 if s.is_empty() {
226 continue;
227 }
228 let wraps = mark_specs(m);
229 for w in &wraps {
230 open(w, out);
231 }
232 escape(s, out);
233 for w in wraps.iter().rev() {
234 close(w.tag, out);
235 }
236 last_break = false;
237 }
238 Inline::HardBreak => {
239 out.push_str("<br>");
240 last_break = true;
241 }
242 Inline::Image { src, alt, title } => {
243 let spec = image_spec(src, alt, title.as_deref());
244 open(&spec, out);
245 if !is_void(spec.tag) {
246 close(spec.tag, out);
247 }
248 last_break = false;
249 }
250 }
251 }
252 if last_break {
253 trailing_break(out);
254 }
255}
256
257fn trailing_break(out: &mut String) {
258 out.push_str("<br class=\"");
259 out.push_str(TRAILING_BREAK);
260 out.push_str("\">");
261}
262
263/// The head of `s` that fits the budget, which it takes from.
264fn cut<'a>(s: &'a str, budget: &mut usize) -> &'a str {
265 let s = match s.char_indices().nth(*budget) {
266 Some((at, _)) => &s[..at],
267 None => s,
268 };
269 *budget -= s.chars().count().min(*budget);
270 s
271}
272
273fn open(spec: &Spec, out: &mut String) {
274 out.push('<');
275 out.push_str(spec.tag);
276 for (k, v) in &spec.attrs {
277 out.push(' ');
278 out.push_str(k);
279 out.push_str("=\"");
280 escape(v, out);
281 out.push('"');
282 }
283 out.push('>');
284}
285
286fn close(tag: &str, out: &mut String) {
287 out.push_str("</");
288 out.push_str(tag);
289 out.push('>');
290}
291
292pub fn escape(s: &str, out: &mut String) {
293 for c in s.chars() {
294 match c {
295 '&' => out.push_str("&amp;"),
296 '<' => out.push_str("&lt;"),
297 '>' => out.push_str("&gt;"),
298 '"' => out.push_str("&quot;"),
299 c => out.push(c),
300 }
301 }
302}