Files
Docwell/Server/ycrdt-wasm/src/lib.rs
T
tajniak81andClaude Opus 5.5 e927653e4b
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / go (Server) (push) Failing after 8m12s
CI / go (Web-App) (push) Successful in 11m16s
CI / frontend (push) Failing after 7m33s
CI / desktop (ubuntu-latest) (push) Successful in 1h25m49s
CI / mobile (push) Failing after 5m48s
CI / docker (push) Successful in 41m19s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add edgeless mode: pages as a canvas with their text as a live note
Phase D of docs/AFFINE.md (ADR-14).

The canvas lives in the page's Y.Doc next to its text, in
ydoc.getMap("surface"): one Y.Map per element, each field its own entry so
concurrent edits merge. The page's text is a note on the canvas bound to
the same "default" fragment, so typing on the canvas is typing in the page.
Canvas edits have their own undo history through a Y.UndoManager.

- New package @docwell/canvas: viewport with pan, zoom and pinch;
  selection, marquee, snapping, resize and rotate; notes, text, shapes
  (plain or scribbled), connectors (straight, curve, elbow, with arrowheads
  and labels), pen and eraser, frames, groups, pictures, embeds and link
  cards, and mind maps (right, left or both sides; Tab, Enter, arrows).
  A style bar over the selection; the last style per kind is the default.
- Presentation through frames, stickers and templates, PNG and SVG export.
- Page/Edgeless switch in the header, ?mode= in page and share links, a
  per-page default (pages.default_mode) and a per-device default for new
  pages; share links show the canvas read-only.
- Server: yrs writes the canvas into the document JSON as "surface",
  adds its text to search, and writes it back on restores and templates.
- Phone: the bridge draws the canvas read-only (protocol 3) and the page
  screen has a canvas button.

Strings are translated into all five languages and the user guide covers
edgeless mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:20:20 +01:00

708 lines
27 KiB
Rust

// SPDX-License-Identifier: AGPL-3.0-or-later
//! yrs compiled to wasm32-wasip1 for the Go server (ADR-3), embedded by
//! Server/internal/ycrdt.
//!
//! ABI: the host allocates input with `dw_alloc`, calls an operation, and on
//! success (return >= 0) reads that many bytes from `dw_out_ptr()`. A negative
//! return `-(n + 1)` means an error whose n-byte message is in the output buffer. Several
//! updates are passed as one buffer of `[u32 little-endian length][bytes]` frames.
use std::cell::RefCell;
use serde_json::{Map, Value};
use yrs::types::text::{Diff, YChange};
use yrs::updates::decoder::Decode;
use yrs::types::{Attrs, ToJson};
use yrs::{
Any, Array, ArrayPrelim, Doc, GetString, In, Map as YMap, MapPrelim, MapRef, Out, ReadTxn, StateVector, Text, Transact,
TransactionMut, Update, WriteTxn, Xml, XmlElementPrelim, XmlFragment, XmlFragmentPrelim, XmlOut, XmlTextPrelim,
};
/// Tiptap's Collaboration extension stores the document in this fragment.
const FRAGMENT: &str = "default";
/// Database blocks keep their records in this map, keyed by the node's id (ADR-13).
const BLOCKS: &str = "blocks";
/// The edgeless canvas keeps its elements in this map, keyed by element id (ADR-14).
const SURFACE: &str = "surface";
thread_local! {
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
fn finish(result: Result<Vec<u8>, String>) -> i32 {
OUT.with(|out| {
let mut out = out.borrow_mut();
match result {
Ok(bytes) => {
*out = bytes;
out.len() as i32
}
Err(msg) => {
*out = msg.into_bytes();
-(out.len() as i32) - 1
}
}
})
}
unsafe fn input<'a>(ptr: *const u8, len: u32) -> &'a [u8] {
if len == 0 {
&[]
} else {
std::slice::from_raw_parts(ptr, len as usize)
}
}
fn frames(mut buf: &[u8]) -> Result<Vec<&[u8]>, String> {
let mut out = Vec::new();
while !buf.is_empty() {
if buf.len() < 4 {
return Err("truncated frame header".into());
}
let n = u32::from_le_bytes(buf[..4].try_into().unwrap()) as usize;
buf = &buf[4..];
if buf.len() < n {
return Err("truncated frame".into());
}
out.push(&buf[..n]);
buf = &buf[n..];
}
Ok(out)
}
fn load(updates: &[&[u8]]) -> Result<Doc, String> {
let doc = Doc::new();
{
let mut txn = doc.transact_mut();
for u in updates {
let update = Update::decode_v1(u).map_err(|e| e.to_string())?;
txn.apply_update(update).map_err(|e| e.to_string())?;
}
}
Ok(doc)
}
#[no_mangle]
pub extern "C" fn dw_alloc(len: u32) -> *mut u8 {
let mut buf = Vec::<u8>::with_capacity(len as usize);
let ptr = buf.as_mut_ptr();
std::mem::forget(buf);
ptr
}
#[no_mangle]
pub unsafe extern "C" fn dw_free(ptr: *mut u8, len: u32) {
drop(Vec::from_raw_parts(ptr, 0, len as usize));
}
#[no_mangle]
pub extern "C" fn dw_out_ptr() -> *const u8 {
OUT.with(|out| out.borrow().as_ptr())
}
/// Merges framed updates into one without building a document (cheap, keeps tombstones).
#[no_mangle]
pub unsafe extern "C" fn dw_merge(ptr: *const u8, len: u32) -> i32 {
finish(frames(input(ptr, len)).and_then(|f| yrs::merge_updates_v1(f).map_err(|e| e.to_string())))
}
/// Applies framed updates to a document and re-encodes its full state (garbage-collects deleted content).
#[no_mangle]
pub unsafe extern "C" fn dw_compact(ptr: *const u8, len: u32) -> i32 {
finish(frames(input(ptr, len)).and_then(|f| {
let doc = load(&f)?;
let txn = doc.transact();
Ok(txn.encode_state_as_update_v1(&StateVector::default()))
}))
}
/// Encodes the state vector of an update.
#[no_mangle]
pub unsafe extern "C" fn dw_state_vector(ptr: *const u8, len: u32) -> i32 {
finish(yrs::encode_state_vector_from_update_v1(input(ptr, len)).map_err(|e| e.to_string()))
}
/// Returns the part of an update that a peer with the given state vector is missing.
#[no_mangle]
pub unsafe extern "C" fn dw_diff(ptr: *const u8, len: u32, sv_ptr: *const u8, sv_len: u32) -> i32 {
finish(yrs::diff_updates_v1(input(ptr, len), input(sv_ptr, sv_len)).map_err(|e| e.to_string()))
}
/// Converts framed updates to ProseMirror JSON, matching y-prosemirror's `yXmlFragmentToProsemirrorJSON`.
#[no_mangle]
pub unsafe extern "C" fn dw_to_json(ptr: *const u8, len: u32) -> i32 {
finish(frames(input(ptr, len)).and_then(|f| {
let doc = load(&f)?;
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
let txn = doc.transact();
let content: Vec<Value> = fragment.children(&txn).flat_map(|n| node_json(&txn, n)).collect();
let mut root = Map::new();
root.insert("type".into(), "doc".into());
root.insert("content".into(), content.into());
if let Some(surface) = surface_json(&txn) {
root.insert("surface".into(), surface);
}
serde_json::to_vec(&Value::Object(root)).map_err(|e| e.to_string())
}))
}
/// Extracts plain text for search: one line per block.
#[no_mangle]
pub unsafe extern "C" fn dw_to_text(ptr: *const u8, len: u32) -> i32 {
finish(frames(input(ptr, len)).and_then(|f| {
let doc = load(&f)?;
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
let txn = doc.transact();
let mut text = String::new();
for node in fragment.children(&txn) {
node_text(&txn, node, &mut text);
text.push('\n');
}
surface_text(&txn, &mut text);
Ok(text.into_bytes())
}))
}
/// Replaces the document in the framed updates with ProseMirror JSON (input 2)
/// and returns the change as one incremental update, written the way
/// y-prosemirror's `prosemirrorToYXmlFragment` would.
#[no_mangle]
pub unsafe extern "C" fn dw_replace(ptr: *const u8, len: u32, json_ptr: *const u8, json_len: u32) -> i32 {
finish(frames(input(ptr, len)).and_then(|f| {
let root: Value = serde_json::from_slice(input(json_ptr, json_len)).map_err(|e| e.to_string())?;
if root.get("type").and_then(Value::as_str) != Some("doc") {
return Err("not a ProseMirror doc".into());
}
let content = match root.get("content") {
Some(Value::Array(c)) => c.as_slice(),
_ => &[],
};
let doc = load(&f)?;
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
let before = doc.transact().state_vector();
{
let mut txn = doc.transact_mut();
let n = fragment.len(&txn);
fragment.remove_range(&mut txn, 0, n);
fill(&mut txn, &fragment, content, 0)?;
// A document without "surface" leaves the canvas as it is (older versions had none).
if let Some(Value::Object(surface)) = root.get("surface") {
write_surface(&mut txn, surface)?;
}
}
let txn = doc.transact();
Ok(txn.encode_state_as_update_v1(&before))
}))
}
/// Appends ProseMirror nodes to parent. Runs of text nodes become one XmlText
/// whose formatting attributes are the marks, as in y-prosemirror.
fn fill<P: XmlFragment>(txn: &mut TransactionMut, parent: &P, nodes: &[Value], depth: u32) -> Result<(), String> {
if depth > 200 {
return Err("document is nested too deeply".into());
}
let node_type = |n: &Value| n.get("type").and_then(Value::as_str).map(str::to_owned);
let mut i = 0;
while i < nodes.len() {
let ty = node_type(&nodes[i]).ok_or("node without a type")?;
let index = parent.len(txn);
if ty == "text" {
let text = parent.insert(txn, index, XmlTextPrelim::new(""));
while i < nodes.len() && node_type(&nodes[i]).as_deref() == Some("text") {
let chunk = nodes[i].get("text").and_then(Value::as_str).unwrap_or("");
let mut attrs = Attrs::new();
if let Some(Value::Array(marks)) = nodes[i].get("marks") {
for mark in marks {
let name = mark.get("type").and_then(Value::as_str).ok_or("mark without a type")?;
let value = mark.get("attrs").cloned().unwrap_or_else(|| Value::Object(Map::new()));
attrs.insert(name.into(), json_any(value)?);
}
}
let at = text.len(txn);
text.insert_with_attributes(txn, at, chunk, attrs);
i += 1;
}
continue;
}
let el = parent.insert(txn, index, XmlElementPrelim::empty(ty.as_str()));
if let Some(Value::Object(attrs)) = nodes[i].get("attrs") {
for (key, value) in attrs {
// y-prosemirror leaves null attributes out; a database's data goes to its map.
if !value.is_null() && !(ty == "database" && key == "data") {
el.insert_attribute(txn, key.as_str(), json_any(value.clone())?);
}
}
if ty == "database" {
if let (Some(Value::String(id)), Some(data @ Value::Object(_))) = (attrs.get("id"), attrs.get("data")) {
if !id.is_empty() {
write_database(txn, id, data, depth)?;
}
}
}
}
if let Some(Value::Array(children)) = nodes[i].get("content") {
fill(txn, &el, children, depth + 1)?;
}
i += 1;
}
Ok(())
}
fn json_any(value: Value) -> Result<Any, String> {
serde_json::from_value(value).map_err(|e| e.to_string())
}
fn node_json<T: ReadTxn>(txn: &T, node: XmlOut) -> Vec<Value> {
match node {
XmlOut::Text(t) => t
.diff(txn, YChange::identity)
.into_iter()
.map(|d| text_json(txn, d))
.collect(),
XmlOut::Element(e) => {
let mut obj = Map::new();
obj.insert("type".into(), e.tag().to_string().into());
let attrs: Map<String, Value> =
e.attributes(txn).map(|(k, v)| (k.to_string(), out_json(txn, v))).collect();
let mut attrs = attrs;
if e.tag().as_ref() == "database" {
if let Some(data) = attrs.get("id").and_then(Value::as_str).and_then(|id| database_json(txn, id)) {
attrs.insert("data".into(), data);
}
}
if !attrs.is_empty() {
obj.insert("attrs".into(), attrs.into());
}
// y-prosemirror writes `content` whenever there are children, even if they are empty text.
if e.first_child().is_some() {
let content: Vec<Value> = e.children(txn).flat_map(|n| node_json(txn, n)).collect();
obj.insert("content".into(), content.into());
}
vec![Value::Object(obj)]
}
XmlOut::Fragment(f) => f.children(txn).flat_map(|n| node_json(txn, n)).collect(),
}
}
fn text_json<T: ReadTxn>(txn: &T, d: Diff<YChange>) -> Value {
let mut obj = Map::new();
obj.insert("type".into(), "text".into());
obj.insert("text".into(), out_json(txn, d.insert));
if let Some(attrs) = d.attributes {
let marks: Vec<Value> = attrs
.iter()
.map(|(name, value)| {
let mut mark = Map::new();
mark.insert("type".into(), name.to_string().into());
// y-prosemirror always writes attrs, even when empty.
let attrs = match any_json(value) {
Value::Object(m) => Value::Object(m),
_ => Value::Object(Map::new()),
};
mark.insert("attrs".into(), attrs);
Value::Object(mark)
})
.collect();
obj.insert("marks".into(), marks.into());
}
Value::Object(obj)
}
fn node_text<T: ReadTxn>(txn: &T, node: XmlOut, buf: &mut String) {
match node {
// get_string would wrap formatted runs in tags like <bold>; search wants plain text.
XmlOut::Text(t) => {
for d in t.diff(txn, YChange::identity) {
match d.insert {
Out::Any(Any::String(s)) => buf.push_str(&s),
other => buf.push_str(&other.to_string(txn)),
}
}
}
XmlOut::Element(e) if e.tag().as_ref() == "database" => {
if let Some(data) = e.get_attribute(txn, "id").and_then(|id| database_json(txn, &id.to_string(txn))) {
buf.push_str(&database_text(&data));
}
}
XmlOut::Element(e) => {
for (i, child) in e.children(txn).enumerate() {
if i > 0 && matches!(child, XmlOut::Element(_)) {
buf.push('\n');
}
node_text(txn, child, buf);
}
}
XmlOut::Fragment(f) => f.children(txn).for_each(|c| node_text(txn, c, buf)),
}
}
fn out_json<T: ReadTxn>(txn: &T, out: Out) -> Value {
match out {
Out::Any(a) => any_json(&a),
Out::YXmlText(t) => t.get_string(txn).into(),
other => other.to_string(txn).into(),
}
}
fn any_json(any: &Any) -> Value {
match any {
Any::Null | Any::Undefined => Value::Null,
Any::Bool(b) => (*b).into(),
Any::Number(yrs::Number::Int(i)) => (*i).into(),
Any::Number(yrs::Number::Float(f)) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number),
Any::String(s) => s.to_string().into(),
Any::Buffer(b) => b.iter().copied().map(Value::from).collect(),
Any::Array(a) => a.iter().map(any_json).collect(),
Any::Map(m) => Value::Object(m.iter().map(|(k, v)| (k.clone(), any_json(v))).collect()),
}
}
// ---- Databases (ADR-13) ----
/// A database's records as JSON: {title, columns, rows, views}, items in display
/// order (by their "pos"), row bodies as ProseMirror nodes in rows[].body.
fn database_json<T: ReadTxn>(txn: &T, id: &str) -> Option<Value> {
let blocks = txn.get_map(BLOCKS)?;
let Some(Out::YMap(db)) = blocks.get(txn, id) else {
return None;
};
let mut out = Map::new();
let title = match db.get(txn, "title") {
Some(Out::Any(Any::String(s))) => s.to_string(),
_ => String::new(),
};
out.insert("title".into(), title.into());
for key in ["columns", "views"] {
let items: Vec<Value> = ordered(txn, &db, key)
.into_iter()
.map(|m| {
let mut v = any_json(&m.to_json(txn));
if let Value::Object(o) = &mut v {
o.remove("pos");
}
v
})
.collect();
out.insert(key.into(), items.into());
}
let rows: Vec<Value> = ordered(txn, &db, "rows").into_iter().map(|m| row_json(txn, &m)).collect();
out.insert("rows".into(), rows.into());
Some(Value::Object(out))
}
fn row_json<T: ReadTxn>(txn: &T, row: &MapRef) -> Value {
let mut out = Map::new();
for (key, value) in row.iter(txn) {
match (key, value) {
("pos", _) => {}
("body", Out::YXmlFragment(f)) => {
let body: Vec<Value> = f.children(txn).flat_map(|n| node_json(txn, n)).collect();
if !body.is_empty() {
out.insert("body".into(), body.into());
}
}
(key, value) => {
out.insert(key.into(), any_json(&value.to_json(txn)));
}
}
}
Value::Object(out)
}
/// The maps of a database list in display order: by "pos", then by array index.
fn ordered<T: ReadTxn>(txn: &T, db: &MapRef, key: &str) -> Vec<MapRef> {
let Some(Out::YArray(list)) = db.get(txn, key) else {
return Vec::new();
};
let mut items: Vec<(f64, usize, MapRef)> = list
.iter(txn)
.enumerate()
.filter_map(|(i, item)| match item {
Out::YMap(m) => {
let pos = match m.get(txn, "pos") {
Some(Out::Any(a)) => any_json(&a).as_f64().unwrap_or(i as f64),
_ => i as f64,
};
Some((pos, i, m))
}
_ => None,
})
.collect();
items.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal).then(a.1.cmp(&b.1)));
items.into_iter().map(|(_, _, m)| m).collect()
}
/// Search text of a database: its title, then each row's cells and body, one row per line.
fn database_text(data: &Value) -> String {
let mut out = String::new();
if let Some(t) = data.get("title").and_then(Value::as_str) {
out.push_str(t);
out.push('\n');
}
let columns = data.get("columns").and_then(Value::as_array).cloned().unwrap_or_default();
for row in data.get("rows").and_then(Value::as_array).into_iter().flatten() {
let cells = row.get("cells");
let mut parts: Vec<String> = Vec::new();
for col in &columns {
let Some(id) = col.get("id").and_then(Value::as_str) else {
continue;
};
let ty = col.get("type").and_then(Value::as_str).unwrap_or("");
let Some(v) = cells.and_then(|c| c.get(id)) else {
continue;
};
let option = |oid: &Value| {
col.get("options")
.and_then(Value::as_array)
.and_then(|o| o.iter().find(|x| x.get("id") == Some(oid)))
.and_then(|o| o.get("name"))
.and_then(Value::as_str)
.map(str::to_owned)
};
match (ty, v) {
("select", v) => parts.extend(option(v)),
("multiSelect", Value::Array(ids)) => parts.extend(ids.iter().filter_map(option)),
("checkbox", _) => {}
(_, Value::String(s)) => parts.push(s.clone()),
(_, Value::Number(n)) => parts.push(n.to_string()),
(_, Value::Array(items)) => parts.extend(
items.iter().filter_map(|x| x.get("name").and_then(Value::as_str)).map(str::to_owned),
),
_ => {}
}
}
if let Some(body) = row.get("body") {
json_text(body, &mut parts);
}
out.push_str(&parts.join(" "));
out.push('\n');
}
out
}
fn json_text(v: &Value, parts: &mut Vec<String>) {
match v {
Value::Array(items) => items.iter().for_each(|x| json_text(x, parts)),
Value::Object(o) => {
if let Some(Value::String(t)) = o.get("text") {
parts.push(t.clone());
}
if let Some(c) = o.get("content") {
json_text(c, parts);
}
}
_ => {}
}
}
/// One item of a database list (a column, row or view) as a map prelim.
fn item_prelim(o: &Map<String, Value>, row: bool, pos: usize) -> Result<MapPrelim, String> {
let mut fields: Vec<(String, In)> = Vec::new();
for (k, v) in o {
if v.is_null() || k == "pos" || k == "body" || k == "hasBody" {
continue;
}
if row && k == "cells" {
let mut cells: Vec<(String, In)> = Vec::new();
if let Value::Object(c) = v {
for (ck, cv) in c {
if !cv.is_null() {
cells.push((ck.clone(), In::Any(json_any(cv.clone())?)));
}
}
}
fields.push((k.clone(), In::Map(MapPrelim::from_iter(cells))));
} else {
fields.push((k.clone(), In::Any(json_any(v.clone())?)));
}
}
if row && !o.contains_key("cells") {
fields.push(("cells".into(), In::Map(MapPrelim::default())));
}
fields.push(("pos".into(), In::Any(Any::from(pos as f64))));
Ok(MapPrelim::from_iter(fields))
}
/// Writes a database from JSON (a node's attrs.data) into the blocks map under id,
/// replacing what was there, the way the editor's store.ts writes it.
fn write_database(txn: &mut TransactionMut, id: &str, data: &Value, depth: u32) -> Result<(), String> {
let objects = |key: &str| -> Vec<Map<String, Value>> {
data.get(key)
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|v| v.as_object().cloned())
.collect()
};
let list = |key: &str| -> Result<ArrayPrelim, String> {
let mut out = Vec::new();
for (i, o) in objects(key).iter().enumerate() {
out.push(In::Map(item_prelim(o, key == "rows", i)?));
}
Ok(ArrayPrelim::from_iter(out))
};
let title = data.get("title").and_then(Value::as_str).unwrap_or("").to_owned();
let prelim = MapPrelim::from_iter([
("title".to_owned(), In::Any(Any::from(title))),
("columns".to_owned(), In::Array(list("columns")?)),
("rows".to_owned(), In::Array(list("rows")?)),
("views".to_owned(), In::Array(list("views")?)),
]);
let blocks = txn.get_or_insert_map(BLOCKS);
let db = blocks.insert(txn, id, prelim);
// Bodies go in once their rows are part of the document.
let Some(Out::YArray(rows)) = db.get(txn, "rows") else {
return Ok(());
};
for (i, o) in objects("rows").iter().enumerate() {
let Some(Value::Array(body)) = o.get("body") else {
continue;
};
if body.is_empty() {
continue;
}
if let Some(Out::YMap(row)) = rows.get(txn, i as u32) {
let fragment = row.insert(txn, "body", XmlFragmentPrelim::default());
fill(txn, &fragment, body, depth + 1)?;
}
}
Ok(())
}
// ---- The edgeless canvas (ADR-14) ----
/// The canvas as {elements: [...]}: each element's fields with its id, a note's
/// body as ProseMirror nodes, a mind map's nodes as an object. None when the
/// page never had a canvas; an empty list when everything was deleted.
fn surface_json<T: ReadTxn>(txn: &T) -> Option<Value> {
let surface = txn.get_map(SURFACE)?;
let mut elements: Vec<(bool, f64, String, Value)> = Vec::new();
for (id, value) in surface.iter(txn) {
let Out::YMap(el) = value else { continue };
let mut out = Map::new();
out.insert("id".into(), id.into());
for (key, v) in el.iter(txn) {
match (key, v) {
("body", Out::YXmlFragment(f)) => {
let body: Vec<Value> = f.children(txn).flat_map(|n| node_json(txn, n)).collect();
out.insert("body".into(), body.into());
}
(key, v @ Out::YMap(_)) => {
out.insert(key.into(), any_json(&v.to_json(txn)));
}
(key, Out::Any(a)) => {
out.insert(key.into(), any_json(&a));
}
_ => {}
}
}
let frame = out.get("type").and_then(Value::as_str) == Some("frame");
let index = out.get("index").and_then(Value::as_f64).unwrap_or(0.0);
elements.push((!frame, index, id.to_owned(), Value::Object(out)));
}
// Drawing order: frames first, then by index, then by id.
elements.sort_by(|a, b| {
a.0.cmp(&b.0)
.then(a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
.then(a.2.cmp(&b.2))
});
let mut root = Map::new();
root.insert("elements".into(), elements.into_iter().map(|e| e.3).collect::<Vec<_>>().into());
Some(Value::Object(root))
}
/// The canvas's words for search: shape and text boxes, frame titles,
/// connector labels, note bodies and mind map nodes, one element per line.
fn surface_text<T: ReadTxn>(txn: &T, buf: &mut String) {
let Some(surface) = txn.get_map(SURFACE) else { return };
for (_, value) in surface.iter(txn) {
let Out::YMap(el) = value else { continue };
let mut line = String::new();
for key in ["text", "title", "label"] {
if let Some(Out::Any(Any::String(s))) = el.get(txn, key) {
if !s.is_empty() {
line.push_str(&s);
line.push(' ');
}
}
}
if let Some(Out::YXmlFragment(f)) = el.get(txn, "body") {
for node in f.children(txn) {
node_text(txn, node, &mut line);
line.push('\n');
}
}
if let Some(nodes @ Out::YMap(_)) = el.get(txn, "nodes") {
if let Value::Object(m) = any_json(&nodes.to_json(txn)) {
for n in m.values() {
if let Some(t) = n.get("text").and_then(Value::as_str) {
line.push_str(t);
line.push(' ');
}
}
}
}
let line = line.trim();
if !line.is_empty() {
buf.push_str(line);
buf.push('\n');
}
}
}
/// Writes the canvas from JSON ({elements: [...]}), replacing what was there,
/// the way the canvas's store.ts writes it.
fn write_surface(txn: &mut TransactionMut, surface: &Map<String, Value>) -> Result<(), String> {
let map = txn.get_or_insert_map(SURFACE);
let keys: Vec<String> = map.keys(txn).map(str::to_owned).collect();
for k in keys {
map.remove(txn, &k);
}
let elements = surface.get("elements").and_then(Value::as_array).cloned().unwrap_or_default();
for el in elements {
let Value::Object(o) = el else { continue };
let Some(id) = o.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned) else {
continue;
};
let mut fields: Vec<(String, In)> = Vec::new();
for (k, v) in &o {
if v.is_null() || k == "id" || k == "body" {
continue;
}
if k == "nodes" {
let mut nodes: Vec<(String, In)> = Vec::new();
if let Value::Object(m) = v {
for (nid, n) in m {
let Value::Object(n) = n else { continue };
let mut entries: Vec<(String, In)> = Vec::new();
for (nk, nv) in n {
if !nv.is_null() {
entries.push((nk.clone(), In::Any(json_any(nv.clone())?)));
}
}
nodes.push((nid.clone(), In::Map(MapPrelim::from_iter(entries))));
}
}
fields.push((k.clone(), In::Map(MapPrelim::from_iter(nodes))));
continue;
}
fields.push((k.clone(), In::Any(json_any(v.clone())?)));
}
let item = map.insert(txn, id.as_str(), MapPrelim::from_iter(fields));
let is_note = o.get("type").and_then(Value::as_str) == Some("note");
let is_page = o.get("page").and_then(Value::as_bool) == Some(true);
if is_note && !is_page {
let body = match o.get("body") {
Some(Value::Array(b)) if !b.is_empty() => b.clone(),
_ => vec![serde_json::json!({ "type": "paragraph" })],
};
let fragment = item.insert(txn, "body", XmlFragmentPrelim::default());
fill(txn, &fragment, &body, 1)?;
}
}
Ok(())
}