improve toggleList

This commit is contained in:
Philipp Kühn
2020-11-02 11:16:18 +01:00
parent 8e480f86b9
commit ca5a60b7a2
3 changed files with 39 additions and 1 deletions

View File

@@ -21,3 +21,4 @@ export { ToggleList } from './toggleList'
export { ToggleMark } from './toggleMark'
export { UpdateMark } from './updateMark'
export { ToggleWrap } from './toggleWrap'
export { WrapInList } from './wrapInList'

View File

@@ -9,7 +9,9 @@ import isList from '../utils/isList'
export const ToggleList = createExtension({
addCommands() {
return {
toggleList: (listTypeOrName: string | NodeType, itemTypeOrName: string | NodeType): Command => ({ tr, state, dispatch }) => {
toggleList: (listTypeOrName: string | NodeType, itemTypeOrName: string | NodeType): Command => ({
tr, state, dispatch, chain,
}) => {
const { extensions } = this.editor.options
const listType = getNodeType(listTypeOrName, state.schema)
const itemType = getNodeType(itemTypeOrName, state.schema)
@@ -24,10 +26,12 @@ export const ToggleList = createExtension({
const parentList = findParentNode(node => isList(node.type.name, extensions))(selection)
if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
// remove list
if (parentList.node.type === listType) {
return liftListItem(itemType)(state, dispatch)
}
// change list type
if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content)) {
tr.setNodeMarkup(parentList.pos, listType)
@@ -35,6 +39,16 @@ export const ToggleList = createExtension({
}
}
const canWrapInList = wrapInList(listType)(state)
// try to convert node to paragraph if needed
if (!canWrapInList) {
return chain()
.setBlockType('paragraph')
.wrapInList(listType)
.run()
}
return wrapInList(listType)(state, dispatch)
},
}

View File

@@ -0,0 +1,23 @@
import { wrapInList } from 'prosemirror-schema-list'
import { NodeType } from 'prosemirror-model'
import { Command } from '../Editor'
import { createExtension } from '../Extension'
import getNodeType from '../utils/getNodeType'
export const WrapInList = createExtension({
addCommands() {
return {
wrapInList: (typeOrName: string | NodeType, attrs?: {}): Command => ({ state, dispatch }) => {
const type = getNodeType(typeOrName, state.schema)
return wrapInList(type, attrs)(state, dispatch)
},
}
},
})
declare module '../Editor' {
interface AllExtensions {
WrapInList: typeof WrapInList,
}
}