Always create new element on nodeAdded event
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / keyboard.js
1 define([
2 'modules/documentCanvas/canvas/documentElement',
3 'modules/documentCanvas/canvas/utils'
4 ], function(documentElement, utils) {
5     
6 'use strict';
7
8
9 var KEYS = {
10     ENTER: 13,
11     ARROW_LEFT: 37,
12     ARROW_UP: 38,
13     ARROW_RIGHT: 39,
14     ARROW_DOWN: 40,
15     BACKSPACE: 8,
16     DELETE: 46,
17     X: 88
18 };
19
20 var handleKey = function(event, canvas) {
21     handlers.some(function(handler) {
22         if(handles(handler, event) && handler[event.type]) {
23             handler[event.type](event, canvas);
24             return true;
25         }
26     });
27 };
28
29 var handles = function(handler, event) {
30     if(handler.key === event.which)
31         return true;
32     if(handler.keys && handler.keys.indexOf(event.which) !== -1)
33         return true;
34     return false;
35 };
36
37 var handlers = [];
38
39
40 handlers.push({key: KEYS.ENTER,
41     keydown: function(event, canvas) {
42         event.preventDefault();
43         var cursor = canvas.getCursor(),
44             position = cursor.getPosition(),
45             element = position.element;
46
47         if(Object.keys(cursor.getPosition()).length === 0) {
48             var currentElement = canvas.getCurrentNodeElement();
49             if(currentElement) {
50                 var added = currentElement.data('wlxmlNode').after({
51                     tag: currentElement.getWlxmlTag() || 'div',
52                     attrs: {'class': currentElement.getWlxmlClass() || 'p'}
53                 });
54                 added.append({text:''});
55                 canvas.setCurrentElement(utils.findCanvasElement(added), {caretTo: 'start'});
56             }
57             return;
58         }
59
60         if(!cursor.isSelecting()) {
61             if(event.ctrlKey) {
62                 if(element instanceof documentElement.DocumentTextElement) {
63                     element = element.parent();
64                 }
65                 var added = element.data('wlxmlNode').after(
66                     {tagName: element.getWlxmlTag() || 'div', attrs: {'class': element.getWlxmlClass() || 'p'}}
67                 );
68                 added.append({text: ''});
69                 canvas.setCurrentElement(utils.findCanvasElement(added), {caretTo: 'start'});
70
71             } else {
72
73                 if(!(element.parent().parent())) {
74                     return false; // top level element is unsplittable
75                 }
76
77                 var nodes = position.element.data('wlxmlNode').split({offset: position.offset}),
78                     newEmpty,
79                     goto,
80                     gotoOptions;
81
82                 if(position.offsetAtBeginning)
83                     newEmpty = nodes.first;
84                 else if(position.offsetAtEnd)
85                     newEmpty = nodes.second;
86                 
87                 if(newEmpty) {
88                     goto = newEmpty.append({text: ''});
89                     gotoOptions = {};
90                 } else {
91                     goto = nodes.second;
92                     gotoOptions = {caretTo: 'start'};
93                 }
94
95                 canvas.setCurrentElement(utils.findCanvasElement(goto), gotoOptions);
96             }
97         }
98     }
99 });
100
101 handlers.push({keys: [KEYS.ARROW_UP, KEYS.ARROW_DOWN, KEYS.ARROW_LEFT, KEYS.ARROW_RIGHT],
102     keydown: function(event, canvas) {
103         var position = canvas.getCursor().getPosition(),
104             element = position.element;
105         if(element && (element instanceof documentElement.DocumentTextElement) && element.isEmpty()) {
106             var direction, caretTo;
107             if(event.which === KEYS.ARROW_LEFT  || event.which === KEYS.ARROW_UP) {
108                 direction = 'above';
109                 caretTo = 'end';
110             } else {
111                 direction = 'below';
112                 caretTo = 'start';
113             }
114             var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
115             canvas.setCurrentElement(el, {caretTo: caretTo});
116         }
117     },
118     keyup: function(event, canvas) {
119         var element = canvas.getCursor().getPosition().element,
120             caretTo = false;
121         if(!element) {
122             // Chrome hack
123             var direction;
124             if(event.which === KEYS.ARROW_LEFT  || event.which === KEYS.ARROW_UP) {
125                 direction = 'above';
126                 caretTo = 'end';
127             } else {
128                 direction = 'below';
129                 caretTo = 'start';
130             }
131             element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
132         }
133         canvas.setCurrentElement(element, {caretTo: caretTo});
134     }
135 });
136
137
138 var selectsWholeTextElement = function(cursor) {
139     if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd)
140         return true;
141     return false;
142 }
143
144 handlers.push({key: KEYS.X,
145     keydown: function(event, canvas) {
146         if(event.ctrlKey && selectsWholeTextElement(canvas.getCursor()))
147             event.preventDefault();
148     }
149 });
150
151 handlers.push({keys: [KEYS.BACKSPACE, KEYS.DELETE],
152     keydown: function(event, canvas) {
153         var cursor = canvas.getCursor(),
154             position = canvas.getCursor().getPosition(),
155             element = position.element;
156
157         if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
158             event.preventDefault();
159             return;
160         }
161             
162         var cursorAtOperationEdge = position.offsetAtBeginning;
163         if(event.which === KEYS.DELETE) {
164             cursorAtOperationEdge = position.offsetAtEnd;
165         }
166
167         var willDeleteWholeText = function() {
168             return element.getText().length === 1 || selectsWholeTextElement(cursor);
169         }
170
171         if(willDeleteWholeText()) {
172             event.preventDefault();
173             element.setText('');
174         }
175         else if(element.isEmpty()) {
176
177             var direction = 'above',
178                 caretTo = 'end';
179                 
180             if(event.which === KEYS.DELETE) {
181                 direction = 'below';
182                 caretTo = 'start';
183             }
184
185             event.preventDefault();
186
187             var parent = element.parent(),
188                 grandParent = parent ? parent.parent() : null,
189                 goto;
190             if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
191                 if(grandParent && grandParent.children().length === 1) {
192                     goto = grandParent.data('wlxmlNode').append({text: ''});
193                 } else {
194                     goto = element.getNearestTextElement(direction);
195                 }
196                 parent.data('wlxmlNode').detach();
197             } else {
198                 goto = element.getNearestTextElement(direction);
199                 element.data('wlxmlNode').detach();
200             }
201             canvas.setCurrentElement(goto, {caretTo: caretTo});
202             canvas.publisher('contentChanged');
203         }
204         else if(cursorAtOperationEdge) {
205             // todo
206             event.preventDefault();
207         }
208     }
209 });
210
211 return {
212     handleKey: handleKey
213 };
214
215 });