2020-11-05 05:38:52 +08:00
|
|
|
import { TextSelection } from 'prosemirror-state'
|
2020-11-17 04:42:35 +08:00
|
|
|
import { Editor } from '../Editor'
|
2020-11-18 02:36:27 +08:00
|
|
|
import { Command, FocusPosition } from '../types'
|
2020-11-05 05:38:52 +08:00
|
|
|
import minMax from '../utils/minMax'
|
|
|
|
|
|
|
|
interface ResolvedSelection {
|
|
|
|
from: number,
|
|
|
|
to: number,
|
|
|
|
}
|
|
|
|
|
2020-11-18 02:36:27 +08:00
|
|
|
function resolveSelection(editor: Editor, position: FocusPosition = null): ResolvedSelection {
|
2020-11-05 05:38:52 +08:00
|
|
|
if (position === null) {
|
|
|
|
return editor.selection
|
|
|
|
}
|
|
|
|
|
|
|
|
if (position === 'start' || position === true) {
|
|
|
|
return {
|
|
|
|
from: 0,
|
|
|
|
to: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (position === 'end') {
|
|
|
|
const { size } = editor.state.doc.content
|
|
|
|
|
|
|
|
return {
|
|
|
|
from: size,
|
|
|
|
to: size - 1, // TODO: -1 only for nodes with content
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
from: position as number,
|
|
|
|
to: position as number,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-18 02:36:27 +08:00
|
|
|
export default (position: FocusPosition = null): Command => ({
|
|
|
|
editor,
|
|
|
|
view,
|
|
|
|
tr,
|
|
|
|
dispatch,
|
2020-11-05 05:38:52 +08:00
|
|
|
}) => {
|
|
|
|
if ((view.hasFocus() && position === null) || position === false) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
const { from, to } = resolveSelection(editor, position)
|
|
|
|
const { doc } = tr
|
|
|
|
const resolvedFrom = minMax(from, 0, doc.content.size)
|
|
|
|
const resolvedEnd = minMax(to, 0, doc.content.size)
|
|
|
|
const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd)
|
|
|
|
|
|
|
|
if (dispatch) {
|
|
|
|
tr.setSelection(selection)
|
|
|
|
view.focus()
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|