Skip to content

Commit 71813a2

Browse files
authored
feat(HorizontalRule): improve horizontal line insertion (#218)
The behavior of inserting horizontal line: - Disabled: - when selecting any text - when cursor inside complex textblock - selection type is some other then TextSelection or NodeSelection - If node selection: replace the selected node with horizontal_rule - If cursor is in an empty paragraph: insert horizontal_rule before current paragraph - If cursor is in another textblock or a non-empty paragraph: insert horizontal_rule and a new empty paragraph after the current textblock
1 parent fc78baa commit 71813a2

File tree

1 file changed

+26
-3
lines changed
  • src/extensions/markdown/HorizontalRule

1 file changed

+26
-3
lines changed

src/extensions/markdown/HorizontalRule/index.ts

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import type {NodeType} from 'prosemirror-model';
2-
import type {Command, Selection} from 'prosemirror-state';
2+
import {Command, Selection, TextSelection} from 'prosemirror-state';
33

44
import type {Action, ExtensionAuto} from '../../../core';
55
import {nodeInputRule} from '../../../utils/inputrules';
6-
import {isNodeSelection} from '../../../utils/selection';
6+
import {get$Cursor, isNodeSelection} from '../../../utils/selection';
77
import {pType} from '../../base/BaseSchema/BaseSchemaSpecs';
88

99
import {
@@ -65,10 +65,33 @@ declare global {
6565
const addHr =
6666
(hr: NodeType): Command =>
6767
(state, dispatch) => {
68-
if (!isHrSelection(state.selection)) {
68+
if (isHrSelection(state.selection)) return true;
69+
70+
if (isNodeSelection(state.selection)) {
6971
dispatch?.(state.tr.replaceSelectionWith(hr.create()).scrollIntoView());
72+
return true;
7073
}
7174

75+
const $cursor = get$Cursor(state.selection);
76+
if (!$cursor || $cursor.parent.type.spec.complex) return false;
77+
78+
if (!dispatch) return true;
79+
80+
const {tr} = state;
81+
const isEmptyParagraph =
82+
$cursor.parent.type === pType(state.schema) && $cursor.parent.nodeSize === 2;
83+
84+
if (isEmptyParagraph) {
85+
const pos = $cursor.before();
86+
tr.insert(pos, hr.create());
87+
} else {
88+
const pos = $cursor.after();
89+
tr.insert(pos, [hr.create(), pType(state.schema).create()]);
90+
tr.setSelection(TextSelection.create(tr.doc, pos + 2)); // set cursor to paragraph after hr
91+
}
92+
93+
dispatch(tr.scrollIntoView());
94+
7295
return true;
7396
};
7497

0 commit comments

Comments
 (0)