roojs-ui.js
[roojs1] / Roo / htmleditor / KeyEnter.js
1
2 /**
3  * @class Roo.htmleditor.KeyEnter
4  * Handle Enter press..
5  * @cfg {Roo.HtmlEditorCore} core the editor.
6  * @constructor
7  * Create a new Filter.
8  * @param {Object} config Configuration options
9  */
10
11
12
13 Roo.htmleditor.KeyEnter = function(cfg) {
14     Roo.apply(this, cfg);
15     // this does not actually call walk as it's really just a abstract class
16  
17     Roo.get(this.core.doc.body).on('keypress', this.keypress, this);
18 }
19
20
21 Roo.htmleditor.KeyEnter.prototype = {
22     
23     core : false,
24     
25     keypress : function(e)
26     {
27         if (e.charCode != 13) {
28             return true;
29         }
30         e.preventDefault();
31         // https://stackoverflow.com/questions/18552336/prevent-contenteditable-adding-div-on-enter-chrome
32         var doc = this.core.doc;
33         
34         var docFragment = doc.createDocumentFragment();
35     
36         //add a new line
37         var newEle = doc.createTextNode('\n');
38         docFragment.appendChild(newEle);
39     
40     
41         var range = this.core.win.getSelection().getRangeAt(0);
42         var n = range.commonAncestorContainer ;
43         while (n && n.nodeType != 1) {
44             n  = n.parentNode;
45         }
46         var li = false;
47         if (n && n.tagName == 'UL') {
48             li = doc.createElement('LI');
49             n.appendChild(li);
50             
51         }
52         if (n && n.tagName == 'LI') {
53             li = doc.createElement('LI');
54             if (n.nextSibling) {
55                 n.parentNode.insertBefore(li, n.firstSibling);
56                 
57             } else {
58                 n.parentNode.appendChild(li);
59             }
60         }
61         if (li) {   
62             range = doc.createRange();
63             range.setStartAfter(li);
64             range.collapse(true);
65         
66             //make the cursor there
67             var sel = this.core.win.getSelection();
68             sel.removeAllRanges();
69             sel.addRange(range);
70             return false;
71             
72             
73         }
74         //add the br, or p, or something else
75         newEle = doc.createElement('br');
76         docFragment.appendChild(newEle);
77     
78         //make the br replace selection
79         
80         range.deleteContents();
81         
82         range.insertNode(docFragment);
83         range = range.cloneRange();
84         range.collapse(true);
85         var sel = this.core.win.getSelection();
86         sel.removeAllRanges();
87         sel.addRange(range);
88         sel.collapseToEnd();
89     
90         return false;
91          
92     }
93 };
94