Skip to content

Commit 909d19d

Browse files
authored
UX: add hard break with double space+enter on rich editor (#34157)
Supports an ENTER key mapping to add a hard break when triggered at the end of a line ending in two spaces.
1 parent 3bb1a77 commit 909d19d

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

app/assets/javascripts/discourse/app/static/prosemirror/core/keymap.js

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import { redo, undo } from "prosemirror-history";
99
import { undoInputRule } from "prosemirror-inputrules";
1010
import { splitListItem } from "prosemirror-schema-list";
11-
import { atBlockStart } from "../lib/plugin-utils";
11+
import { atBlockStart, inNode } from "../lib/plugin-utils";
1212

1313
const BACKSPACE_UNSET_NODES = ["heading", "code_block"];
1414

@@ -69,7 +69,31 @@ export function buildKeymap(
6969
return true;
7070
});
7171

72-
keys["Enter"] = splitListItem(schema.nodes.list_item);
72+
const doubleSpaceHardBreak = (state, dispatch) => {
73+
const { $from } = state.selection;
74+
if ($from.parent.type.spec.code || inNode(state, schema.nodes.code_block)) {
75+
return false;
76+
}
77+
78+
if ($from.nodeBefore?.text.endsWith(" ")) {
79+
if (dispatch) {
80+
const tr = state.tr.replaceRangeWith(
81+
$from.pos - 2,
82+
$from.pos,
83+
schema.nodes.hard_break.create()
84+
);
85+
86+
dispatch(tr.scrollIntoView());
87+
}
88+
return true;
89+
}
90+
return false;
91+
};
92+
93+
keys["Enter"] = chainCommands(
94+
doubleSpaceHardBreak,
95+
splitListItem(schema.nodes.list_item)
96+
);
7397

7498
keys["Mod-Shift-_"] = (state, dispatch) => {
7599
dispatch?.(

spec/system/composer/prosemirror_editor_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,16 @@ def body(title)
600600
expect(rich).to have_css("hr")
601601
end
602602

603+
it "creates hard break when pressing Enter after double space at end of line" do
604+
open_composer
605+
composer.type_content("Line with double space ")
606+
composer.send_keys(:enter)
607+
composer.type_content("Next line")
608+
609+
composer.toggle_rich_editor
610+
expect(composer).to have_value("Line with double space\nNext line")
611+
end
612+
603613
it "supports Backspace to reset a heading" do
604614
open_composer
605615
composer.type_content("# With text")

0 commit comments

Comments
 (0)