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