1use super::format_list::{
4 merge_nested_lists_at_seam, merge_next_sibling_list_if_same_type,
5 update_children_list_item_value,
6};
7use super::generated_json::{export_compact_list_node, export_list_node, update_list_node};
8use super::list_item_node::{create_list_item_node, is_list_item_node};
9use crate::LexicalError;
10use crate::json::Object;
11use crate::lexical_utils::{set_node_key, with_writable};
12use crate::node::{LexicalNode, NodeBase, NodeRef};
13use crate::nodes::element::{self, ElementData};
14use crate::schema::{
15 NodeSchema, NumberValueOptions, aliased_value, enum_value, node_schema, number_value,
16 schema_getter, schema_setter, with_accessors, with_field,
17};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum ListType {
22 #[default]
23 Number,
24 Bullet,
25 Check,
26}
27
28impl ListType {
29 pub fn as_str(self) -> &'static str {
30 match self {
31 ListType::Number => "number",
32 ListType::Bullet => "bullet",
33 ListType::Check => "check",
34 }
35 }
36
37 pub fn parse(list_type: &str) -> Option<Self> {
40 Some(match list_type {
41 "number" => ListType::Number,
42 "bullet" => ListType::Bullet,
43 "check" => ListType::Check,
44 _ => return None,
45 })
46 }
47
48 pub fn tag(self) -> &'static str {
51 match self {
52 ListType::Number => "ol",
53 _ => "ul",
54 }
55 }
56}
57
58#[derive(Clone, Debug)]
64pub struct ListNode {
65 base: NodeBase,
66 pub(super) element: ElementData,
67 pub(super) list_type: ListType,
68 pub(super) start: f64,
69}
70
71impl Default for ListNode {
72 fn default() -> Self {
74 ListNode {
75 base: NodeBase::default(),
76 element: ElementData::default(),
77 list_type: ListType::Number,
78 start: 1.0,
79 }
80 }
81}
82
83pub fn create_list_node(list_type: ListType, start: f64) -> NodeRef {
85 crate::lexical_utils::replaced(set_node_key(Box::new(ListNode {
86 list_type,
87 start,
88 ..ListNode::default()
89 })))
90}
91
92pub fn is_list_node(node: &NodeRef) -> bool {
94 node.get_latest().is::<ListNode>()
95}
96
97impl NodeRef {
98 pub fn get_list_type(&self) -> Option<ListType> {
100 self.get_latest()
101 .downcast_ref::<ListNode>()
102 .map(|l| l.list_type)
103 }
104
105 pub fn set_list_type(&self, list_type: ListType) {
107 if is_list_node(self) {
108 with_writable(self.get_key(), |n| {
109 n.downcast_mut::<ListNode>().expect("a list").list_type = list_type;
110 });
111 }
112 }
113
114 pub fn get_list_tag(&self) -> Option<&'static str> {
116 self.get_list_type().map(ListType::tag)
117 }
118
119 pub fn get_list_start(&self) -> Option<f64> {
121 self.get_latest()
122 .downcast_ref::<ListNode>()
123 .map(|l| l.start)
124 }
125
126 pub fn set_list_start(&self, start: f64) {
128 if is_list_node(self) {
129 with_writable(self.get_key(), |n| {
130 n.downcast_mut::<ListNode>().expect("a list").start = start;
131 });
132 }
133 }
134}
135
136impl ListNode {
137 pub fn list_type(&self) -> ListType {
138 self.list_type
139 }
140
141 pub fn start(&self) -> f64 {
142 self.start
143 }
144}
145
146thread_local! {
147 static LIST_NODE_SCHEMA: NodeSchema = build_list_node_schema().expect("ListNode's schema");
148}
149
150pub fn list_node_schema() -> NodeSchema {
154 LIST_NODE_SCHEMA.with(Clone::clone)
155}
156
157fn build_list_node_schema() -> Result<NodeSchema, LexicalError> {
158 node_schema(vec![
159 (
160 "listType",
161 with_accessors(
162 aliased_value(
163 enum_value(vec!["number".into(), "bullet".into(), "check".into()], None)?,
164 vec![
165 ("ol".to_owned(), "number".into()),
166 ("ul".to_owned(), "bullet".into()),
167 ],
168 )?,
169 Some(schema_getter(|n: &ListNode| n.list_type.as_str().into())),
170 Some(schema_setter(|n: &mut ListNode, value| {
171 n.list_type = value.as_str().and_then(ListType::parse).unwrap_or_default();
172 })),
173 )?,
174 ),
175 (
176 "start",
177 with_field(
178 number_value(1.0, NumberValueOptions::default())?,
179 |n: &ListNode| &n.start,
180 |n: &mut ListNode| &mut n.start,
181 )?,
182 ),
183 (
184 "tag",
185 with_accessors(
186 enum_value(vec!["ul".into(), "ol".into()], None)?,
187 Some(schema_getter(|n: &ListNode| n.list_type.tag().into())),
188 None,
189 )?,
190 ),
191 ])
192}
193
194impl LexicalNode for ListNode {
195 fn json_schema_chain(&self) -> Vec<NodeSchema> {
196 vec![list_node_schema(), element::element_node_schema()]
197 }
198 fn static_node_config_chain(&self) -> Vec<crate::structure::NodeConfigLink> {
202 use crate::structure::{
203 MergeAdjacentDeclaration, MergeAdjacentEntry, NodeChildEntry, NodeChildrenConfig,
204 NodeClassRef, NodeConfigLink, StaticNodeConfig,
205 };
206 vec![NodeConfigLink::new(
207 "list",
208 StaticNodeConfig {
209 children: Some(NodeChildrenConfig::List(vec![NodeChildEntry::Class(
210 NodeClassRef::of::<super::ListItemNode>(),
211 )])),
212 merge_adjacent: Some(MergeAdjacentDeclaration::By(vec![
213 MergeAdjacentEntry::Field("listType"),
214 ])),
215 ..StaticNodeConfig::default()
216 },
217 )]
218 }
219 fn update_dom(&self, prev_node: &dyn LexicalNode) -> bool {
222 prev_node
223 .downcast_ref::<ListNode>()
224 .is_some_and(|prev| prev.list_type != self.list_type)
225 }
226 fn get_type(&self) -> &'static str {
227 "list"
228 }
229 #[cfg(feature = "html")]
230 fn create_dom(
231 &self,
232 this: &NodeRef,
233 config: &crate::EditorConfig,
234 _editor: &crate::Editor,
235 ) -> Result<crate::dom::DomNode, LexicalError> {
236 list_dom::create_dom(self, this, config)
237 }
238 #[cfg(feature = "html")]
239 fn export_dom(
240 &self,
241 this: &NodeRef,
242 editor: &crate::Editor,
243 ) -> Result<crate::lexical_dom::DomExportOutput, LexicalError> {
244 list_dom::export_dom(self, this, editor)
245 }
246 #[cfg(feature = "html")]
247 fn import_dom(&self) -> Option<crate::lexical_dom::DomConversionMap> {
248 Some(list_dom::import_dom())
249 }
250 fn base(&self) -> &NodeBase {
251 &self.base
252 }
253 fn base_mut(&mut self) -> &mut NodeBase {
254 &mut self.base
255 }
256 fn element(&self) -> Option<&ElementData> {
257 Some(&self.element)
258 }
259 fn element_mut(&mut self) -> Option<&mut ElementData> {
260 Some(&mut self.element)
261 }
262
263 fn can_be_empty(&self) -> bool {
265 false
266 }
267
268 fn extract_with_child(
271 &self,
272 _: &NodeRef,
273 child: &NodeRef,
274 _: Option<&crate::lexical_selection::SelectionRef>,
275 _: &str,
276 ) -> Result<bool, LexicalError> {
277 Ok(is_list_item_node(child))
278 }
279
280 fn can_indent(&self) -> bool {
282 false
283 }
284
285 fn generated_export_json(&self, compact: bool) -> Option<Object> {
287 Some(if compact {
288 export_compact_list_node(self)
289 } else {
290 export_list_node(self)
291 })
292 }
293
294 fn generated_update_from_json(&mut self, json: &Object) -> bool {
296 update_list_node(self, json);
297 true
298 }
299
300 fn splice(
304 &self,
305 this: &NodeRef,
306 start: usize,
307 delete_count: usize,
308 nodes_to_insert: &[NodeRef],
309 ) -> Result<(), LexicalError> {
310 let mut list_item_nodes_to_insert = Vec::with_capacity(nodes_to_insert.len());
311 for node in nodes_to_insert {
312 if is_list_item_node(node) {
313 list_item_nodes_to_insert.push(node.clone());
314 continue;
315 }
316 let list_item = create_list_item_node(None);
317 if node.is_element() && !(is_list_node(node) || node.is_inline()) {
318 list_item.append(&node.get_children())?;
321 } else {
322 list_item.append(std::slice::from_ref(node))?;
323 }
324 list_item_nodes_to_insert.push(list_item);
325 }
326 element::splice(this, start, delete_count, &list_item_nodes_to_insert)
327 }
328
329 fn transform(&self, this: &NodeRef) -> Result<(), LexicalError> {
335 let structure_merges = this
336 .get_next_sibling()
337 .is_some_and(|next| crate::structure::structure_merges(this, &next));
338 if !structure_merges {
339 merge_next_sibling_list_if_same_type(this)?;
340 }
341 update_children_list_item_value(this);
342 Ok(())
343 }
344
345 fn internal_after_structure_merge(
350 &self,
351 _: &NodeRef,
352 last: &NodeRef,
353 first: &NodeRef,
354 ) -> Result<bool, LexicalError> {
355 merge_nested_lists_at_seam(Some(last.clone()), Some(first.clone()), true)?;
356 Ok(true)
357 }
358
359 fn internal_after_structure_split(
363 &self,
364 this: &NodeRef,
365 original: &NodeRef,
366 preceding: &[NodeRef],
367 ) -> Result<(), LexicalError> {
368 if self.list_type == ListType::Number {
369 let mut start = original.get_list_start().unwrap_or(1.0);
370 for node in preceding {
371 if is_list_item_node(node)
374 && !node.get_first_child().is_some_and(|c| is_list_node(&c))
375 {
376 start += 1.0;
377 }
378 }
379 this.set_list_start(start);
380 }
381 Ok(())
382 }
383}
384
385#[cfg(feature = "html")]
388pub(super) mod list_dom {
389 use super::super::list_item_node::{create_list_item_node, is_list_item_node};
390 use super::super::utils::get_list_depth;
391 use super::{ListNode, ListType, create_list_node, is_list_node};
392 use crate::dom::DomNode;
393 use crate::json::{Object, Value};
394 use crate::lexical_dom::{
395 DomConversionMap, DomConversionNode, DomConversionOutput, DomExportOutput, get_document,
396 importer, normalize_class_names, set_direction_from_dom,
397 };
398 use crate::node::NodeRef;
399 use crate::{EditorConfig, LexicalError};
400
401 pub(crate) fn create_dom(
404 node: &ListNode,
405 this: &NodeRef,
406 config: &EditorConfig,
407 ) -> Result<DomNode, LexicalError> {
408 let dom = get_document().create_element(node.list_type.tag());
409 if node.start != 1.0 {
410 dom.set_attribute("start", &crate::json::number_to_string(node.start));
411 }
412 set_list_theme_class_names(&dom, &config.theme, node, this)?;
413 Ok(dom)
414 }
415
416 pub(crate) fn export_dom(
419 node: &ListNode,
420 this: &NodeRef,
421 editor: &crate::Editor,
422 ) -> Result<DomExportOutput, LexicalError> {
423 let element = create_dom(node, this, editor.config())?;
424 if node.start != 1.0 {
425 element.set_attribute("start", &crate::json::number_to_string(node.start));
426 }
427 if node.list_type == ListType::Check {
428 element.set_attribute("__lexicalListType", "check");
429 }
430 if let Some(direction) = node.element.get_direction() {
431 element.set_dir(direction.as_str());
432 }
433 Ok(DomExportOutput::element(element))
434 }
435
436 fn class_names_of(value: Option<&Value>) -> Vec<String> {
439 value
440 .and_then(Value::as_str)
441 .map(|v| normalize_class_names(&[v]))
442 .unwrap_or_default()
443 }
444
445 fn set_list_theme_class_names(
447 dom: &DomNode,
448 theme: &Object,
449 node: &ListNode,
450 this: &NodeRef,
451 ) -> Result<(), LexicalError> {
452 let mut classes_to_add: Vec<String> = Vec::new();
453 let mut classes_to_remove: Vec<String> = Vec::new();
454 if let Some(list_theme) = theme.get("list").filter(|v| !v.is_undefined()) {
455 let tag = node.list_type.tag();
456 let empty = Vec::new();
457 let list_levels_class_names = list_theme
458 .get(&format!("{tag}Depth"))
459 .and_then(Value::as_array)
460 .unwrap_or(&empty);
461 let list_depth = get_list_depth(this)? as i64 - 1;
464 let normalized_list_depth = (!list_levels_class_names.is_empty())
465 .then(|| list_depth.rem_euclid(list_levels_class_names.len() as i64) as usize);
466 let list_level_class_name =
467 normalized_list_depth.and_then(|i| list_levels_class_names.get(i));
468 if let Some(list_class_name) = list_theme.get(tag) {
469 classes_to_add.extend(class_names_of(Some(list_class_name)));
470 }
471 if node.list_type == ListType::Check {
472 classes_to_add.extend(class_names_of(list_theme.get("checklist")));
473 }
474 if let Some(list_level_class_name) = list_level_class_name {
475 classes_to_add.extend(class_names_of(Some(list_level_class_name)));
476 for (i, class_name) in list_levels_class_names.iter().enumerate() {
477 if Some(i) != normalized_list_depth {
478 classes_to_remove.extend(class_names_of(Some(class_name)));
479 }
480 }
481 }
482 let nested_list_class_name = list_theme
483 .get("nested")
484 .and_then(|n| n.get("list"))
485 .filter(|l| l.as_str().is_some_and(|s| !s.is_empty()));
486 if nested_list_class_name.is_some() {
487 let nested_list_item_classes = class_names_of(nested_list_class_name);
488 if list_depth > 1 {
489 classes_to_add.extend(nested_list_item_classes);
490 } else {
491 classes_to_remove.extend(nested_list_item_classes);
492 }
493 }
494 }
495 if !classes_to_remove.is_empty() {
496 dom.class_list().remove(&classes_to_remove);
497 }
498 if !classes_to_add.is_empty() {
499 dom.class_list().add(&classes_to_add);
500 }
501 Ok(())
502 }
503
504 pub(crate) fn import_dom() -> DomConversionMap {
506 vec![
507 ("ol".to_owned(), importer(0, convert_list_node)),
508 ("ul".to_owned(), importer(0, convert_list_node)),
509 ]
510 }
511
512 fn normalize_children(nodes: Vec<NodeRef>) -> Result<Vec<NodeRef>, LexicalError> {
516 let mut normalized_list_items = Vec::new();
517 for node in nodes {
518 if is_list_item_node(&node) {
519 normalized_list_items.push(node.clone());
520 let children = node.get_children();
521 if children.len() > 1 {
522 for child in children {
523 if is_list_node(&child) {
524 let wrapper = create_list_item_node(None);
525 wrapper.append(&[child])?;
526 normalized_list_items.push(wrapper);
527 }
528 }
529 }
530 } else {
531 let wrapper = create_list_item_node(None);
532 wrapper.append(&[node])?;
533 normalized_list_items.push(wrapper);
534 }
535 }
536 Ok(normalized_list_items)
537 }
538
539 fn is_dom_checklist(dom_node: &DomNode) -> bool {
542 if dom_node.get_attribute("__lexicallisttype").as_deref() == Some("check")
543 || dom_node.class_list().contains("contains-task-list")
544 || dom_node.get_attribute("data-is-checklist").as_deref() == Some("1")
545 {
546 return true;
547 }
548 dom_node
549 .child_nodes()
550 .iter()
551 .any(|child| child.is_element() && child.has_attribute("aria-checked"))
552 }
553
554 pub(crate) fn ol_start(element: &DomNode) -> f64 {
557 let Some(value) = element.get_attribute("start") else {
558 return 1.0;
559 };
560 let rest = value.trim_start_matches([' ', '\t', '\n', '\u{c}', '\r']);
561 let (sign, rest) = match rest.as_bytes().first() {
562 Some(b'-') => (-1, &rest[1..]),
563 Some(b'+') => (1, &rest[1..]),
564 _ => (1, rest),
565 };
566 let digits = &rest[..rest
567 .bytes()
568 .position(|b| !b.is_ascii_digit())
569 .unwrap_or(rest.len())];
570 match digits.parse::<i64>() {
571 Ok(n) if (-2_147_483_648..=2_147_483_647).contains(&(sign * n)) => (sign * n) as f64,
572 _ => 1.0,
573 }
574 }
575
576 fn convert_list_node(dom_node: &DomNode) -> Result<Option<DomConversionOutput>, LexicalError> {
579 let node = if dom_node.is_element() && dom_node.local_name() == "ol" {
580 create_list_node(ListType::Number, ol_start(dom_node))
581 } else if is_dom_checklist(dom_node) {
582 create_list_node(ListType::Check, 1.0)
583 } else {
584 create_list_node(ListType::Bullet, 1.0)
585 };
586 set_direction_from_dom(&node, dom_node);
587 Ok(Some(DomConversionOutput {
588 node: DomConversionNode::One(node),
589 after: Some(Box::new(normalize_children)),
590 ..DomConversionOutput::default()
591 }))
592 }
593}