-
Notifications
You must be signed in to change notification settings - Fork 37
/
list-commands.ts
1024 lines (921 loc) · 29.1 KB
/
list-commands.ts
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
import {
autoJoin,
chainCommands,
Command,
EditorState,
Fragment,
liftListItem,
liftTarget,
Node,
NodeRange,
NodeSelection,
NodeType,
ReplaceAroundStep,
ResolvedPos,
Schema,
Selection,
sinkListItem,
Slice,
TextSelection,
Transaction,
wrapInList as pmWrapInList,
} from '@bangle.dev/pm';
import type { MoveDirection } from '@bangle.dev/pm-commands';
import {
compose,
extendDispatch,
filter,
findCutBefore,
findParentNode,
findParentNodeOfType,
findPositionOfNodeBefore,
flatten,
GapCursorSelection,
getNodeType,
hasParentNodeOfType,
hasVisibleContent,
isEmptySelectionAtStart,
isFirstChildOfParent,
isNodeEmpty,
isRangeOfType,
safeInsert,
sanitiseSelectionMarksForWrapping,
validListParent,
validPos,
} from '@bangle.dev/utils';
import {
isNodeTodo,
removeTodoCheckedAttr,
setTodoCheckedAttr,
} from './list-todo';
import { liftFollowingList, liftSelectionList } from './list-transforms';
const maxIndentation = 4;
// Returns the number of nested lists that are ancestors of the given selection
const numberNestedLists = (
resolvedPos: ResolvedPos,
nodes: Schema['nodes'],
) => {
const { bulletList, orderedList } = nodes;
let count = 0;
for (let i = resolvedPos.depth - 1; i > 0; i--) {
const node = resolvedPos.node(i);
if (node.type === bulletList || node.type === orderedList) {
count += 1;
}
}
return count;
};
const isInsideList = (state: EditorState, listType: NodeType) => {
const { $from } = state.selection;
const parent = $from.node(-2);
const grandGrandParent = $from.node(-3);
return (
(parent && parent.type === listType) ||
(grandGrandParent && grandGrandParent.type === listType)
);
};
const canOutdent = (type?: NodeType) => (state: EditorState) => {
const { parent } = state.selection.$from;
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { paragraph } = state.schema.nodes;
if (state.selection instanceof GapCursorSelection) {
return parent.type === listItem;
}
return (
parent.type === paragraph && hasParentNodeOfType(listItem!)(state.selection)
);
};
/**
* Check if we can sink the list.
* @returns {boolean} - true if we can sink the list
* - false if we reach the max indentation level
*/
function canSink(initialIndentationLevel: number, state: EditorState) {
/*
- Keep going forward in document until indentation of the node is < than the initial
- If indentation is EVER > max indentation, return true and don't sink the list
*/
let currentIndentationLevel: number | null;
let currentPos = state.tr.selection.$to.pos;
do {
const resolvedPos = state.doc.resolve(currentPos);
currentIndentationLevel = numberNestedLists(
resolvedPos,
state.schema.nodes,
);
if (currentIndentationLevel > maxIndentation) {
// Cancel sink list.
// If current indentation less than the initial, it won't be
// larger than the max, and the loop will terminate at end of this iteration
return false;
}
currentPos++;
} while (currentIndentationLevel >= initialIndentationLevel);
return true;
}
export const isInsideListItem =
(type: NodeType | undefined) => (state: EditorState) => {
const { $from } = state.selection;
let listItem = type;
if (!listItem) {
listItem = getNodeType(state, 'listItem');
}
const { paragraph } = state.schema.nodes;
if (state.selection instanceof GapCursorSelection) {
return $from.parent.type === listItem;
}
return (
hasParentNodeOfType(listItem)(state.selection) &&
$from.parent.type === paragraph
);
};
// Get the depth of the nearest ancestor list
const rootListDepth = (
type: NodeType,
pos: ResolvedPos,
nodes: Schema['nodes'],
) => {
let listItem = type;
const { bulletList, orderedList } = nodes;
let depth: number | null;
for (let i = pos.depth - 1; i > 0; i--) {
const node = pos.node(i);
if (node.type === bulletList || node.type === orderedList) {
depth = i;
}
if (
node.type !== bulletList &&
node.type !== orderedList &&
node.type !== listItem
) {
break;
}
}
return depth!;
};
function canToJoinToPreviousListItem(state: EditorState) {
const { $from } = state.selection;
const { bulletList, orderedList } = state.schema.nodes;
const $before = state.doc.resolve($from.pos - 1);
let nodeBefore = $before ? $before.nodeBefore : null;
if (state.selection instanceof GapCursorSelection) {
nodeBefore = $from.nodeBefore;
}
return (
!!nodeBefore && [bulletList, orderedList].indexOf(nodeBefore.type) > -1
);
}
/**
* ------------------
* Command Factories
* ------------------
*/
/**
*
* @param {Object} listType bulletList, orderedList,
* @param {Object} itemType 'listItem'
* @param {boolean} todo if true and the final result of toggle is a bulletList
* set `todoChecked` attr for each listItem.
*/
export function toggleList(
listType: NodeType,
itemType?: NodeType,
todo?: boolean,
): Command {
return (state, dispatch, view) => {
const { selection } = state;
const fromNode = selection.$from.node(selection.$from.depth - 2);
const endNode = selection.$to.node(selection.$to.depth - 2);
if (
!fromNode ||
fromNode.type.name !== listType.name ||
!endNode ||
endNode.type.name !== listType.name
) {
return toggleListCommand(listType, todo)(state, dispatch, view);
} else {
// If current ListType is the same as `listType` in arg,
// toggle the list to `p`.
const listItem = itemType ? itemType : getNodeType(state, 'listItem');
const depth = rootListDepth(listItem, selection.$to, state.schema.nodes);
let liftFrom = selection.$to.pos;
// I am not fully sure the best solution,
// but if we donot handle the the nodeSelection of itemType
// an incorrect content error in thrown by liftFollowingList.
if (
selection instanceof NodeSelection &&
selection.node.type === listItem
) {
liftFrom =
selection.$from.pos + selection.node.firstChild!.content.size;
}
let baseTr = state.tr;
let tr = liftFollowingList(
listItem,
state,
liftFrom,
selection.$to.end(depth),
depth || 0,
baseTr,
);
tr = liftSelectionList(listItem, state, tr);
if (dispatch) {
dispatch(tr);
}
return true;
}
};
}
function toggleListCommand(listType: NodeType, todo: boolean = false): Command {
/**
* A function which will set todoChecked attribute
* in any of the nodes that have modified on the tr
*/
const setTodoListTr = (schema: Schema) => (tr: Transaction) => {
if (!tr.isGeneric) {
return tr;
}
// The following code gets a list of ranges that were changed
// From wrapDispatchForJoin: https://github.com/prosemirror/prosemirror-commands/blob/e5f8c303be55147086bfe4521cf7419e6effeb8f/src%2Fcommands.js#L495
// and https://discuss.prosemirror.net/t/finding-out-what-changed-in-a-transaction/2372
let ranges: number[] = [];
for (let i = 0; i < tr.mapping.maps.length; i++) {
let map = tr.mapping.maps[i]!;
for (let j = 0; j < ranges.length; j++) {
ranges[j] = map.map(ranges[j]!);
}
map.forEach((_s, _e, from, to) => {
ranges.push(from, to);
});
}
const canBeTodo = (node: Node, parentNode: Node | null) =>
node.type === getNodeType(schema, 'listItem') &&
parentNode?.type === getNodeType(schema, 'bulletList');
for (let i = 0; i < ranges.length; i += 2) {
let from = ranges[i]!;
let to = ranges[i + 1]!;
tr.doc.nodesBetween(from, to, (node, pos, parentNode) => {
if (pos >= from && pos < to && canBeTodo(node, parentNode)) {
setTodoCheckedAttr(tr, schema, node, pos);
}
});
}
return tr;
};
return function (state, dispatch, view) {
if (dispatch) {
dispatch(
state.tr.setSelection(
adjustSelectionInList(state.doc, state.selection),
),
);
}
if (!view) {
return false;
}
state = view.state;
const { $from, $to } = state.selection;
const isRangeOfSingleType = isRangeOfType(state.doc, $from, $to, listType);
if (isInsideList(state, listType) && isRangeOfSingleType) {
return liftListItems()(state, dispatch);
} else {
// Converts list type e.g. bulletList -> orderedList if needed
if (!isRangeOfSingleType) {
liftListItems()(state, dispatch);
state = view.state;
}
// Remove any invalid marks that are not supported
const tr = sanitiseSelectionMarksForWrapping(state, listType);
if (tr && dispatch) {
dispatch(tr);
state = view.state;
}
// Wraps selection in list
return wrapInList(listType)(
state,
todo ? extendDispatch(dispatch, setTodoListTr(state.schema)) : dispatch,
);
}
};
}
function wrapInList(nodeType: NodeType, attrs?: Node['attrs']): Command {
return autoJoin(
pmWrapInList(nodeType, attrs),
(before, after) => before.type === after.type && before.type === nodeType,
);
}
function liftListItems(): Command {
return function (state, dispatch) {
const { tr } = state;
const { $from, $to } = state.selection;
tr.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
// Following condition will ensure that block types paragraph, heading, codeBlock, blockquote, panel are lifted.
// isTextblock is true for paragraph, heading, codeBlock.
if (node.isTextblock) {
const sel = new NodeSelection(tr.doc.resolve(tr.mapping.map(pos)));
const range = sel.$from.blockRange(sel.$to);
if (
!range ||
![getNodeType(state, 'listItem')].includes(sel.$from.parent.type)
) {
return false;
}
const target = range && liftTarget(range);
if (target === undefined || target === null) {
return false;
}
tr.lift(range, target);
}
return;
});
if (dispatch) {
dispatch(tr);
}
return true;
};
}
/**
* Sometimes a selection in the editor can be slightly offset, for example:
* it's possible for a selection to start or end at an empty node at the very end of
* a line. This isn't obvious by looking at the editor and it's likely not what the
* user intended - so we need to adjust the selection a bit in scenarios like that.
*/
function adjustSelectionInList(doc: Node, selection: Selection) {
let { $from, $to } = selection;
const isSameLine = $from.pos === $to.pos;
let startPos = $from.pos;
let endPos = $to.pos;
if (isSameLine && startPos === doc.nodeSize - 3) {
// Line is empty, don't do anything
return selection;
}
// Selection started at the very beginning of a line and therefor points to the previous line.
if ($from.nodeBefore && !isSameLine) {
startPos++;
let node = doc.nodeAt(startPos);
while (!node || (node && !node.isText)) {
startPos++;
node = doc.nodeAt(startPos);
}
}
if (endPos === startPos) {
return new TextSelection(doc.resolve(startPos));
}
return new TextSelection(doc.resolve(startPos), doc.resolve(endPos));
}
export function indentList(type: NodeType) {
const handleTodo = (schema: Schema) => (tr: Transaction) => {
if (!tr.isGeneric) {
return tr;
}
const range = tr.selection.$from.blockRange(
tr.selection.$to,
(node) =>
node.childCount > 0 &&
node.firstChild!.type === getNodeType(schema, 'listItem'),
);
if (
!range ||
// we donot have an existing node to check if todo is needed or not
range.startIndex === 0
) {
return tr;
}
const isNodeBeforeATodo = isNodeTodo(
range.parent.child(range.startIndex - 1),
schema,
);
const { parent, startIndex, endIndex } = range;
let offset = 0;
for (let i = startIndex; i < endIndex; i++) {
const child = parent.child(i);
const pos = range.start + offset;
tr = isNodeBeforeATodo
? setTodoCheckedAttr(tr, schema, child, pos)
: removeTodoCheckedAttr(tr, schema, child, pos);
offset += child.nodeSize;
}
return tr;
};
return function indentListCommand(
state: EditorState,
dispatch?: (tr: Transaction) => void,
) {
let listItem = type;
if (!listItem) {
listItem = getNodeType(state, 'listItem');
}
if (isInsideListItem(listItem)(state)) {
// Record initial list indentation
const initialIndentationLevel = numberNestedLists(
state.selection.$from,
state.schema.nodes,
);
if (canSink(initialIndentationLevel, state)) {
sinkListItem(listItem)(
state,
extendDispatch(dispatch, handleTodo(state.schema)),
);
}
return true;
}
return false;
};
}
export function outdentList(type: NodeType): Command {
return function (state, dispatch, view) {
let listItem = type;
if (!listItem) {
listItem = getNodeType(state, 'listItem');
}
const { $from, $to } = state.selection;
if (!isInsideListItem(listItem)(state)) {
return false;
}
// if we're backspacing at the start of a list item, unindent it
// take the the range of nodes we might be lifting
// the predicate is for when you're backspacing a top level list item:
// we don't want to go up past the doc node, otherwise the range
// to clear will include everything
let range = $from.blockRange(
$to,
(node) => node.childCount > 0 && node.firstChild!.type === listItem,
);
if (!range) {
return false;
}
const isGreatGrandTodo = isNodeTodo(
state.selection.$from.node(-3),
state.schema,
);
// TODO this is not quite as lean as the indent approach of todo
// check if we need to set todoCheck attribute
if (dispatch && view) {
const grandParent = state.selection.$from.node(-2);
const grandParentPos = state.selection.$from.start(-2);
let tr = state.tr;
for (const { node, pos } of flatten(grandParent, false)) {
const absPos = pos + grandParentPos;
// -1 so that we cover the entire list item
if (
absPos >= state.selection.$from.before(-1) &&
absPos < state.selection.$to.after(-1)
) {
if (isGreatGrandTodo) {
setTodoCheckedAttr(tr, state.schema, node, absPos);
} else {
removeTodoCheckedAttr(tr, state.schema, node, absPos);
}
}
}
dispatch(tr);
state = view.state;
}
const composedCommand = compose(
mergeLists(listItem, range), // 2. Check if I need to merge nearest list
liftListItem, // 1. First lift list item
)(listItem);
return composedCommand(state, dispatch, view);
};
}
/**
* Merge closest bullet list blocks into one
*
* @param {NodeType} listItem
* @param {NodeRange} range
* @returns
*/
function mergeLists(
listItem: NodeType,
range: NodeRange,
): (command: Command) => Command {
return (command: Command) => {
return (state, dispatch, view) => {
const newDispatch = (tr: Transaction) => {
/* we now need to handle the case that we lifted a sublist out,
* and any listItems at the current level get shifted out to
* their own new list; e.g.:
*
* unorderedList
* listItem(A)
* listItem
* unorderedList
* listItem(B)
* listItem(C)
*
* becomes, after unindenting the first, top level listItem, A:
*
* content of A
* unorderedList
* listItem(B)
* unorderedList
* listItem(C)
*
* so, we try to merge these two lists if they're of the same type, to give:
*
* content of A
* unorderedList
* listItem(B)
* listItem(C)
*/
const $start = state.doc.resolve(range.start);
const $end = state.doc.resolve(range.end);
const $join = tr.doc.resolve(tr.mapping.map(range.end - 1));
if (
$join.nodeBefore &&
$join.nodeAfter &&
$join.nodeBefore.type === $join.nodeAfter.type
) {
if (
$end.nodeAfter &&
$end.nodeAfter.type === listItem &&
$end.parent.type === $start.parent.type
) {
tr.join($join.pos);
}
}
if (dispatch) {
dispatch(tr.scrollIntoView());
}
};
return command(state, newDispatch, view);
};
};
}
// Chaining runs each command until one of them returns true
export const backspaceKeyCommand =
(type: NodeType): Command =>
(state, dispatch, view) => {
return chainCommands(
// if we're at the start of a list item, we need to either backspace
// directly to an empty list item above, or outdent this node
filter(
[
isInsideListItem(type),
isEmptySelectionAtStart,
// list items might have multiple paragraphs; only do this at the first one
isFirstChildOfParent,
canOutdent(type),
],
chainCommands(deletePreviousEmptyListItem(type), outdentList(type)),
),
// if we're just inside a paragraph node (or gapcursor is shown) and backspace, then try to join
// the text to the previous list item, if one exists
filter(
[isEmptySelectionAtStart, canToJoinToPreviousListItem],
joinToPreviousListItem(type),
),
)(state, dispatch, view);
};
export function enterKeyCommand(type: NodeType): Command {
return (state, dispatch, view) => {
const { selection } = state;
if (selection.empty) {
const { $from } = selection;
let listItem = type;
if (!listItem) {
listItem = getNodeType(state, 'listItem');
}
const { codeBlock } = state.schema.nodes;
const node = $from.node($from.depth);
const wrapper = $from.node($from.depth - 1);
if (wrapper && wrapper.type === listItem) {
/** Check if the wrapper has any visible content */
const wrapperHasContent = hasVisibleContent(wrapper);
if (isNodeEmpty(node) && !wrapperHasContent) {
const grandParent = $from.node($from.depth - 3);
// To allow for cases where a non-todo item is nested inside a todo item
// pressing enter should convert that type into a todo listItem and outdent.
if (
isNodeTodo(grandParent, state.schema) &&
!isNodeTodo(wrapper, state.schema)
) {
return outdentList(getNodeType(state, 'listItem'))(
state,
dispatch,
view,
);
} else {
return outdentList(listItem)(state, dispatch, view);
}
} else if (!codeBlock || !hasParentNodeOfType(codeBlock)(selection)) {
return splitListItem(listItem, (node) => {
if (!isNodeTodo(node, state.schema)) {
return node.attrs;
}
return {
...node.attrs,
todoChecked: false,
};
})(state, dispatch);
}
}
}
return false;
};
}
/***
* Implementation taken from PM and mk-2
* Splits the list items, specific implementation take from PM
*
* splitAttrs(node): attrs - if defined the new split item will get attrs returned by this.
* where node is the currently active node.
*/
function splitListItem(
itemType: NodeType,
splitAttrs?: (node: Node) => Node['attrs'],
): Command {
return function (state, dispatch) {
const ref = state.selection;
const $from = ref.$from;
const $to = ref.$to;
const node: Node | null = (ref as any).node;
if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {
return false;
}
const grandParent = $from.node(-1);
if (grandParent.type !== itemType) {
return false;
}
/** --> The following line changed from the original PM implementation to allow list additions with multiple paragraphs */
if (
// @ts-ignore Fragment.content is missing in @types/prosemirror-model
grandParent.content.content.length <= 1 &&
$from.parent.content.size === 0 &&
!(grandParent.content.size === 0)
) {
// In an empty block. If this is a nested list, the wrapping
// list item should be split. Otherwise, bail out and let next
// command handle lifting.
if (
$from.depth === 2 ||
$from.node(-3).type !== itemType ||
$from.index(-2) !== $from.node(-2).childCount - 1
) {
return false;
}
if (dispatch) {
let wrap = Fragment.empty;
const keepItem = $from.index(-1) > 0;
// Build a fragment containing empty versions of the structure
// from the outer list item to the parent node of the cursor
for (
let d = $from.depth - (keepItem ? 1 : 2);
d >= $from.depth - 3;
d--
) {
wrap = Fragment.from($from.node(d).copy(wrap));
}
// Add a second list item with an empty default start node
wrap = wrap.append(Fragment.from(itemType.createAndFill()!));
const tr$1 = state.tr.replace(
$from.before(keepItem ? undefined : -1),
$from.after(-3),
new Slice(wrap, keepItem ? 3 : 2, 2),
);
tr$1.setSelection(
Selection.near(tr$1.doc.resolve($from.pos + (keepItem ? 3 : 2))),
);
dispatch(tr$1.scrollIntoView());
}
return true;
}
const nextType =
$to.pos === $from.end()
? grandParent.contentMatchAt(0).defaultType
: undefined;
const tr = state.tr.delete($from.pos, $to.pos);
const types = [
splitAttrs
? { type: itemType, attrs: splitAttrs(grandParent) }
: undefined,
nextType && { type: nextType },
];
if (dispatch) {
dispatch(tr.split($from.pos, 2, types as any).scrollIntoView());
}
return true;
};
}
function joinToPreviousListItem(type?: NodeType): Command {
return (state, dispatch) => {
let listItem = type;
if (!listItem) {
({ listItem } = state.schema.nodes);
}
const { $from } = state.selection;
const { paragraph, codeBlock, heading, bulletList, orderedList } =
state.schema.nodes;
const isGapCursorShown = state.selection instanceof GapCursorSelection;
const $cutPos = isGapCursorShown ? state.doc.resolve($from.pos + 1) : $from;
let $cut = findCutBefore($cutPos);
if (!$cut) {
return false;
}
// see if the containing node is a list
if (
$cut.nodeBefore &&
[bulletList, orderedList].indexOf($cut.nodeBefore.type) > -1
) {
// and the node after this is a paragraph / codeBlock / heading
if (
$cut.nodeAfter &&
[paragraph, codeBlock, heading].indexOf($cut.nodeAfter.type) > -1
) {
// find the nearest paragraph that precedes this node
let $lastNode = $cut.doc.resolve($cut.pos - 1);
while ($lastNode.parent.type !== paragraph) {
$lastNode = state.doc.resolve($lastNode.pos - 1);
}
let { tr } = state;
if (isGapCursorShown) {
const nodeBeforePos = findPositionOfNodeBefore(tr.selection);
if (typeof nodeBeforePos !== 'number') {
return false;
}
// append the paragraph / codeblock / heading to the list node
const list = $cut.nodeBefore.copy(
$cut.nodeBefore.content.append(
Fragment.from(listItem!.createChecked({}, $cut.nodeAfter)!),
),
);
tr.replaceWith(
nodeBeforePos,
$from.pos + $cut.nodeAfter.nodeSize,
list,
);
} else {
// take the text content of the paragraph and insert after the paragraph up until before the the cut
tr = tr.step(
new ReplaceAroundStep(
$lastNode.pos,
$cut.pos + $cut.nodeAfter.nodeSize,
$cut.pos + 1,
$cut.pos + $cut.nodeAfter.nodeSize - 1,
state.tr.doc.slice($lastNode.pos, $cut.pos),
0,
true,
),
);
}
// find out if there's now another list following and join them
// as in, [list, p, list] => [list with p, list], and we want [joined list]
let $postCut = tr.doc.resolve(
tr.mapping.map($cut.pos + $cut.nodeAfter.nodeSize),
);
if (
$postCut.nodeBefore &&
$postCut.nodeAfter &&
$postCut.nodeBefore.type === $postCut.nodeAfter.type &&
[bulletList, orderedList].indexOf($postCut.nodeBefore.type) > -1
) {
tr = tr.join($postCut.pos);
}
if (dispatch) {
dispatch(tr.scrollIntoView());
}
return true;
}
}
return false;
};
}
function deletePreviousEmptyListItem(type: NodeType): Command {
return (state, dispatch) => {
const { $from } = state.selection;
let listItem = type;
if (!listItem) {
listItem = getNodeType(state, 'listItem');
}
const $cut = findCutBefore($from);
if (!$cut || !$cut.nodeBefore || !($cut.nodeBefore.type === listItem)) {
return false;
}
const previousListItemEmpty =
$cut.nodeBefore.childCount === 1 &&
$cut.nodeBefore.firstChild!.nodeSize <= 2;
if (previousListItemEmpty) {
const { tr } = state;
if (dispatch) {
dispatch(
tr
.delete($cut.pos - $cut.nodeBefore.nodeSize, $from.pos)
.scrollIntoView(),
);
}
return true;
}
return false;
};
}
export function moveEdgeListItem(
type: NodeType,
dir: MoveDirection = 'UP',
): Command {
const isDown = dir === 'DOWN';
const isItemAtEdge = (state: EditorState) => {
const currentResolved = findParentNodeOfType(type)(state.selection);
if (!currentResolved) {
return false;
}
const currentNode = currentResolved.node;
const { $from } = state.selection;
const parent = $from.node(currentResolved.depth - 1);
const matchedChild = parent && parent[isDown ? 'lastChild' : 'firstChild'];
if (currentNode && matchedChild === currentNode) {
return true;
}
return false;
};
const command: Command = (state, dispatch, view) => {
let listItem = type;
if (!listItem) {
listItem = getNodeType(state, 'listItem');
}
if (!state.selection.empty) {
return false;
}
const grandParent = findParentNode((node) =>
validListParent(node.type, state.schema.nodes),
)(state.selection);
const parent = findParentNodeOfType(listItem)(state.selection);
if (!(grandParent && grandParent.node) || !(parent && parent.node)) {
return false;
}
// outdent if the not nested list item i.e. top level
if (state.selection.$from.depth === 3) {
return outdentList(listItem)(state, dispatch, view);
}
// If there is only one element, we need to delete the entire
// bulletList/orderedList so as not to leave any empty list behind.
let nodeToRemove = grandParent.node.childCount === 1 ? grandParent : parent;
let tr = state.tr.delete(
nodeToRemove.pos,
nodeToRemove.pos + nodeToRemove.node.nodeSize,
);
// - first // doing a (-1) will move us to end of 'first' hence allowing us to add an item
// - second // start(-3) will give 11 which is the start of this listItem,
// - third{<>}
let insertPos = state.selection.$from.before(-3);
// when going down move the position by the size of remaining content (after deletion)
if (isDown) {
let uncleNodePos = state.selection.$from.after(-3);
insertPos = uncleNodePos - nodeToRemove.node.nodeSize;
let uncle =
validPos(uncleNodePos, state.doc) && state.doc.nodeAt(uncleNodePos);
if (uncle && uncle.type === listItem) {
// Example
// - first
// - second
// - third{<>}
// - uncle
// {x} <== you want to go down here
insertPos += uncle.nodeSize;
}
}
let nodeToInsert = parent.node;
const newTr = safeInsert(nodeToInsert, insertPos)(tr);
// no change hence dont mutate anything
if (newTr === tr) {
return false;
}
if (dispatch) {
dispatch(newTr);
}
return true;
};
return filter([isItemAtEdge], command);
}
export function updateNodeAttrs(
type: NodeType,
cb: (attrs: Node['attrs']) => Node['attrs'],
): Command {
return (state, dispatch) => {
const { $from } = state.selection;
const current = $from.node(-1);