editor: fixing nodeMoved event handling in Canvas
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
4 'libs/backbone',
5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/keyboard',
7 'modules/documentCanvas/canvas/utils',
8 'modules/documentCanvas/canvas/wlxmlListener'
9 ], function($, _, Backbone, documentElement, keyboard, utils, wlxmlListener) {
10     
11 'use strict';
12 /* global document:false, window:false, Node:false */
13
14
15 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
16 $.extend(TextHandler.prototype, {
17     handle: function(node, text) {
18         this.setText(text, node);
19         // return;
20         // if(!this.node) {
21         //     this.node = node;
22         // }
23         // if(this.node.sameNode(node)) {
24         //     this._ping(text);
25         // } else {
26         //     this.flush();
27         //     this.node = node;
28         //     this._ping(text);
29         // }
30     },
31     _ping: _.throttle(function(text) {
32         this.buffer = text;
33         this.flush();
34     }, 1000),
35     flush: function() {
36         if(this.buffer !== null) {
37             this.setText(this.buffer, this.node);
38             this.buffer = null;
39         }
40     },
41     setText: function(text, node) {
42         //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
43         node.setText(text);
44
45     }
46
47 });
48
49
50 var Canvas = function(wlxmlDocument, publisher) {
51     this.eventBus = _.extend({}, Backbone.Events);
52     this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
53     this.wlxmlListener = wlxmlListener.create(this);
54     this.loadWlxmlDocument(wlxmlDocument);
55     this.setupEventHandling();
56     this.publisher = publisher ? publisher : function() {};
57     this.textHandler = new TextHandler(this);
58 };
59
60 $.extend(Canvas.prototype, {
61
62     loadWlxmlDocument: function(wlxmlDocument) {
63         if(!wlxmlDocument) {
64             return false;
65         }
66
67         this.wlxmlListener.listenTo(wlxmlDocument);
68         this.wlxmlDocument = wlxmlDocument;
69         this.reloadRoot();
70     },
71
72     reloadRoot: function() {
73         var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
74         //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
75
76         this.wrapper.empty();
77         this.wrapper.append(canvasDOM);
78         this.d = this.wrapper.children(0);
79     },
80
81     generateCanvasDOM: function(wlxmlNode) {
82         var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
83         return element.dom();
84     },
85
86     setupEventHandling: function() {
87         var canvas = this;
88         this.wrapper.on('keyup keydown keypress', function(e) {
89             keyboard.handleKey(e, this);
90         }.bind(this));
91
92         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
93             e.stopPropagation();
94             canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
95         });
96
97         this.wrapper.on('paste', function(e) {
98             e.preventDefault();
99
100             var clipboardData = e.originalEvent.clipboardData;
101             if(!clipboardData || !clipboardData.getData) {
102                 return; // TODO: alert
103             }
104
105             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
106                 cursor = canvas.getCursor(),
107                 element = cursor.getPosition().element,
108                 lhs, rhs;
109             
110             if(element && cursor.isWithinElement()) {
111                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
112                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
113                 element.setText(lhs+text+rhs);
114                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
115             } else {
116                 /* jshint noempty:false */
117                 // TODO: alert
118             }
119         });
120
121         /* globals MutationObserver */
122         var observer = new MutationObserver(function(mutations) {
123             mutations.forEach(function(mutation) {
124                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
125                     observer.disconnect();
126                     if(mutation.target.data === '') {
127                         mutation.target.data = utils.unicode.ZWS;
128                     }
129                     else if(mutation.oldValue === utils.unicode.ZWS) {
130                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
131                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
132                     }
133                     observer.observe(canvas.wrapper[0], config);
134                     canvas.publisher('contentChanged');
135
136                     var textElement = canvas.getDocumentElement(mutation.target),
137                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
138
139                     //textElement.data('wlxmlNode').setText(toSet);
140                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
141                     if(textElement.data('wlxmlNode').getText() !== toSet) {
142                         canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
143                     }
144                 }
145             });
146         });
147         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
148         observer.observe(this.wrapper[0], config);
149
150
151         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
152             var el = canvas.getDocumentElement(e.currentTarget);
153             if(!el) {
154                 return;
155             }
156             e.stopPropagation();
157             if(el instanceof documentElement.DocumentTextElement) {
158                 el = el.parent();
159             }
160             el.toggleLabel(true);
161         });
162         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
163             var el = canvas.getDocumentElement(e.currentTarget);
164             if(!el) {
165                 return;
166             }
167             e.stopPropagation();
168             if(el instanceof documentElement.DocumentTextElement) {
169                 el = el.parent();
170             }
171             el.toggleLabel(false);
172         });
173
174         this.eventBus.on('elementToggled', function(toggle, element) {
175             if(!toggle) {
176                 canvas.setCurrentElement(element.getPreviousTextElement());
177             }
178         });
179     },
180
181     view: function() {
182         return this.wrapper;
183     },
184
185     doc: function() {
186         if(this.d === null) {
187             return null;
188         }
189         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
190     },
191
192     toggleElementHighlight: function(node, toggle) {
193         var element = utils.findCanvasElement(node);
194         element.toggleHighlight(toggle);
195     },
196
197     createNodeElement: function(params) {
198         return documentElement.DocumentNodeElement.create(params, this);
199     },
200
201     getDocumentElement: function(from) {
202         /* globals HTMLElement, Text */
203         if(from instanceof HTMLElement || from instanceof Text) {
204            return documentElement.DocumentElement.fromHTMLElement(from, this);
205         }
206     },
207     getCursor: function() {
208         return new Cursor(this);
209     },
210
211     
212     getCurrentNodeElement: function() {
213         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
214     },
215
216     getCurrentTextElement: function() {
217         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
218     },
219
220
221
222     setCurrentElement: function(element, params) {
223         if(!(element instanceof documentElement.DocumentElement)) {
224             element = utils.findCanvasElement(element);
225         }
226
227         params = _.extend({caretTo: 'end'}, params);
228         var findFirstDirectTextChild = function(e, nodeToLand) {
229             var byBrowser = this.getCursor().getPosition().element;
230             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
231                 return byBrowser;
232             }
233             var children = e.children();
234             for(var i = 0; i < children.length; i++) {
235                 if(children[i] instanceof documentElement.DocumentTextElement) {
236                     return children[i];
237                 }
238             }
239             return null;
240         }.bind(this);
241         var _markAsCurrent = function(element) {
242             if(element instanceof documentElement.DocumentTextElement) {
243                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
244                 element.dom().addClass('current-text-element');
245             } else {
246                 this.wrapper.find('.current-node-element').removeClass('current-node-element');
247                 element._container().addClass('current-node-element');
248                 this.publisher('currentElementChanged', element);
249             }
250         }.bind(this);
251
252
253         var isTextElement = element instanceof documentElement.DocumentTextElement,
254             nodeElementToLand = isTextElement ? element.parent() : element,
255             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
256             currentTextElement = this.getCurrentTextElement(),
257             currentNodeElement = this.getCurrentNodeElement();
258
259         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
260             this.wrapper.find('.current-text-element').removeClass('current-text-element');
261         }
262
263         if(textElementToLand) {
264             _markAsCurrent(textElementToLand);
265             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
266                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
267             }
268             if(!(textElementToLand.sameNode(currentTextElement))) {
269                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
270             }
271         } else {
272             document.getSelection().removeAllRanges();
273         }
274
275         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
276             _markAsCurrent(nodeElementToLand);
277
278             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
279         }
280     },
281
282     _moveCaretToTextElement: function(element, where) {
283         var range = document.createRange(),
284             node = element.dom().contents()[0];
285
286         if(typeof where !== 'number') {
287             range.selectNodeContents(node);
288         } else {
289             range.setStart(node, where);
290         }
291         
292         var collapseArg = true;
293         if(where === 'end') {
294             collapseArg = false;
295         }
296         range.collapse(collapseArg);
297         
298         var selection = document.getSelection();
299
300         selection.removeAllRanges();
301         selection.addRange(range);
302         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
303     },
304
305     setCursorPosition: function(position) {
306         if(position.element) {
307             this._moveCaretToTextElement(position.element, position.offset);
308         }
309     }
310 });
311
312
313 var Cursor = function(canvas) {
314     this.canvas = canvas;
315 };
316
317 $.extend(Cursor.prototype, {
318     isSelecting: function() {
319         var selection = window.getSelection();
320         return !selection.isCollapsed;
321     },
322     isSelectingWithinElement: function() {
323         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
324     },
325     isWithinElement: function() {
326         return !this.isSelecting() || this.isSelectingWithinElement();
327     },
328     isSelectingSiblings: function() {
329         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
330     },
331     getPosition: function() {
332         return this.getSelectionAnchor();
333     },
334     getSelectionStart: function() {
335         return this.getSelectionBoundry('start');
336     },
337     getSelectionEnd: function() {
338         return this.getSelectionBoundry('end');
339     },
340     getSelectionAnchor: function() {
341         return this.getSelectionBoundry('anchor');
342     },
343     getSelectionFocus: function() {
344         return this.getSelectionBoundry('focus');
345     },
346     getSelectionBoundry: function(which) {
347         /* globals window */
348         var selection = window.getSelection(),
349             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
350             focusElement = this.canvas.getDocumentElement(selection.focusNode);
351         
352         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
353             return {};
354         }
355
356         if(which === 'anchor') {
357             return {
358                 element: anchorElement,
359                 offset: selection.anchorOffset,
360                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
361                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
362             };
363         }
364         if(which === 'focus') {
365             return {
366                 element: focusElement,
367                 offset: selection.focusOffset,
368                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
369                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
370             };
371         }
372         
373         var getPlaceData = function(anchorFirst) {
374             var element, offset;
375             if(anchorFirst) {
376                 if(which === 'start') {
377                     element = anchorElement;
378                     offset = selection.anchorOffset;
379                 }
380                 else if(which === 'end') {
381                     element = focusElement;
382                     offset = selection.focusOffset;
383                 }
384             } else {
385                 if(which === 'start') {
386                     element = focusElement;
387                     offset = selection.focusOffset;
388                 }
389                 else if(which === 'end') {
390                     element = anchorElement;
391                     offset = selection.anchorOffset;
392                 }
393             }
394             return {element: element, offset: offset};
395         };
396
397         var anchorFirst, placeData, parent;
398
399         if(anchorElement.parent().sameNode(focusElement.parent())) {
400             parent = anchorElement.parent();
401             if(selection.anchorNode === selection.focusNode) {
402                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
403             } else {
404                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
405             }
406             placeData = getPlaceData(anchorFirst);
407         } else {
408             /*jshint bitwise: false*/
409             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
410             placeData = getPlaceData(anchorFirst);
411         }
412
413         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
414         return {
415             element: placeData.element,
416             offset: placeData.offset,
417             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
418             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
419         };
420     }
421 });
422
423 return {
424     fromXMLDocument: function(wlxmlDocument, publisher) {
425         return new Canvas(wlxmlDocument, publisher);
426     }
427 };
428
429 });