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