Skip to content

Commit

Permalink
Add custom keymapping for addresses
Browse files Browse the repository at this point in the history
Unlike other components, addresses use hardbreaks between lines of the address rather than new paragraphs.

This PR disables the shift+enter mapping for linebreaks and instead adds custom mapping to the enter key to insert linebreaks when in an address instead.

When the user is at the end of an address and presses enter for a second time we instead insert a paragraph and return false to let the default handler lift the paragraph out of the address.
  • Loading branch information
dnkrj authored and lauraghiorghisor-tw committed May 22, 2024
1 parent ba8968f commit 787ada2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/plugins.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import { exampleSetup } from "prosemirror-example-setup";
import customInputRules from "./plugins/custom-input-rules";
import editorGovspeakClass from "./plugins/editor-govspeak-class";
import customKeymap from "./plugins/custom-keymap";
import menu from "./plugins/menu";

const mapKeys = {
"Mod-Enter": false,
"Shift-Enter": false,
"Ctrl-Enter": false,
};

export default (options) => {
const plugins = [
customInputRules(options.schema),
editorGovspeakClass,
customKeymap(options.schema),
menu(options.schema),
];

options.menuBar = false;
options.mapKeys = mapKeys;
const examplePlugins = exampleSetup(options);
// Remove the "ProseMirror-example-setup-style" class name plugin
examplePlugins.pop();
Expand Down
35 changes: 35 additions & 0 deletions lib/plugins/custom-keymap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Selection } from "prosemirror-state";
import { keymap } from "prosemirror-keymap";

const newlineInAddress = (schema) => {
return (state, dispatch) => {
const { $head, $anchor } = state.selection;
if (!$head.sameParent($anchor)) return false;

const paragraphParent = $head.node($head.depth - 1);
if (!(paragraphParent.type === schema.nodes.address)) return false;

if (
$head.nodeBefore.type === schema.nodes.hard_break &&
$head.parentOffset === $head.parent.content.size
) {
const pos = $head.after();
const tr = state.tr.deleteRange(pos - 2, pos);
tr.replaceWith(pos - 2, pos - 2, schema.nodes.paragraph.createAndFill());
tr.setSelection(Selection.near(tr.doc.resolve(pos - 1), 1));
tr.split(pos - 1);
dispatch(tr.scrollIntoView());
return false;
}

const hardBreak = schema.node("hard_break");
dispatch(state.tr.replaceSelectionWith(hardBreak).scrollIntoView());
return true;
};
};

export default function customKeymap(schema) {
return keymap({
Enter: newlineInAddress(schema),
});
}

0 comments on commit 787ada2

Please sign in to comment.