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