Skip to main content

lexical_ui/
serialized_export.rs

1//! `LexicalSerializedExport.ts`: which JSON form an export writes.
2
3use 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
11/// `$withCompactExport(compact, f)`: runs `f` writing the compact form (or,
12/// with `false`, the legacy form) for any export it performs.
13pub 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
24/// `$isCompactExport()`: whether the export walk in progress writes the
25/// compact form.
26pub fn is_compact_export() -> bool {
27    COMPACT_EXPORT.with(Cell::get)
28}
29
30/// `$exportNodeJSON(node)`: one node's JSON in the active form, checked as
31/// every export walk checks it. A failed check is a bug in the node's
32/// implementation, so it panics.
33pub 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}