editor: handle undefined action state
[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             added;
49
50         if(Object.keys(cursor.getPosition()).length === 0) {
51             var currentElement = canvas.getCurrentNodeElement();
52             if(currentElement) {
53                 canvas.wlxmlDocument.startTransaction(gettext('Splitting text'));
54                 added = currentElement.wlxmlNode.after({
55                     tagName: currentElement.getWlxmlTag() || 'div',
56                     attrs: {'class': currentElement.getWlxmlClass() || 'p'}
57                 });
58                 added.append({text:''});
59                 canvas.wlxmlDocument.endTransaction();
60                 canvas.setCurrentElement(utils.findCanvasElement(added), {caretTo: 'start'});
61             }
62             return;
63         }
64
65         if(!cursor.isSelecting()) {
66             if(event.ctrlKey) {
67                 if(element instanceof documentElement.DocumentTextElement) {
68                     element = element.parent();
69                 }
70
71                 canvas.wlxmlDocument.startTransaction(gettext('Splitting text'));
72                 added = element.wlxmlNode.after(
73                     {tagName: element.getWlxmlTag() || 'div', attrs: {'class': element.getWlxmlClass() || 'p'}}
74                 );
75                 added.append({text: ''});
76                 canvas.wlxmlDocument.endTransaction();
77                 canvas.setCurrentElement(utils.findCanvasElement(added), {caretTo: 'start'});
78
79             } else {
80
81                 if(!(element.parent().parent())) {
82                     return false; // top level element is unsplittable
83                 }
84
85                 //var nodes = position.element.data('wlxmlNode').split({offset: position.offset}),
86                 // var nodes = position.element.data('wlxmlNode').transform('split', {offset: position.offset}),
87                 //     newEmpty,
88                 //     goto,
89                 //     gotoOptions;
90
91                 // if(position.offsetAtBeginning)
92                 //     newEmpty = nodes.first;
93                 // else if(position.offsetAtEnd)
94                 //     newEmpty = nodes.second;
95                 
96                 // if(newEmpty) {
97                 //     //goto = newEmpty.append({text: ''});
98                 //     gotoOptions = {};
99                 // } else {
100                 //     goto = nodes.second;
101                 //     gotoOptions = {caretTo: 'start'};
102                 // }
103                 var node = position.element.wlxmlNode,
104                     result, goto, gotoOptions;
105
106                 node.document.transaction(function() {
107                     result = position.element.wlxmlNode.breakContent({offset: position.offset});
108                 }, this, gettext('Splitting text'));
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.findCanvasElement(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 = start.element.getNearestTextElement('above');
212                     caretTo = 'end';
213                 } else {
214                     goto = start.element;
215                     caretTo = start.offset;
216                 }
217             } else {
218                 if(end.offsetAtEnd) {
219                     goto = start.element.getNearestTextElement('below');
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 = element.getNearestTextElement(direction);
269                     }
270                     parent.wlxmlNode.detach();
271                 } else {
272                     goto = element.getNearestTextElement(direction);
273                     element.wlxmlNode.detach();
274                 }
275                 canvas.setCurrentElement(goto, {caretTo: caretTo});
276             }
277             else if(cursorAtOperationEdge) {
278                 if(direction === 'below') {
279                     element = element.getNearestTextElement(direction);
280                 }
281                 if(element) {
282                     goto = element.wlxmlNode.mergeContentUp();
283                     canvas.setCurrentElement(goto.node, {caretTo: goto.offset});
284                 }
285                 event.preventDefault();
286             }
287         });
288     }
289 });
290
291 return {
292     handleKey: handleKey
293 };
294
295 });