lexical_ui/
serialized_export.rs1use crate::json::{Object, Value};
4use crate::node::LexicalNode;
5use std::cell::Cell;
6
7thread_local! {
8 static COMPACT_EXPORT: Cell<bool> = const { Cell::new(false) };
9}
10
11pub fn with_compact_export<R>(compact: bool, f: impl FnOnce() -> R) -> R {
14 struct Restore(bool);
15 impl Drop for Restore {
16 fn drop(&mut self) {
17 COMPACT_EXPORT.with(|c| c.set(self.0));
18 }
19 }
20 let _restore = Restore(COMPACT_EXPORT.with(|c| c.replace(compact)));
21 f()
22}
23
24pub fn is_compact_export() -> bool {
27 COMPACT_EXPORT.with(Cell::get)
28}
29
30pub fn export_node_json(node: &dyn LexicalNode) -> Object {
34 let serialized_node = crate::node_state::export_json_with_state(node, is_compact_export());
35 if serialized_node.get("type").and_then(Value::as_str) != Some(node.get_type()) {
36 panic!(
37 "LexicalNode: Node {} does not match the serialized type. Check if .exportJSON() is implemented and it is returning the correct type.",
38 node.get_type()
39 );
40 }
41 if node.element().is_some()
42 && serialized_node
43 .get("children")
44 .and_then(Value::as_array)
45 .is_none()
46 {
47 panic!(
48 "LexicalNode: Node {} is an element but .exportJSON() does not have a children array.",
49 node.get_type()
50 );
51 }
52 serialized_node
53}