0b584432c05b640342cc1cd941df9b5f78c0757e
[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                 added = currentElement.data('wlxmlNode').after({
54                     tag: currentElement.getWlxmlTag() || 'div',
55                     attrs: {'class': currentElement.getWlxmlClass() || 'p'}
56                 });
57                 added.append({text:''});
58                 canvas.setCurrentElement(utils.findCanvasElement(added), {caretTo: 'start'});
59             }
60             return;
61         }
62
63         if(!cursor.isSelecting()) {
64             if(event.ctrlKey) {
65                 if(element instanceof documentElement.DocumentTextElement) {
66                     element = element.parent();
67                 }
68                 added = element.data('wlxmlNode').after(
69                     {tagName: element.getWlxmlTag() || 'div', attrs: {'class': element.getWlxmlClass() || 'p'}}
70                 );
71                 added.append({text: ''});
72                 canvas.setCurrentElement(utils.findCanvasElement(added), {caretTo: 'start'});
73
74             } else {
75
76                 if(!(element.parent().parent())) {
77                     return false; // top level element is unsplittable
78                 }
79
80                 //var nodes = position.element.data('wlxmlNode').split({offset: position.offset}),
81                 // var nodes = position.element.data('wlxmlNode').transform('split', {offset: position.offset}),
82                 //     newEmpty,
83                 //     goto,
84                 //     gotoOptions;
85
86                 // if(position.offsetAtBeginning)
87                 //     newEmpty = nodes.first;
88                 // else if(position.offsetAtEnd)
89                 //     newEmpty = nodes.second;
90                 
91                 // if(newEmpty) {
92                 //     //goto = newEmpty.append({text: ''});
93                 //     gotoOptions = {};
94                 // } else {
95                 //     goto = nodes.second;
96                 //     gotoOptions = {caretTo: 'start'};
97                 // }
98
99                 var result = position.element.data('wlxmlNode').breakContent({offset: position.offset}),
100                     goto, gotoOptions;
101                 if(result.emptyText) {
102                     goto = result.createdEmpty;
103                     gotoOptions = {};
104                 } else {
105                     goto = result.second;
106                     gotoOptions = {caretTo: 'start'};
107                 }
108
109                 canvas.setCurrentElement(utils.findCanvasElement(goto), gotoOptions);
110             }
111         }
112     }
113 });
114
115 handlers.push({keys: [KEYS.ARROW_UP, KEYS.ARROW_DOWN, KEYS.ARROW_LEFT, KEYS.ARROW_RIGHT],
116     keydown: function(event, canvas) {
117         var position = canvas.getCursor().getPosition(),
118             element = position.element;
119         if(element && (element instanceof documentElement.DocumentTextElement) && element.isEmpty()) {
120             var direction, caretTo;
121             if(event.which === KEYS.ARROW_LEFT  || event.which === KEYS.ARROW_UP) {
122                 direction = 'above';
123                 caretTo = 'end';
124             } else {
125                 direction = 'below';
126                 caretTo = 'start';
127             }
128             var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
129             canvas.setCurrentElement(el, {caretTo: caretTo});
130         }
131     },
132     keyup: function(event, canvas) {
133         var element = canvas.getCursor().getPosition().element,
134             caretTo = false;
135         if(!element) {
136             // Chrome hack
137             var direction;
138             if(event.which === KEYS.ARROW_LEFT  || event.which === KEYS.ARROW_UP) {
139                 direction = 'above';
140                 caretTo = 'end';
141             } else {
142                 direction = 'below';
143                 caretTo = 'start';
144             }
145             /* globals window */
146             element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
147         }
148         canvas.setCurrentElement(element, {caretTo: caretTo});
149     }
150 });
151
152
153 var selectsWholeTextElement = function(cursor) {
154     if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd) {
155         return true;
156     }
157     return false;
158 };
159
160 handlers.push({key: KEYS.X,
161     keydown: function(event, canvas) {
162         if(event.ctrlKey && selectsWholeTextElement(canvas.getCursor())) {
163             event.preventDefault();
164         }
165     }
166 });
167
168 handlers.push({keys: [KEYS.BACKSPACE, KEYS.DELETE],
169     keydown: function(event, canvas) {
170         var cursor = canvas.getCursor(),
171             position = canvas.getCursor().getPosition(),
172             element = position.element;
173
174         if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
175             event.preventDefault();
176             return;
177         }
178             
179         var cursorAtOperationEdge = position.offsetAtBeginning;
180         if(event.which === KEYS.DELETE) {
181             cursorAtOperationEdge = position.offsetAtEnd;
182         }
183
184         var willDeleteWholeText = function() {
185             return element.getText().length === 1 || selectsWholeTextElement(cursor);
186         };
187
188         if(willDeleteWholeText()) {
189             event.preventDefault();
190             element.setText('');
191         }
192         else if(element.isEmpty()) {
193
194             var direction = 'above',
195                 caretTo = 'end';
196                 
197             if(event.which === KEYS.DELETE) {
198                 direction = 'below';
199                 caretTo = 'start';
200             }
201
202             event.preventDefault();
203
204             var parent = element.parent(),
205                 grandParent = parent ? parent.parent() : null,
206                 goto;
207             if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
208                 if(grandParent && grandParent.children().length === 1) {
209                     goto = grandParent.data('wlxmlNode').append({text: ''});
210                 } else {
211                     goto = element.getNearestTextElement(direction);
212                 }
213                 parent.data('wlxmlNode').detach();
214             } else {
215                 goto = element.getNearestTextElement(direction);
216                 element.data('wlxmlNode').detach();
217             }
218             canvas.setCurrentElement(goto, {caretTo: caretTo});
219             canvas.publisher('contentChanged');
220         }
221         else if(cursorAtOperationEdge) {
222             // todo
223             event.preventDefault();
224         }
225     }
226 });
227
228 return {
229     handleKey: handleKey
230 };
231
232 });