646c68a17f66056297bf53deb04561df7aa1ef85
[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 nodes = position.element.data('wlxmlNode').split({offset: position.offset}),
100                 // var nodes = position.element.data('wlxmlNode').transform('split', {offset: position.offset}),
101                 //     newEmpty,
102                 //     goto,
103                 //     gotoOptions;
104
105                 // if(position.offsetAtBeginning)
106                 //     newEmpty = nodes.first;
107                 // else if(position.offsetAtEnd)
108                 //     newEmpty = nodes.second;
109                 
110                 // if(newEmpty) {
111                 //     //goto = newEmpty.append({text: ''});
112                 //     gotoOptions = {};
113                 // } else {
114                 //     goto = nodes.second;
115                 //     gotoOptions = {caretTo: 'start'};
116                 // }
117                 var node = position.element.wlxmlNode,
118                     result, goto, gotoOptions;
119
120                 node.document.transaction(function() {
121                     result = position.element.wlxmlNode.breakContent({offset: position.offset});
122                 }, {
123                     metadata: {
124                         description: gettext('Splitting text')
125                     }
126                 });
127
128                 if(result.emptyText) {
129                     goto = result.emptyText;
130                     gotoOptions = {};
131                 } else {
132                     goto = result.second;
133                     gotoOptions = {caretTo: 'start'};
134                 }
135
136                 canvas.setCurrentElement(utils.getElementForNode(goto), gotoOptions);
137             }
138         }
139     }
140 });
141
142 handlers.push({keys: [KEYS.ARROW_UP, KEYS.ARROW_DOWN, KEYS.ARROW_LEFT, KEYS.ARROW_RIGHT],
143     keydown: function(event, canvas) {
144         var position = canvas.getCursor().getPosition(),
145             element = position.element;
146         if(element && (element instanceof documentElement.DocumentTextElement) && element.isEmpty()) {
147             var direction, caretTo;
148             if(event.which === KEYS.ARROW_LEFT  || event.which === KEYS.ARROW_UP) {
149                 direction = 'above';
150                 caretTo = 'end';
151             } else {
152                 direction = 'below';
153                 caretTo = 'start';
154             }
155             var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom[0]));
156             if(el) {
157                 canvas.setCurrentElement(el, {caretTo: caretTo});
158             }
159         }
160     },
161     keyup: function(event, canvas) {
162         var element = canvas.getCursor().getPosition().element,
163             caretTo = false;
164         if(!element) {
165             // Chrome hack
166
167             var moves = [{direction: 'above', caretTo: 'end'}, {direction: 'below', caretTo: 'start'}];
168             if(event.which === KEYS.ARROW_RIGHT  || event.which === KEYS.ARROW_DOWN) {
169                 moves.reverse();
170             }
171             moves.some(function(move) {
172                 /* globals window */
173                 var targetNode = utils.nearestInDocumentOrder('[document-text-element]:visible', move.direction, window.getSelection().focusNode);
174                 if(targetNode) {
175                     element = canvas.getDocumentElement(targetNode);
176                     caretTo = move.caretTo;
177                     return true; // break
178                 }
179             });
180         }
181         if(element) {
182             canvas.setCurrentElement(element, {caretTo: caretTo});
183         }
184     }
185 });
186
187
188 var selectsWholeTextElement = function(cursor) {
189     if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd) {
190         return true;
191     }
192     return false;
193 };
194
195 handlers.push({key: KEYS.X,
196     keydown: function(event, canvas) {
197         if(event.ctrlKey && selectsWholeTextElement(canvas.getCursor())) {
198             event.preventDefault();
199         }
200     }
201 });
202
203 handlers.push({keys: [KEYS.BACKSPACE, KEYS.DELETE],
204     keydown: function(event, canvas) {
205         var cursor = canvas.getCursor(),
206             position = canvas.getCursor().getPosition(),
207             element = position.element,
208             node = element ? element.wlxmlNode : null,
209             direction = 'above',
210             caretTo = 'end',
211             goto;
212
213         if(!element || !node) {
214             return;
215         }
216             
217         if(event.which === KEYS.DELETE) {
218             direction = 'below';
219             caretTo = 'start';
220         }
221
222         if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
223             event.preventDefault();
224             var start = cursor.getSelectionStart(),
225                 end = cursor.getSelectionEnd();
226
227             if(direction === 'above') {
228                 if(start.offsetAtBeginning) {
229                     goto = canvas.getNearestTextElement('above', start.element);
230                     caretTo = 'end';
231                 } else {
232                     goto = start.element;
233                     caretTo = start.offset;
234                 }
235             } else {
236                 if(end.offsetAtEnd) {
237                     goto = canvas.getNearestTextElement('below', start.element);
238                     caretTo = 'start';
239                 } else {
240                     goto = end.element;
241                     caretTo = 0;
242                 }
243             }
244
245             canvas.wlxmlDocument.deleteText({
246                 from: {
247                     node: start.element.wlxmlNode,
248                     offset: start.offset
249                 },
250                 to: {
251                     node: end.element.wlxmlNode,
252                     offset: end.offset
253                 }
254             });
255             if(goto) {
256                 canvas.setCurrentElement(goto, {caretTo: caretTo});
257             }
258             return;
259         }
260             
261         var cursorAtOperationEdge = position.offsetAtBeginning;
262         if(event.which === KEYS.DELETE) {
263             cursorAtOperationEdge = position.offsetAtEnd;
264         }
265
266         var willDeleteWholeText = function() {
267             return element.getText().length === 1 || selectsWholeTextElement(cursor);
268         };
269
270         canvas.wlxmlDocument.transaction(function() {
271             if(willDeleteWholeText()) {
272                 event.preventDefault();
273                 node.setText('');
274             }
275             else if(element.isEmpty()) {
276                 event.preventDefault();
277                 var parent = element.parent(),
278                     grandParent = parent ? parent.parent() : null;
279                 if(!grandParent && parent.children().length === 1) {
280                     return;
281                 }
282                 if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
283                     if(grandParent && grandParent.children().length === 1) {
284                         goto = grandParent.wlxmlNode.append({text: ''});
285                     } else {
286                         goto = canvas.getNearestTextElement(direction, element);
287                     }
288                     parent.wlxmlNode.detach();
289                 } else {
290                     goto = canvas.getNearestTextElement(direction, element);
291                     element.wlxmlNode.detach();
292                 }
293                 canvas.setCurrentElement(goto, {caretTo: caretTo});
294             }
295             else if(cursorAtOperationEdge) {
296                 if(direction === 'below') {
297                     element = canvas.getNearestTextElement(direction, element);
298                 }
299                 if(element) {
300                     goto = element.wlxmlNode.mergeContentUp();
301                     if(goto) {
302                         canvas.setCurrentElement(goto.node, {caretTo: goto.offset});
303                     }
304                 }
305                 event.preventDefault();
306             }
307         }, {
308             metadata: {
309                 description: gettext('Remove text')
310             }
311         });
312     }
313 });
314
315 return {
316     handleKey: handleKey
317 };
318
319 });