use base64::Engine as _;
use onetaskgraph_plugin_api::{MetadataRecord, NativeId, StoredHeading};
use serde_json::Value;
use yrs::types::xml::XmlOut;
use yrs::updates::decoder::Decode;
use yrs::{Any, Doc, Out, Text, Transact, Update, Xml, XmlFragment};
const FRAGMENT: &str = "prosemirror";
#[must_use]
pub fn decoded(state: &str) -> Option<Vec<StoredHeading>> {
let bytes = base64::engine::general_purpose::STANDARD
.decode(state)
.ok()?;
let update = Update::decode_v1(&bytes).ok()?;
let doc = Doc::new();
let fragment = doc.get_or_insert_xml_fragment(FRAGMENT);
doc.transact_mut().apply_update(update).ok()?;
let txn = doc.transact();
let mut headings = Vec::new();
for node in fragment.successors(&txn) {
let XmlOut::Element(element) = node else {
continue;
};
if element.tag().as_ref() != "heading" {
continue;
}
let Some(Out::Any(Any::String(id))) = element.get_attribute(&txn, "id") else {
continue;
};
if !id.chars().all(|c| c.is_ascii_hexdigit() || c == '-')
|| id.chars().filter(char::is_ascii_hexdigit).count() < 8
{
continue;
}
let mut text = String::new();
for inner in element.successors(&txn) {
if let XmlOut::Text(run) = inner {
for chunk in run.diff(&txn, |_| ()) {
if let Out::Any(Any::String(piece)) = chunk.insert {
text.push_str(&piece);
}
}
}
}
headings.push(StoredHeading {
text: text.trim().to_owned(),
id: id.to_string(),
});
}
Some(headings)
}
#[must_use]
pub fn carried(data: &Value) -> Vec<Carried> {
let mut found = Vec::new();
walk(data, &mut found);
found
}
pub type Carried = ((MetadataRecord, NativeId), Option<Vec<StoredHeading>>);
fn walk(value: &Value, found: &mut Vec<Carried>) {
match value {
Value::Object(object) => {
if let Some(Value::String(id)) = object.get("id") {
let held = match (object.get("descriptionState"), object.get("contentState")) {
(Some(state), _) => Some((MetadataRecord::Task, state)),
(_, Some(state)) if object.contains_key("name") => {
Some((MetadataRecord::Project, state))
}
(_, Some(state)) => Some((MetadataRecord::Document, state)),
_ => None,
};
if let Some((record, state)) = held {
found.push((
(record, NativeId(id.clone())),
state.as_str().and_then(decoded),
));
}
}
for inner in object.values() {
walk(inner, found);
}
}
Value::Array(items) => {
for inner in items {
walk(inner, found);
}
}
_ => {}
}
}