Skip to content

Commit f1d2262

Browse files
eguitarzbantic
authored andcommitted
feat(willHandleNewline): add willHandleNewline hook (#489)
1 parent 3335357 commit f1d2262

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/js/editor/editor.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ const CALLBACK_QUEUES = {
6363
DID_RENDER: 'didRender',
6464
WILL_DELETE: 'willDelete',
6565
DID_DELETE: 'didDelete',
66+
WILL_HANDLE_NEWLINE: 'willHandleNewline',
6667
CURSOR_DID_CHANGE: 'cursorDidChange',
6768
DID_REPARSE: 'didReparse',
6869
POST_DID_CHANGE: 'postDidChange',
@@ -339,6 +340,13 @@ class Editor {
339340
return;
340341
}
341342
}
343+
344+
// Above logic might delete redundant range, so callback must run after it.
345+
let defaultPrevented = false;
346+
const event = { preventDefault() { defaultPrevented = true; } };
347+
this.runCallbacks(CALLBACK_QUEUES.WILL_HANDLE_NEWLINE, [event]);
348+
if (defaultPrevented) { return; }
349+
342350
cursorSection = postEditor.splitSection(range.head)[1];
343351
postEditor.setRange(cursorSection.headPosition());
344352
});
@@ -782,6 +790,14 @@ class Editor {
782790
this.addCallback(CALLBACK_QUEUES.DID_DELETE, callback);
783791
}
784792

793+
/**
794+
* @param {Function} callback This callback will be called before handling new line.
795+
* @public
796+
*/
797+
willHandleNewline(callback) {
798+
this.addCallback(CALLBACK_QUEUES.WILL_HANDLE_NEWLINE, callback);
799+
}
800+
785801
/**
786802
* @param {Function} callback This callback will be called every time the cursor
787803
* position (or selection) changes.

tests/acceptance/basic-editor-test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,3 +210,17 @@ test('keypress events when the editor does not have selection are ignored', (ass
210210
done();
211211
});
212212
});
213+
214+
test('prevent handling newline', (assert) => {
215+
editor = Helpers.editor.buildFromText('', {element: editorElement});
216+
217+
editor.willHandleNewline(event => {
218+
assert.ok(true, 'willHandleNewline should be triggered');
219+
event.preventDefault();
220+
});
221+
let {post: expected} = Helpers.postAbstract.buildFromText(['Line1']);
222+
223+
Helpers.dom.insertText(editor, 'Line1');
224+
Helpers.dom.insertText(editor, ENTER);
225+
assert.postIsSimilar(editor.post, expected);
226+
});

0 commit comments

Comments
 (0)