-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(Lists): add auto merging of adjacent list of same type (#241)
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import {Plugin, Transaction} from 'prosemirror-state'; | ||
import {findChildren, hasParentNode} from 'prosemirror-utils'; | ||
|
||
import {isListNode} from '../utils'; | ||
|
||
export const mergeListsPlugin = () => | ||
new Plugin({ | ||
appendTransaction(trs, oldState, newState) { | ||
const docChanged = trs.some((tr) => tr.docChanged); | ||
if (!docChanged) return null; | ||
|
||
const hasParentList = | ||
hasParentNode(isListNode)(newState.selection) || | ||
hasParentNode(isListNode)(oldState.selection); | ||
if (!hasParentList) return null; | ||
|
||
const {tr} = newState; | ||
const listNodes = findChildren(tr.doc, isListNode, true); | ||
|
||
mergeAdjacentNodesWithSameType(tr, listNodes); | ||
|
||
return tr.docChanged ? tr : null; | ||
}, | ||
}); | ||
|
||
function mergeAdjacentNodesWithSameType( | ||
tr: Transaction, | ||
nodes: ReturnType<typeof findChildren>, | ||
): void { | ||
for (let i = 0; i < nodes.length - 1; i++) { | ||
const current = nodes[i]; | ||
const next = nodes[i + 1]; | ||
|
||
if ( | ||
current.node.type === next.node.type && | ||
current.pos + current.node.nodeSize === next.pos | ||
) { | ||
tr.join(next.pos); | ||
} | ||
} | ||
} |