lexical-ui 0.1.2

A Rust port of Lexical's model and headless packages, at parity with the JS implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
//! `LexicalNodeState.ts`: NodeState, the ad-hoc data an app keeps on any
//! node beside the properties of its class. A [`StateConfig`] made with
//! [`create_state`] names a key and how its value parses from JSON, writes
//! back and compares; [`get_state`] and [`set_state`] read and write it on a
//! node, and the node's JSON carries the values that aren't their default
//! under `"$"` (or at the top level, for a state its class declares flat).
//! Keys no config has read stay as their JSON, and are written back as they
//! came.
//!
//! As in JS, a node version shares its NodeState with the version it was
//! cloned from until one of them writes it, which copies it (parsing the
//! JSON of the keys a config has read on its node type). JS tells the
//! version that owns a NodeState by object identity; here a node version is
//! its key and the editor state it was made writable in.
//!
//! A config's value may be described by a schema (`createState(key,
//! {parse: schema})`, [`StateValueConfig::from_schema`]), which then gives
//! its equality and default, and a set-valued one (`arraySetValue`) puts a
//! value written with `$setState` in its canonical form.
//!
//! Not ported: `$getStateChange`'s use in `updateDOM`, which comes with the
//! DOM, and the `Object.prototype` check on flat keys (rust/PARITY.md).

use crate::LexicalError;
use crate::error::invariant;
use crate::json::{Object, Value, array_index};
use crate::lexical_utils::{get_writable, mutate};
use crate::node::{LexicalNode, NodeKey, NodeRef};
use crate::schema::{SchemaValue, SerializationSchema, SerializationSchemaMeta, is_schema_equal};
use crate::updates::{error_on_read_only, get_active_editor_state, get_registry_editor};
use std::any::Any;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::rc::Rc;

/// A value a state can hold without saying how it serializes and compares:
/// one that JSON writes as it is (JS's default `unparse`), compared with
/// `Object.is` (JS's default `isEqual`).
pub trait StateValue: Clone + 'static {
    /// The value as JSON.
    fn to_json(&self) -> Value;
    /// `Object.is(self, other)`.
    fn object_is(&self, other: &Self) -> bool;
}

impl StateValue for f64 {
    fn to_json(&self) -> Value {
        Value::Number(*self)
    }
    fn object_is(&self, other: &Self) -> bool {
        (self.is_nan() && other.is_nan()) || self.to_bits() == other.to_bits()
    }
}

impl StateValue for bool {
    fn to_json(&self) -> Value {
        Value::Bool(*self)
    }
    fn object_is(&self, other: &Self) -> bool {
        self == other
    }
}

impl StateValue for String {
    fn to_json(&self) -> Value {
        Value::String(self.clone())
    }
    fn object_is(&self, other: &Self) -> bool {
        self == other
    }
}

/// `None` is `null`.
impl<T: StateValue> StateValue for Option<T> {
    fn to_json(&self) -> Value {
        self.as_ref().map_or(Value::Null, StateValue::to_json)
    }
    fn object_is(&self, other: &Self) -> bool {
        match (self, other) {
            (None, None) => true,
            (Some(a), Some(b)) => a.object_is(b),
            _ => false,
        }
    }
}

/// A state's `isEqual`: whether two of its values are the same value.
pub type StateIsEqual<V> = Rc<dyn Fn(&V, &V) -> bool>;

/// `StateValueConfig`: how a state's value parses from JSON (`parse`, which
/// gives the default for `undefined`), writes back (`unparse`) and compares
/// (`isEqual`), whether `$copyNode` resets it (`resetOnCopyNode`), whether
/// the node's own code recomputes it (`derived`, `@experimental`), and the
/// schema `parse` was given as (`StateConfig.schema`), when it was one.
pub struct StateValueConfig<V> {
    pub parse: Rc<dyn Fn(&Value) -> V>,
    pub unparse: Rc<dyn Fn(&V) -> Value>,
    pub is_equal: StateIsEqual<V>,
    pub reset_on_copy_node: bool,
    pub derived: bool,
    pub schema: Option<SerializationSchema>,
}

impl<V> Clone for StateValueConfig<V> {
    fn clone(&self) -> Self {
        Self {
            parse: self.parse.clone(),
            unparse: self.unparse.clone(),
            is_equal: self.is_equal.clone(),
            reset_on_copy_node: self.reset_on_copy_node,
            derived: self.derived,
            schema: self.schema.clone(),
        }
    }
}

impl<V: StateValue> StateValueConfig<V> {
    /// `{parse}`, with JS's defaults for the rest: the value as JSON,
    /// `Object.is`, and kept by a copy.
    pub fn new(parse: impl Fn(&Value) -> V + 'static) -> Self {
        Self {
            parse: Rc::new(parse),
            unparse: Rc::new(StateValue::to_json),
            is_equal: Rc::new(StateValue::object_is),
            reset_on_copy_node: false,
            derived: false,
            schema: None,
        }
    }
}

impl<V: SchemaValue + 'static> StateValueConfig<V> {
    /// `{parse: schema}`: a state whose value `schema` describes, which also
    /// gives it its equality (`isSchemaEqual`) and default, written back as
    /// the value it parsed to. `V` holds the values the schema parses to
    /// (`Value` holds any).
    pub fn from_schema(schema: SerializationSchema) -> Self {
        let parse_schema = schema.clone();
        let equal_schema = schema.clone();
        Self {
            parse: Rc::new(move |value| {
                V::from_schema_value(&parse_schema.parse(value))
                    .expect("a value of the type the schema parses to")
            }),
            unparse: Rc::new(V::to_schema_value),
            is_equal: Rc::new(move |a, b| {
                is_schema_equal(&equal_schema, &a.to_schema_value(), &b.to_schema_value())
            }),
            reset_on_copy_node: false,
            derived: false,
            schema: Some(schema),
        }
    }
}

struct StateConfigInner<V> {
    key: String,
    config: StateValueConfig<V>,
    /// `defaultValue`, `parse(undefined)`, computed once: every node without
    /// a value of its own reads this one.
    default_value: Rc<dyn Any>,
}

/// `StateConfig`: what [`create_state`] returns, for [`get_state`] and
/// [`set_state`]. Clones are the same config: nodes tell configs apart by
/// identity, as JS does.
pub struct StateConfig<V>(Rc<StateConfigInner<V>>);

impl<V> Clone for StateConfig<V> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<V> fmt::Debug for StateConfig<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "StateConfig({:?})", self.0.key)
    }
}

impl<V: Clone + 'static> StateConfig<V> {
    /// `key`: the key the state serializes under.
    pub fn key(&self) -> &str {
        &self.0.key
    }

    /// `parse(value)`; `Value::Undefined` gives the default.
    pub fn parse(&self, value: &Value) -> V {
        (self.0.config.parse)(value)
    }

    /// `unparse(value)`.
    pub fn unparse(&self, value: &V) -> Value {
        (self.0.config.unparse)(value)
    }

    /// `isEqual(a, b)`.
    pub fn is_equal(&self, a: &V, b: &V) -> bool {
        (self.0.config.is_equal)(a, b)
    }

    /// `defaultValue`.
    pub fn default_value(&self) -> V {
        downcast::<V>(&self.0.default_value)
    }

    /// `resetOnCopyNode`.
    pub fn reset_on_copy_node(&self) -> bool {
        self.0.config.reset_on_copy_node
    }

    /// `derived` (`@experimental`).
    pub fn derived(&self) -> bool {
        self.0.config.derived
    }

    /// `schema`: the schema `parse` was given as, when it was one.
    pub fn schema(&self) -> Option<SerializationSchema> {
        self.0.config.schema.clone()
    }

    /// This config without its value type (`AnyStateConfig`).
    pub fn erased(&self) -> AnyStateConfig {
        AnyStateConfig(self.0.clone())
    }
}

fn downcast<V: Clone + 'static>(value: &Rc<dyn Any>) -> V {
    value
        .downcast_ref::<V>()
        .expect("a state value of its config's type")
        .clone()
}

/// What a node's NodeState needs of a config whose value type it doesn't
/// know.
trait ErasedStateConfig {
    fn key(&self) -> &str;
    fn parse_any(&self, value: &Value) -> Rc<dyn Any>;
    fn unparse_any(&self, value: &dyn Any) -> Value;
    fn is_equal_any(&self, a: &dyn Any, b: &dyn Any) -> bool;
    fn default_any(&self) -> Rc<dyn Any>;
    fn reset_on_copy_node(&self) -> bool;
    fn derived(&self) -> bool;
    fn schema(&self) -> Option<SerializationSchema>;
}

impl<V: 'static> ErasedStateConfig for StateConfigInner<V> {
    fn key(&self) -> &str {
        &self.key
    }
    fn parse_any(&self, value: &Value) -> Rc<dyn Any> {
        Rc::new((self.config.parse)(value))
    }
    fn unparse_any(&self, value: &dyn Any) -> Value {
        (self.config.unparse)(
            value
                .downcast_ref::<V>()
                .expect("a value of the config's type"),
        )
    }
    fn is_equal_any(&self, a: &dyn Any, b: &dyn Any) -> bool {
        match (a.downcast_ref::<V>(), b.downcast_ref::<V>()) {
            (Some(a), Some(b)) => (self.config.is_equal)(a, b),
            _ => false,
        }
    }
    fn default_any(&self) -> Rc<dyn Any> {
        self.default_value.clone()
    }
    fn reset_on_copy_node(&self) -> bool {
        self.config.reset_on_copy_node
    }
    fn derived(&self) -> bool {
        self.config.derived
    }
    fn schema(&self) -> Option<SerializationSchema> {
        self.config.schema.clone()
    }
}

/// `AnyStateConfig`: a [`StateConfig`] of any value type.
#[derive(Clone)]
pub struct AnyStateConfig(Rc<dyn ErasedStateConfig>);

impl AnyStateConfig {
    /// The config's key.
    pub fn key(&self) -> &str {
        self.0.key()
    }

    /// Whether `self` and `other` are the same config (`===`).
    pub fn is(&self, other: &AnyStateConfig) -> bool {
        std::ptr::addr_eq(Rc::as_ptr(&self.0), Rc::as_ptr(&other.0))
    }

    /// `derived` (`@experimental`).
    pub fn derived(&self) -> bool {
        self.0.derived()
    }

    /// `schema`.
    pub fn schema(&self) -> Option<SerializationSchema> {
        self.0.schema()
    }

    /// `canonicalValue(stateConfig, value)`: what `$setState` stores. A
    /// set-valued state (`arraySetValue`) stores what its parse makes of the
    /// value, so a value set directly is stored, read back and compared
    /// like one loaded from JSON; any other state stores the value as
    /// given.
    fn canonical_value(&self, value: Rc<dyn Any>) -> Rc<dyn Any> {
        match self.0.schema() {
            Some(schema) if matches!(schema.meta(), SerializationSchemaMeta::Set { .. }) => {
                self.0.parse_any(&self.0.unparse_any(&*value))
            }
            _ => value,
        }
    }

    /// `isEqual(a, b)` of two values of the config's type.
    pub(crate) fn is_equal_erased(&self, a: &dyn Any, b: &dyn Any) -> bool {
        self.0.is_equal_any(a, b)
    }
}

impl fmt::Debug for AnyStateConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AnyStateConfig({:?})", self.key())
    }
}

/// `createState(key, {parse})`: a state with JS's default `unparse` and
/// `isEqual` ([`StateValue`]).
pub fn create_state<V: StateValue>(
    key: &str,
    parse: impl Fn(&Value) -> V + 'static,
) -> StateConfig<V> {
    create_state_with(key, StateValueConfig::new(parse))
}

/// `createState(key, valueConfig)`.
pub fn create_state_with<V: 'static>(key: &str, config: StateValueConfig<V>) -> StateConfig<V> {
    let default_value: Rc<dyn Any> = Rc::new((config.parse)(&Value::Undefined));
    StateConfig(Rc::new(StateConfigInner {
        key: key.to_owned(),
        config,
        default_value,
    }))
}

/// `RequiredNodeStateConfig`: a state a node class declares in its
/// `$config`'s `stateConfigs` ([`LexicalNode::state_configs`]), which its
/// type knows before any node reads it; a `flat` one serializes at the top
/// level of the node's JSON instead of under `"$"`.
#[derive(Clone, Debug)]
pub struct RequiredNodeStateConfig {
    pub(crate) state_config: AnyStateConfig,
    pub(crate) flat: bool,
}

impl RequiredNodeStateConfig {
    /// `stateConfig` or `{stateConfig, flat}`.
    pub fn new<V: Clone + 'static>(state_config: &StateConfig<V>, flat: bool) -> Self {
        Self {
            state_config: state_config.erased(),
            flat,
        }
    }
}

/// `SharedNodeState`: the configs a node type knows in an editor, by key
/// (`sharedConfigMap`), and the keys it serializes flat (`flatKeys`), shared
/// by every node of the type.
#[derive(Debug, Default)]
pub(crate) struct SharedNodeState {
    pub(crate) shared_config_map: RefCell<HashMap<String, AnyStateConfig>>,
    flat_keys: Vec<String>,
}

/// `createSharedNodeState(nodeConfig)`.
pub(crate) fn create_shared_node_state(configs: Vec<RequiredNodeStateConfig>) -> SharedNodeState {
    let shared = SharedNodeState::default();
    let mut flat_keys = Vec::new();
    for required in configs {
        let key = required.state_config.key().to_owned();
        if required.flat && !flat_keys.contains(&key) {
            flat_keys.push(key.clone());
        }
        shared
            .shared_config_map
            .borrow_mut()
            .insert(key, required.state_config);
    }
    SharedNodeState {
        flat_keys,
        ..shared
    }
}

/// `UNSAFE_STATE_KEYS`.
const UNSAFE_STATE_KEYS: [&str; 3] = ["__proto__", "constructor", "prototype"];

/// An `UnknownStateRecord`: JSON values by key, in a JS object's order. The
/// values are shared, as JS shares the objects, so two records compare
/// their objects and arrays by identity (`===`).
#[derive(Clone, Debug, Default)]
pub(crate) struct UnknownState(Vec<(String, Rc<Value>)>);

impl UnknownState {
    pub(crate) fn get(&self, key: &str) -> Option<&Rc<Value>> {
        self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v)
    }

    pub(crate) fn contains_key(&self, key: &str) -> bool {
        self.get(key).is_some()
    }

    /// `record[key] = value`, keeping a JS object's key order.
    fn insert(&mut self, key: &str, value: Rc<Value>) {
        if let Some(entry) = self.0.iter_mut().find(|(k, _)| k == key) {
            entry.1 = value;
            return;
        }
        let at = match array_index(key) {
            Some(index) => self
                .0
                .iter()
                .position(|(k, _)| array_index(k).is_none_or(|i| i > index))
                .unwrap_or(self.0.len()),
            None => self.0.len(),
        };
        self.0.insert(at, (key.to_owned(), value));
    }

    fn remove(&mut self, key: &str) {
        self.0.retain(|(k, _)| k != key);
    }

    pub(crate) fn iter(&self) -> impl Iterator<Item = (&str, &Rc<Value>)> {
        self.0.iter().map(|(k, v)| (k.as_str(), v))
    }
}

/// `a === b` for two JSON values: objects and arrays by identity.
pub(crate) fn json_strict_equals(a: Option<&Rc<Value>>, b: Option<&Rc<Value>>) -> bool {
    let undefined = |v: Option<&Rc<Value>>| v.is_none_or(|v| v.is_undefined());
    match (a, b) {
        _ if undefined(a) && undefined(b) => true,
        (Some(a), Some(b)) => match (&**a, &**b) {
            (Value::Object(_), Value::Object(_)) | (Value::Array(_), Value::Array(_)) => {
                Rc::ptr_eq(a, b)
            }
            (Value::Number(x), Value::Number(y)) => x == y,
            (Value::Object(_) | Value::Array(_), _) | (_, Value::Object(_) | Value::Array(_)) => {
                false
            }
            (x, y) => x == y,
        },
        _ => false,
    }
}

/// A node version, as a NodeState knows the one it belongs to (JS's
/// `state.node`): its key, and the id of the editor state it was made
/// writable (or created) in.
pub(crate) type NodeVersion = (NodeKey, u64);

/// The version of `node` (this version of it).
pub(crate) fn version_of(node: &dyn LexicalNode) -> NodeVersion {
    let base = node.base();
    (base.key.clone(), base.written_in)
}

/// `NodeState`: the state values of a node version.
pub(crate) struct NodeState {
    /// `node`: the version this state belongs to; another one copies it
    /// before writing.
    node: NodeVersion,
    /// `knownState`: parsed values by config, in the order they came.
    known_state: Vec<(AnyStateConfig, Rc<dyn Any>)>,
    /// `unknownState`: values still as JSON.
    pub(crate) unknown_state: Option<UnknownState>,
    pub(crate) shared_node_state: Rc<SharedNodeState>,
    /// `size`: the keys of both, counted once.
    pub(crate) size: usize,
}

/// A node's NodeState, shared by the versions that haven't written it.
pub(crate) type NodeStateRef = Rc<RefCell<NodeState>>;

impl fmt::Debug for NodeState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodeState")
            .field("node", &self.node)
            .field(
                "known_state",
                &self
                    .known_state
                    .iter()
                    .map(|(c, _)| c.key())
                    .collect::<Vec<_>>(),
            )
            .field("unknown_state", &self.unknown_state)
            .field("size", &self.size)
            .finish()
    }
}

/// `computeSize(sharedConfigMap, unknownState, knownState)`.
fn compute_size(
    shared_config_map: &HashMap<String, AnyStateConfig>,
    unknown_state: Option<&UnknownState>,
    known_state: &[(AnyStateConfig, Rc<dyn Any>)],
) -> usize {
    let mut size = known_state.len();
    for (k, _) in unknown_state.into_iter().flat_map(UnknownState::iter) {
        let shared_config = shared_config_map.get(k);
        if shared_config.is_none_or(|c| !known_state.iter().any(|(k, _)| k.is(c))) {
            size += 1;
        }
    }
    size
}

impl NodeState {
    fn new(
        node: NodeVersion,
        shared_node_state: Rc<SharedNodeState>,
        unknown_state: Option<UnknownState>,
        known_state: Vec<(AnyStateConfig, Rc<dyn Any>)>,
        size: Option<usize>,
    ) -> Self {
        let computed_size = compute_size(
            &shared_node_state.shared_config_map.borrow(),
            unknown_state.as_ref(),
            &known_state,
        );
        // JS checks these in DEV builds.
        debug_assert!(size.is_none_or(|s| s == computed_size));
        Self {
            node,
            known_state,
            unknown_state,
            shared_node_state,
            size: computed_size,
        }
    }

    /// The known value of `config`, if any.
    fn known(&self, config: &AnyStateConfig) -> Option<&Rc<dyn Any>> {
        self.known_state
            .iter()
            .find(|(c, _)| c.is(config))
            .map(|(_, v)| v)
    }

    fn has_known(&self, config: &AnyStateConfig) -> bool {
        self.known(config).is_some()
    }

    /// `knownState.set(config, value)`.
    fn set_known(&mut self, config: &AnyStateConfig, value: Rc<dyn Any>) {
        match self.known_state.iter_mut().find(|(c, _)| c.is(config)) {
            Some(entry) => entry.1 = value,
            None => self.known_state.push((config.clone(), value)),
        }
    }

    /// The keys of the known values, in their order.
    pub(crate) fn known_entries(&self) -> Vec<(AnyStateConfig, Rc<dyn Any>)> {
        self.known_state.clone()
    }

    /// `getValue(stateConfig)`: the known value, or the one parsed from the
    /// JSON, which it keeps (without changing the order `toJSON` writes),
    /// or the default.
    pub(crate) fn get_value(&mut self, config: &AnyStateConfig) -> Rc<dyn Any> {
        if let Some(known) = self.known(config) {
            return known.clone();
        }
        self.shared_node_state
            .shared_config_map
            .borrow_mut()
            .insert(config.key().to_owned(), config.clone());
        let mut parsed = config.0.default_any();
        if let Some(json_value) = self
            .unknown_state
            .as_ref()
            .and_then(|u| u.get(config.key()))
            .cloned()
        {
            if !json_value.is_undefined() {
                parsed = config.0.parse_any(&json_value);
            }
            self.set_known(config, parsed.clone());
        }
        parsed
    }

    /// `toJSON()`: the values that aren't their default, the flat keys of
    /// the node's type at the top level and the rest under `"$"`.
    pub(crate) fn to_json(&self) -> Object {
        let mut state: Object = self
            .unknown_state
            .iter()
            .flat_map(UnknownState::iter)
            .map(|(k, v)| (k, (**v).clone()))
            .collect();
        let mut flat_state = Object::new();
        for (config, v) in &self.known_state {
            if config.0.is_equal_any(&**v, &*config.0.default_any()) {
                state.remove(config.key());
            } else {
                state.insert(config.key(), config.0.unparse_any(&**v));
            }
        }
        for key in &self.shared_node_state.flat_keys {
            if let Some(value) = state.remove(key) {
                flat_state.insert(key.as_str(), value);
            }
        }
        if !state.is_empty() {
            flat_state.insert(crate::constants::NODE_STATE_KEY, Value::Object(state));
        }
        flat_state
    }

    /// `getWritable(node)`: `this` when it belongs to `node`, else a copy
    /// for it, with the JSON of the keys its type knows parsed.
    pub(crate) fn get_writable(this: &NodeStateRef, node: NodeVersion) -> NodeStateRef {
        let state = this.borrow();
        if state.node == node {
            return this.clone();
        }
        let mut next_known_state = state.known_state.clone();
        let next_unknown_state = parse_and_prune_next_unknown_state(
            &state.shared_node_state.shared_config_map.borrow(),
            &mut next_known_state,
            state.unknown_state.as_ref(),
        );
        Rc::new(RefCell::new(NodeState::new(
            node,
            state.shared_node_state.clone(),
            next_unknown_state,
            next_known_state,
            Some(state.size),
        )))
    }

    /// `resetOnCopyNode()`.
    fn reset_on_copy_node(&mut self) {
        for (config, value) in &mut self.known_state {
            if config.0.reset_on_copy_node() {
                *value = config.0.default_any();
            }
        }
    }

    /// `updateFromKnown(stateConfig, value)`.
    pub(crate) fn update_from_known(&mut self, config: &AnyStateConfig, value: Rc<dyn Any>) {
        let key = config.key();
        self.shared_node_state
            .shared_config_map
            .borrow_mut()
            .insert(key.to_owned(), config.clone());
        let in_unknown = self
            .unknown_state
            .as_ref()
            .is_some_and(|u| u.contains_key(key));
        if in_unknown {
            // The known value replaces the JSON copy. The key is already
            // counted in size.
            let unknown = self.unknown_state.as_mut().expect("checked");
            unknown.remove(key);
            if unknown.0.is_empty() {
                self.unknown_state = None;
            }
        } else if !self.has_known(config) {
            self.size += 1;
        }
        self.set_known(config, value);
    }

    /// `updateFromUnknown(k, v)`: parsed when the node's type knows the key.
    pub(crate) fn update_from_unknown(&mut self, k: &str, v: Rc<Value>) {
        if UNSAFE_STATE_KEYS.contains(&k) {
            return;
        }
        let config = self
            .shared_node_state
            .shared_config_map
            .borrow()
            .get(k)
            .cloned();
        match config {
            Some(config) => {
                let parsed = config.0.parse_any(&v);
                self.update_from_known(&config, parsed);
            }
            None => {
                let unknown = self.unknown_state.get_or_insert_default();
                if !unknown.contains_key(k) {
                    self.size += 1;
                }
                unknown.insert(k, v);
            }
        }
    }

    /// `updateFromJSON(unknownState)`: every known value back to its
    /// default, then the entries of `unknown_state` (`Object.entries`).
    fn update_from_json(&mut self, unknown_state: &Value) {
        for (config, value) in &mut self.known_state {
            *value = config.0.default_any();
        }
        self.size = self.known_state.len();
        self.unknown_state = None;
        if is_truthy(unknown_state) {
            for (k, v) in object_entries(unknown_state) {
                self.update_from_unknown(&k, v);
            }
        }
    }
}

/// Whether a JSON value is truthy in JS.
fn is_truthy(value: &Value) -> bool {
    match value {
        Value::Undefined | Value::Null => false,
        Value::Bool(b) => *b,
        Value::Number(n) => *n != 0.0 && !n.is_nan(),
        Value::String(s) => !s.is_empty(),
        Value::Array(_) | Value::Object(_) => true,
    }
}

/// `Object.entries(value)` of a JSON value: an object's properties, an
/// array's or a string's (UTF-16 code units) by index, nothing for the rest.
fn object_entries(value: &Value) -> Vec<(String, Rc<Value>)> {
    match value {
        Value::Object(object) => object
            .iter()
            .map(|(k, v)| (k.to_owned(), Rc::new(v.clone())))
            .collect(),
        Value::Array(array) => array
            .iter()
            .enumerate()
            .map(|(i, v)| (i.to_string(), Rc::new(v.clone())))
            .collect(),
        Value::String(s) => s
            .encode_utf16()
            .enumerate()
            .map(|(i, unit)| {
                (
                    i.to_string(),
                    Rc::new(Value::String(String::from_utf16_lossy(&[unit]))),
                )
            })
            .collect(),
        _ => Vec::new(),
    }
}

/// `parseAndPruneNextUnknownState(sharedConfigMap, nextKnownState,
/// unknownState)`.
fn parse_and_prune_next_unknown_state(
    shared_config_map: &HashMap<String, AnyStateConfig>,
    next_known_state: &mut Vec<(AnyStateConfig, Rc<dyn Any>)>,
    unknown_state: Option<&UnknownState>,
) -> Option<UnknownState> {
    let mut next_unknown_state: Option<UnknownState> = None;
    for (k, v) in unknown_state.into_iter().flat_map(UnknownState::iter) {
        if UNSAFE_STATE_KEYS.contains(&k) {
            continue;
        }
        match shared_config_map.get(k) {
            Some(config) => {
                if !next_known_state.iter().any(|(c, _)| c.is(config)) {
                    next_known_state.push((config.clone(), config.0.parse_any(v)));
                }
            }
            None => next_unknown_state
                .get_or_insert_default()
                .insert(k, v.clone()),
        }
    }
    next_unknown_state
}

/// `$checkCollision(node, stateConfig, state)` (a DEV check in JS, which
/// the vectors come from): another config with the same key already used
/// on the node's type.
fn check_collision(
    node: &dyn LexicalNode,
    config: &AnyStateConfig,
    state: &NodeState,
) -> Result<(), LexicalError> {
    let collision = state
        .shared_node_state
        .shared_config_map
        .borrow()
        .get(config.key())
        .cloned();
    invariant!(
        collision.is_none_or(|c| c.is(config)),
        "$setState: State key collision {} detected in {} node with type {} and key {}. Only one StateConfig with a given key should be used on a node.",
        Value::from(config.key()),
        node.class_name(),
        node.get_type(),
        node.base().key
    );
    Ok(())
}

/// `$getSharedNodeState(node)`: the node's, or its type's in the active
/// editor.
fn get_shared_node_state(node: &dyn LexicalNode) -> Result<Rc<SharedNodeState>, LexicalError> {
    if let Some(state) = &node.base().state {
        return Ok(state.borrow().shared_node_state.clone());
    }
    let editor = get_registry_editor()
        .ok_or_else(|| LexicalError::new("Unable to find an active editor."))?;
    editor.shared_node_state(node.get_type()).ok_or_else(|| {
        LexicalError::new(format!(
            "getRegisteredNode: Type {} not found",
            node.get_type()
        ))
    })
}

/// `$getWritableNodeState(node)`: makes the node writable and gives it a
/// NodeState of its own.
pub(crate) fn get_writable_node_state(node: &NodeRef) -> Result<NodeStateRef, LexicalError> {
    get_writable(node.get_key());
    let state = {
        let writable = node.get_latest();
        let version = version_of(&*writable);
        match &writable.base().state {
            Some(state) => NodeState::get_writable(state, version),
            None => Rc::new(RefCell::new(NodeState::new(
                version,
                get_shared_node_state(&*writable)?,
                None,
                Vec::new(),
                None,
            ))),
        }
    };
    mutate(node.get_key(), |n| n.base_mut().state = Some(state.clone()));
    Ok(state)
}

/// [`get_state_any`], for the node structure normalization's
/// `mergeAdjacent` comparison.
pub(crate) fn get_state_erased(
    node: &dyn LexicalNode,
    config: &AnyStateConfig,
) -> Result<Rc<dyn Any>, LexicalError> {
    get_state_any(node, config)
}

/// Whether a value of `config` was ever set on this version of `node`, or
/// on the node it was split or copied from: `__state.knownState` has the
/// config, or `__state.unknownState` its key (`@lexical/mark`'s
/// `$hasMarkIDsState` reads them).
#[cfg(all(feature = "mark", feature = "extension"))]
pub(crate) fn has_state_value(node: &dyn LexicalNode, config: &AnyStateConfig) -> bool {
    node.base().state.as_ref().is_some_and(|state| {
        let state = state.borrow();
        state.has_known(config)
            || state
                .unknown_state
                .as_ref()
                .is_some_and(|unknown| unknown.contains_key(config.key()))
    })
}

/// `$getState(node, stateConfig, NODE_STATE_DIRECT)` without its value type.
fn get_state_any(
    node: &dyn LexicalNode,
    config: &AnyStateConfig,
) -> Result<Rc<dyn Any>, LexicalError> {
    match &node.base().state {
        Some(state) => {
            check_collision(node, config, &state.borrow())?;
            Ok(state.borrow_mut().get_value(config))
        }
        None => Ok(config.0.default_any()),
    }
}

/// `$getState(node, stateConfig)`: the value of the state on the latest
/// version of the node, or its default. Fails when another config with the
/// same key was used on the node's type.
pub fn get_state<V: Clone + 'static>(
    node: &NodeRef,
    config: &StateConfig<V>,
) -> Result<V, LexicalError> {
    get_state_direct(&*node.get_latest(), config)
}

/// `$getState(node, stateConfig, NODE_STATE_DIRECT)`: the value on this
/// version of the node, which needs no editor state.
pub fn get_state_direct<V: Clone + 'static>(
    node: &dyn LexicalNode,
    config: &StateConfig<V>,
) -> Result<V, LexicalError> {
    Ok(downcast::<V>(&get_state_any(node, &config.erased())?))
}

/// `$getStateChange(node, prevNode, stateConfig)`: `None` when the two
/// versions hold equal values, else `(value, prevValue)`.
pub fn get_state_change<V: Clone + 'static>(
    node: &dyn LexicalNode,
    prev_node: &dyn LexicalNode,
    config: &StateConfig<V>,
) -> Result<Option<(V, V)>, LexicalError> {
    let value = get_state_direct(node, config)?;
    let prev_value = get_state_direct(prev_node, config)?;
    Ok((!config.is_equal(&value, &prev_value)).then_some((value, prev_value)))
}

/// The writing half of `$setState`.
fn write_state(
    node: &NodeRef,
    config: &AnyStateConfig,
    value: Rc<dyn Any>,
) -> Result<NodeRef, LexicalError> {
    get_writable(node.get_key());
    let state = get_writable_node_state(node)?;
    check_collision(&*node.get_latest(), config, &state.borrow())?;
    state.borrow_mut().update_from_known(config, value);
    Ok(node.clone())
}

/// `$setState(node, stateConfig, valueOrUpdater)` with an updater, without
/// its value type: nothing is written when the value is equal to the one
/// the node has.
fn set_state_any_with(
    node: &NodeRef,
    config: &AnyStateConfig,
    updater: impl FnOnce(&Rc<dyn Any>) -> Rc<dyn Any>,
) -> Result<NodeRef, LexicalError> {
    error_on_read_only();
    let prev_value = get_state_any(&*node.get_latest(), config)?;
    let value = config.canonical_value(updater(&prev_value));
    if config.0.is_equal_any(&*prev_value, &*value) {
        return Ok(node.clone());
    }
    write_state(node, config, value)
}

/// `$setState(node, stateConfig, value)`: sets the state on the node (the
/// node is written even when the value is the one it has). Fails when
/// another config with the same key was used on the node's type.
pub fn set_state<V: Clone + 'static>(
    node: &NodeRef,
    config: &StateConfig<V>,
    value: V,
) -> Result<NodeRef, LexicalError> {
    error_on_read_only();
    let config = config.erased();
    let value = config.canonical_value(Rc::new(value));
    write_state(node, &config, value)
}

/// `$setState(node, stateConfig, updater)`: sets the state to what
/// `updater` makes of the node's value, unless that is equal to it, when
/// the node is left as it is.
pub fn set_state_with<V: Clone + 'static>(
    node: &NodeRef,
    config: &StateConfig<V>,
    updater: impl FnOnce(&V) -> V,
) -> Result<NodeRef, LexicalError> {
    set_state_any_with(node, &config.erased(), |prev| {
        Rc::new(updater(
            prev.downcast_ref::<V>()
                .expect("a value of the config's type"),
        ))
    })
}

/// `$updateStateFromJSON(node, serializedNode)`: the node's NodeState from
/// the `"$"` of its JSON, when it has one or the node has a state.
pub(crate) fn update_state_from_json(node: &NodeRef, json: &Object) -> Result<(), LexicalError> {
    let unknown_state = json
        .get(crate::constants::NODE_STATE_KEY)
        .cloned()
        .unwrap_or(Value::Undefined);
    if node.get_latest().base().state.is_some() || is_truthy(&unknown_state) {
        get_writable_node_state(node)?
            .borrow_mut()
            .update_from_json(&unknown_state);
    }
    Ok(())
}

/// `$applyFlatStates(node, serializedNode, flatStates)`: each flat state the
/// node's class declares, from the top level of its JSON, where it is.
pub(crate) fn apply_flat_states(node: &NodeRef, json: &Object) -> Result<(), LexicalError> {
    let flat_states: Vec<AnyStateConfig> = node
        .get_latest()
        .state_configs()
        .into_iter()
        .filter(|required| required.flat)
        .map(|required| required.state_config)
        .collect();
    for config in flat_states {
        if let Some(raw) = json.get(config.key()).filter(|v| !v.is_undefined()) {
            let parsed = config.0.parse_any(raw);
            set_state_any_with(node, &config, |_| parsed)?;
        }
    }
    Ok(())
}

/// `exportJSON(compact)`: the node's own JSON, then its NodeState.
pub(crate) fn export_json_with_state(node: &dyn LexicalNode, compact: bool) -> Object {
    let mut json = node.export_json(compact);
    if let Some(state) = &node.base().state {
        for (key, value) in state.borrow().to_json().iter() {
            json.insert(key, value.clone());
        }
    }
    json
}

/// `$cloneNodeState(from, to)`: for `to`, a new node, a copy of the
/// NodeState of the version `from` when it belongs to it, else the same.
pub(crate) fn clone_node_state(from: &dyn LexicalNode, to_key: &str) -> Option<NodeStateRef> {
    let state = from.base().state.as_ref()?;
    if state.borrow().node == version_of(from) {
        let to = (to_key.to_owned(), get_active_editor_state().0.id);
        Some(NodeState::get_writable(state, to))
    } else {
        Some(state.clone())
    }
}

/// What `$copyNode` and `afterCloneFrom` give a copy of a node with another
/// key: a copy of the NodeState, with the values of the configs that ask
/// for it reset (`resetOnCopyNodeFrom`) unless `skip_reset`.
pub(crate) fn copy_node_state(
    state: &NodeStateRef,
    to_key: &str,
    skip_reset: bool,
) -> NodeStateRef {
    let to = (to_key.to_owned(), get_active_editor_state().0.id);
    let copy = NodeState::get_writable(state, to);
    if !skip_reset {
        copy.borrow_mut().reset_on_copy_node();
    }
    copy
}

/// `hasUnequalMapEntry(keys, sourceState, otherState)`.
fn has_unequal_map_entry(
    keys: &mut HashSet<String>,
    source_state: &NodeStateRef,
    other_state: Option<&NodeStateRef>,
) -> bool {
    let known = source_state.borrow().known_entries();
    for (config, value) in known {
        if !keys.insert(config.key().to_owned()) {
            continue;
        }
        let other_value = match other_state {
            Some(other) => other.borrow_mut().get_value(&config),
            None => config.0.default_any(),
        };
        if !Rc::ptr_eq(&other_value, &value) && !config.0.is_equal_any(&*other_value, &*value) {
            return true;
        }
    }
    false
}

/// `hasUnequalRecordEntry(keys, sourceState, otherState)`.
fn has_unequal_record_entry(
    keys: &mut HashSet<String>,
    source_state: &NodeStateRef,
    other_state: Option<&NodeStateRef>,
) -> bool {
    let source = source_state.borrow();
    let other = other_state.map(|o| o.borrow());
    let other_unknown = other.as_ref().and_then(|o| o.unknown_state.as_ref());
    for (key, value) in source.unknown_state.iter().flat_map(UnknownState::iter) {
        if !keys.insert(key.to_owned()) {
            continue;
        }
        if !json_strict_equals(Some(value), other_unknown.and_then(|u| u.get(key))) {
            return true;
        }
    }
    false
}

/// `nodeStatesAreEquivalent(a, b)`: whether two text nodes with these
/// states may merge.
pub(crate) fn node_states_are_equivalent(
    a: Option<&NodeStateRef>,
    b: Option<&NodeStateRef>,
) -> bool {
    match (a, b) {
        (None, None) => return true,
        (Some(a), Some(b)) if Rc::ptr_eq(a, b) => return true,
        _ => {}
    }
    let mut keys = HashSet::new();
    !(a.is_some_and(|a| has_unequal_map_entry(&mut keys, a, b))
        || b.is_some_and(|b| has_unequal_map_entry(&mut keys, b, a))
        || a.is_some_and(|a| has_unequal_record_entry(&mut keys, a, b))
        || b.is_some_and(|b| has_unequal_record_entry(&mut keys, b, a)))
}

/// `$carryNodeState(from, to)`: gives `to`, a node that takes the place of
/// `from` with the same content, the NodeState of `from`: known values as
/// they are (as JSON when the type of `to` has another config for the
/// key), JSON as it is, defaults left out, and the keys `to` holds kept.
pub(crate) fn carry_node_state(from: &NodeRef, to: &NodeRef) -> Result<(), LexicalError> {
    let Some(from_state) = from.get_latest().base().state.clone() else {
        return Ok(());
    };
    if from_state.borrow().size == 0 {
        return Ok(());
    }
    let mut done = HashSet::new();
    if let Some(to_state) = to.get_latest().base().state.clone() {
        let to_state = to_state.borrow();
        for (config, _) in &to_state.known_state {
            done.insert(config.key().to_owned());
        }
        for (key, _) in to_state.unknown_state.iter().flat_map(UnknownState::iter) {
            done.insert(key.to_owned());
        }
    }
    let state = get_writable_node_state(to)?;
    let (known, unknown) = {
        let from_state = from_state.borrow();
        (from_state.known_entries(), from_state.unknown_state.clone())
    };
    for (config, value) in known {
        if !done.insert(config.key().to_owned()) {
            continue;
        }
        if config.0.is_equal_any(&*value, &*config.0.default_any()) {
            continue;
        }
        let mut state = state.borrow_mut();
        let own = state
            .shared_node_state
            .shared_config_map
            .borrow()
            .get(config.key())
            .cloned();
        if own.is_none_or(|own| own.is(&config)) {
            state.update_from_known(&config, value);
        } else {
            let json = Rc::new(config.0.unparse_any(&*value));
            state.update_from_unknown(config.key(), json);
        }
    }
    for (key, value) in unknown.iter().flat_map(UnknownState::iter) {
        if !done.contains(key) {
            state.borrow_mut().update_from_unknown(key, value.clone());
        }
    }
    Ok(())
}

/// The value of a known config for a JSON read, as `unparse` writes it
/// (what `registerLexicalTextEntity`'s `$carryNodeState` needs).
#[cfg(any(feature = "text", feature = "devtools"))]
pub(crate) fn unparse(config: &AnyStateConfig, value: &Rc<dyn Any>) -> Value {
    config.0.unparse_any(&**value)
}

/// Whether `value` is the default of `config`.
#[cfg(any(feature = "text", feature = "devtools"))]
pub(crate) fn is_default(config: &AnyStateConfig, value: &Rc<dyn Any>) -> bool {
    config.0.is_equal_any(&**value, &*config.0.default_any())
}

/// `readStateValue(state, stateConfig)` (`registerLexicalTextEntity.ts`):
/// the value `getValue` would give, without keeping a value it parses.
#[cfg(feature = "text")]
fn read_state_value(state: Option<&NodeStateRef>, config: &AnyStateConfig) -> Rc<dyn Any> {
    let Some(state) = state else {
        return config.0.default_any();
    };
    let state = state.borrow();
    if let Some(known) = state.known(config) {
        return known.clone();
    }
    if let Some(json_value) = state
        .unknown_state
        .as_ref()
        .and_then(|u| u.get(config.key()))
    {
        return config.0.parse_any(json_value);
    }
    config.0.default_any()
}

/// `haveEquivalentNodeState(a, b)` (`registerLexicalTextEntity.ts`):
/// whether two states hold equivalent NodeState by the rule that decides
/// whether text nodes merge, as [`node_states_are_equivalent`] does, but
/// reading the other state's values without keeping what it parses.
#[cfg(feature = "text")]
pub(crate) fn have_equivalent_node_state(
    state_a: Option<&NodeStateRef>,
    state_b: Option<&NodeStateRef>,
) -> bool {
    match (state_a, state_b) {
        (None, None) => return true,
        (Some(a), Some(b)) if Rc::ptr_eq(a, b) => return true,
        _ => {}
    }
    let mut keys = HashSet::new();
    let mut has_unequal_known = |source: Option<&NodeStateRef>, other: Option<&NodeStateRef>| {
        let Some(source) = source else {
            return false;
        };
        let known = source.borrow().known_entries();
        for (config, value) in known {
            if !keys.insert(config.key().to_owned()) {
                continue;
            }
            let other_value = read_state_value(other, &config);
            if !Rc::ptr_eq(&other_value, &value) && !config.0.is_equal_any(&*other_value, &*value) {
                return true;
            }
        }
        false
    };
    if has_unequal_known(state_a, state_b) || has_unequal_known(state_b, state_a) {
        return false;
    }
    !(state_a.is_some_and(|a| has_unequal_record_entry(&mut keys, a, state_b))
        || state_b.is_some_and(|b| has_unequal_record_entry(&mut keys, b, state_a)))
}