Skip to content

Commit

Permalink
add willhandlenewline hook
Browse files Browse the repository at this point in the history
  • Loading branch information
eguitarz committed Sep 9, 2016
1 parent 059fd66 commit cf1024d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/js/editor/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ const CALLBACK_QUEUES = {
DID_RENDER: 'didRender',
WILL_DELETE: 'willDelete',
DID_DELETE: 'didDelete',
WILL_HANDLE_NEWLINE: 'willHandleNewline',
CURSOR_DID_CHANGE: 'cursorDidChange',
DID_REPARSE: 'didReparse',
POST_DID_CHANGE: 'postDidChange',
Expand Down Expand Up @@ -339,6 +340,13 @@ class Editor {
return;
}
}

// Above logic might delete redundant range, so callback must run after it.
let defaultPrevented = false;
const event = { preventDefault() { defaultPrevented = true; } };
this.runCallbacks(CALLBACK_QUEUES.WILL_HANDLE_NEWLINE, [event]);
if (defaultPrevented) { return; }

cursorSection = postEditor.splitSection(range.head)[1];
postEditor.setRange(cursorSection.headPosition());
});
Expand Down Expand Up @@ -786,6 +794,14 @@ class Editor {
this.addCallback(CALLBACK_QUEUES.DID_DELETE, callback);
}

/**
* @param {Function} callback This callback will be called before handling new line.
* @public
*/
willHandleNewline(callback) {
this.addCallback(CALLBACK_QUEUES.WILL_HANDLE_NEWLINE, callback);
}

/**
* @param {Function} callback This callback will be called every time the cursor
* position (or selection) changes.
Expand Down
14 changes: 14 additions & 0 deletions tests/acceptance/basic-editor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,17 @@ test('keypress events when the editor does not have selection are ignored', (ass
done();
});
});

test('prevent handling newline', (assert) => {
editor = Helpers.editor.buildFromText('', {element: editorElement});

editor.willHandleNewline(event => {
assert.ok(true, 'willHandleNewline should be triggered');
event.preventDefault();
});
let {post: expected} = Helpers.postAbstract.buildFromText(['Line1']);

Helpers.dom.insertText(editor, 'Line1');
Helpers.dom.insertText(editor, ENTER);
assert.postIsSimilar(editor.post, expected);
});

0 comments on commit cf1024d

Please sign in to comment.