fix(desktop): preserve markdown block-prefix escapes, trailing breaks, and validate AVIF boxes

Escape literal dollar signs and break tags in Markdown text, encode trailing
block line breaks as explicit break tags for lossless roundtrips alongside
inline and block equations, and validate full ISO BMFF ftyp, meta, and mdat
boxes before embedding AVIF images in visual exports.
This commit is contained in:
DarkSky committed 2026-12-05 03:53:42 +09:00
1 parent 2e383e1127
commit 61644812f5
8 files changed
+972 -90

No files matched your search

@@ -1,5 +1,7 @@
use std::fmt::Write;
use anyhow::{Context as _, Result};
use blocksuite_editor::{
clipboard::sanitize::sanitize_url,
database::{format_database_date, format_database_number, format_database_progress},
@@ -15,7 +17,7 @@ use y_octo::{Any, TextAttributes, TextDeltaOp, TextInsert};
use crate::doc_store::{DesktopDocStore, LiveDocEntry};
use super::base64;
use super::{base64, image_mime, markdown_escape};
use playground::room_client::BlobMap;
#[derive(Clone, Copy)]
@@ -34,10 +36,10 @@ pub(super) fn markdown(
store: &DesktopDocStore,
origin: &str,
workspace: &str,
) -> String {
) -> Result<String> {
let mut out = format!(
"# {}\n\n",
markdown_text(&entry.meta.title.replace('\n', " "))
markdown_escape::text(&entry.meta.title.replace('\n', " "))
);
Document {
html: false,
@@ -48,8 +50,8 @@ pub(super) fn markdown(
workspace,
images: None,
}
.write_body(entry, &mut out);
out
.write_body(entry, &mut out)?;
Ok(out)
}
pub(super) fn html(
@@ -58,7 +60,7 @@ pub(super) fn html(
origin: &str,
workspace: &str,
images: Option<&BlobMap>,
) -> String {
) -> Result<String> {
let title = escape(&entry.meta.title);
let mut out = format!(
r#"<!doctype html>
@@ -84,25 +86,26 @@ figure{{margin:1em 0;break-inside:avoid}} img{{display:block;max-width:100%;heig
workspace,
images,
}
.write_body(entry, &mut out);
.write_body(entry, &mut out)?;
out.push_str("</main></body></html>\n");
out
Ok(out)
}
impl<'a> Document<'a> {
fn write_body(self, entry: &LiveDocEntry, out: &mut String) {
fn write_body(self, entry: &LiveDocEntry, out: &mut String) -> Result<()> {
if let Some(root) = &entry.snapshot.root {
for note in root
.children
.iter()
.filter(|node| node.is_page_visible_note())
{
self.write_blocks(&note.children, out);
self.write_blocks(&note.children, out)?;
}
}
Ok(())
}
fn write_blocks(self, blocks: &[BlockNode], out: &mut String) {
fn write_blocks(self, blocks: &[BlockNode], out: &mut String) -> Result<()> {
let mut remaining = blocks;
while let Some((block, rest)) = remaining.split_first() {
if let BlockContent::List { kind, .. } = &block.content {
@@ -121,7 +124,7 @@ impl<'a> Document<'a> {
let _ = writeln!(out, "<{tag}{start}>");
}
for item in remaining.iter().take(count) {
self.list_item(item, out);
self.list_item(item, out)?;
}
if self.html {
let _ = writeln!(out, "</{tag}>");
@@ -130,13 +133,14 @@ impl<'a> Document<'a> {
}
remaining = remaining.get(count..).unwrap_or_default();
} else {
self.write_block(block, out);
self.write_block(block, out)?;
remaining = rest;
}
}
Ok(())
}
fn list_item(self, block: &BlockNode, out: &mut String) {
fn list_item(self, block: &BlockNode, out: &mut String) -> Result<()> {
let BlockContent::List {
kind,
checked,
@@ -146,7 +150,7 @@ impl<'a> Document<'a> {
..
} = &block.content
else {
return;
return Ok(());
};
let text = self.inline(text);
if self.html {
@@ -159,7 +163,7 @@ impl<'a> Document<'a> {
} else {
let _ = write!(out, "<li>{text}");
}
self.write_blocks(&block.children, out);
self.write_blocks(&block.children, out)?;
out.push_str("</li>\n");
} else {
let prefix = match kind {
@@ -179,17 +183,18 @@ impl<'a> Document<'a> {
let _ = writeln!(
out,
"{prefix}{}",
text.replace('\n', &format!(" \n{indent}"))
markdown_escape::hard_breaks(&markdown_escape::block_prefixes(&text), &indent)
);
let mut children = String::new();
self.write_blocks(&block.children, &mut children);
self.write_blocks(&block.children, &mut children)?;
for line in children.trim_end().lines() {
let _ = writeln!(out, "{indent}{line}");
}
}
Ok(())
}
fn write_block(self, block: &BlockNode, out: &mut String) {
fn write_block(self, block: &BlockNode, out: &mut String) -> Result<()> {
match &block.content {
BlockContent::Paragraph { kind, text, .. } => {
let text = self.inline(text);
@@ -213,7 +218,12 @@ impl<'a> Document<'a> {
{
let _ = write!(out, "{} ", "#".repeat(level));
}
let _ = writeln!(out, "{}\n", text.replace('\n', " \n"));
let text = if *kind == ParagraphType::Text {
markdown_escape::block_prefixes(&text)
} else {
text
};
let _ = writeln!(out, "{}\n", markdown_escape::hard_breaks(&text, ""));
}
}
BlockContent::Divider => out.push_str(if self.html { "<hr>\n" } else { "---\n\n" }),
@@ -236,7 +246,7 @@ impl<'a> Document<'a> {
}
BlockContent::Callout { icon, text, .. } => {
let mut children = String::new();
self.write_blocks(&block.children, &mut children);
self.write_blocks(&block.children, &mut children)?;
let text = self.inline(text);
if self.html {
let _ = writeln!(
@@ -251,7 +261,7 @@ impl<'a> Document<'a> {
}
out.push('\n');
}
return;
return Ok(());
}
BlockContent::Table(table) => self.table(self.simple_rows(table), out),
BlockContent::Database(data) => {
@@ -264,7 +274,7 @@ impl<'a> Document<'a> {
}
}
self.table(self.database_rows(data), out);
return;
return Ok(());
}
BlockContent::Latex { latex } => {
if self.html {
@@ -292,11 +302,12 @@ impl<'a> Document<'a> {
} => {
let image = self
.images
.filter(|_| !source_id.is_empty())
.and_then(|blobs| blobs.get(source_id))
.map(|bytes| bytes.as_slice());
if let Some((mime, data)) =
image.and_then(|data| image_mime(data).map(|mime| (mime, data)))
{
if let Some(data) = image {
let mime = image_mime::sniff(data)
.context("Cannot export this document because it contains an unsupported image format.")?;
out.push_str("<figure><img alt=\"\"");
for (name, size) in [("width", width), ("height", height)] {
if let Some(size) = size.filter(|size| size.is_finite() && *size >= 1.0) {
@@ -325,17 +336,17 @@ impl<'a> Document<'a> {
embed_depth: 1,
..self
}
.write_body(entry, out);
.write_body(entry, out)?;
} else {
self.document_link(page_id, out);
}
return;
return Ok(());
}
BlockContent::SurfaceRef { caption, .. }
| BlockContent::Attachment { name: caption, .. } => self.caption(caption, out),
_ => {}
}
self.write_blocks(&block.children, out);
self.write_blocks(&block.children, out)
}
fn document_title(self, id: &str) -> Option<&'a str> {
@@ -599,7 +610,7 @@ impl<'a> Document<'a> {
if self.html {
escape(value)
} else {
markdown_text(value)
markdown_escape::text(value)
}
}
@@ -666,17 +677,6 @@ fn fence(text: &str, min: usize) -> String {
"`".repeat(min.max(longest + 1))
}
fn markdown_text(text: &str) -> String {
let mut escaped = String::new();
for ch in text.chars() {
if matches!(ch, '\\' | '`' | '*' | '[' | ']' | '~') {
escaped.push('\\');
}
escaped.push(ch);
}
escaped
}
fn markdown_url(url: &str) -> String {
let mut escaped = String::new();
for ch in url.chars() {
@@ -718,22 +718,6 @@ fn escape(text: &str) -> String {
.replace('\'', "&#39;")
}
fn image_mime(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("image/png")
} else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
Some("image/jpeg")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
Some("image/gif")
} else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
Some("image/webp")
} else if bytes.starts_with(b"BM") {
Some("image/bmp")
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,117 @@
pub(super) fn sniff(bytes: &[u8]) -> Option<&'static str> {
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("image/png")
} else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
Some("image/jpeg")
} else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
Some("image/gif")
} else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") {
Some("image/webp")
} else if bytes.starts_with(b"BM") {
Some("image/bmp")
} else if is_avif(bytes) {
Some("image/avif")
} else {
None
}
}
fn is_avif(bytes: &[u8]) -> bool {
let Some((file_type, mut rest)) = BoxHeader::read(bytes) else {
return false;
};
let brand = |brand: &[u8]| matches!(brand, b"avif" | b"avis");
let Some(major) = file_type.payload.get(..4) else {
return false;
};
let Some(compatible) = file_type.payload.get(8..) else {
return false;
};
if file_type.kind != b"ftyp"
|| !compatible.len().is_multiple_of(4)
|| !(brand(major) || compatible.chunks_exact(4).any(brand))
{
return false;
}
let mut has_meta = false;
let mut has_media_data = false;
while !rest.is_empty() {
let Some((header, tail)) = BoxHeader::read(rest) else {
return false;
};
match header.kind {
b"meta" => has_meta |= header.payload.len() > 4,
b"mdat" => has_media_data |= !header.payload.is_empty(),
_ => {}
}
rest = tail;
}
has_meta && has_media_data
}
struct BoxHeader<'a> {
kind: &'a [u8; 4],
payload: &'a [u8],
}
impl<'a> BoxHeader<'a> {
fn read(bytes: &'a [u8]) -> Option<(Self, &'a [u8])> {
let size = u32::from_be_bytes(*bytes.first_chunk()?);
let kind = bytes.get(4..)?.first_chunk()?;
let (header_len, end) = match size {
0 => (8, bytes.len()),
1 => (
16,
usize::try_from(u64::from_be_bytes(*bytes.get(8..)?.first_chunk()?)).ok()?,
),
size => (8, usize::try_from(size).ok()?),
};
let header_len = header_len + if kind == b"uuid" { 16 } else { 0 };
let payload = bytes.get(header_len..end)?;
Some((Self { kind, payload }, &bytes[end..]))
}
}
#[cfg(test)]
mod tests {
use super::sniff;
#[test]
fn avif_requires_complete_brands_metadata_and_media_data() {
const META: &[u8] = b"\0\0\0\x14meta\0\0\0\0\0\0\0\x08free";
const MDAT: &[u8] = b"\0\0\0\x09mdat\x01";
for (ftyp, expected) in [
(b"\0\0\0\x10ftypavif\0\0\0\0".as_slice(), Some("image/avif")),
(b"\0\0\0\x14ftypmif1\0\0\0\0avis", Some("image/avif")),
(
b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x18avis\0\0\0\0",
Some("image/avif"),
),
(b"\0\0\0\x0cftypavis", None),
(b"\0\0\0\x0dftypavif\0", None),
(b"\0\0\0\x11ftypavif\0\0\0\0a", None),
(b"\0\0\0\x10ftypmif1avif", None),
(b"\0\0\0\x01ftyp\0\0\0\0\0\0\0\x10", None),
] {
assert_eq!(sniff(&[ftyp, META, MDAT].concat()), expected, "{ftyp:?}");
}
let ftyp = b"\0\0\0\x10ftypavif\0\0\0\0".as_slice();
for boxes in [
vec![ftyp],
vec![ftyp, META],
vec![ftyp, MDAT],
vec![ftyp, b"\0\0\0\x0cmeta\0\0\0\0", MDAT],
vec![ftyp, META, &MDAT[..8]],
vec![ftyp, META, b"\0\0\0\x08mdat"],
vec![ftyp, META, MDAT, b"\0"],
] {
assert_eq!(sniff(&boxes.concat()), None, "{boxes:?}");
}
assert_eq!(
sniff(&[ftyp, META, b"\0\0\0\0mdat\x01"].concat()),
Some("image/avif")
);
}
}
@@ -0,0 +1,64 @@
use super::markdown_inline::BREAK_TAG;
pub(super) fn text(text: &str) -> String {
let mut escaped = String::new();
for (index, ch) in text.char_indices() {
if matches!(ch, '\\' | '`' | '*' | '[' | ']' | '~' | '$')
|| (ch == '<' && text[index..].starts_with(BREAK_TAG))
{
escaped.push('\\');
}
escaped.push(ch);
}
escaped
}
pub(super) fn hard_breaks(text: &str, indent: &str) -> String {
let body = text.trim_end_matches('\n');
let mut rendered = body.replace('\n', &format!(" \n{indent}"));
for _ in body.len()..text.len() {
rendered.push_str(BREAK_TAG);
}
rendered
}
pub(super) fn block_prefixes(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for (index, line) in text.split('\n').enumerate() {
if index > 0 {
out.push('\n');
}
let trimmed = line.trim_start_matches([' ', '\t']);
let bullets = trimmed.as_bytes();
let digits = digit_prefix_len(trimmed);
let blank_after = |offset| {
bullets
.get(offset)
.is_none_or(|byte| matches!(byte, b' ' | b'\t' | b'\r'))
};
let escape = match bullets.first() {
Some(b'#' | b'>' | b'=' | b'_') => Some(0),
Some(b'-') if blank_after(1) || bullets.get(1) == Some(&b'-') => Some(0),
Some(b'+') if blank_after(1) => Some(0),
Some(_) if digits > 0 => match bullets.get(digits) {
Some(b')') => Some(digits),
Some(b'.') if blank_after(digits + 1) => Some(digits),
_ => None,
},
_ => None,
};
if let Some(offset) = escape {
let offset = line.len() - trimmed.len() + offset;
out.push_str(&line[..offset]);
out.push('\\');
out.push_str(&line[offset..]);
} else {
out.push_str(line);
}
}
out
}
pub(super) fn digit_prefix_len(text: &str) -> usize {
text.bytes().take_while(u8::is_ascii_digit).count()
}
@@ -2,6 +2,8 @@ use anyhow::{Result, ensure};
use blocksuite_editor::clipboard::{Slice, SliceBlock};
use blocksuite_playground_doc::read::MAX_BLOCK_DEPTH;
use super::{markdown_escape::digit_prefix_len, markdown_inline};
pub(super) fn parse(source: &str) -> Result<Slice> {
let normalized = source.replace("\r\n", "\n").replace('\r', "\n");
let lines: Vec<_> = normalized.split('\n').collect();
@@ -35,26 +37,31 @@ fn parse_blocks(lines: &[&str], depth: usize) -> Result<Vec<SliceBlock>> {
}
blocks.push(block);
remaining = end.map_or(&[][..], |end| &tail[end + 1..]);
} else if is_list_item(trimmed)
&& let Some(mut list) = Slice::from_markdown(trimmed)
&& let Some(mut parent) = list.content.pop()
&& parent.flavour == "affine:list"
{
let end = tail
} else if trimmed.trim_end() == "$$" {
let count = tail
.iter()
.position(|line| line.trim() == "$$")
.map_or(remaining.len(), |end| end + 2);
if let Some(parsed) = Slice::from_markdown(&remaining[..count].join("\n")) {
blocks.extend(parsed.content);
}
remaining = &remaining[count..];
} else if let Some((mut parent, used)) = parse_list_item(remaining, indent) {
let rest = &remaining[used..];
let end = rest
.iter()
.position(|line| {
!line.trim().is_empty()
&& line.len() - line.trim_start_matches(' ').len() <= indent
})
.unwrap_or(tail.len());
if tail[..end].iter().any(|line| !line.trim().is_empty()) {
let child_indent = tail[..end]
.iter()
.filter(|line| !line.trim().is_empty())
.map(|line| line.len() - line.trim_start_matches(' ').len())
.min()
.unwrap_or(indent);
let children: Vec<_> = tail[..end]
.unwrap_or(rest.len());
if let Some(child_indent) = rest[..end]
.iter()
.filter(|line| !line.trim().is_empty())
.map(|line| line.len() - line.trim_start_matches(' ').len())
.min()
{
let children: Vec<_> = rest[..end]
.iter()
.map(|line| {
let available = line.len() - line.trim_start_matches(' ').len();
@@ -64,30 +71,146 @@ fn parse_blocks(lines: &[&str], depth: usize) -> Result<Vec<SliceBlock>> {
parent.children = parse_blocks(&children, depth + 1)?;
}
blocks.push(parent);
remaining = &tail[end..];
remaining = &rest[end..];
} else {
let count = 1 + tail
.iter()
.take_while(|line| {
let line = line.trim_start_matches(' ');
!is_list_item(line) && Fence::parse(line).is_none()
list_prefix_len(line).is_none()
&& Fence::parse(line).is_none()
&& line.trim_end() != "$$"
})
.count();
if let Some(parsed) = Slice::from_markdown(&remaining[..count].join("\n")) {
blocks.extend(parsed.content);
}
blocks.extend(parse_paragraphs(&remaining[..count]));
remaining = &remaining[count..];
}
}
Ok(blocks)
}
fn is_list_item(line: &str) -> bool {
fn list_prefix_len(line: &str) -> Option<usize> {
if matches!(line.as_bytes().get(..2), Some(b"- " | b"+ " | b"* ")) {
return true;
let task = matches!(line.as_bytes().get(2..6), Some(b"[ ] " | b"[x] " | b"[X] "));
return Some(if task { 6 } else { 2 });
}
line.split_once(". ")
.is_some_and(|(n, _)| !n.is_empty() && n.bytes().all(|byte| byte.is_ascii_digit()))
let digits = digit_prefix_len(line);
(digits > 0 && line.as_bytes().get(digits..digits + 2) == Some(b". ")).then_some(digits + 2)
}
fn parse_list_item(lines: &[&str], indent: usize) -> Option<(SliceBlock, usize)> {
let first = lines.first()?.get(indent..)?;
let prefix_len = list_prefix_len(first)?;
let (marker, mut text) = first.split_at(prefix_len);
let is_task = matches!(
marker.as_bytes().get(2..6),
Some(b"[ ] " | b"[x] " | b"[X] ")
);
let continuation_indent = indent + if is_task { 2 } else { prefix_len };
let mut source = if is_task && marker.starts_with('+') {
format!("-{}", &marker[1..])
} else {
marker.to_owned()
};
let mut used = 1;
for next in &lines[1..] {
let Some(body) = text.strip_suffix(" ") else {
break;
};
let Some(next) = next.get(continuation_indent..).filter(|tail| {
next[..continuation_indent].bytes().all(|byte| byte == b' ')
&& (!tail.trim().is_empty() || tail.ends_with(" "))
}) else {
break;
};
let protected = markdown_inline::protect(body);
if used == 1
&& !body.trim().is_empty()
&& !Slice::from_markdown(&format!("{source}{protected}")).is_some_and(|parsed| {
parsed
.content
.first()
.is_some_and(|block| block.flavour == "affine:list")
})
{
return None;
}
if Fence::parse(next.trim_start()).is_some()
|| !is_paragraph_line(&markdown_inline::protect(next))
{
break;
}
source.push_str(&protected);
source.push_str(markdown_inline::HARD_BREAK);
text = next;
used += 1;
}
source.push_str(&markdown_inline::protect(text));
let mut blocks = read_protected(&source);
let block = blocks.pop()?;
(block.flavour == "affine:list").then_some((block, used))
}
fn parse_paragraphs(lines: &[&str]) -> Vec<SliceBlock> {
let lines: Vec<_> = lines
.iter()
.map(|line| markdown_inline::protect(line))
.collect();
let mut source = lines.first().cloned().unwrap_or_default();
for (index, pair) in lines.windows(2).enumerate() {
let [previous, next] = pair else { continue };
if previous.ends_with(" ")
&& !is_table_start(&lines[index..])
&& !is_table_start(&lines[index + 1..])
&& is_paragraph_line(previous)
&& is_paragraph_line(next)
{
source.truncate(source.len() - 2);
source.push_str(markdown_inline::HARD_BREAK);
} else {
source.push('\n');
}
source.push_str(next);
}
read_protected(&source)
}
fn is_table_start(lines: &[String]) -> bool {
let [first, second, ..] = lines else {
return false;
};
first.trim_start().starts_with('|')
&& second.trim_start().starts_with('|')
&& Slice::from_markdown(&format!("{first}\n{second}")).is_some_and(|parsed| {
parsed
.content
.iter()
.any(|block| block.flavour == "affine:table")
})
}
fn is_paragraph_line(line: &str) -> bool {
if line.trim().is_empty() {
return line.ends_with(" ");
}
Slice::from_markdown(line).is_some_and(|parsed| {
matches!(parsed.content.as_slice(), [block]
if block.flavour == "affine:paragraph"
&& block.props.get("type").and_then(serde_json::Value::as_str) == Some("text"))
})
}
fn read_protected(source: &str) -> Vec<SliceBlock> {
let Some(parsed) = Slice::from_markdown(source) else {
return Vec::new();
};
fn restore(block: &mut SliceBlock) {
block.props.values_mut().for_each(markdown_inline::restore);
block.children.iter_mut().for_each(restore);
}
let mut blocks = parsed.content;
blocks.iter_mut().for_each(restore);
blocks
}
struct Fence<'a> {
@@ -124,3 +247,97 @@ impl<'a> Fence<'a> {
count >= self.count && line[count..].trim().is_empty()
}
}
#[cfg(test)]
mod tests {
use anyhow::{Context as _, Result};
use super::parse;
#[test]
fn escaped_punctuation_stays_literal_in_block_math() -> Result<()> {
let blocks = parse("$$\n- x\n1. x\n```\n\\# x\n$$\n\n\\# Text")?.content;
let [math, paragraph] = blocks.as_slice() else {
anyhow::bail!("Expected a math block and a paragraph.");
};
assert_eq!(math.flavour, "affine:latex");
assert_eq!(
math.props.get("latex").context("Math source")?.as_str(),
Some("- x\n1. x\n```\n\\# x")
);
assert_eq!(paragraph.plain(), "# Text");
Ok(())
}
#[test]
fn task_continuation_keeps_leading_break_and_nested_child() -> Result<()> {
let blocks = parse("- [x] \n \\# Title \n - Child")?.content;
let [task] = blocks.as_slice() else {
anyhow::bail!("Expected one task item.");
};
assert_eq!(task.flavour, "affine:list");
assert_eq!(task.plain(), "\n# Title");
let [child] = task.children.as_slice() else {
anyhow::bail!("Expected one nested list item.");
};
assert_eq!(child.flavour, "affine:list");
assert_eq!(child.plain(), "Child");
Ok(())
}
#[test]
fn escaped_inline_text_avoids_markup_and_preserves_verbatim_spans() -> Result<()> {
use y_octo::{Any, TextDeltaOp, TextInsert};
let source = format!(
"{}\n\n{}\n\n{}\n\n{}",
r"\[draft\] \*note\* \_private\_ \~fine\~ \` \| \$ \\ \a",
format_args!("{} \u{e000}\u{e001}", r"\# marker"),
"+ [X] \\# Task\n* [ ] \\+ Task",
r"> **\[bold\]** [\[link\]](https://example.com/a) `\*code\*` $\alpha_\{1\}$"
);
let blocks = parse(&source)?.content;
let [plain, private, checked, unchecked, quote] = blocks.as_slice() else {
anyhow::bail!("Expected two paragraphs, two task items, and one quote.");
};
assert_eq!(
plain.plain(),
"[draft] *note* _private_ ~fine~ \x60 | $ \\ \\a"
);
assert_eq!(private.plain(), "# marker \u{e000}\u{e001}");
for (item, text, checked) in [(checked, "# Task", true), (unchecked, "+ Task", false)] {
assert_eq!(item.flavour, "affine:list");
assert_eq!(
item.props.get("type").and_then(serde_json::Value::as_str),
Some("todo")
);
assert_eq!(
item.props
.get("checked")
.and_then(serde_json::Value::as_bool),
Some(checked)
);
assert_eq!(item.plain(), text);
}
let delta = quote.delta();
for (label, mark, expected) in [
("[bold]", "bold", Any::True),
(
"[link]",
"link",
Any::String("https://example.com/a".into()),
),
(r"\*code\*", "code", Any::True),
(" ", "latex", Any::String(r"\alpha_\{1\}".into())),
] {
assert!(
delta.iter().any(|op| matches!(op,
TextDeltaOp::Insert { insert: TextInsert::Text(text), format: Some(attrs) }
if text == label && attrs.get(mark) == Some(&expected)
)),
"{label}: {delta:?}"
);
}
Ok(())
}
}
@@ -0,0 +1,110 @@
use serde_json::Value;
// Protect punctuation from the block and inline parser until it has built the text deltas.
// Double literal escape characters so text in the private use area can also round trip.
const ESCAPE: char = '\u{e000}';
pub(super) const HARD_BREAK: &str = "\u{e000}\u{e001}";
pub(super) const BREAK_TAG: &str = "<br />";
const PUNCTUATION_BASE: u32 = 0xe100;
pub(super) fn protect(text: &str) -> String {
let mut rest = text;
let mut out = String::with_capacity(text.len());
while let Some(ch) = rest.chars().next() {
let tail = &rest[ch.len_utf8()..];
if ch == '\\'
&& let Some(punctuation) = tail.chars().next().filter(char::is_ascii_punctuation)
&& let Some(token) = char::from_u32(PUNCTUATION_BASE + u32::from(punctuation))
{
out.push(ESCAPE);
out.push(token);
rest = &tail[1..];
continue;
}
if let Some(span) = verbatim_prefix(rest) {
for ch in span.chars() {
if ch == ESCAPE {
out.push(ESCAPE);
}
out.push(ch);
}
rest = &rest[span.len()..];
continue;
}
if let Some(tail) = rest.strip_prefix(BREAK_TAG) {
out.push_str(HARD_BREAK);
rest = tail;
continue;
}
if ch == ESCAPE {
out.push(ESCAPE);
}
out.push(ch);
rest = tail;
}
out
}
fn verbatim_prefix(text: &str) -> Option<&str> {
if text.starts_with('\x60') {
let width = text.bytes().take_while(|byte| *byte == b'\x60').count();
let mut tail = &text[width..];
while let Some(start) = tail.find('\x60') {
let end = start
+ tail[start..]
.bytes()
.take_while(|byte| *byte == b'\x60')
.count();
tail = &tail[end..];
if end - start == width {
return Some(&text[..text.len() - tail.len()]);
}
}
return Some(&text[..width]);
}
if let Some(after) = text.strip_prefix("$$") {
let (formula, tail) = after.split_once("$$")?;
return (!formula.trim().is_empty()).then(|| &text[..text.len() - tail.len()]);
}
let after = text.strip_prefix('$')?;
let (formula, tail) = after.split_once('$')?;
(!formula.is_empty()
&& !formula.starts_with(char::is_whitespace)
&& !formula.ends_with(char::is_whitespace)
&& !tail.starts_with(|ch: char| ch.is_ascii_digit()))
.then(|| &text[..text.len() - tail.len()])
}
pub(super) fn restore(value: &mut Value) {
match value {
Value::String(text) if text.contains(ESCAPE) => {
let mut decoded = String::with_capacity(text.len());
let mut chars = text.chars();
while let Some(ch) = chars.next() {
if ch == ESCAPE {
match chars.next() {
Some(ESCAPE) => decoded.push(ESCAPE),
Some('\u{e001}') => decoded.push('\n'),
Some(token) => {
let literal =
char::from_u32(u32::from(token).saturating_sub(PUNCTUATION_BASE));
if let Some(literal) = literal.filter(char::is_ascii_punctuation) {
decoded.push(literal);
} else {
decoded.push(ch);
decoded.push(token);
}
}
None => decoded.push(ch),
}
} else {
decoded.push(ch);
}
}
*text = decoded;
}
Value::Array(values) => values.iter_mut().for_each(restore),
Value::Object(values) => values.values_mut().for_each(restore),
_ => {}
}
}
@@ -0,0 +1,273 @@
use blocksuite_playground_doc::read::BlockContent;
use super::{
tests::{TIME, TODAY, file},
*,
};
#[test]
fn markdown_exports_roundtrip_text_hard_breaks_and_block_types() -> Result<()> {
use blocksuite_playground_doc::schema::{ListType, ParagraphType};
let paragraphs = [
("# Release draft", r"\# Release draft"),
("> 5 units", r"\> 5 units"),
("1. literal text", r"1\. literal text"),
("- literal dash", r"\- literal dash"),
("+ literal plus", r"\+ literal plus"),
("* literal star", r"\* literal star"),
("1) literal paren", r"1\) literal paren"),
("```text", r"\`\`\`text"),
("~~~text", r"\~\~\~text"),
("---", r"\---"),
("* * *", r"\* \* \*"),
("v0.27.5 - ready", "v0.27.5 - ready"),
(
r"# Release [draft] *note* ~test~ \path",
r"\# Release \[draft\] \*note\* \~test\~ \\path",
),
("# Release draft\nnext", "\\# Release draft \nnext"),
("Opening\n# Release draft", "Opening \n\\# Release draft"),
("$$", r"\$\$"),
("$$\n", r"\$\$<br />"),
("# Release\n\nending", "\\# Release \n \nending"),
("literal <br />\n\n", r"literal \<br /><br /><br />"),
("Opening\n$$\nClosing", "Opening \n\\$\\$ \nClosing"),
];
let headings_and_quotes = [
(ParagraphType::H2, "Real heading", "## Real heading"),
(ParagraphType::Quote, "Real quote", "> Real quote"),
];
let lists = [
(
ListType::Bulleted,
false,
"# Literal in bullet\n- continuation [draft]",
"- \\# Literal in bullet \n \\- continuation \\[draft\\]",
),
(
ListType::Numbered,
false,
"1. Literal in order\n$$",
"1. 1\\. Literal in order \n \\$\\$",
),
(
ListType::Todo,
false,
"# Release [draft]",
r"- [ ] \# Release \[draft\]",
),
(ListType::Todo, true, "1. Tail\n", r"- [x] 1\. Tail<br />"),
(
ListType::Todo,
true,
"1. Literal *note*\n+ Plus",
"- [x] 1\\. Literal \\*note\\* \n \\+ Plus",
),
];
let mut store = DesktopDocStore::seed_showcase(TODAY);
let id = ImportedDoc::read(
ImportFormat::Markdown,
file("Release.md", "# Release"),
TIME,
)?
.install(&mut store, TIME)?;
let entry = store.get_doc(&id).context("Document")?;
let mut edit = PageDocSession::new(&id, 285)?;
edit.apply_remote_update_v1(&entry.session.encode_update_v1()?)?;
let vacant = entry
.snapshot
.root
.as_ref()
.context("Document root")?
.children
.iter()
.find(|node| node.id == entry.note_id)
.and_then(|note| note.children.first())
.context("Empty paragraph")?;
edit.delete_block_subtree(&entry.note_id, &vacant.id, TIME as u64)?;
let mut expected = Vec::new();
let mut lines = vec!["# Release"];
for (kind, text, line) in paragraphs
.map(|(text, line)| (ParagraphType::Text, text, line))
.into_iter()
.chain(headings_and_quotes)
{
edit.add_block(
&format!("paragraph-{}", expected.len()),
BlockSpec::Paragraph {
paragraph_type: kind,
text: text.into(),
},
Some(&entry.note_id),
None,
TIME as u64,
)?;
expected.push(("affine:paragraph", kind.as_str(), text, false));
lines.push(line);
}
for (kind, checked, text, line) in lists {
edit.add_block(
&format!("list-{}", expected.len()),
BlockSpec::List {
list_type: kind,
text: text.into(),
checked,
order: None,
},
Some(&entry.note_id),
None,
TIME as u64,
)?;
expected.push(("affine:list", kind.as_str(), text, checked));
lines.push(line);
}
assert!(store.apply_remote_doc_update(&id, &edit.encode_update_v1()?));
for format in [ExportFormat::Markdown, ExportFormat::CopyMarkdown] {
let entry = store.get_doc(&id).context("Edited document")?;
let space = &store.active_workspace().id;
let output = export(entry, format, &store, "https://app.affine.pro", space, None)?;
let markdown = std::str::from_utf8(&output.bytes)?;
assert_eq!(
markdown
.lines()
.filter(|line| !line.is_empty())
.collect::<Vec<_>>(),
lines
.iter()
.flat_map(|line| line.lines())
.collect::<Vec<_>>(),
);
let imported = ImportedDoc::read(
ImportFormat::Markdown,
SourceFile {
name: output.name,
bytes: output.bytes,
},
TIME,
)?;
let snapshot = imported.page.read_page_snapshot()?;
let root = snapshot.root.context("Imported document root")?;
let note = root
.children
.iter()
.find(|node| node.is_page_visible_note())
.context("Imported note")?;
let actual = note
.children
.iter()
.map(|node| {
ensure!(
node.children.is_empty(),
"Unexpected children in {}",
node.flavour
);
let (kind, text, checked) = match &node.content {
BlockContent::Paragraph { kind, text, .. } => (kind.as_str(), text, false),
BlockContent::List {
kind,
checked,
text,
..
} => (kind.as_str(), text, *checked),
_ => bail!("Unexpected imported block: {}", node.flavour),
};
Ok((node.flavour.as_str(), kind, text.plain.as_str(), checked))
})
.collect::<Result<Vec<_>>>()?;
assert_eq!(actual, expected);
}
Ok(())
}
#[test]
fn markdown_roundtrip_keeps_literal_dollars_and_equations() -> Result<()> {
use blocksuite_playground_doc::schema::{ListType, ParagraphType};
let mut store = DesktopDocStore::seed_showcase(TODAY);
let id = ImportedDoc::read(
ImportFormat::Markdown,
file(
"Math.md",
"# Math\n\nAn equation $x + y$\n\n$$\na^2 + b^2\n$$",
),
TIME,
)?
.install(&mut store, TIME)?;
let entry = store.get_doc(&id).context("Document")?;
let mut edit = PageDocSession::new(&id, 285)?;
edit.apply_remote_update_v1(&entry.session.encode_update_v1()?)?;
for (id, spec) in [
(
"paired",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "$$x$$".into(),
},
),
(
"task",
BlockSpec::List {
list_type: ListType::Todo,
checked: true,
text: "$$a + b$$".into(),
order: None,
},
),
(
"delimiter",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "$$".into(),
},
),
] {
edit.add_block(id, spec, Some(&entry.note_id), None, TIME as u64)?;
}
assert!(store.apply_remote_doc_update(&id, &edit.encode_update_v1()?));
let space = store.active_workspace().id.clone();
let origin = "https://app.affine.pro";
let entry = store.get_doc(&id).context("Edited document")?;
let original = export(entry, ExportFormat::Html, &store, origin, &space, None)?;
let html = std::str::from_utf8(&original.bytes)?;
for expected in [
"<p>$$x$$</p>",
"<li data-task><input type=\"checkbox\" disabled checked> $$a + b$$</li>",
"<p>$$</p>",
"<p>An equation <code>x + y</code></p>",
"<pre>a^2 + b^2</pre>",
] {
assert!(html.contains(expected), "{expected}: {html}");
}
for format in [ExportFormat::Markdown, ExportFormat::CopyMarkdown] {
let entry = store.get_doc(&id).context("Edited document")?;
let exported = export(entry, format, &store, origin, &space, None)?;
let markdown = std::str::from_utf8(&exported.bytes)?;
for expected in [
r"\$\$x\$\$",
r"- [x] \$\$a + b\$\$",
r"\$\$",
"An equation $x + y$",
"$$\na^2 + b^2\n$$",
] {
assert!(markdown.contains(expected), "{expected}: {markdown}");
}
let id = ImportedDoc::read(
ImportFormat::Markdown,
SourceFile {
name: exported.name,
bytes: exported.bytes,
},
TIME,
)?
.install(&mut store, TIME)?;
let imported = store.get_doc(&id).context("Reimported document")?;
let roundtrip = export(imported, ExportFormat::Html, &store, origin, &space, None)?;
assert_eq!(std::str::from_utf8(&roundtrip.bytes)?, html);
}
Ok(())
}
@@ -1,6 +1,9 @@
mod base64;
mod document;
mod image_mime;
mod markdown_escape;
mod markdown_import;
mod markdown_inline;
#[cfg(not(target_arch = "wasm32"))]
mod native;
#[cfg(target_arch = "wasm32")]
@@ -383,12 +386,12 @@ pub(crate) fn export(
ExportFormat::Markdown | ExportFormat::CopyMarkdown => (
".md",
"text/markdown;charset=utf-8",
document::markdown(entry, store, origin, workspace).into_bytes(),
document::markdown(entry, store, origin, workspace)?.into_bytes(),
),
ExportFormat::Html | ExportFormat::Pdf | ExportFormat::Print | ExportFormat::Png => (
".html",
"text/html;charset=utf-8",
document::html(entry, store, origin, workspace, images).into_bytes(),
document::html(entry, store, origin, workspace, images)?.into_bytes(),
),
};
let stem: String = entry
@@ -436,5 +439,7 @@ fn check_file_count(count: usize) -> Result<()> {
Ok(())
}
#[cfg(test)]
mod markdown_tests;
#[cfg(test)]
mod tests;
@@ -6,10 +6,10 @@ use ui_tokens::ThemeMode;
use super::*;
use crate::{DesktopAppState, StoredWorkspaces, doc_store::SessionWriter};
const TIME: i64 = 1_764_500_000_000;
const TODAY: &str = "2026-12-02";
pub(super) const TIME: i64 = 1_764_500_000_000;
pub(super) const TODAY: &str = "2026-12-02";
fn file(name: &str, text: &str) -> SourceFile {
pub(super) fn file(name: &str, text: &str) -> SourceFile {
SourceFile {
name: name.into(),
bytes: text.as_bytes().to_vec(),
@@ -242,6 +242,116 @@ fn visual_exports_embed_uncaptioned_images_with_the_original_pixels() -> Result<
Ok(())
}
#[test]
fn visual_exports_embed_avif_and_report_unsupported_images() -> Result<()> {
let mut store = DesktopDocStore::seed_showcase(TODAY);
let id = ImportedDoc::read(
ImportFormat::Markdown,
file("Palette.md", "# Palette"),
TIME,
)?
.install(&mut store, TIME)?;
let entry = store.get_doc(&id).context("Document")?;
let mut edit = PageDocSession::new(&id, 285)?;
edit.apply_remote_update_v1(&entry.session.encode_update_v1()?)?;
edit.add_block(
"swatch",
BlockSpec::Image {
source_id: "swatch".into(),
caption: String::new(),
width: 16.0,
height: 16.0,
xywh: None,
},
Some(&entry.note_id),
None,
TIME as u64,
)?;
assert!(store.apply_remote_doc_update(&id, &edit.encode_update_v1()?));
let entry = store.get_doc(&id).context("Document with a swatch")?;
let space = &store.active_workspace().id;
// A 16 by 16 red AVIF image.
let avif = base64::decode(concat!(
"AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAAD5bWV0YQAAAAAAAAAvaGRscg",
"AAAAAAAAAAcGljdAAAAAAAAAAAAAAAAFBpY3R1cmVIYW5kbGVyAAAAAA5waXRtAAAAAAAB",
"AAAAHmlsb2MAAAAARAAAAQABAAAAAQAAASEAAAAdAAAAKGlpbmYAAAAAAAEAAAAaaW5mZQ",
"IAAAAAAQAAYXYwMUNvbG9yAAAAAGppcHJwAAAAS2lwY28AAAAUaXNwZQAAAAAAAAAQAAAA",
"EAAAABBwaXhpAAAAAAMICAgAAAAMYXYxQ4EADAAAAAATY29scm5jbHgAAgACAAIAAAAAF2",
"lwbWEAAAAAAAAAAQABBAECgwQAAAAlbWRhdAoGGAz/2wCAMhMYAAAAUAAAAACpjmy2qrHGtoVA",
))?;
// A 16 by 16 AVIF sequence with two frames.
let avis = base64::decode(concat!(
"AAAALGZ0eXBhdmlzAAAAAGF2aXNhdmlmbXNmMWlzbzhtaWYxbWlhZk1BMUIAAAD5bWV0YQAAAAAA",
"AAAvaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAFBpY3R1cmVIYW5kbGVyAAAAAA5waXRtAAAA",
"AAABAAAAHmlsb2MAAAAARAAAAQABAAAAAQAAA+gAAAAiAAAAKGlpbmYAAAAAAAEAAAAaaW5mZQIA",
"AAAAAQAAYXYwMUNvbG9yAAAAAGppcHJwAAAAS2lwY28AAAAUaXNwZQAAAAAAAAAQAAAAEAAAABBw",
"aXhpAAAAAAMICAgAAAAMYXYxQ4EADAAAAAATY29scm5jbHgAAgACAAIAAAAAF2lwbWEAAAAAAAAA",
"AQABBAECgwQAAAK7bW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAA+gAAQAAAQAAAAAAAAAA",
"AAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
"AAAAAAAAAAAAAgAAAkd0cmFrAAAAaHRraGQBAAADAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAf///",
"//////8AAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAA",
"ABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAQAAAAEAAAPoAAAAAAABAAAAAAGzbWRpYQAAACBt",
"ZGhkAAAAAAAAAAAAAAAAAABAAAAAQABVxAAAAAAAL2hkbHIAAAAAAAAAAHBpY3QAAAAAAAAAAAAA",
"AABQaWN0dXJlSGFuZGxlcgAAAAFcbWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAc",
"ZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAABHHN0YmwAAACcc3RzZAAAAAAAAAABAAAAjGF2MDEA",
"AAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAEAAQAEgAAABIAAAAAAAAAAEYTGF2YzYxLjE5LjEwMSBs",
"aWJhb20tYXYxAAAAAAAAAAAY//8AAAAMYXYxQ4EADAAAAAAKZmllbAEAAAAAEHBhc3AAAAABAAAA",
"AQAAABBjY3N0AAAAAHwAAAAAAAAYc3R0cwAAAAAAAAABAAAAAgAAIAAAAAAUc3RzcwAAAAAAAAAB",
"AAAAAQAAABxzdHNjAAAAAAAAAAEAAAABAAAAAgAAAAEAAAAcc3RzegAAAAAAAAAAAAAAAgAAACIA",
"AAAUAAAAFHN0Y28AAAAAAAAAAQAAA+gAAAA+bWRhdAoKAAAAAZ/5tfMAgDIUEADAAAACgAAAAKmO",
"bLaqsca2hUAyEjADwIAAAAbAAAACgAAAgAB2kA==",
))?;
let mut images = playground::room_client::BlobMap::default();
let vector_image = concat!("<", "svg xmlns='http://www.w3.org/2000/svg'/>");
for format in [
ExportFormat::Html,
ExportFormat::Png,
ExportFormat::Print,
ExportFormat::Pdf,
] {
let render = |images: &playground::room_client::BlobMap| {
export(
entry,
format,
&store,
"https://app.affine.pro",
space,
Some(images),
)
};
images.remove("swatch");
let missing = String::from_utf8(render(&images)?.bytes)?;
assert!(!missing.contains("<img"));
for sample in [&avif, &avis] {
images.insert("swatch".into(), Arc::new(sample.clone()));
let html = String::from_utf8(render(&images)?.bytes)?;
let (_, tail) = html
.split_once(r#"<img alt="" width="16" height="16" src="data:image/avif;base64,"#)
.context("Uncaptioned AVIF image")?;
let (data, _) = tail.split_once('"').context("End of image source")?;
assert_eq!(base64::decode(data)?, *sample);
assert!(!html.contains("<figcaption>"));
}
for unsupported in [
b"unknown format".as_slice(),
vector_image.as_bytes(),
b"\0\0\0\x0cftypavis",
b"\0\0\0\x0dftypavif\0",
&avif[..31],
&avif[..32],
] {
images.insert("swatch".into(), Arc::new(unsupported.to_vec()));
let Err(error) = render(&images) else {
bail!("Visual export accepted an unsupported image format.");
};
assert!(error.to_string().contains("unsupported image format"));
}
}
Ok(())
}
#[test]
fn snapshot_payload_reads_base64_and_legacy_arrays_under_the_file_limit() -> Result<()> {
let snapshot = Snapshot {
@@ -411,9 +521,9 @@ fn markdown_roundtrip_keeps_punctuation_emphasis_and_link_targets() -> Result<()
}
#[test]
fn markdown_roundtrip_keeps_nested_lists_and_long_code_fences() -> Result<()> {
fn markdown_roundtrip_keeps_list_continuations_children_and_long_code_fences() -> Result<()> {
let mut store = DesktopDocStore::seed_showcase(TODAY);
let original = "# Notes\n\n- Parent\n 1. Child\n - [x] Grandchild\n- Sibling\n\n````markdown\nExample:\n```rust\nfn main() {}\n```\n````\n\n~~~text\nTilde fence\n~~~\n";
let original = "# Notes\n\n- Parent \n \\# continuation\n 1. Child\n - [x] Grandchild\n- Sibling\n\n````markdown\nExample:\n```rust\nfn main() {}\n```\n````\n\n~~~text\nTilde fence\n~~~\n";
let first = ImportedDoc::read(ImportFormat::Markdown, file("Notes.md", original), TIME)?
.install(&mut store, TIME)?;
let entry = store.get_doc(&first).context("First import")?;
@@ -426,7 +536,7 @@ fn markdown_roundtrip_keeps_nested_lists_and_long_code_fences() -> Result<()> {
None,
)?;
let text = std::str::from_utf8(&md.bytes)?;
assert!(text.contains("- Parent\n 1. Child\n - [x] Grandchild"));
assert!(text.contains("- Parent \n \\# continuation\n 1. Child\n - [x] Grandchild"));
assert!(text.contains("````markdown\nExample:\n```rust\nfn main() {}\n```\n````"));
let second = ImportedDoc::read(
ImportFormat::Markdown,
@@ -440,9 +550,11 @@ fn markdown_roundtrip_keeps_nested_lists_and_long_code_fences() -> Result<()> {
for id in [first, second] {
let entry = store.get_doc(&id).context("Imported entry")?;
let root = entry.snapshot.root.as_ref().context("Root")?;
let parent = root.walk().find(|block| matches!(&block.content, BlockContent::List { text, .. } if text.plain == "Parent")).context("Parent")?;
let parent = root.walk().find(|block| matches!(&block.content, BlockContent::List { text, .. } if text.plain == "Parent\n# continuation")).context("Parent")?;
let child = parent.children.first().context("Child")?;
let grandchild = child.children.first().context("Grandchild")?;
assert_eq!(parent.children.len(), 1);
assert_eq!(child.children.len(), 1);
use blocksuite_playground_doc::schema::ListType;
assert!(
matches!(&child.content, BlockContent::List { kind: ListType::Numbered, text, .. } if text.plain == "Child")