@ekz/lexical-list 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1638 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ */
8
+
9
+ import { effect, namedSignals } from '@ekz/lexical-extension';
10
+ import { $getNearestNodeOfType, removeClassNamesFromElement, addClassNamesToElement, isHTMLElement, mergeRegister, $findMatchingParent, calculateZoomLevel } from '@ekz/lexical-utils';
11
+ import { $getSelection, $isRangeSelection, $isRootOrShadowRoot, $createParagraphNode, $isElementNode, $isLeafNode, $setPointFromCaret, $normalizeCaret, $getChildCaret, $isTextNode, ElementNode, buildImportMap, $isParagraphNode, $applyNodeReplacement, normalizeClassNames, $createTextNode, createCommand, COMMAND_PRIORITY_LOW, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_UP_COMMAND, KEY_ESCAPE_COMMAND, KEY_SPACE_COMMAND, $getNearestNodeFromDOMNode, KEY_ARROW_LEFT_COMMAND, getNearestEditorFromDOMNode, defineExtension, safeCast, $getNodeByKey, INSERT_PARAGRAPH_COMMAND, TextNode } from '@ekz/lexical';
12
+ import { getStyleObjectFromCSS } from '@ekz/lexical-selection';
13
+
14
+ /**
15
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
16
+ *
17
+ * This source code is licensed under the MIT license found in the
18
+ * LICENSE file in the root directory of this source tree.
19
+ *
20
+ */
21
+
22
+ // Do not require this module directly! Use normal `invariant` calls.
23
+
24
+ function formatDevErrorMessage(message) {
25
+ throw new Error(message);
26
+ }
27
+
28
+ /**
29
+ * Checks the depth of listNode from the root node.
30
+ * @param listNode - The ListNode to be checked.
31
+ * @returns The depth of the ListNode.
32
+ */
33
+ function $getListDepth(listNode) {
34
+ let depth = 1;
35
+ let parent = listNode.getParent();
36
+ while (parent != null) {
37
+ if ($isListItemNode(parent)) {
38
+ const parentList = parent.getParent();
39
+ if ($isListNode(parentList)) {
40
+ depth++;
41
+ parent = parentList.getParent();
42
+ continue;
43
+ }
44
+ {
45
+ formatDevErrorMessage(`A ListItemNode must have a ListNode for a parent.`);
46
+ }
47
+ }
48
+ return depth;
49
+ }
50
+ return depth;
51
+ }
52
+
53
+ /**
54
+ * Finds the nearest ancestral ListNode and returns it, throws an invariant if listItem is not a ListItemNode.
55
+ * @param listItem - The node to be checked.
56
+ * @returns The ListNode found.
57
+ */
58
+ function $getTopListNode(listItem) {
59
+ let list = listItem.getParent();
60
+ if (!$isListNode(list)) {
61
+ {
62
+ formatDevErrorMessage(`A ListItemNode must have a ListNode for a parent.`);
63
+ }
64
+ }
65
+ let parent = list;
66
+ while (parent !== null) {
67
+ parent = parent.getParent();
68
+ if ($isListNode(parent)) {
69
+ list = parent;
70
+ }
71
+ }
72
+ return list;
73
+ }
74
+
75
+ /**
76
+ * A recursive Depth-First Search (Postorder Traversal) that finds all of a node's children
77
+ * that are of type ListItemNode and returns them in an array.
78
+ * @param node - The ListNode to start the search.
79
+ * @returns An array containing all nodes of type ListItemNode found.
80
+ */
81
+ // This should probably be $getAllChildrenOfType
82
+ function $getAllListItems(node) {
83
+ let listItemNodes = [];
84
+ const listChildren = node.getChildren().filter($isListItemNode);
85
+ for (let i = 0; i < listChildren.length; i++) {
86
+ const listItemNode = listChildren[i];
87
+ const firstChild = listItemNode.getFirstChild();
88
+ if ($isListNode(firstChild)) {
89
+ listItemNodes = listItemNodes.concat($getAllListItems(firstChild));
90
+ } else {
91
+ listItemNodes.push(listItemNode);
92
+ }
93
+ }
94
+ return listItemNodes;
95
+ }
96
+
97
+ /**
98
+ * Checks to see if the passed node is a ListItemNode and has a ListNode as a child.
99
+ * @param node - The node to be checked.
100
+ * @returns true if the node is a ListItemNode and has a ListNode child, false otherwise.
101
+ */
102
+ function isNestedListNode(node) {
103
+ return $isListItemNode(node) && $isListNode(node.getFirstChild());
104
+ }
105
+
106
+ /**
107
+ * Takes a deeply nested ListNode or ListItemNode and traverses up the branch to delete the first
108
+ * ancestral ListNode (which could be the root ListNode) or ListItemNode with siblings, essentially
109
+ * bringing the deeply nested node up the branch once. Would remove sublist if it has siblings.
110
+ * Should not break ListItem -> List -> ListItem chain as empty List/ItemNodes should be removed on .remove().
111
+ * @param sublist - The nested ListNode or ListItemNode to be brought up the branch.
112
+ */
113
+ function $removeHighestEmptyListParent(sublist) {
114
+ // Nodes may be repeatedly indented, to create deeply nested lists that each
115
+ // contain just one bullet.
116
+ // Our goal is to remove these (empty) deeply nested lists. The easiest
117
+ // way to do that is crawl back up the tree until we find a node that has siblings
118
+ // (e.g. is actually part of the list contents) and delete that, or delete
119
+ // the root of the list (if no list nodes have siblings.)
120
+ let emptyListPtr = sublist;
121
+ while (emptyListPtr.getNextSibling() == null && emptyListPtr.getPreviousSibling() == null) {
122
+ const parent = emptyListPtr.getParent();
123
+ if (parent == null || !($isListItemNode(parent) || $isListNode(parent))) {
124
+ break;
125
+ }
126
+ emptyListPtr = parent;
127
+ }
128
+ emptyListPtr.remove();
129
+ }
130
+
131
+ /**
132
+ * Wraps a node into a ListItemNode.
133
+ * @param node - The node to be wrapped into a ListItemNode
134
+ * @returns The ListItemNode which the passed node is wrapped in.
135
+ */
136
+ function $wrapInListItem(node) {
137
+ const listItemWrapper = $createListItemNode();
138
+ return listItemWrapper.append(node);
139
+ }
140
+
141
+ function $isSelectingEmptyListItem(anchorNode, nodes) {
142
+ return $isListItemNode(anchorNode) && (nodes.length === 0 || nodes.length === 1 && anchorNode.is(nodes[0]) && anchorNode.getChildrenSize() === 0);
143
+ }
144
+
145
+ /**
146
+ * Inserts a new ListNode. If the selection's anchor node is an empty ListItemNode and is a child of
147
+ * the root/shadow root, it will replace the ListItemNode with a ListNode and the old ListItemNode.
148
+ * Otherwise it will replace its parent with a new ListNode and re-insert the ListItemNode and any previous children.
149
+ * If the selection's anchor node is not an empty ListItemNode, it will add a new ListNode or merge an existing ListNode,
150
+ * unless the the node is a leaf node, in which case it will attempt to find a ListNode up the branch and replace it with
151
+ * a new ListNode, or create a new ListNode at the nearest root/shadow root.
152
+ * @param listType - The type of list, "number" | "bullet" | "check".
153
+ */
154
+ function $insertList(listType) {
155
+ const selection = $getSelection();
156
+ if (selection !== null) {
157
+ let nodes = selection.getNodes();
158
+ if ($isRangeSelection(selection)) {
159
+ const anchorAndFocus = selection.getStartEndPoints();
160
+ if (!(anchorAndFocus !== null)) {
161
+ formatDevErrorMessage(`insertList: anchor should be defined`);
162
+ }
163
+ const [anchor] = anchorAndFocus;
164
+ const anchorNode = anchor.getNode();
165
+ const anchorNodeParent = anchorNode.getParent();
166
+ if ($isRootOrShadowRoot(anchorNode)) {
167
+ const firstChild = anchorNode.getFirstChild();
168
+ if (firstChild) {
169
+ nodes = firstChild.selectStart().getNodes();
170
+ } else {
171
+ const paragraph = $createParagraphNode();
172
+ anchorNode.append(paragraph);
173
+ nodes = paragraph.select().getNodes();
174
+ }
175
+ } else if ($isSelectingEmptyListItem(anchorNode, nodes)) {
176
+ const list = $createListNode(listType);
177
+ if ($isRootOrShadowRoot(anchorNodeParent)) {
178
+ anchorNode.replace(list);
179
+ const listItem = $createListItemNode();
180
+ if ($isElementNode(anchorNode)) {
181
+ listItem.setFormat(anchorNode.getFormatType());
182
+ listItem.setIndent(anchorNode.getIndent());
183
+ }
184
+ list.append(listItem);
185
+ } else if ($isListItemNode(anchorNode)) {
186
+ const parent = anchorNode.getParentOrThrow();
187
+ append(list, parent.getChildren());
188
+ parent.replace(list);
189
+ }
190
+ return;
191
+ }
192
+ }
193
+ const handled = new Set();
194
+ for (let i = 0; i < nodes.length; i++) {
195
+ const node = nodes[i];
196
+ if ($isElementNode(node) && node.isEmpty() && !$isListItemNode(node) && !handled.has(node.getKey())) {
197
+ $createListOrMerge(node, listType);
198
+ continue;
199
+ }
200
+ let parent = $isLeafNode(node) ? node.getParent() : $isListItemNode(node) && node.isEmpty() ? node : null;
201
+ while (parent != null) {
202
+ const parentKey = parent.getKey();
203
+ if ($isListNode(parent)) {
204
+ if (!handled.has(parentKey)) {
205
+ const newListNode = $createListNode(listType);
206
+ append(newListNode, parent.getChildren());
207
+ parent.replace(newListNode);
208
+ handled.add(parentKey);
209
+ }
210
+ break;
211
+ } else {
212
+ const nextParent = parent.getParent();
213
+ if ($isRootOrShadowRoot(nextParent) && !handled.has(parentKey)) {
214
+ handled.add(parentKey);
215
+ $createListOrMerge(parent, listType);
216
+ break;
217
+ }
218
+ parent = nextParent;
219
+ }
220
+ }
221
+ }
222
+ }
223
+ }
224
+ function append(node, nodesToAppend) {
225
+ node.splice(node.getChildrenSize(), 0, nodesToAppend);
226
+ }
227
+ function $createListOrMerge(node, listType) {
228
+ if ($isListNode(node)) {
229
+ return node;
230
+ }
231
+ const previousSibling = node.getPreviousSibling();
232
+ const nextSibling = node.getNextSibling();
233
+ const listItem = $createListItemNode();
234
+ append(listItem, node.getChildren());
235
+ let targetList;
236
+ if ($isListNode(previousSibling) && listType === previousSibling.getListType()) {
237
+ previousSibling.append(listItem);
238
+ // if the same type of list is on both sides, merge them.
239
+ if ($isListNode(nextSibling) && listType === nextSibling.getListType()) {
240
+ append(previousSibling, nextSibling.getChildren());
241
+ nextSibling.remove();
242
+ }
243
+ targetList = previousSibling;
244
+ } else if ($isListNode(nextSibling) && listType === nextSibling.getListType()) {
245
+ nextSibling.getFirstChildOrThrow().insertBefore(listItem);
246
+ targetList = nextSibling;
247
+ } else {
248
+ const list = $createListNode(listType);
249
+ list.append(listItem);
250
+ node.replace(list);
251
+ targetList = list;
252
+ }
253
+ // listItem needs to be attached to root prior to setting indent
254
+ listItem.setFormat(node.getFormatType());
255
+ listItem.setIndent(node.getIndent());
256
+
257
+ // Preserve element-anchored selections by updating them to anchor to the listItem instead of the listNode.
258
+ const selection = $getSelection();
259
+ if ($isRangeSelection(selection)) {
260
+ if (targetList.getKey() === selection.anchor.key) {
261
+ selection.anchor.set(listItem.getKey(), selection.anchor.offset, 'element');
262
+ }
263
+ if (targetList.getKey() === selection.focus.key) {
264
+ selection.focus.set(listItem.getKey(), selection.focus.offset, 'element');
265
+ }
266
+ }
267
+ node.remove();
268
+ return targetList;
269
+ }
270
+
271
+ /**
272
+ * A recursive function that goes through each list and their children, including nested lists,
273
+ * appending list2 children after list1 children and updating ListItemNode values.
274
+ * @param list1 - The first list to be merged.
275
+ * @param list2 - The second list to be merged.
276
+ */
277
+ function mergeLists(list1, list2) {
278
+ const listItem1 = list1.getLastChild();
279
+ const listItem2 = list2.getFirstChild();
280
+ if (listItem1 && listItem2 && isNestedListNode(listItem1) && isNestedListNode(listItem2)) {
281
+ mergeLists(listItem1.getFirstChild(), listItem2.getFirstChild());
282
+ listItem2.remove();
283
+ }
284
+ const toMerge = list2.getChildren();
285
+ if (toMerge.length > 0) {
286
+ list1.append(...toMerge);
287
+ }
288
+ list2.remove();
289
+ }
290
+
291
+ /**
292
+ * Searches for the nearest ancestral ListNode and removes it. If selection is an empty ListItemNode
293
+ * it will remove the whole list, including the ListItemNode. For each ListItemNode in the ListNode,
294
+ * removeList will also generate new ParagraphNodes in the removed ListNode's place. Any child node
295
+ * inside a ListItemNode will be appended to the new ParagraphNodes.
296
+ */
297
+ function $removeList() {
298
+ const selection = $getSelection();
299
+ if ($isRangeSelection(selection)) {
300
+ const listNodes = new Set();
301
+ const nodes = selection.getNodes();
302
+ const anchorNode = selection.anchor.getNode();
303
+ if ($isSelectingEmptyListItem(anchorNode, nodes)) {
304
+ listNodes.add($getTopListNode(anchorNode));
305
+ } else {
306
+ for (let i = 0; i < nodes.length; i++) {
307
+ const node = nodes[i];
308
+ if ($isLeafNode(node)) {
309
+ const listItemNode = $getNearestNodeOfType(node, ListItemNode);
310
+ if (listItemNode != null) {
311
+ listNodes.add($getTopListNode(listItemNode));
312
+ }
313
+ }
314
+ }
315
+ }
316
+ for (const listNode of listNodes) {
317
+ let insertionPoint = listNode;
318
+ const listItems = $getAllListItems(listNode);
319
+ for (const listItemNode of listItems) {
320
+ const paragraph = $createParagraphNode().setTextStyle(selection.style).setTextFormat(selection.format);
321
+ append(paragraph, listItemNode.getChildren());
322
+ insertionPoint.insertAfter(paragraph);
323
+ insertionPoint = paragraph;
324
+
325
+ // When the anchor and focus fall on the textNode
326
+ // we don't have to change the selection because the textNode will be appended to
327
+ // the newly generated paragraph.
328
+ // When selection is in empty nested list item, selection is actually on the listItemNode.
329
+ // When the corresponding listItemNode is deleted and replaced by the newly generated paragraph
330
+ // we should manually set the selection's focus and anchor to the newly generated paragraph.
331
+ if (listItemNode.__key === selection.anchor.key) {
332
+ $setPointFromCaret(selection.anchor, $normalizeCaret($getChildCaret(paragraph, 'next')));
333
+ }
334
+ if (listItemNode.__key === selection.focus.key) {
335
+ $setPointFromCaret(selection.focus, $normalizeCaret($getChildCaret(paragraph, 'next')));
336
+ }
337
+ listItemNode.remove();
338
+ }
339
+ listNode.remove();
340
+ }
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Takes the value of a child ListItemNode and makes it the value the ListItemNode
346
+ * should be if it isn't already. Also ensures that checked is undefined if the
347
+ * parent does not have a list type of 'check'.
348
+ * @param list - The list whose children are updated.
349
+ */
350
+ function updateChildrenListItemValue(list) {
351
+ const isNotChecklist = list.getListType() !== 'check';
352
+ let value = list.getStart();
353
+ for (const child of list.getChildren()) {
354
+ if ($isListItemNode(child)) {
355
+ if (child.getValue() !== value) {
356
+ child.setValue(value);
357
+ }
358
+ if (isNotChecklist && child.getLatest().__checked != null) {
359
+ child.setChecked(undefined);
360
+ }
361
+ if (!$isListNode(child.getFirstChild())) {
362
+ value++;
363
+ }
364
+ }
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Merge the next sibling list if same type.
370
+ * <ul> will merge with <ul>, but NOT <ul> with <ol>.
371
+ * @param list - The list whose next sibling should be potentially merged
372
+ */
373
+ function mergeNextSiblingListIfSameType(list) {
374
+ const nextSibling = list.getNextSibling();
375
+ if ($isListNode(nextSibling) && list.getListType() === nextSibling.getListType()) {
376
+ mergeLists(list, nextSibling);
377
+ }
378
+ }
379
+
380
+ /**
381
+ * Adds an empty ListNode/ListItemNode chain at listItemNode, so as to
382
+ * create an indent effect. Won't indent ListItemNodes that have a ListNode as
383
+ * a child, but does merge sibling ListItemNodes if one has a nested ListNode.
384
+ * @param listItemNode - The ListItemNode to be indented.
385
+ */
386
+ function $handleIndent(listItemNode) {
387
+ // go through each node and decide where to move it.
388
+ const removed = new Set();
389
+ if (isNestedListNode(listItemNode) || removed.has(listItemNode.getKey())) {
390
+ return;
391
+ }
392
+ const parent = listItemNode.getParent();
393
+
394
+ // We can cast both of the below `isNestedListNode` only returns a boolean type instead of a user-defined type guards
395
+ const nextSibling = listItemNode.getNextSibling();
396
+ const previousSibling = listItemNode.getPreviousSibling();
397
+ // if there are nested lists on either side, merge them all together.
398
+
399
+ if (isNestedListNode(nextSibling) && isNestedListNode(previousSibling)) {
400
+ const innerList = previousSibling.getFirstChild();
401
+ if ($isListNode(innerList)) {
402
+ innerList.append(listItemNode);
403
+ const nextInnerList = nextSibling.getFirstChild();
404
+ if ($isListNode(nextInnerList)) {
405
+ const children = nextInnerList.getChildren();
406
+ append(innerList, children);
407
+ nextSibling.remove();
408
+ removed.add(nextSibling.getKey());
409
+ }
410
+ }
411
+ } else if (isNestedListNode(nextSibling)) {
412
+ // if the ListItemNode is next to a nested ListNode, merge them
413
+ const innerList = nextSibling.getFirstChild();
414
+ if ($isListNode(innerList)) {
415
+ const firstChild = innerList.getFirstChild();
416
+ if (firstChild !== null) {
417
+ firstChild.insertBefore(listItemNode);
418
+ }
419
+ }
420
+ } else if (isNestedListNode(previousSibling)) {
421
+ const innerList = previousSibling.getFirstChild();
422
+ if ($isListNode(innerList)) {
423
+ innerList.append(listItemNode);
424
+ }
425
+ } else {
426
+ // otherwise, we need to create a new nested ListNode
427
+
428
+ if ($isListNode(parent)) {
429
+ const newListItem = $createListItemNode().setTextFormat(listItemNode.getTextFormat()).setTextStyle(listItemNode.getTextStyle());
430
+ const newList = $createListNode(parent.getListType()).setTextFormat(parent.getTextFormat()).setTextStyle(parent.getTextStyle());
431
+ newListItem.append(newList);
432
+ newList.append(listItemNode);
433
+ if (previousSibling) {
434
+ previousSibling.insertAfter(newListItem);
435
+ } else if (nextSibling) {
436
+ nextSibling.insertBefore(newListItem);
437
+ } else {
438
+ parent.append(newListItem);
439
+ }
440
+ }
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Removes an indent by removing an empty ListNode/ListItemNode chain. An indented ListItemNode
446
+ * has a great grandparent node of type ListNode, which is where the ListItemNode will reside
447
+ * within as a child.
448
+ * @param listItemNode - The ListItemNode to remove the indent (outdent).
449
+ */
450
+ function $handleOutdent(listItemNode) {
451
+ // go through each node and decide where to move it.
452
+
453
+ if (isNestedListNode(listItemNode)) {
454
+ return;
455
+ }
456
+ const parentList = listItemNode.getParent();
457
+ const grandparentListItem = parentList ? parentList.getParent() : undefined;
458
+ const greatGrandparentList = grandparentListItem ? grandparentListItem.getParent() : undefined;
459
+ // If it doesn't have these ancestors, it's not indented.
460
+
461
+ if ($isListNode(greatGrandparentList) && $isListItemNode(grandparentListItem) && $isListNode(parentList)) {
462
+ // if it's the first child in it's parent list, insert it into the
463
+ // great grandparent list before the grandparent
464
+ const firstChild = parentList ? parentList.getFirstChild() : undefined;
465
+ const lastChild = parentList ? parentList.getLastChild() : undefined;
466
+ if (listItemNode.is(firstChild)) {
467
+ grandparentListItem.insertBefore(listItemNode);
468
+ if (parentList.isEmpty()) {
469
+ grandparentListItem.remove();
470
+ }
471
+ // if it's the last child in it's parent list, insert it into the
472
+ // great grandparent list after the grandparent.
473
+ } else if (listItemNode.is(lastChild)) {
474
+ grandparentListItem.insertAfter(listItemNode);
475
+ if (parentList.isEmpty()) {
476
+ grandparentListItem.remove();
477
+ }
478
+ } else {
479
+ // otherwise, we need to split the siblings into two new nested lists
480
+ const listType = parentList.getListType();
481
+ const previousSiblingsListItem = $createListItemNode();
482
+ const previousSiblingsList = $createListNode(listType);
483
+ previousSiblingsListItem.append(previousSiblingsList);
484
+ listItemNode.getPreviousSiblings().forEach(sibling => previousSiblingsList.append(sibling));
485
+ const nextSiblingsListItem = $createListItemNode();
486
+ const nextSiblingsList = $createListNode(listType);
487
+ nextSiblingsListItem.append(nextSiblingsList);
488
+ append(nextSiblingsList, listItemNode.getNextSiblings());
489
+ // put the sibling nested lists on either side of the grandparent list item in the great grandparent.
490
+ grandparentListItem.insertBefore(previousSiblingsListItem);
491
+ grandparentListItem.insertAfter(nextSiblingsListItem);
492
+ // replace the grandparent list item (now between the siblings) with the outdented list item.
493
+ grandparentListItem.replace(listItemNode);
494
+ }
495
+ }
496
+ }
497
+
498
+ /**
499
+ * Attempts to insert a ParagraphNode at selection and selects the new node. The selection must contain a ListItemNode
500
+ * or a node that does not already contain text. If its grandparent is the root/shadow root, it will get the ListNode
501
+ * (which should be the parent node) and insert the ParagraphNode as a sibling to the ListNode. If the ListNode is
502
+ * nested in a ListItemNode instead, it will add the ParagraphNode after the grandparent ListItemNode.
503
+ * Throws an invariant if the selection is not a child of a ListNode.
504
+ * @returns true if a ParagraphNode was inserted successfully, false if there is no selection
505
+ * or the selection does not contain a ListItemNode or the node already holds text.
506
+ */
507
+ function $handleListInsertParagraph() {
508
+ const selection = $getSelection();
509
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
510
+ return false;
511
+ }
512
+ // Only run this code on empty list items (including whitespace-only)
513
+ const anchor = selection.anchor.getNode();
514
+ let listItem = null;
515
+ if ($isListItemNode(anchor) && anchor.getChildrenSize() === 0) {
516
+ // Truly empty list item (element selection)
517
+ listItem = anchor;
518
+ } else if ($isTextNode(anchor)) {
519
+ // Check if the entire list item contains only whitespace text nodes
520
+ const parentListItem = anchor.getParent();
521
+ if ($isListItemNode(parentListItem) && parentListItem.getChildren().every(node => $isTextNode(node) && node.getTextContent().trim() === '')) {
522
+ listItem = parentListItem;
523
+ }
524
+ }
525
+ if (listItem === null) {
526
+ return false;
527
+ }
528
+ const topListNode = $getTopListNode(listItem);
529
+ const parent = listItem.getParent();
530
+ if (!$isListNode(parent)) {
531
+ formatDevErrorMessage(`A ListItemNode must have a ListNode for a parent.`);
532
+ }
533
+ const grandparent = parent.getParent();
534
+ let replacementNode;
535
+ if ($isRootOrShadowRoot(grandparent)) {
536
+ replacementNode = $createParagraphNode();
537
+ topListNode.insertAfter(replacementNode);
538
+ } else if ($isListItemNode(grandparent)) {
539
+ replacementNode = $createListItemNode();
540
+ grandparent.insertAfter(replacementNode);
541
+ } else {
542
+ return false;
543
+ }
544
+ replacementNode.setTextStyle(selection.style).setTextFormat(selection.format).select();
545
+ const nextSiblings = listItem.getNextSiblings();
546
+ if (nextSiblings.length > 0) {
547
+ const newList = $createListNode(parent.getListType());
548
+ if ($isListItemNode(replacementNode)) {
549
+ const newListItem = $createListItemNode();
550
+ newListItem.append(newList);
551
+ replacementNode.insertAfter(newListItem);
552
+ } else {
553
+ replacementNode.insertAfter(newList);
554
+ }
555
+ newList.append(...nextSiblings);
556
+ }
557
+
558
+ // Don't leave hanging nested empty lists
559
+ $removeHighestEmptyListParent(listItem);
560
+ return true;
561
+ }
562
+
563
+ function applyMarkerStyles(dom, node, prevNode) {
564
+ const styles = getStyleObjectFromCSS(node.__textStyle);
565
+ for (const k in styles) {
566
+ dom.style.setProperty(`--listitem-marker-${k}`, styles[k]);
567
+ }
568
+ if (prevNode) {
569
+ for (const k in getStyleObjectFromCSS(prevNode.__textStyle)) {
570
+ if (!(k in styles)) {
571
+ dom.style.removeProperty(`--listitem-marker-${k}`);
572
+ }
573
+ }
574
+ }
575
+ }
576
+
577
+ /** @noInheritDoc */
578
+ class ListItemNode extends ElementNode {
579
+ /** @internal */
580
+ __value;
581
+ /** @internal */
582
+ __checked;
583
+
584
+ /** @internal */
585
+ $config() {
586
+ return this.config('listitem', {
587
+ $transform: node => {
588
+ if (node.__checked == null) {
589
+ return;
590
+ }
591
+ const parent = node.getParent();
592
+ if ($isListNode(parent)) {
593
+ if (parent.getListType() !== 'check' && node.getChecked() != null) {
594
+ node.setChecked(undefined);
595
+ }
596
+ }
597
+ },
598
+ extends: ElementNode,
599
+ importDOM: buildImportMap({
600
+ li: () => ({
601
+ conversion: $convertListItemElement,
602
+ priority: 0
603
+ })
604
+ })
605
+ });
606
+ }
607
+ constructor(value = 1, checked = undefined, key) {
608
+ super(key);
609
+ this.__value = value === undefined ? 1 : value;
610
+ this.__checked = checked;
611
+ }
612
+ afterCloneFrom(prevNode) {
613
+ super.afterCloneFrom(prevNode);
614
+ this.__value = prevNode.__value;
615
+ this.__checked = prevNode.__checked;
616
+ }
617
+ createDOM(config) {
618
+ const element = document.createElement('li');
619
+ this.updateListItemDOM(null, element, config);
620
+ return element;
621
+ }
622
+ updateListItemDOM(prevNode, dom, config) {
623
+ updateListItemChecked(dom, this, prevNode);
624
+ dom.value = this.__value;
625
+ $setListItemThemeClassNames(dom, config.theme, this);
626
+ const prevStyle = prevNode ? prevNode.__style : '';
627
+ const nextStyle = this.__style;
628
+ if (prevStyle !== nextStyle) {
629
+ if (nextStyle === '') {
630
+ dom.removeAttribute('style');
631
+ } else {
632
+ dom.style.cssText = nextStyle;
633
+ }
634
+ }
635
+ applyMarkerStyles(dom, this, prevNode);
636
+ }
637
+ updateDOM(prevNode, dom, config) {
638
+ // @ts-expect-error - this is always HTMLListItemElement
639
+ const element = dom;
640
+ this.updateListItemDOM(prevNode, element, config);
641
+ return false;
642
+ }
643
+ updateFromJSON(serializedNode) {
644
+ return super.updateFromJSON(serializedNode).setValue(serializedNode.value).setChecked(serializedNode.checked);
645
+ }
646
+ exportDOM(editor) {
647
+ const element = this.createDOM(editor._config);
648
+ const formatType = this.getFormatType();
649
+ if (formatType) {
650
+ element.style.textAlign = formatType;
651
+ }
652
+ const direction = this.getDirection();
653
+ if (direction) {
654
+ element.dir = direction;
655
+ }
656
+ return {
657
+ element
658
+ };
659
+ }
660
+ exportJSON() {
661
+ return {
662
+ ...super.exportJSON(),
663
+ checked: this.getChecked(),
664
+ value: this.getValue()
665
+ };
666
+ }
667
+ append(...nodes) {
668
+ for (let i = 0; i < nodes.length; i++) {
669
+ const node = nodes[i];
670
+ if ($isElementNode(node) && this.canMergeWith(node)) {
671
+ const children = node.getChildren();
672
+ this.append(...children);
673
+ node.remove();
674
+ } else {
675
+ super.append(node);
676
+ }
677
+ }
678
+ return this;
679
+ }
680
+ replace(replaceWithNode, includeChildren) {
681
+ if ($isListItemNode(replaceWithNode)) {
682
+ return super.replace(replaceWithNode);
683
+ }
684
+ this.setIndent(0);
685
+ const list = this.getParentOrThrow();
686
+ if (!$isListNode(list)) {
687
+ return replaceWithNode;
688
+ }
689
+ if (list.__first === this.getKey()) {
690
+ list.insertBefore(replaceWithNode);
691
+ } else if (list.__last === this.getKey()) {
692
+ list.insertAfter(replaceWithNode);
693
+ } else {
694
+ // Split the list
695
+ const newList = $createListNode(list.getListType());
696
+ let nextSibling = this.getNextSibling();
697
+ while (nextSibling) {
698
+ const nodeToAppend = nextSibling;
699
+ nextSibling = nextSibling.getNextSibling();
700
+ newList.append(nodeToAppend);
701
+ }
702
+ list.insertAfter(replaceWithNode);
703
+ replaceWithNode.insertAfter(newList);
704
+ }
705
+ if (includeChildren) {
706
+ if (!$isElementNode(replaceWithNode)) {
707
+ formatDevErrorMessage(`includeChildren should only be true for ElementNodes`);
708
+ }
709
+ this.getChildren().forEach(child => {
710
+ replaceWithNode.append(child);
711
+ });
712
+ }
713
+ this.remove();
714
+ if (list.getChildrenSize() === 0) {
715
+ list.remove();
716
+ }
717
+ return replaceWithNode;
718
+ }
719
+ insertAfter(node, restoreSelection = true) {
720
+ const listNode = this.getParentOrThrow();
721
+ if (!$isListNode(listNode)) {
722
+ {
723
+ formatDevErrorMessage(`insertAfter: list node is not parent of list item node`);
724
+ }
725
+ }
726
+ if ($isListItemNode(node)) {
727
+ return super.insertAfter(node, restoreSelection);
728
+ }
729
+ const siblings = this.getNextSiblings();
730
+
731
+ // Split the lists and insert the node in between them
732
+ listNode.insertAfter(node, restoreSelection);
733
+ if (siblings.length !== 0) {
734
+ const newListNode = $createListNode(listNode.getListType());
735
+ siblings.forEach(sibling => newListNode.append(sibling));
736
+ node.insertAfter(newListNode, restoreSelection);
737
+ }
738
+ return node;
739
+ }
740
+ remove(preserveEmptyParent) {
741
+ const prevSibling = this.getPreviousSibling();
742
+ const nextSibling = this.getNextSibling();
743
+ super.remove(preserveEmptyParent);
744
+ if (prevSibling && nextSibling && isNestedListNode(prevSibling) && isNestedListNode(nextSibling)) {
745
+ mergeLists(prevSibling.getFirstChild(), nextSibling.getFirstChild());
746
+ nextSibling.remove();
747
+ }
748
+ }
749
+ insertNewAfter(_, restoreSelection = true) {
750
+ const newElement = $createListItemNode().updateFromJSON(this.exportJSON()).setChecked(this.getChecked() ? false : undefined);
751
+ this.insertAfter(newElement, restoreSelection);
752
+ return newElement;
753
+ }
754
+ collapseAtStart(selection) {
755
+ const paragraph = $createParagraphNode();
756
+ const children = this.getChildren();
757
+ children.forEach(child => paragraph.append(child));
758
+ const listNode = this.getParentOrThrow();
759
+ const listNodeParent = listNode.getParentOrThrow();
760
+ const isIndented = $isListItemNode(listNodeParent);
761
+ if (listNode.getChildrenSize() === 1) {
762
+ if (isIndented) {
763
+ // if the list node is nested, we just want to remove it,
764
+ // effectively unindenting it.
765
+ listNode.remove();
766
+ listNodeParent.select();
767
+ } else {
768
+ listNode.insertBefore(paragraph);
769
+ listNode.remove();
770
+ // If we have selection on the list item, we'll need to move it
771
+ // to the paragraph
772
+ const anchor = selection.anchor;
773
+ const focus = selection.focus;
774
+ const key = paragraph.getKey();
775
+ if (anchor.type === 'element' && anchor.getNode().is(this)) {
776
+ anchor.set(key, anchor.offset, 'element');
777
+ }
778
+ if (focus.type === 'element' && focus.getNode().is(this)) {
779
+ focus.set(key, focus.offset, 'element');
780
+ }
781
+ }
782
+ } else {
783
+ listNode.insertBefore(paragraph);
784
+ this.remove();
785
+ }
786
+ return true;
787
+ }
788
+ getValue() {
789
+ const self = this.getLatest();
790
+ return self.__value;
791
+ }
792
+ setValue(value) {
793
+ const self = this.getWritable();
794
+ self.__value = value;
795
+ return self;
796
+ }
797
+ getChecked() {
798
+ const self = this.getLatest();
799
+ let listType;
800
+ const parent = this.getParent();
801
+ if ($isListNode(parent)) {
802
+ listType = parent.getListType();
803
+ }
804
+ return listType === 'check' ? Boolean(self.__checked) : undefined;
805
+ }
806
+ setChecked(checked) {
807
+ const self = this.getWritable();
808
+ self.__checked = checked;
809
+ return self;
810
+ }
811
+ toggleChecked() {
812
+ const self = this.getWritable();
813
+ return self.setChecked(!self.__checked);
814
+ }
815
+ getIndent() {
816
+ // If we don't have a parent, we are likely serializing
817
+ const parent = this.getParent();
818
+ if (parent === null || !this.isAttached()) {
819
+ return this.getLatest().__indent;
820
+ }
821
+ // ListItemNode should always have a ListNode for a parent.
822
+ let listNodeParent = parent.getParentOrThrow();
823
+ let indentLevel = 0;
824
+ while ($isListItemNode(listNodeParent)) {
825
+ listNodeParent = listNodeParent.getParentOrThrow().getParentOrThrow();
826
+ indentLevel++;
827
+ }
828
+ return indentLevel;
829
+ }
830
+ setIndent(indent) {
831
+ if (!(typeof indent === 'number')) {
832
+ formatDevErrorMessage(`Invalid indent value.`);
833
+ }
834
+ indent = Math.floor(indent);
835
+ if (!(indent >= 0)) {
836
+ formatDevErrorMessage(`Indent value must be non-negative.`);
837
+ }
838
+ let currentIndent = this.getIndent();
839
+ while (currentIndent !== indent) {
840
+ if (currentIndent < indent) {
841
+ $handleIndent(this);
842
+ currentIndent++;
843
+ } else {
844
+ $handleOutdent(this);
845
+ currentIndent--;
846
+ }
847
+ }
848
+ return this;
849
+ }
850
+
851
+ /** @deprecated @internal */
852
+ canInsertAfter(node) {
853
+ return $isListItemNode(node);
854
+ }
855
+
856
+ /** @deprecated @internal */
857
+ canReplaceWith(replacement) {
858
+ return $isListItemNode(replacement);
859
+ }
860
+ canMergeWith(node) {
861
+ return $isListItemNode(node) || $isParagraphNode(node);
862
+ }
863
+ extractWithChild(child, selection) {
864
+ if (!$isRangeSelection(selection)) {
865
+ return false;
866
+ }
867
+ const anchorNode = selection.anchor.getNode();
868
+ const focusNode = selection.focus.getNode();
869
+ return this.isParentOf(anchorNode) && this.isParentOf(focusNode) && this.getTextContent().length === selection.getTextContent().length;
870
+ }
871
+ isParentRequired() {
872
+ return true;
873
+ }
874
+ createParentElementNode() {
875
+ return $createListNode('bullet');
876
+ }
877
+ canMergeWhenEmpty() {
878
+ return true;
879
+ }
880
+ }
881
+ function $setListItemThemeClassNames(dom, editorThemeClasses, node) {
882
+ const classesToAdd = [];
883
+ const classesToRemove = [];
884
+ const listTheme = editorThemeClasses.list;
885
+ const listItemClassName = listTheme ? listTheme.listitem : undefined;
886
+ let nestedListItemClassName;
887
+ if (listTheme && listTheme.nested) {
888
+ nestedListItemClassName = listTheme.nested.listitem;
889
+ }
890
+ if (listItemClassName !== undefined) {
891
+ classesToAdd.push(...normalizeClassNames(listItemClassName));
892
+ }
893
+ if (listTheme) {
894
+ const parentNode = node.getParent();
895
+ const isCheckList = $isListNode(parentNode) && parentNode.getListType() === 'check';
896
+ const checked = node.getChecked();
897
+ if (!isCheckList || checked) {
898
+ classesToRemove.push(listTheme.listitemUnchecked);
899
+ }
900
+ if (!isCheckList || !checked) {
901
+ classesToRemove.push(listTheme.listitemChecked);
902
+ }
903
+ if (isCheckList) {
904
+ classesToAdd.push(checked ? listTheme.listitemChecked : listTheme.listitemUnchecked);
905
+ }
906
+ }
907
+ if (nestedListItemClassName !== undefined) {
908
+ const nestedListItemClasses = normalizeClassNames(nestedListItemClassName);
909
+ if (node.getChildren().some(child => $isListNode(child))) {
910
+ classesToAdd.push(...nestedListItemClasses);
911
+ } else {
912
+ classesToRemove.push(...nestedListItemClasses);
913
+ }
914
+ }
915
+ if (classesToRemove.length > 0) {
916
+ removeClassNamesFromElement(dom, ...classesToRemove);
917
+ }
918
+ if (classesToAdd.length > 0) {
919
+ addClassNamesToElement(dom, ...classesToAdd);
920
+ }
921
+ }
922
+ function updateListItemChecked(dom, listItemNode, prevListItemNode) {
923
+ const parent = listItemNode.getParent();
924
+ const isCheckbox = $isListNode(parent) && parent.getListType() === 'check' &&
925
+ // Only add attributes for leaf list items
926
+ !$isListNode(listItemNode.getFirstChild());
927
+ if (!isCheckbox) {
928
+ dom.removeAttribute('role');
929
+ dom.removeAttribute('tabIndex');
930
+ dom.removeAttribute('aria-checked');
931
+ } else {
932
+ dom.setAttribute('role', 'checkbox');
933
+ dom.setAttribute('tabIndex', '-1');
934
+ if (!prevListItemNode || listItemNode.__checked !== prevListItemNode.__checked) {
935
+ dom.setAttribute('aria-checked', listItemNode.getChecked() ? 'true' : 'false');
936
+ }
937
+ }
938
+ }
939
+ function $convertListItemElement(domNode) {
940
+ const isGitHubCheckList = domNode.classList.contains('task-list-item');
941
+ if (isGitHubCheckList) {
942
+ for (const child of domNode.children) {
943
+ if (child.tagName === 'INPUT') {
944
+ return $convertCheckboxInput(child);
945
+ }
946
+ }
947
+ }
948
+ const isJoplinCheckList = domNode.classList.contains('joplin-checkbox');
949
+ if (isJoplinCheckList) {
950
+ for (const child of domNode.children) {
951
+ if (child.classList.contains('checkbox-wrapper') && child.children.length > 0 && child.children[0].tagName === 'INPUT') {
952
+ return $convertCheckboxInput(child.children[0]);
953
+ }
954
+ }
955
+ }
956
+ const ariaCheckedAttr = domNode.getAttribute('aria-checked');
957
+ const checked = ariaCheckedAttr === 'true' ? true : ariaCheckedAttr === 'false' ? false : undefined;
958
+ return {
959
+ node: $createListItemNode(checked)
960
+ };
961
+ }
962
+ function $convertCheckboxInput(domNode) {
963
+ const isCheckboxInput = domNode.getAttribute('type') === 'checkbox';
964
+ if (!isCheckboxInput) {
965
+ return {
966
+ node: null
967
+ };
968
+ }
969
+ const checked = domNode.hasAttribute('checked');
970
+ return {
971
+ node: $createListItemNode(checked)
972
+ };
973
+ }
974
+
975
+ /**
976
+ * Creates a new List Item node, passing true/false will convert it to a checkbox input.
977
+ * @param checked - Is the List Item a checkbox and, if so, is it checked? undefined/null: not a checkbox, true/false is a checkbox and checked/unchecked, respectively.
978
+ * @returns The new List Item.
979
+ */
980
+ function $createListItemNode(checked) {
981
+ return $applyNodeReplacement(new ListItemNode(undefined, checked));
982
+ }
983
+
984
+ /**
985
+ * Checks to see if the node is a ListItemNode.
986
+ * @param node - The node to be checked.
987
+ * @returns true if the node is a ListItemNode, false otherwise.
988
+ */
989
+ function $isListItemNode(node) {
990
+ return node instanceof ListItemNode;
991
+ }
992
+
993
+ /**
994
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
995
+ *
996
+ * This source code is licensed under the MIT license found in the
997
+ * LICENSE file in the root directory of this source tree.
998
+ *
999
+ */
1000
+
1001
+ /** @noInheritDoc */
1002
+ class ListNode extends ElementNode {
1003
+ /** @internal */
1004
+ __tag;
1005
+ /** @internal */
1006
+ __start;
1007
+ /** @internal */
1008
+ __listType;
1009
+
1010
+ /** @internal */
1011
+ $config() {
1012
+ return this.config('list', {
1013
+ $transform: node => {
1014
+ mergeNextSiblingListIfSameType(node);
1015
+ updateChildrenListItemValue(node);
1016
+ },
1017
+ extends: ElementNode,
1018
+ importDOM: buildImportMap({
1019
+ ol: () => ({
1020
+ conversion: $convertListNode,
1021
+ priority: 0
1022
+ }),
1023
+ ul: () => ({
1024
+ conversion: $convertListNode,
1025
+ priority: 0
1026
+ })
1027
+ })
1028
+ });
1029
+ }
1030
+ constructor(listType = 'number', start = 1, key) {
1031
+ super(key);
1032
+ const _listType = TAG_TO_LIST_TYPE[listType] || listType;
1033
+ this.__listType = _listType;
1034
+ this.__tag = _listType === 'number' ? 'ol' : 'ul';
1035
+ this.__start = start;
1036
+ }
1037
+ afterCloneFrom(prevNode) {
1038
+ super.afterCloneFrom(prevNode);
1039
+ this.__listType = prevNode.__listType;
1040
+ this.__tag = prevNode.__tag;
1041
+ this.__start = prevNode.__start;
1042
+ }
1043
+ getTag() {
1044
+ return this.getLatest().__tag;
1045
+ }
1046
+ setListType(type) {
1047
+ const writable = this.getWritable();
1048
+ writable.__listType = type;
1049
+ writable.__tag = type === 'number' ? 'ol' : 'ul';
1050
+ return writable;
1051
+ }
1052
+ getListType() {
1053
+ return this.getLatest().__listType;
1054
+ }
1055
+ getStart() {
1056
+ return this.getLatest().__start;
1057
+ }
1058
+ setStart(start) {
1059
+ const self = this.getWritable();
1060
+ self.__start = start;
1061
+ return self;
1062
+ }
1063
+
1064
+ // View
1065
+
1066
+ createDOM(config, _editor) {
1067
+ const tag = this.__tag;
1068
+ const dom = document.createElement(tag);
1069
+ if (this.__start !== 1) {
1070
+ dom.setAttribute('start', String(this.__start));
1071
+ }
1072
+ // @ts-expect-error Internal field.
1073
+ dom.__lexicalListType = this.__listType;
1074
+ $setListThemeClassNames(dom, config.theme, this);
1075
+ return dom;
1076
+ }
1077
+ updateDOM(prevNode, dom, config) {
1078
+ if (prevNode.__tag !== this.__tag || prevNode.__listType !== this.__listType) {
1079
+ return true;
1080
+ }
1081
+ $setListThemeClassNames(dom, config.theme, this);
1082
+ return false;
1083
+ }
1084
+ updateFromJSON(serializedNode) {
1085
+ return super.updateFromJSON(serializedNode).setListType(serializedNode.listType).setStart(serializedNode.start);
1086
+ }
1087
+ exportDOM(editor) {
1088
+ const element = this.createDOM(editor._config, editor);
1089
+ if (isHTMLElement(element)) {
1090
+ if (this.__start !== 1) {
1091
+ element.setAttribute('start', String(this.__start));
1092
+ }
1093
+ if (this.__listType === 'check') {
1094
+ element.setAttribute('__lexicalListType', 'check');
1095
+ }
1096
+ }
1097
+ return {
1098
+ element
1099
+ };
1100
+ }
1101
+ exportJSON() {
1102
+ return {
1103
+ ...super.exportJSON(),
1104
+ listType: this.getListType(),
1105
+ start: this.getStart(),
1106
+ tag: this.getTag()
1107
+ };
1108
+ }
1109
+ canBeEmpty() {
1110
+ return false;
1111
+ }
1112
+ canIndent() {
1113
+ return false;
1114
+ }
1115
+ splice(start, deleteCount, nodesToInsert) {
1116
+ let listItemNodesToInsert = nodesToInsert;
1117
+ for (let i = 0; i < nodesToInsert.length; i++) {
1118
+ const node = nodesToInsert[i];
1119
+ if (!$isListItemNode(node)) {
1120
+ if (listItemNodesToInsert === nodesToInsert) {
1121
+ listItemNodesToInsert = [...nodesToInsert];
1122
+ }
1123
+ listItemNodesToInsert[i] = $createListItemNode().append($isElementNode(node) && !($isListNode(node) || node.isInline()) ? $createTextNode(node.getTextContent()) : node);
1124
+ }
1125
+ }
1126
+ return super.splice(start, deleteCount, listItemNodesToInsert);
1127
+ }
1128
+ extractWithChild(child) {
1129
+ return $isListItemNode(child);
1130
+ }
1131
+ }
1132
+ function $setListThemeClassNames(dom, editorThemeClasses, node) {
1133
+ const classesToAdd = [];
1134
+ const classesToRemove = [];
1135
+ const listTheme = editorThemeClasses.list;
1136
+ if (listTheme !== undefined) {
1137
+ const listLevelsClassNames = listTheme[`${node.__tag}Depth`] || [];
1138
+ const listDepth = $getListDepth(node) - 1;
1139
+ const normalizedListDepth = listDepth % listLevelsClassNames.length;
1140
+ const listLevelClassName = listLevelsClassNames[normalizedListDepth];
1141
+ const listClassName = listTheme[node.__tag];
1142
+ let nestedListClassName;
1143
+ const nestedListTheme = listTheme.nested;
1144
+ const checklistClassName = listTheme.checklist;
1145
+ if (nestedListTheme !== undefined && nestedListTheme.list) {
1146
+ nestedListClassName = nestedListTheme.list;
1147
+ }
1148
+ if (listClassName !== undefined) {
1149
+ classesToAdd.push(listClassName);
1150
+ }
1151
+ if (checklistClassName !== undefined && node.__listType === 'check') {
1152
+ classesToAdd.push(checklistClassName);
1153
+ }
1154
+ if (listLevelClassName !== undefined) {
1155
+ classesToAdd.push(...normalizeClassNames(listLevelClassName));
1156
+ for (let i = 0; i < listLevelsClassNames.length; i++) {
1157
+ if (i !== normalizedListDepth) {
1158
+ classesToRemove.push(node.__tag + i);
1159
+ }
1160
+ }
1161
+ }
1162
+ if (nestedListClassName !== undefined) {
1163
+ const nestedListItemClasses = normalizeClassNames(nestedListClassName);
1164
+ if (listDepth > 1) {
1165
+ classesToAdd.push(...nestedListItemClasses);
1166
+ } else {
1167
+ classesToRemove.push(...nestedListItemClasses);
1168
+ }
1169
+ }
1170
+ }
1171
+ if (classesToRemove.length > 0) {
1172
+ removeClassNamesFromElement(dom, ...classesToRemove);
1173
+ }
1174
+ if (classesToAdd.length > 0) {
1175
+ addClassNamesToElement(dom, ...classesToAdd);
1176
+ }
1177
+ }
1178
+
1179
+ /*
1180
+ * This function normalizes the children of a ListNode after the conversion from HTML,
1181
+ * ensuring that they are all ListItemNodes and contain either a single nested ListNode
1182
+ * or some other inline content.
1183
+ */
1184
+ function $normalizeChildren(nodes) {
1185
+ const normalizedListItems = [];
1186
+ for (let i = 0; i < nodes.length; i++) {
1187
+ const node = nodes[i];
1188
+ if ($isListItemNode(node)) {
1189
+ normalizedListItems.push(node);
1190
+ const children = node.getChildren();
1191
+ if (children.length > 1) {
1192
+ children.forEach(child => {
1193
+ if ($isListNode(child)) {
1194
+ normalizedListItems.push($wrapInListItem(child));
1195
+ }
1196
+ });
1197
+ }
1198
+ } else {
1199
+ normalizedListItems.push($wrapInListItem(node));
1200
+ }
1201
+ }
1202
+ return normalizedListItems;
1203
+ }
1204
+ function isDomChecklist(domNode) {
1205
+ if (domNode.getAttribute('__lexicallisttype') === 'check' ||
1206
+ // is github checklist
1207
+ domNode.classList.contains('contains-task-list') ||
1208
+ // is joplin checklist
1209
+ domNode.getAttribute('data-is-checklist') === '1') {
1210
+ return true;
1211
+ }
1212
+ // if children are checklist items, the node is a checklist ul. Applicable for googledoc checklist pasting.
1213
+ for (const child of domNode.childNodes) {
1214
+ if (isHTMLElement(child) && child.hasAttribute('aria-checked')) {
1215
+ return true;
1216
+ }
1217
+ }
1218
+ return false;
1219
+ }
1220
+ function $convertListNode(domNode) {
1221
+ const nodeName = domNode.nodeName.toLowerCase();
1222
+ let node = null;
1223
+ if (nodeName === 'ol') {
1224
+ // @ts-ignore
1225
+ const start = domNode.start;
1226
+ node = $createListNode('number', start);
1227
+ } else if (nodeName === 'ul') {
1228
+ if (isDomChecklist(domNode)) {
1229
+ node = $createListNode('check');
1230
+ } else {
1231
+ node = $createListNode('bullet');
1232
+ }
1233
+ }
1234
+ return {
1235
+ after: $normalizeChildren,
1236
+ node
1237
+ };
1238
+ }
1239
+ const TAG_TO_LIST_TYPE = {
1240
+ ol: 'number',
1241
+ ul: 'bullet'
1242
+ };
1243
+
1244
+ /**
1245
+ * Creates a ListNode of listType.
1246
+ * @param listType - The type of list to be created. Can be 'number', 'bullet', or 'check'.
1247
+ * @param start - Where an ordered list starts its count, start = 1 if left undefined.
1248
+ * @returns The new ListNode
1249
+ */
1250
+ function $createListNode(listType = 'number', start = 1) {
1251
+ return $applyNodeReplacement(new ListNode(listType, start));
1252
+ }
1253
+
1254
+ /**
1255
+ * Checks to see if the node is a ListNode.
1256
+ * @param node - The node to be checked.
1257
+ * @returns true if the node is a ListNode, false otherwise.
1258
+ */
1259
+ function $isListNode(node) {
1260
+ return node instanceof ListNode;
1261
+ }
1262
+
1263
+ /**
1264
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1265
+ *
1266
+ * This source code is licensed under the MIT license found in the
1267
+ * LICENSE file in the root directory of this source tree.
1268
+ *
1269
+ */
1270
+
1271
+ const INSERT_CHECK_LIST_COMMAND = createCommand('INSERT_CHECK_LIST_COMMAND');
1272
+ function registerCheckList(editor) {
1273
+ return mergeRegister(editor.registerCommand(INSERT_CHECK_LIST_COMMAND, () => {
1274
+ $insertList('check');
1275
+ return true;
1276
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ARROW_DOWN_COMMAND, event => {
1277
+ return handleArrowUpOrDown(event, editor, false);
1278
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ARROW_UP_COMMAND, event => {
1279
+ return handleArrowUpOrDown(event, editor, true);
1280
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ESCAPE_COMMAND, () => {
1281
+ const activeItem = getActiveCheckListItem();
1282
+ if (activeItem != null) {
1283
+ const rootElement = editor.getRootElement();
1284
+ if (rootElement != null) {
1285
+ rootElement.focus();
1286
+ }
1287
+ return true;
1288
+ }
1289
+ return false;
1290
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_SPACE_COMMAND, event => {
1291
+ const activeItem = getActiveCheckListItem();
1292
+ if (activeItem != null && editor.isEditable()) {
1293
+ editor.update(() => {
1294
+ const listItemNode = $getNearestNodeFromDOMNode(activeItem);
1295
+ if ($isListItemNode(listItemNode)) {
1296
+ event.preventDefault();
1297
+ listItemNode.toggleChecked();
1298
+ }
1299
+ });
1300
+ return true;
1301
+ }
1302
+ return false;
1303
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ARROW_LEFT_COMMAND, event => {
1304
+ return editor.getEditorState().read(() => {
1305
+ const selection = $getSelection();
1306
+ if ($isRangeSelection(selection) && selection.isCollapsed()) {
1307
+ const {
1308
+ anchor
1309
+ } = selection;
1310
+ const isElement = anchor.type === 'element';
1311
+ if (isElement || anchor.offset === 0) {
1312
+ const anchorNode = anchor.getNode();
1313
+ const elementNode = $findMatchingParent(anchorNode, node => $isElementNode(node) && !node.isInline());
1314
+ if ($isListItemNode(elementNode)) {
1315
+ const parent = elementNode.getParent();
1316
+ if ($isListNode(parent) && parent.getListType() === 'check' && (isElement || elementNode.getFirstDescendant() === anchorNode)) {
1317
+ const domNode = editor.getElementByKey(elementNode.__key);
1318
+ if (domNode != null && document.activeElement !== domNode) {
1319
+ domNode.focus();
1320
+ event.preventDefault();
1321
+ return true;
1322
+ }
1323
+ }
1324
+ }
1325
+ }
1326
+ }
1327
+ return false;
1328
+ });
1329
+ }, COMMAND_PRIORITY_LOW), editor.registerRootListener((rootElement, prevElement) => {
1330
+ if (rootElement !== null) {
1331
+ rootElement.addEventListener('click', handleClick);
1332
+ rootElement.addEventListener('pointerdown', handlePointerDown);
1333
+ }
1334
+ if (prevElement !== null) {
1335
+ prevElement.removeEventListener('click', handleClick);
1336
+ prevElement.removeEventListener('pointerdown', handlePointerDown);
1337
+ }
1338
+ }));
1339
+ }
1340
+ function handleCheckItemEvent(event, callback) {
1341
+ const target = event.target;
1342
+ if (!isHTMLElement(target)) {
1343
+ return;
1344
+ }
1345
+
1346
+ // Ignore clicks on LI that have nested lists
1347
+ const firstChild = target.firstChild;
1348
+ if (isHTMLElement(firstChild) && (firstChild.tagName === 'UL' || firstChild.tagName === 'OL')) {
1349
+ return;
1350
+ }
1351
+ const parentNode = target.parentNode;
1352
+
1353
+ // @ts-ignore internal field
1354
+ if (!parentNode || parentNode.__lexicalListType !== 'check') {
1355
+ return;
1356
+ }
1357
+ const rect = target.getBoundingClientRect();
1358
+ const zoom = calculateZoomLevel(target);
1359
+ const clientX = event.clientX / zoom;
1360
+
1361
+ // Use getComputedStyle if available, otherwise fallback to 0px width
1362
+ const beforeStyles = window.getComputedStyle ? window.getComputedStyle(target, '::before') : {
1363
+ width: '0px'
1364
+ };
1365
+ const beforeWidthInPixels = parseFloat(beforeStyles.width);
1366
+
1367
+ // Make click area slightly larger for touch devices to improve accessibility
1368
+ const isTouchEvent = event.pointerType === 'touch';
1369
+ const clickAreaPadding = isTouchEvent ? 32 : 0; // Add 32px padding for touch events
1370
+
1371
+ if (target.dir === 'rtl' ? clientX < rect.right + clickAreaPadding && clientX > rect.right - beforeWidthInPixels - clickAreaPadding : clientX > rect.left - clickAreaPadding && clientX < rect.left + beforeWidthInPixels + clickAreaPadding) {
1372
+ callback();
1373
+ }
1374
+ }
1375
+ function handleClick(event) {
1376
+ handleCheckItemEvent(event, () => {
1377
+ if (isHTMLElement(event.target)) {
1378
+ const domNode = event.target;
1379
+ const editor = getNearestEditorFromDOMNode(domNode);
1380
+ if (editor != null && editor.isEditable()) {
1381
+ editor.update(() => {
1382
+ const node = $getNearestNodeFromDOMNode(domNode);
1383
+ if ($isListItemNode(node)) {
1384
+ domNode.focus();
1385
+ node.toggleChecked();
1386
+ }
1387
+ });
1388
+ }
1389
+ }
1390
+ });
1391
+ }
1392
+ function handlePointerDown(event) {
1393
+ handleCheckItemEvent(event, () => {
1394
+ // Prevents caret moving when clicking on check mark
1395
+ event.preventDefault();
1396
+ });
1397
+ }
1398
+ function getActiveCheckListItem() {
1399
+ const activeElement = document.activeElement;
1400
+ return isHTMLElement(activeElement) && activeElement.tagName === 'LI' && activeElement.parentNode != null &&
1401
+ // @ts-ignore internal field
1402
+ activeElement.parentNode.__lexicalListType === 'check' ? activeElement : null;
1403
+ }
1404
+ function findCheckListItemSibling(node, backward) {
1405
+ let sibling = backward ? node.getPreviousSibling() : node.getNextSibling();
1406
+ let parent = node;
1407
+
1408
+ // Going up in a tree to get non-null sibling
1409
+ while (sibling == null && $isListItemNode(parent)) {
1410
+ // Get li -> parent ul/ol -> parent li
1411
+ parent = parent.getParentOrThrow().getParent();
1412
+ if (parent != null) {
1413
+ sibling = backward ? parent.getPreviousSibling() : parent.getNextSibling();
1414
+ }
1415
+ }
1416
+
1417
+ // Going down in a tree to get first non-nested list item
1418
+ while ($isListItemNode(sibling)) {
1419
+ const firstChild = backward ? sibling.getLastChild() : sibling.getFirstChild();
1420
+ if (!$isListNode(firstChild)) {
1421
+ return sibling;
1422
+ }
1423
+ sibling = backward ? firstChild.getLastChild() : firstChild.getFirstChild();
1424
+ }
1425
+ return null;
1426
+ }
1427
+ function handleArrowUpOrDown(event, editor, backward) {
1428
+ const activeItem = getActiveCheckListItem();
1429
+ if (activeItem != null) {
1430
+ editor.update(() => {
1431
+ const listItem = $getNearestNodeFromDOMNode(activeItem);
1432
+ if (!$isListItemNode(listItem)) {
1433
+ return;
1434
+ }
1435
+ const nextListItem = findCheckListItemSibling(listItem, backward);
1436
+ if (nextListItem != null) {
1437
+ nextListItem.selectStart();
1438
+ const dom = editor.getElementByKey(nextListItem.__key);
1439
+ if (dom != null) {
1440
+ event.preventDefault();
1441
+ setTimeout(() => {
1442
+ dom.focus();
1443
+ }, 0);
1444
+ }
1445
+ }
1446
+ });
1447
+ }
1448
+ return false;
1449
+ }
1450
+
1451
+ /**
1452
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1453
+ *
1454
+ * This source code is licensed under the MIT license found in the
1455
+ * LICENSE file in the root directory of this source tree.
1456
+ *
1457
+ */
1458
+
1459
+ const UPDATE_LIST_START_COMMAND = createCommand('UPDATE_LIST_START_COMMAND');
1460
+ const INSERT_UNORDERED_LIST_COMMAND = createCommand('INSERT_UNORDERED_LIST_COMMAND');
1461
+ const INSERT_ORDERED_LIST_COMMAND = createCommand('INSERT_ORDERED_LIST_COMMAND');
1462
+ const REMOVE_LIST_COMMAND = createCommand('REMOVE_LIST_COMMAND');
1463
+ function registerList(editor) {
1464
+ const removeListener = mergeRegister(editor.registerCommand(INSERT_ORDERED_LIST_COMMAND, () => {
1465
+ $insertList('number');
1466
+ return true;
1467
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(UPDATE_LIST_START_COMMAND, payload => {
1468
+ const {
1469
+ listNodeKey,
1470
+ newStart
1471
+ } = payload;
1472
+ const listNode = $getNodeByKey(listNodeKey);
1473
+ if (!$isListNode(listNode)) {
1474
+ return false;
1475
+ }
1476
+ if (listNode.getListType() === 'number') {
1477
+ listNode.setStart(newStart);
1478
+ updateChildrenListItemValue(listNode);
1479
+ }
1480
+ return true;
1481
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(INSERT_UNORDERED_LIST_COMMAND, () => {
1482
+ $insertList('bullet');
1483
+ return true;
1484
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(REMOVE_LIST_COMMAND, () => {
1485
+ $removeList();
1486
+ return true;
1487
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => $handleListInsertParagraph(), COMMAND_PRIORITY_LOW), editor.registerNodeTransform(ListItemNode, node => {
1488
+ const firstChild = node.getFirstChild();
1489
+ if (firstChild) {
1490
+ if ($isTextNode(firstChild)) {
1491
+ const style = firstChild.getStyle();
1492
+ const format = firstChild.getFormat();
1493
+ if (node.getTextStyle() !== style) {
1494
+ node.setTextStyle(style);
1495
+ }
1496
+ if (node.getTextFormat() !== format) {
1497
+ node.setTextFormat(format);
1498
+ }
1499
+ }
1500
+ } else {
1501
+ // If it's empty, check the selection
1502
+ const selection = $getSelection();
1503
+ if ($isRangeSelection(selection) && (selection.style !== node.getTextStyle() || selection.format !== node.getTextFormat()) && selection.isCollapsed() && node.is(selection.anchor.getNode())) {
1504
+ node.setTextStyle(selection.style).setTextFormat(selection.format);
1505
+ }
1506
+ }
1507
+ }), editor.registerNodeTransform(TextNode, node => {
1508
+ const listItemParentNode = node.getParent();
1509
+ if ($isListItemNode(listItemParentNode) && node.is(listItemParentNode.getFirstChild())) {
1510
+ const style = node.getStyle();
1511
+ const format = node.getFormat();
1512
+ if (style !== listItemParentNode.getTextStyle() || format !== listItemParentNode.getTextFormat()) {
1513
+ listItemParentNode.setTextStyle(style).setTextFormat(format);
1514
+ }
1515
+ }
1516
+ }));
1517
+ return removeListener;
1518
+ }
1519
+ function registerListStrictIndentTransform(editor) {
1520
+ const $formatListIndentStrict = listItemNode => {
1521
+ const listNode = listItemNode.getParent();
1522
+ if ($isListNode(listItemNode.getFirstChild()) || !$isListNode(listNode)) {
1523
+ return;
1524
+ }
1525
+ const startingListItemNode = $findMatchingParent(listItemNode, node => $isListItemNode(node) && $isListNode(node.getParent()) && $isListItemNode(node.getPreviousSibling()));
1526
+ if (startingListItemNode === null && listItemNode.getIndent() > 0) {
1527
+ listItemNode.setIndent(0);
1528
+ } else if ($isListItemNode(startingListItemNode)) {
1529
+ const prevListItemNode = startingListItemNode.getPreviousSibling();
1530
+ if ($isListItemNode(prevListItemNode)) {
1531
+ const endListItemNode = $findChildrenEndListItemNode(prevListItemNode);
1532
+ const endListNode = endListItemNode.getParent();
1533
+ if ($isListNode(endListNode)) {
1534
+ const prevDepth = $getListDepth(endListNode);
1535
+ const depth = $getListDepth(listNode);
1536
+ if (prevDepth + 1 < depth) {
1537
+ listItemNode.setIndent(prevDepth);
1538
+ }
1539
+ }
1540
+ }
1541
+ }
1542
+ };
1543
+ const $processListWithStrictIndent = listNode => {
1544
+ const queue = [listNode];
1545
+ while (queue.length > 0) {
1546
+ const node = queue.shift();
1547
+ if (!$isListNode(node)) {
1548
+ continue;
1549
+ }
1550
+ for (const child of node.getChildren()) {
1551
+ if ($isListItemNode(child)) {
1552
+ $formatListIndentStrict(child);
1553
+ const firstChild = child.getFirstChild();
1554
+ if ($isListNode(firstChild)) {
1555
+ queue.push(firstChild);
1556
+ }
1557
+ }
1558
+ }
1559
+ }
1560
+ };
1561
+ return editor.registerNodeTransform(ListNode, $processListWithStrictIndent);
1562
+ }
1563
+ function $findChildrenEndListItemNode(listItemNode) {
1564
+ let current = listItemNode;
1565
+ let firstChild = current.getFirstChild();
1566
+ while ($isListNode(firstChild)) {
1567
+ const lastChild = firstChild.getLastChild();
1568
+ if ($isListItemNode(lastChild)) {
1569
+ current = lastChild;
1570
+ firstChild = current.getFirstChild();
1571
+ } else {
1572
+ break;
1573
+ }
1574
+ }
1575
+ return current;
1576
+ }
1577
+
1578
+ /**
1579
+ * @deprecated use {@link $insertList} from an update or command listener.
1580
+ *
1581
+ * Inserts a new ListNode. If the selection's anchor node is an empty ListItemNode and is a child of
1582
+ * the root/shadow root, it will replace the ListItemNode with a ListNode and the old ListItemNode.
1583
+ * Otherwise it will replace its parent with a new ListNode and re-insert the ListItemNode and any previous children.
1584
+ * If the selection's anchor node is not an empty ListItemNode, it will add a new ListNode or merge an existing ListNode,
1585
+ * unless the the node is a leaf node, in which case it will attempt to find a ListNode up the branch and replace it with
1586
+ * a new ListNode, or create a new ListNode at the nearest root/shadow root.
1587
+ * @param editor - The lexical editor.
1588
+ * @param listType - The type of list, "number" | "bullet" | "check".
1589
+ */
1590
+ function insertList(editor, listType) {
1591
+ editor.update(() => $insertList(listType));
1592
+ }
1593
+
1594
+ /**
1595
+ * @deprecated use {@link $removeList} from an update or command listener.
1596
+ *
1597
+ * Searches for the nearest ancestral ListNode and removes it. If selection is an empty ListItemNode
1598
+ * it will remove the whole list, including the ListItemNode. For each ListItemNode in the ListNode,
1599
+ * removeList will also generate new ParagraphNodes in the removed ListNode's place. Any child node
1600
+ * inside a ListItemNode will be appended to the new ParagraphNodes.
1601
+ * @param editor - The lexical editor.
1602
+ */
1603
+ function removeList(editor) {
1604
+ editor.update(() => $removeList());
1605
+ }
1606
+ /**
1607
+ * Configures {@link ListNode}, {@link ListItemNode} and registers
1608
+ * the strict indent transform if `hasStrictIndent` is true (default false).
1609
+ */
1610
+ const ListExtension = defineExtension({
1611
+ build(editor, config, state) {
1612
+ return namedSignals(config);
1613
+ },
1614
+ config: safeCast({
1615
+ hasStrictIndent: false
1616
+ }),
1617
+ name: '@ekz/lexical-list/List',
1618
+ nodes: () => [ListNode, ListItemNode],
1619
+ register(editor, config, state) {
1620
+ const stores = state.getOutput();
1621
+ return mergeRegister(registerList(editor), effect(() => stores.hasStrictIndent.value ? registerListStrictIndentTransform(editor) : undefined));
1622
+ }
1623
+ });
1624
+
1625
+ /**
1626
+ * Registers checklist functionality for {@link ListNode} and
1627
+ * {@link ListItemNode} with a
1628
+ * {@link INSERT_CHECK_LIST_COMMAND} listener and
1629
+ * the expected keyboard and mouse interactions for
1630
+ * checkboxes.
1631
+ */
1632
+ const CheckListExtension = defineExtension({
1633
+ dependencies: [ListExtension],
1634
+ name: '@ekz/lexical-list/CheckList',
1635
+ register: registerCheckList
1636
+ });
1637
+
1638
+ export { $createListItemNode, $createListNode, $getListDepth, $handleListInsertParagraph, $insertList, $isListItemNode, $isListNode, $removeList, CheckListExtension, INSERT_CHECK_LIST_COMMAND, INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, ListExtension, ListItemNode, ListNode, REMOVE_LIST_COMMAND, UPDATE_LIST_START_COMMAND, insertList, registerCheckList, registerList, registerListStrictIndentTransform, removeList };