Skip to main content

lexical_ui/
node_state.rs

1//! `LexicalNodeState.ts`: NodeState, the ad-hoc data an app keeps on any
2//! node beside the properties of its class. A [`StateConfig`] made with
3//! [`create_state`] names a key and how its value parses from JSON, writes
4//! back and compares; [`get_state`] and [`set_state`] read and write it on a
5//! node, and the node's JSON carries the values that aren't their default
6//! under `"$"` (or at the top level, for a state its class declares flat).
7//! Keys no config has read stay as their JSON, and are written back as they
8//! came.
9//!
10//! As in JS, a node version shares its NodeState with the version it was
11//! cloned from until one of them writes it, which copies it (parsing the
12//! JSON of the keys a config has read on its node type). JS tells the
13//! version that owns a NodeState by object identity; here a node version is
14//! its key and the editor state it was made writable in.
15//!
16//! A config's value may be described by a schema (`createState(key,
17//! {parse: schema})`, [`StateValueConfig::from_schema`]), which then gives
18//! its equality and default, and a set-valued one (`arraySetValue`) puts a
19//! value written with `$setState` in its canonical form.
20//!
21//! Not ported: `$getStateChange`'s use in `updateDOM`, which comes with the
22//! DOM, and the `Object.prototype` check on flat keys (rust/PARITY.md).
23
24use crate::LexicalError;
25use crate::error::invariant;
26use crate::json::{Object, Value, array_index};
27use crate::lexical_utils::{get_writable, mutate};
28use crate::node::{LexicalNode, NodeKey, NodeRef};
29use crate::schema::{SchemaValue, SerializationSchema, SerializationSchemaMeta, is_schema_equal};
30use crate::updates::{error_on_read_only, get_active_editor_state, get_registry_editor};
31use std::any::Any;
32use std::cell::RefCell;
33use std::collections::{HashMap, HashSet};
34use std::fmt;
35use std::rc::Rc;
36
37/// A value a state can hold without saying how it serializes and compares:
38/// one that JSON writes as it is (JS's default `unparse`), compared with
39/// `Object.is` (JS's default `isEqual`).
40pub trait StateValue: Clone + 'static {
41    /// The value as JSON.
42    fn to_json(&self) -> Value;
43    /// `Object.is(self, other)`.
44    fn object_is(&self, other: &Self) -> bool;
45}
46
47impl StateValue for f64 {
48    fn to_json(&self) -> Value {
49        Value::Number(*self)
50    }
51    fn object_is(&self, other: &Self) -> bool {
52        (self.is_nan() && other.is_nan()) || self.to_bits() == other.to_bits()
53    }
54}
55
56impl StateValue for bool {
57    fn to_json(&self) -> Value {
58        Value::Bool(*self)
59    }
60    fn object_is(&self, other: &Self) -> bool {
61        self == other
62    }
63}
64
65impl StateValue for String {
66    fn to_json(&self) -> Value {
67        Value::String(self.clone())
68    }
69    fn object_is(&self, other: &Self) -> bool {
70        self == other
71    }
72}
73
74/// `None` is `null`.
75impl<T: StateValue> StateValue for Option<T> {
76    fn to_json(&self) -> Value {
77        self.as_ref().map_or(Value::Null, StateValue::to_json)
78    }
79    fn object_is(&self, other: &Self) -> bool {
80        match (self, other) {
81            (None, None) => true,
82            (Some(a), Some(b)) => a.object_is(b),
83            _ => false,
84        }
85    }
86}
87
88/// A state's `isEqual`: whether two of its values are the same value.
89pub type StateIsEqual<V> = Rc<dyn Fn(&V, &V) -> bool>;
90
91/// `StateValueConfig`: how a state's value parses from JSON (`parse`, which
92/// gives the default for `undefined`), writes back (`unparse`) and compares
93/// (`isEqual`), whether `$copyNode` resets it (`resetOnCopyNode`), whether
94/// the node's own code recomputes it (`derived`, `@experimental`), and the
95/// schema `parse` was given as (`StateConfig.schema`), when it was one.
96pub struct StateValueConfig<V> {
97    pub parse: Rc<dyn Fn(&Value) -> V>,
98    pub unparse: Rc<dyn Fn(&V) -> Value>,
99    pub is_equal: StateIsEqual<V>,
100    pub reset_on_copy_node: bool,
101    pub derived: bool,
102    pub schema: Option<SerializationSchema>,
103}
104
105impl<V> Clone for StateValueConfig<V> {
106    fn clone(&self) -> Self {
107        Self {
108            parse: self.parse.clone(),
109            unparse: self.unparse.clone(),
110            is_equal: self.is_equal.clone(),
111            reset_on_copy_node: self.reset_on_copy_node,
112            derived: self.derived,
113            schema: self.schema.clone(),
114        }
115    }
116}
117
118impl<V: StateValue> StateValueConfig<V> {
119    /// `{parse}`, with JS's defaults for the rest: the value as JSON,
120    /// `Object.is`, and kept by a copy.
121    pub fn new(parse: impl Fn(&Value) -> V + 'static) -> Self {
122        Self {
123            parse: Rc::new(parse),
124            unparse: Rc::new(StateValue::to_json),
125            is_equal: Rc::new(StateValue::object_is),
126            reset_on_copy_node: false,
127            derived: false,
128            schema: None,
129        }
130    }
131}
132
133impl<V: SchemaValue + 'static> StateValueConfig<V> {
134    /// `{parse: schema}`: a state whose value `schema` describes, which also
135    /// gives it its equality (`isSchemaEqual`) and default, written back as
136    /// the value it parsed to. `V` holds the values the schema parses to
137    /// (`Value` holds any).
138    pub fn from_schema(schema: SerializationSchema) -> Self {
139        let parse_schema = schema.clone();
140        let equal_schema = schema.clone();
141        Self {
142            parse: Rc::new(move |value| {
143                V::from_schema_value(&parse_schema.parse(value))
144                    .expect("a value of the type the schema parses to")
145            }),
146            unparse: Rc::new(V::to_schema_value),
147            is_equal: Rc::new(move |a, b| {
148                is_schema_equal(&equal_schema, &a.to_schema_value(), &b.to_schema_value())
149            }),
150            reset_on_copy_node: false,
151            derived: false,
152            schema: Some(schema),
153        }
154    }
155}
156
157struct StateConfigInner<V> {
158    key: String,
159    config: StateValueConfig<V>,
160    /// `defaultValue`, `parse(undefined)`, computed once: every node without
161    /// a value of its own reads this one.
162    default_value: Rc<dyn Any>,
163}
164
165/// `StateConfig`: what [`create_state`] returns, for [`get_state`] and
166/// [`set_state`]. Clones are the same config: nodes tell configs apart by
167/// identity, as JS does.
168pub struct StateConfig<V>(Rc<StateConfigInner<V>>);
169
170impl<V> Clone for StateConfig<V> {
171    fn clone(&self) -> Self {
172        Self(self.0.clone())
173    }
174}
175
176impl<V> fmt::Debug for StateConfig<V> {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        write!(f, "StateConfig({:?})", self.0.key)
179    }
180}
181
182impl<V: Clone + 'static> StateConfig<V> {
183    /// `key`: the key the state serializes under.
184    pub fn key(&self) -> &str {
185        &self.0.key
186    }
187
188    /// `parse(value)`; `Value::Undefined` gives the default.
189    pub fn parse(&self, value: &Value) -> V {
190        (self.0.config.parse)(value)
191    }
192
193    /// `unparse(value)`.
194    pub fn unparse(&self, value: &V) -> Value {
195        (self.0.config.unparse)(value)
196    }
197
198    /// `isEqual(a, b)`.
199    pub fn is_equal(&self, a: &V, b: &V) -> bool {
200        (self.0.config.is_equal)(a, b)
201    }
202
203    /// `defaultValue`.
204    pub fn default_value(&self) -> V {
205        downcast::<V>(&self.0.default_value)
206    }
207
208    /// `resetOnCopyNode`.
209    pub fn reset_on_copy_node(&self) -> bool {
210        self.0.config.reset_on_copy_node
211    }
212
213    /// `derived` (`@experimental`).
214    pub fn derived(&self) -> bool {
215        self.0.config.derived
216    }
217
218    /// `schema`: the schema `parse` was given as, when it was one.
219    pub fn schema(&self) -> Option<SerializationSchema> {
220        self.0.config.schema.clone()
221    }
222
223    /// This config without its value type (`AnyStateConfig`).
224    pub fn erased(&self) -> AnyStateConfig {
225        AnyStateConfig(self.0.clone())
226    }
227}
228
229fn downcast<V: Clone + 'static>(value: &Rc<dyn Any>) -> V {
230    value
231        .downcast_ref::<V>()
232        .expect("a state value of its config's type")
233        .clone()
234}
235
236/// What a node's NodeState needs of a config whose value type it doesn't
237/// know.
238trait ErasedStateConfig {
239    fn key(&self) -> &str;
240    fn parse_any(&self, value: &Value) -> Rc<dyn Any>;
241    fn unparse_any(&self, value: &dyn Any) -> Value;
242    fn is_equal_any(&self, a: &dyn Any, b: &dyn Any) -> bool;
243    fn default_any(&self) -> Rc<dyn Any>;
244    fn reset_on_copy_node(&self) -> bool;
245    fn derived(&self) -> bool;
246    fn schema(&self) -> Option<SerializationSchema>;
247}
248
249impl<V: 'static> ErasedStateConfig for StateConfigInner<V> {
250    fn key(&self) -> &str {
251        &self.key
252    }
253    fn parse_any(&self, value: &Value) -> Rc<dyn Any> {
254        Rc::new((self.config.parse)(value))
255    }
256    fn unparse_any(&self, value: &dyn Any) -> Value {
257        (self.config.unparse)(
258            value
259                .downcast_ref::<V>()
260                .expect("a value of the config's type"),
261        )
262    }
263    fn is_equal_any(&self, a: &dyn Any, b: &dyn Any) -> bool {
264        match (a.downcast_ref::<V>(), b.downcast_ref::<V>()) {
265            (Some(a), Some(b)) => (self.config.is_equal)(a, b),
266            _ => false,
267        }
268    }
269    fn default_any(&self) -> Rc<dyn Any> {
270        self.default_value.clone()
271    }
272    fn reset_on_copy_node(&self) -> bool {
273        self.config.reset_on_copy_node
274    }
275    fn derived(&self) -> bool {
276        self.config.derived
277    }
278    fn schema(&self) -> Option<SerializationSchema> {
279        self.config.schema.clone()
280    }
281}
282
283/// `AnyStateConfig`: a [`StateConfig`] of any value type.
284#[derive(Clone)]
285pub struct AnyStateConfig(Rc<dyn ErasedStateConfig>);
286
287impl AnyStateConfig {
288    /// The config's key.
289    pub fn key(&self) -> &str {
290        self.0.key()
291    }
292
293    /// Whether `self` and `other` are the same config (`===`).
294    pub fn is(&self, other: &AnyStateConfig) -> bool {
295        std::ptr::addr_eq(Rc::as_ptr(&self.0), Rc::as_ptr(&other.0))
296    }
297
298    /// `derived` (`@experimental`).
299    pub fn derived(&self) -> bool {
300        self.0.derived()
301    }
302
303    /// `schema`.
304    pub fn schema(&self) -> Option<SerializationSchema> {
305        self.0.schema()
306    }
307
308    /// `canonicalValue(stateConfig, value)`: what `$setState` stores. A
309    /// set-valued state (`arraySetValue`) stores what its parse makes of the
310    /// value, so a value set directly is stored, read back and compared
311    /// like one loaded from JSON; any other state stores the value as
312    /// given.
313    fn canonical_value(&self, value: Rc<dyn Any>) -> Rc<dyn Any> {
314        match self.0.schema() {
315            Some(schema) if matches!(schema.meta(), SerializationSchemaMeta::Set { .. }) => {
316                self.0.parse_any(&self.0.unparse_any(&*value))
317            }
318            _ => value,
319        }
320    }
321
322    /// `isEqual(a, b)` of two values of the config's type.
323    pub(crate) fn is_equal_erased(&self, a: &dyn Any, b: &dyn Any) -> bool {
324        self.0.is_equal_any(a, b)
325    }
326}
327
328impl fmt::Debug for AnyStateConfig {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        write!(f, "AnyStateConfig({:?})", self.key())
331    }
332}
333
334/// `createState(key, {parse})`: a state with JS's default `unparse` and
335/// `isEqual` ([`StateValue`]).
336pub fn create_state<V: StateValue>(
337    key: &str,
338    parse: impl Fn(&Value) -> V + 'static,
339) -> StateConfig<V> {
340    create_state_with(key, StateValueConfig::new(parse))
341}
342
343/// `createState(key, valueConfig)`.
344pub fn create_state_with<V: 'static>(key: &str, config: StateValueConfig<V>) -> StateConfig<V> {
345    let default_value: Rc<dyn Any> = Rc::new((config.parse)(&Value::Undefined));
346    StateConfig(Rc::new(StateConfigInner {
347        key: key.to_owned(),
348        config,
349        default_value,
350    }))
351}
352
353/// `RequiredNodeStateConfig`: a state a node class declares in its
354/// `$config`'s `stateConfigs` ([`LexicalNode::state_configs`]), which its
355/// type knows before any node reads it; a `flat` one serializes at the top
356/// level of the node's JSON instead of under `"$"`.
357#[derive(Clone, Debug)]
358pub struct RequiredNodeStateConfig {
359    pub(crate) state_config: AnyStateConfig,
360    pub(crate) flat: bool,
361}
362
363impl RequiredNodeStateConfig {
364    /// `stateConfig` or `{stateConfig, flat}`.
365    pub fn new<V: Clone + 'static>(state_config: &StateConfig<V>, flat: bool) -> Self {
366        Self {
367            state_config: state_config.erased(),
368            flat,
369        }
370    }
371}
372
373/// `SharedNodeState`: the configs a node type knows in an editor, by key
374/// (`sharedConfigMap`), and the keys it serializes flat (`flatKeys`), shared
375/// by every node of the type.
376#[derive(Debug, Default)]
377pub(crate) struct SharedNodeState {
378    pub(crate) shared_config_map: RefCell<HashMap<String, AnyStateConfig>>,
379    flat_keys: Vec<String>,
380}
381
382/// `createSharedNodeState(nodeConfig)`.
383pub(crate) fn create_shared_node_state(configs: Vec<RequiredNodeStateConfig>) -> SharedNodeState {
384    let shared = SharedNodeState::default();
385    let mut flat_keys = Vec::new();
386    for required in configs {
387        let key = required.state_config.key().to_owned();
388        if required.flat && !flat_keys.contains(&key) {
389            flat_keys.push(key.clone());
390        }
391        shared
392            .shared_config_map
393            .borrow_mut()
394            .insert(key, required.state_config);
395    }
396    SharedNodeState {
397        flat_keys,
398        ..shared
399    }
400}
401
402/// `UNSAFE_STATE_KEYS`.
403const UNSAFE_STATE_KEYS: [&str; 3] = ["__proto__", "constructor", "prototype"];
404
405/// An `UnknownStateRecord`: JSON values by key, in a JS object's order. The
406/// values are shared, as JS shares the objects, so two records compare
407/// their objects and arrays by identity (`===`).
408#[derive(Clone, Debug, Default)]
409pub(crate) struct UnknownState(Vec<(String, Rc<Value>)>);
410
411impl UnknownState {
412    pub(crate) fn get(&self, key: &str) -> Option<&Rc<Value>> {
413        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
414    }
415
416    pub(crate) fn contains_key(&self, key: &str) -> bool {
417        self.get(key).is_some()
418    }
419
420    /// `record[key] = value`, keeping a JS object's key order.
421    fn insert(&mut self, key: &str, value: Rc<Value>) {
422        if let Some(entry) = self.0.iter_mut().find(|(k, _)| k == key) {
423            entry.1 = value;
424            return;
425        }
426        let at = match array_index(key) {
427            Some(index) => self
428                .0
429                .iter()
430                .position(|(k, _)| array_index(k).is_none_or(|i| i > index))
431                .unwrap_or(self.0.len()),
432            None => self.0.len(),
433        };
434        self.0.insert(at, (key.to_owned(), value));
435    }
436
437    fn remove(&mut self, key: &str) {
438        self.0.retain(|(k, _)| k != key);
439    }
440
441    pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, &Rc<Value>)> {
442        self.0.iter().map(|(k, v)| (k.as_str(), v))
443    }
444}
445
446/// `a === b` for two JSON values: objects and arrays by identity.
447pub(crate) fn json_strict_equals(a: Option<&Rc<Value>>, b: Option<&Rc<Value>>) -> bool {
448    let undefined = |v: Option<&Rc<Value>>| v.is_none_or(|v| v.is_undefined());
449    match (a, b) {
450        _ if undefined(a) && undefined(b) => true,
451        (Some(a), Some(b)) => match (&**a, &**b) {
452            (Value::Object(_), Value::Object(_)) | (Value::Array(_), Value::Array(_)) => {
453                Rc::ptr_eq(a, b)
454            }
455            (Value::Number(x), Value::Number(y)) => x == y,
456            (Value::Object(_) | Value::Array(_), _) | (_, Value::Object(_) | Value::Array(_)) => {
457                false
458            }
459            (x, y) => x == y,
460        },
461        _ => false,
462    }
463}
464
465/// A node version, as a NodeState knows the one it belongs to (JS's
466/// `state.node`): its key, and the id of the editor state it was made
467/// writable (or created) in.
468pub(crate) type NodeVersion = (NodeKey, u64);
469
470/// The version of `node` (this version of it).
471pub(crate) fn version_of(node: &dyn LexicalNode) -> NodeVersion {
472    let base = node.base();
473    (base.key.clone(), base.written_in)
474}
475
476/// `NodeState`: the state values of a node version.
477pub(crate) struct NodeState {
478    /// `node`: the version this state belongs to; another one copies it
479    /// before writing.
480    node: NodeVersion,
481    /// `knownState`: parsed values by config, in the order they came.
482    known_state: Vec<(AnyStateConfig, Rc<dyn Any>)>,
483    /// `unknownState`: values still as JSON.
484    pub(crate) unknown_state: Option<UnknownState>,
485    pub(crate) shared_node_state: Rc<SharedNodeState>,
486    /// `size`: the keys of both, counted once.
487    pub(crate) size: usize,
488}
489
490/// A node's NodeState, shared by the versions that haven't written it.
491pub(crate) type NodeStateRef = Rc<RefCell<NodeState>>;
492
493impl fmt::Debug for NodeState {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        f.debug_struct("NodeState")
496            .field("node", &self.node)
497            .field(
498                "known_state",
499                &self
500                    .known_state
501                    .iter()
502                    .map(|(c, _)| c.key())
503                    .collect::<Vec<_>>(),
504            )
505            .field("unknown_state", &self.unknown_state)
506            .field("size", &self.size)
507            .finish()
508    }
509}
510
511/// `computeSize(sharedConfigMap, unknownState, knownState)`.
512fn compute_size(
513    shared_config_map: &HashMap<String, AnyStateConfig>,
514    unknown_state: Option<&UnknownState>,
515    known_state: &[(AnyStateConfig, Rc<dyn Any>)],
516) -> usize {
517    let mut size = known_state.len();
518    for (k, _) in unknown_state.into_iter().flat_map(UnknownState::iter) {
519        let shared_config = shared_config_map.get(k);
520        if shared_config.is_none_or(|c| !known_state.iter().any(|(k, _)| k.is(c))) {
521            size += 1;
522        }
523    }
524    size
525}
526
527impl NodeState {
528    fn new(
529        node: NodeVersion,
530        shared_node_state: Rc<SharedNodeState>,
531        unknown_state: Option<UnknownState>,
532        known_state: Vec<(AnyStateConfig, Rc<dyn Any>)>,
533        size: Option<usize>,
534    ) -> Self {
535        let computed_size = compute_size(
536            &shared_node_state.shared_config_map.borrow(),
537            unknown_state.as_ref(),
538            &known_state,
539        );
540        // JS checks these in DEV builds.
541        debug_assert!(size.is_none_or(|s| s == computed_size));
542        Self {
543            node,
544            known_state,
545            unknown_state,
546            shared_node_state,
547            size: computed_size,
548        }
549    }
550
551    /// The known value of `config`, if any.
552    fn known(&self, config: &AnyStateConfig) -> Option<&Rc<dyn Any>> {
553        self.known_state
554            .iter()
555            .find(|(c, _)| c.is(config))
556            .map(|(_, v)| v)
557    }
558
559    fn has_known(&self, config: &AnyStateConfig) -> bool {
560        self.known(config).is_some()
561    }
562
563    /// `knownState.set(config, value)`.
564    fn set_known(&mut self, config: &AnyStateConfig, value: Rc<dyn Any>) {
565        match self.known_state.iter_mut().find(|(c, _)| c.is(config)) {
566            Some(entry) => entry.1 = value,
567            None => self.known_state.push((config.clone(), value)),
568        }
569    }
570
571    /// The keys of the known values, in their order.
572    pub(crate) fn known_entries(&self) -> Vec<(AnyStateConfig, Rc<dyn Any>)> {
573        self.known_state.clone()
574    }
575
576    /// `getValue(stateConfig)`: the known value, or the one parsed from the
577    /// JSON, which it keeps (without changing the order `toJSON` writes),
578    /// or the default.
579    pub(crate) fn get_value(&mut self, config: &AnyStateConfig) -> Rc<dyn Any> {
580        if let Some(known) = self.known(config) {
581            return known.clone();
582        }
583        self.shared_node_state
584            .shared_config_map
585            .borrow_mut()
586            .insert(config.key().to_owned(), config.clone());
587        let mut parsed = config.0.default_any();
588        if let Some(json_value) = self
589            .unknown_state
590            .as_ref()
591            .and_then(|u| u.get(config.key()))
592            .cloned()
593        {
594            if !json_value.is_undefined() {
595                parsed = config.0.parse_any(&json_value);
596            }
597            self.set_known(config, parsed.clone());
598        }
599        parsed
600    }
601
602    /// `toJSON()`: the values that aren't their default, the flat keys of
603    /// the node's type at the top level and the rest under `"$"`.
604    pub(crate) fn to_json(&self) -> Object {
605        let mut state: Object = self
606            .unknown_state
607            .iter()
608            .flat_map(UnknownState::iter)
609            .map(|(k, v)| (k, (**v).clone()))
610            .collect();
611        let mut flat_state = Object::new();
612        for (config, v) in &self.known_state {
613            if config.0.is_equal_any(&**v, &*config.0.default_any()) {
614                state.remove(config.key());
615            } else {
616                state.insert(config.key(), config.0.unparse_any(&**v));
617            }
618        }
619        for key in &self.shared_node_state.flat_keys {
620            if let Some(value) = state.remove(key) {
621                flat_state.insert(key.as_str(), value);
622            }
623        }
624        if !state.is_empty() {
625            flat_state.insert(crate::constants::NODE_STATE_KEY, Value::Object(state));
626        }
627        flat_state
628    }
629
630    /// `getWritable(node)`: `this` when it belongs to `node`, else a copy
631    /// for it, with the JSON of the keys its type knows parsed.
632    pub(crate) fn get_writable(this: &NodeStateRef, node: NodeVersion) -> NodeStateRef {
633        let state = this.borrow();
634        if state.node == node {
635            return this.clone();
636        }
637        let mut next_known_state = state.known_state.clone();
638        let next_unknown_state = parse_and_prune_next_unknown_state(
639            &state.shared_node_state.shared_config_map.borrow(),
640            &mut next_known_state,
641            state.unknown_state.as_ref(),
642        );
643        Rc::new(RefCell::new(NodeState::new(
644            node,
645            state.shared_node_state.clone(),
646            next_unknown_state,
647            next_known_state,
648            Some(state.size),
649        )))
650    }
651
652    /// `resetOnCopyNode()`.
653    fn reset_on_copy_node(&mut self) {
654        for (config, value) in &mut self.known_state {
655            if config.0.reset_on_copy_node() {
656                *value = config.0.default_any();
657            }
658        }
659    }
660
661    /// `updateFromKnown(stateConfig, value)`.
662    pub(crate) fn update_from_known(&mut self, config: &AnyStateConfig, value: Rc<dyn Any>) {
663        let key = config.key();
664        self.shared_node_state
665            .shared_config_map
666            .borrow_mut()
667            .insert(key.to_owned(), config.clone());
668        let in_unknown = self
669            .unknown_state
670            .as_ref()
671            .is_some_and(|u| u.contains_key(key));
672        if in_unknown {
673            // The known value replaces the JSON copy. The key is already
674            // counted in size.
675            let unknown = self.unknown_state.as_mut().expect("checked");
676            unknown.remove(key);
677            if unknown.0.is_empty() {
678                self.unknown_state = None;
679            }
680        } else if !self.has_known(config) {
681            self.size += 1;
682        }
683        self.set_known(config, value);
684    }
685
686    /// `updateFromUnknown(k, v)`: parsed when the node's type knows the key.
687    pub(crate) fn update_from_unknown(&mut self, k: &str, v: Rc<Value>) {
688        if UNSAFE_STATE_KEYS.contains(&k) {
689            return;
690        }
691        let config = self
692            .shared_node_state
693            .shared_config_map
694            .borrow()
695            .get(k)
696            .cloned();
697        match config {
698            Some(config) => {
699                let parsed = config.0.parse_any(&v);
700                self.update_from_known(&config, parsed);
701            }
702            None => {
703                let unknown = self.unknown_state.get_or_insert_default();
704                if !unknown.contains_key(k) {
705                    self.size += 1;
706                }
707                unknown.insert(k, v);
708            }
709        }
710    }
711
712    /// `updateFromJSON(unknownState)`: every known value back to its
713    /// default, then the entries of `unknown_state` (`Object.entries`).
714    fn update_from_json(&mut self, unknown_state: &Value) {
715        for (config, value) in &mut self.known_state {
716            *value = config.0.default_any();
717        }
718        self.size = self.known_state.len();
719        self.unknown_state = None;
720        if is_truthy(unknown_state) {
721            for (k, v) in object_entries(unknown_state) {
722                self.update_from_unknown(&k, v);
723            }
724        }
725    }
726}
727
728/// Whether a JSON value is truthy in JS.
729fn is_truthy(value: &Value) -> bool {
730    match value {
731        Value::Undefined | Value::Null => false,
732        Value::Bool(b) => *b,
733        Value::Number(n) => *n != 0.0 && !n.is_nan(),
734        Value::String(s) => !s.is_empty(),
735        Value::Array(_) | Value::Object(_) => true,
736    }
737}
738
739/// `Object.entries(value)` of a JSON value: an object's properties, an
740/// array's or a string's (UTF-16 code units) by index, nothing for the rest.
741fn object_entries(value: &Value) -> Vec<(String, Rc<Value>)> {
742    match value {
743        Value::Object(object) => object
744            .iter()
745            .map(|(k, v)| (k.to_owned(), Rc::new(v.clone())))
746            .collect(),
747        Value::Array(array) => array
748            .iter()
749            .enumerate()
750            .map(|(i, v)| (i.to_string(), Rc::new(v.clone())))
751            .collect(),
752        Value::String(s) => s
753            .encode_utf16()
754            .enumerate()
755            .map(|(i, unit)| {
756                (
757                    i.to_string(),
758                    Rc::new(Value::String(String::from_utf16_lossy(&[unit]))),
759                )
760            })
761            .collect(),
762        _ => Vec::new(),
763    }
764}
765
766/// `parseAndPruneNextUnknownState(sharedConfigMap, nextKnownState,
767/// unknownState)`.
768fn parse_and_prune_next_unknown_state(
769    shared_config_map: &HashMap<String, AnyStateConfig>,
770    next_known_state: &mut Vec<(AnyStateConfig, Rc<dyn Any>)>,
771    unknown_state: Option<&UnknownState>,
772) -> Option<UnknownState> {
773    let mut next_unknown_state: Option<UnknownState> = None;
774    for (k, v) in unknown_state.into_iter().flat_map(UnknownState::iter) {
775        if UNSAFE_STATE_KEYS.contains(&k) {
776            continue;
777        }
778        match shared_config_map.get(k) {
779            Some(config) => {
780                if !next_known_state.iter().any(|(c, _)| c.is(config)) {
781                    next_known_state.push((config.clone(), config.0.parse_any(v)));
782                }
783            }
784            None => next_unknown_state
785                .get_or_insert_default()
786                .insert(k, v.clone()),
787        }
788    }
789    next_unknown_state
790}
791
792/// `$checkCollision(node, stateConfig, state)` (a DEV check in JS, which
793/// the vectors come from): another config with the same key already used
794/// on the node's type.
795fn check_collision(
796    node: &dyn LexicalNode,
797    config: &AnyStateConfig,
798    state: &NodeState,
799) -> Result<(), LexicalError> {
800    let collision = state
801        .shared_node_state
802        .shared_config_map
803        .borrow()
804        .get(config.key())
805        .cloned();
806    invariant!(
807        collision.is_none_or(|c| c.is(config)),
808        "$setState: State key collision {} detected in {} node with type {} and key {}. Only one StateConfig with a given key should be used on a node.",
809        Value::from(config.key()),
810        node.class_name(),
811        node.get_type(),
812        node.base().key
813    );
814    Ok(())
815}
816
817/// `$getSharedNodeState(node)`: the node's, or its type's in the active
818/// editor.
819fn get_shared_node_state(node: &dyn LexicalNode) -> Result<Rc<SharedNodeState>, LexicalError> {
820    if let Some(state) = &node.base().state {
821        return Ok(state.borrow().shared_node_state.clone());
822    }
823    let editor = get_registry_editor()
824        .ok_or_else(|| LexicalError::new("Unable to find an active editor."))?;
825    editor.shared_node_state(node.get_type()).ok_or_else(|| {
826        LexicalError::new(format!(
827            "getRegisteredNode: Type {} not found",
828            node.get_type()
829        ))
830    })
831}
832
833/// `$getWritableNodeState(node)`: makes the node writable and gives it a
834/// NodeState of its own.
835pub(crate) fn get_writable_node_state(node: &NodeRef) -> Result<NodeStateRef, LexicalError> {
836    get_writable(node.get_key());
837    let state = {
838        let writable = node.get_latest();
839        let version = version_of(&*writable);
840        match &writable.base().state {
841            Some(state) => NodeState::get_writable(state, version),
842            None => Rc::new(RefCell::new(NodeState::new(
843                version,
844                get_shared_node_state(&*writable)?,
845                None,
846                Vec::new(),
847                None,
848            ))),
849        }
850    };
851    mutate(node.get_key(), |n| n.base_mut().state = Some(state.clone()));
852    Ok(state)
853}
854
855/// [`get_state_any`], for the node structure normalization's
856/// `mergeAdjacent` comparison.
857pub(crate) fn get_state_erased(
858    node: &dyn LexicalNode,
859    config: &AnyStateConfig,
860) -> Result<Rc<dyn Any>, LexicalError> {
861    get_state_any(node, config)
862}
863
864/// Whether a value of `config` was ever set on this version of `node`, or
865/// on the node it was split or copied from: `__state.knownState` has the
866/// config, or `__state.unknownState` its key (`@lexical/mark`'s
867/// `$hasMarkIDsState` reads them).
868#[cfg(all(feature = "mark", feature = "extension"))]
869pub(crate) fn has_state_value(node: &dyn LexicalNode, config: &AnyStateConfig) -> bool {
870    node.base().state.as_ref().is_some_and(|state| {
871        let state = state.borrow();
872        state.has_known(config)
873            || state
874                .unknown_state
875                .as_ref()
876                .is_some_and(|unknown| unknown.contains_key(config.key()))
877    })
878}
879
880/// `$getState(node, stateConfig, NODE_STATE_DIRECT)` without its value type.
881fn get_state_any(
882    node: &dyn LexicalNode,
883    config: &AnyStateConfig,
884) -> Result<Rc<dyn Any>, LexicalError> {
885    match &node.base().state {
886        Some(state) => {
887            check_collision(node, config, &state.borrow())?;
888            Ok(state.borrow_mut().get_value(config))
889        }
890        None => Ok(config.0.default_any()),
891    }
892}
893
894/// `$getState(node, stateConfig)`: the value of the state on the latest
895/// version of the node, or its default. Fails when another config with the
896/// same key was used on the node's type.
897pub fn get_state<V: Clone + 'static>(
898    node: &NodeRef,
899    config: &StateConfig<V>,
900) -> Result<V, LexicalError> {
901    get_state_direct(&*node.get_latest(), config)
902}
903
904/// `$getState(node, stateConfig, NODE_STATE_DIRECT)`: the value on this
905/// version of the node, which needs no editor state.
906pub fn get_state_direct<V: Clone + 'static>(
907    node: &dyn LexicalNode,
908    config: &StateConfig<V>,
909) -> Result<V, LexicalError> {
910    Ok(downcast::<V>(&get_state_any(node, &config.erased())?))
911}
912
913/// `$getStateChange(node, prevNode, stateConfig)`: `None` when the two
914/// versions hold equal values, else `(value, prevValue)`.
915pub fn get_state_change<V: Clone + 'static>(
916    node: &dyn LexicalNode,
917    prev_node: &dyn LexicalNode,
918    config: &StateConfig<V>,
919) -> Result<Option<(V, V)>, LexicalError> {
920    let value = get_state_direct(node, config)?;
921    let prev_value = get_state_direct(prev_node, config)?;
922    Ok((!config.is_equal(&value, &prev_value)).then_some((value, prev_value)))
923}
924
925/// The writing half of `$setState`.
926fn write_state(
927    node: &NodeRef,
928    config: &AnyStateConfig,
929    value: Rc<dyn Any>,
930) -> Result<NodeRef, LexicalError> {
931    get_writable(node.get_key());
932    let state = get_writable_node_state(node)?;
933    check_collision(&*node.get_latest(), config, &state.borrow())?;
934    state.borrow_mut().update_from_known(config, value);
935    Ok(node.clone())
936}
937
938/// `$setState(node, stateConfig, valueOrUpdater)` with an updater, without
939/// its value type: nothing is written when the value is equal to the one
940/// the node has.
941fn set_state_any_with(
942    node: &NodeRef,
943    config: &AnyStateConfig,
944    updater: impl FnOnce(&Rc<dyn Any>) -> Rc<dyn Any>,
945) -> Result<NodeRef, LexicalError> {
946    error_on_read_only();
947    let prev_value = get_state_any(&*node.get_latest(), config)?;
948    let value = config.canonical_value(updater(&prev_value));
949    if config.0.is_equal_any(&*prev_value, &*value) {
950        return Ok(node.clone());
951    }
952    write_state(node, config, value)
953}
954
955/// `$setState(node, stateConfig, value)`: sets the state on the node (the
956/// node is written even when the value is the one it has). Fails when
957/// another config with the same key was used on the node's type.
958pub fn set_state<V: Clone + 'static>(
959    node: &NodeRef,
960    config: &StateConfig<V>,
961    value: V,
962) -> Result<NodeRef, LexicalError> {
963    error_on_read_only();
964    let config = config.erased();
965    let value = config.canonical_value(Rc::new(value));
966    write_state(node, &config, value)
967}
968
969/// `$setState(node, stateConfig, updater)`: sets the state to what
970/// `updater` makes of the node's value, unless that is equal to it, when
971/// the node is left as it is.
972pub fn set_state_with<V: Clone + 'static>(
973    node: &NodeRef,
974    config: &StateConfig<V>,
975    updater: impl FnOnce(&V) -> V,
976) -> Result<NodeRef, LexicalError> {
977    set_state_any_with(node, &config.erased(), |prev| {
978        Rc::new(updater(
979            prev.downcast_ref::<V>()
980                .expect("a value of the config's type"),
981        ))
982    })
983}
984
985/// `$updateStateFromJSON(node, serializedNode)`: the node's NodeState from
986/// the `"$"` of its JSON, when it has one or the node has a state.
987pub(crate) fn update_state_from_json(node: &NodeRef, json: &Object) -> Result<(), LexicalError> {
988    let unknown_state = json
989        .get(crate::constants::NODE_STATE_KEY)
990        .cloned()
991        .unwrap_or(Value::Undefined);
992    if node.get_latest().base().state.is_some() || is_truthy(&unknown_state) {
993        get_writable_node_state(node)?
994            .borrow_mut()
995            .update_from_json(&unknown_state);
996    }
997    Ok(())
998}
999
1000/// `$applyFlatStates(node, serializedNode, flatStates)`: each flat state the
1001/// node's class declares, from the top level of its JSON, where it is.
1002pub(crate) fn apply_flat_states(node: &NodeRef, json: &Object) -> Result<(), LexicalError> {
1003    let flat_states: Vec<AnyStateConfig> = node
1004        .get_latest()
1005        .state_configs()
1006        .into_iter()
1007        .filter(|required| required.flat)
1008        .map(|required| required.state_config)
1009        .collect();
1010    for config in flat_states {
1011        if let Some(raw) = json.get(config.key()).filter(|v| !v.is_undefined()) {
1012            let parsed = config.0.parse_any(raw);
1013            set_state_any_with(node, &config, |_| parsed)?;
1014        }
1015    }
1016    Ok(())
1017}
1018
1019/// `exportJSON(compact)`: the node's own JSON, then its NodeState.
1020pub(crate) fn export_json_with_state(node: &dyn LexicalNode, compact: bool) -> Object {
1021    let mut json = node.export_json(compact);
1022    if let Some(state) = &node.base().state {
1023        for (key, value) in state.borrow().to_json().iter() {
1024            json.insert(key, value.clone());
1025        }
1026    }
1027    json
1028}
1029
1030/// `$cloneNodeState(from, to)`: for `to`, a new node, a copy of the
1031/// NodeState of the version `from` when it belongs to it, else the same.
1032pub(crate) fn clone_node_state(from: &dyn LexicalNode, to_key: &str) -> Option<NodeStateRef> {
1033    let state = from.base().state.as_ref()?;
1034    if state.borrow().node == version_of(from) {
1035        let to = (to_key.to_owned(), get_active_editor_state().0.id);
1036        Some(NodeState::get_writable(state, to))
1037    } else {
1038        Some(state.clone())
1039    }
1040}
1041
1042/// What `$copyNode` and `afterCloneFrom` give a copy of a node with another
1043/// key: a copy of the NodeState, with the values of the configs that ask
1044/// for it reset (`resetOnCopyNodeFrom`) unless `skip_reset`.
1045pub(crate) fn copy_node_state(
1046    state: &NodeStateRef,
1047    to_key: &str,
1048    skip_reset: bool,
1049) -> NodeStateRef {
1050    let to = (to_key.to_owned(), get_active_editor_state().0.id);
1051    let copy = NodeState::get_writable(state, to);
1052    if !skip_reset {
1053        copy.borrow_mut().reset_on_copy_node();
1054    }
1055    copy
1056}
1057
1058/// `hasUnequalMapEntry(keys, sourceState, otherState)`.
1059fn has_unequal_map_entry(
1060    keys: &mut HashSet<String>,
1061    source_state: &NodeStateRef,
1062    other_state: Option<&NodeStateRef>,
1063) -> bool {
1064    let known = source_state.borrow().known_entries();
1065    for (config, value) in known {
1066        if !keys.insert(config.key().to_owned()) {
1067            continue;
1068        }
1069        let other_value = match other_state {
1070            Some(other) => other.borrow_mut().get_value(&config),
1071            None => config.0.default_any(),
1072        };
1073        if !Rc::ptr_eq(&other_value, &value) && !config.0.is_equal_any(&*other_value, &*value) {
1074            return true;
1075        }
1076    }
1077    false
1078}
1079
1080/// `hasUnequalRecordEntry(keys, sourceState, otherState)`.
1081fn has_unequal_record_entry(
1082    keys: &mut HashSet<String>,
1083    source_state: &NodeStateRef,
1084    other_state: Option<&NodeStateRef>,
1085) -> bool {
1086    let source = source_state.borrow();
1087    let other = other_state.map(|o| o.borrow());
1088    let other_unknown = other.as_ref().and_then(|o| o.unknown_state.as_ref());
1089    for (key, value) in source.unknown_state.iter().flat_map(UnknownState::iter) {
1090        if !keys.insert(key.to_owned()) {
1091            continue;
1092        }
1093        if !json_strict_equals(Some(value), other_unknown.and_then(|u| u.get(key))) {
1094            return true;
1095        }
1096    }
1097    false
1098}
1099
1100/// `nodeStatesAreEquivalent(a, b)`: whether two text nodes with these
1101/// states may merge.
1102pub(crate) fn node_states_are_equivalent(
1103    a: Option<&NodeStateRef>,
1104    b: Option<&NodeStateRef>,
1105) -> bool {
1106    match (a, b) {
1107        (None, None) => return true,
1108        (Some(a), Some(b)) if Rc::ptr_eq(a, b) => return true,
1109        _ => {}
1110    }
1111    let mut keys = HashSet::new();
1112    !(a.is_some_and(|a| has_unequal_map_entry(&mut keys, a, b))
1113        || b.is_some_and(|b| has_unequal_map_entry(&mut keys, b, a))
1114        || a.is_some_and(|a| has_unequal_record_entry(&mut keys, a, b))
1115        || b.is_some_and(|b| has_unequal_record_entry(&mut keys, b, a)))
1116}
1117
1118/// `$carryNodeState(from, to)`: gives `to`, a node that takes the place of
1119/// `from` with the same content, the NodeState of `from`: known values as
1120/// they are (as JSON when the type of `to` has another config for the
1121/// key), JSON as it is, defaults left out, and the keys `to` holds kept.
1122pub(crate) fn carry_node_state(from: &NodeRef, to: &NodeRef) -> Result<(), LexicalError> {
1123    let Some(from_state) = from.get_latest().base().state.clone() else {
1124        return Ok(());
1125    };
1126    if from_state.borrow().size == 0 {
1127        return Ok(());
1128    }
1129    let mut done = HashSet::new();
1130    if let Some(to_state) = to.get_latest().base().state.clone() {
1131        let to_state = to_state.borrow();
1132        for (config, _) in &to_state.known_state {
1133            done.insert(config.key().to_owned());
1134        }
1135        for (key, _) in to_state.unknown_state.iter().flat_map(UnknownState::iter) {
1136            done.insert(key.to_owned());
1137        }
1138    }
1139    let state = get_writable_node_state(to)?;
1140    let (known, unknown) = {
1141        let from_state = from_state.borrow();
1142        (from_state.known_entries(), from_state.unknown_state.clone())
1143    };
1144    for (config, value) in known {
1145        if !done.insert(config.key().to_owned()) {
1146            continue;
1147        }
1148        if config.0.is_equal_any(&*value, &*config.0.default_any()) {
1149            continue;
1150        }
1151        let mut state = state.borrow_mut();
1152        let own = state
1153            .shared_node_state
1154            .shared_config_map
1155            .borrow()
1156            .get(config.key())
1157            .cloned();
1158        if own.is_none_or(|own| own.is(&config)) {
1159            state.update_from_known(&config, value);
1160        } else {
1161            let json = Rc::new(config.0.unparse_any(&*value));
1162            state.update_from_unknown(config.key(), json);
1163        }
1164    }
1165    for (key, value) in unknown.iter().flat_map(UnknownState::iter) {
1166        if !done.contains(key) {
1167            state.borrow_mut().update_from_unknown(key, value.clone());
1168        }
1169    }
1170    Ok(())
1171}
1172
1173/// The value of a known config for a JSON read, as `unparse` writes it
1174/// (what `registerLexicalTextEntity`'s `$carryNodeState` needs).
1175#[cfg(any(feature = "text", feature = "devtools"))]
1176pub(crate) fn unparse(config: &AnyStateConfig, value: &Rc<dyn Any>) -> Value {
1177    config.0.unparse_any(&**value)
1178}
1179
1180/// Whether `value` is the default of `config`.
1181#[cfg(any(feature = "text", feature = "devtools"))]
1182pub(crate) fn is_default(config: &AnyStateConfig, value: &Rc<dyn Any>) -> bool {
1183    config.0.is_equal_any(&**value, &*config.0.default_any())
1184}
1185
1186/// `readStateValue(state, stateConfig)` (`registerLexicalTextEntity.ts`):
1187/// the value `getValue` would give, without keeping a value it parses.
1188#[cfg(feature = "text")]
1189fn read_state_value(state: Option<&NodeStateRef>, config: &AnyStateConfig) -> Rc<dyn Any> {
1190    let Some(state) = state else {
1191        return config.0.default_any();
1192    };
1193    let state = state.borrow();
1194    if let Some(known) = state.known(config) {
1195        return known.clone();
1196    }
1197    if let Some(json_value) = state
1198        .unknown_state
1199        .as_ref()
1200        .and_then(|u| u.get(config.key()))
1201    {
1202        return config.0.parse_any(json_value);
1203    }
1204    config.0.default_any()
1205}
1206
1207/// `haveEquivalentNodeState(a, b)` (`registerLexicalTextEntity.ts`):
1208/// whether two states hold equivalent NodeState by the rule that decides
1209/// whether text nodes merge, as [`node_states_are_equivalent`] does, but
1210/// reading the other state's values without keeping what it parses.
1211#[cfg(feature = "text")]
1212pub(crate) fn have_equivalent_node_state(
1213    state_a: Option<&NodeStateRef>,
1214    state_b: Option<&NodeStateRef>,
1215) -> bool {
1216    match (state_a, state_b) {
1217        (None, None) => return true,
1218        (Some(a), Some(b)) if Rc::ptr_eq(a, b) => return true,
1219        _ => {}
1220    }
1221    let mut keys = HashSet::new();
1222    let mut has_unequal_known = |source: Option<&NodeStateRef>, other: Option<&NodeStateRef>| {
1223        let Some(source) = source else {
1224            return false;
1225        };
1226        let known = source.borrow().known_entries();
1227        for (config, value) in known {
1228            if !keys.insert(config.key().to_owned()) {
1229                continue;
1230            }
1231            let other_value = read_state_value(other, &config);
1232            if !Rc::ptr_eq(&other_value, &value) && !config.0.is_equal_any(&*other_value, &*value) {
1233                return true;
1234            }
1235        }
1236        false
1237    };
1238    if has_unequal_known(state_a, state_b) || has_unequal_known(state_b, state_a) {
1239        return false;
1240    }
1241    !(state_a.is_some_and(|a| has_unequal_record_entry(&mut keys, a, state_b))
1242        || state_b.is_some_and(|b| has_unequal_record_entry(&mut keys, b, state_a)))
1243}