editor: minor refactoring
[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 /* globals gettext */
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     }
33     if(handler.keys && handler.keys.indexOf(event.which) !== -1) {
34         return true;
35     }
36     return false;
37 };
38
39 var handlers = [];
40
41
42 handlers.push({key: KEYS.ENTER,
43     keydown: function(event, canvas) {
44         event.preventDefault();
45         var cursor = canvas.getCursor(),
46             position = cursor.getPosition(),
47             element = position.element;
48
49         if(Object.keys(cursor.getPosition()).length === 0) {
50             var currentElement = canvas.getCurrentNodeElement();
51             if(currentElement && !currentElement.wlxmlNode.isRoot()) {
52                 canvas.wlxmlDocument.transaction(function() {
53                     var added = currentElement.wlxmlNode.after({
54                         tagName: currentElement.wlxmlNode.getTagName() || 'div',
55                         attrs: {'class': currentElement.wlxmlNode.getClass() || 'p'}
56                     });
57                     added.append({text:''});
58                     return added;
59                 }, {
60                     metadata: {
61                         description: gettext('Splitting text')
62                     },
63                     success: function(ret) {
64                         canvas.setCurrentElement(utils.getElementForNode(ret), {caretTo: 'start'});
65                     }
66                 });
67
68             }
69             return;
70         }
71
72         if(!cursor.isSelecting()) {
73             if(event.ctrlKey) {
74                 if(element instanceof documentElement.DocumentTextElement) {
75                     element = element.parent();
76                 }
77
78                 canvas.wlxmlDocument.transaction(function() {
79                     var added = element.wlxmlNode.after(
80                         {tagName: element.wlxmlNode.getTagName() || 'div', attrs: {'class': element.wlxmlNode.getClass() || 'p'}}
81                     );
82                     added.append({text: ''});
83                     return added;
84                 }, {
85                     metadata: {
86                         description: gettext('Splitting text')
87                     },
88                     success: function(ret) {
89                         canvas.setCurrentElement(utils.getElementForNode(ret), {caretTo: 'start'});
90                     }
91                 });
92
93             } else {
94
95                 if(!(element.parent().parent())) {
96                     return false; // top level element is unsplittable
97                 }
98
99                 var node = position.element.wlxmlNode,
100                     result, goto, gotoOptions;
101
102                 node.document.transaction(function() {
103                     result = position.element.wlxmlNode.breakContent({offset: position.offset});
104                 }, {
105                     metadata: {
106                         description: gettext('Splitting text')
107                     }
108                 });
109
110                 if(result.emptyText) {
111                     goto = result.emptyText;
112                     gotoOptions = {};
113                 } else {
114                     goto = result.second;
115                     gotoOptions = {caretTo: 'start'};
116                 }
117
118                 canvas.setCurrentElement(utils.getElementForNode(goto), gotoOptions);
119             }
120         }
121     }
122 });
123
124 handlers.push({keys: [KEYS.ARROW_UP, KEYS.ARROW_DOWN, KEYS.ARROW_LEFT, KEYS.ARROW_RIGHT],
125     keydown: function(event, canvas) {
126         var position = canvas.getCursor().getPosition(),
127             element = position.element;
128         if(element && (element instanceof documentElement.DocumentTextElement) && element.isEmpty()) {
129             var direction, caretTo;
130             if(event.which === KEYS.ARROW_LEFT  || event.which === KEYS.ARROW_UP) {
131                 direction = 'above';
132                 caretTo = 'end';
133             } else {
134                 direction = 'below';
135                 caretTo = 'start';
136             }
137             var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom[0]));
138             if(el) {
139                 canvas.setCurrentElement(el, {caretTo: caretTo});
140             }
141         }
142     },
143     keyup: function(event, canvas) {
144         var element = canvas.getCursor().getPosition().element,
145             caretTo = false;
146         if(!element) {
147             // Chrome hack
148
149             var moves = [{direction: 'above', caretTo: 'end'}, {direction: 'below', caretTo: 'start'}];
150             if(event.which === KEYS.ARROW_RIGHT  || event.which === KEYS.ARROW_DOWN) {
151                 moves.reverse();
152             }
153             moves.some(function(move) {
154                 /* globals window */
155                 var targetNode = utils.nearestInDocumentOrder('[document-text-element]:visible', move.direction, window.getSelection().focusNode);
156                 if(targetNode) {
157                     element = canvas.getDocumentElement(targetNode);
158                     caretTo = move.caretTo;
159                     return true; // break
160                 }
161             });
162         }
163         if(element) {
164             canvas.setCurrentElement(element, {caretTo: caretTo});
165         }
166     }
167 });
168
169
170 var selectsWholeTextElement = function(cursor) {
171     if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd) {
172         return true;
173     }
174     return false;
175 };
176
177 handlers.push({key: KEYS.X,
178     keydown: function(event, canvas) {
179         if(event.ctrlKey && selectsWholeTextElement(canvas.getCursor())) {
180             event.preventDefault();
181         }
182     }
183 });
184
185 handlers.push({keys: [KEYS.BACKSPACE, KEYS.DELETE],
186     keydown: function(event, canvas) {
187         var cursor = canvas.getCursor(),
188             position = canvas.getCursor().getPosition(),
189             element = position.element,
190             node = element ? element.wlxmlNode : null,
191             direction = 'above',
192             caretTo = 'end',
193             goto;
194
195         if(!element || !node) {
196             return;
197         }
198             
199         if(event.which === KEYS.DELETE) {
200             direction = 'below';
201             caretTo = 'start';
202         }
203
204         if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
205             event.preventDefault();
206             var start = cursor.getSelectionStart(),
207                 end = cursor.getSelectionEnd();
208
209             if(direction === 'above') {
210                 if(start.offsetAtBeginning) {
211                     goto = canvas.getNearestTextElement('above', start.element);
212                     caretTo = 'end';
213                 } else {
214                     goto = start.element;
215                     caretTo = start.offset;
216                 }
217             } else {
218                 if(end.offsetAtEnd) {
219                     goto = canvas.getNearestTextElement('below', start.element);
220                     caretTo = 'start';
221                 } else {
222                     goto = end.element;
223                     caretTo = 0;
224                 }
225             }
226
227             canvas.wlxmlDocument.deleteText({
228                 from: {
229                     node: start.element.wlxmlNode,
230                     offset: start.offset
231                 },
232                 to: {
233                     node: end.element.wlxmlNode,
234                     offset: end.offset
235                 }
236             });
237             if(goto) {
238                 canvas.setCurrentElement(goto, {caretTo: caretTo});
239             }
240             return;
241         }
242             
243         var cursorAtOperationEdge = position.offsetAtBeginning;
244         if(event.which === KEYS.DELETE) {
245             cursorAtOperationEdge = position.offsetAtEnd;
246         }
247
248         var willDeleteWholeText = function() {
249             return element.getText().length === 1 || selectsWholeTextElement(cursor);
250         };
251
252         canvas.wlxmlDocument.transaction(function() {
253             if(willDeleteWholeText()) {
254                 event.preventDefault();
255                 node.setText('');
256             }
257             else if(element.isEmpty()) {
258                 event.preventDefault();
259                 var parent = element.parent(),
260                     grandParent = parent ? parent.parent() : null;
261                 if(!grandParent && parent.children().length === 1) {
262                     return;
263                 }
264                 if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
265                     if(grandParent && grandParent.children().length === 1) {
266                         goto = grandParent.wlxmlNode.append({text: ''});
267                     } else {
268                         goto = canvas.getNearestTextElement(direction, element);
269                     }
270                     parent.wlxmlNode.detach();
271                 } else {
272                     goto = canvas.getNearestTextElement(direction, element);
273                     element.wlxmlNode.detach();
274                 }
275                 canvas.setCurrentElement(goto, {caretTo: caretTo});
276             }
277             else if(cursorAtOperationEdge) {
278                 if(direction === 'below') {
279                     element = canvas.getNearestTextElement(direction, element);
280                 }
281                 if(element) {
282                     goto = element.wlxmlNode.mergeContentUp();
283                     if(goto) {
284                         canvas.setCurrentElement(goto.node, {caretTo: goto.offset});
285                     }
286                 }
287                 event.preventDefault();
288             }
289         }, {
290             metadata: {
291                 description: gettext('Remove text')
292             }
293         });
294     }
295 });
296
297 return {
298     handleKey: handleKey
299 };
300
301 });