editor: fix selecting text spanning multiple nodes in Chrome
[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         var mouseDown;
93         this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
94             mouseDown = e.target;
95         });
96
97         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
98             e.stopPropagation();
99             if(e.originalEvent.detail === 3) {
100                 e.preventDefault();
101                 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
102             } else {
103                 if(mouseDown === e.target) {
104                     canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
105                 }
106             }
107         });
108
109         this.wrapper.on('paste', function(e) {
110             e.preventDefault();
111
112             var clipboardData = e.originalEvent.clipboardData;
113             if(!clipboardData || !clipboardData.getData) {
114                 return; // TODO: alert
115             }
116
117             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
118                 cursor = canvas.getCursor(),
119                 element = cursor.getPosition().element,
120                 lhs, rhs;
121             
122             if(element && cursor.isWithinElement()) {
123                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
124                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
125                 element.setText(lhs+text+rhs);
126                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
127             } else {
128                 /* jshint noempty:false */
129                 // TODO: alert
130             }
131         });
132
133         /* globals MutationObserver */
134         var observer = new MutationObserver(function(mutations) {
135             mutations.forEach(function(mutation) {
136                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
137                     observer.disconnect();
138                     if(mutation.target.data === '') {
139                         mutation.target.data = utils.unicode.ZWS;
140                     }
141                     else if(mutation.oldValue === utils.unicode.ZWS) {
142                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
143                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
144                     }
145                     observer.observe(canvas.wrapper[0], config);
146                     canvas.publisher('contentChanged');
147
148                     var textElement = canvas.getDocumentElement(mutation.target),
149                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
150
151                     //textElement.data('wlxmlNode').setText(toSet);
152                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
153                     if(textElement.data('wlxmlNode').getText() !== toSet) {
154                         canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
155                     }
156                 }
157             });
158         });
159         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
160         observer.observe(this.wrapper[0], config);
161
162
163         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
164             var el = canvas.getDocumentElement(e.currentTarget);
165             if(!el) {
166                 return;
167             }
168             e.stopPropagation();
169             if(el instanceof documentElement.DocumentTextElement) {
170                 el = el.parent();
171             }
172             el.toggleLabel(true);
173         });
174         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
175             var el = canvas.getDocumentElement(e.currentTarget);
176             if(!el) {
177                 return;
178             }
179             e.stopPropagation();
180             if(el instanceof documentElement.DocumentTextElement) {
181                 el = el.parent();
182             }
183             el.toggleLabel(false);
184         });
185
186         this.eventBus.on('elementToggled', function(toggle, element) {
187             if(!toggle) {
188                 canvas.setCurrentElement(element.getPreviousTextElement());
189             }
190         });
191     },
192
193     view: function() {
194         return this.wrapper;
195     },
196
197     doc: function() {
198         if(this.d === null) {
199             return null;
200         }
201         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
202     },
203
204     toggleElementHighlight: function(node, toggle) {
205         var element = utils.findCanvasElement(node);
206         element.toggleHighlight(toggle);
207     },
208
209     createNodeElement: function(params) {
210         return documentElement.DocumentNodeElement.create(params, this);
211     },
212
213     getDocumentElement: function(from) {
214         /* globals HTMLElement, Text */
215         if(from instanceof HTMLElement || from instanceof Text) {
216            return documentElement.DocumentElement.fromHTMLElement(from, this);
217         }
218     },
219     getCursor: function() {
220         return new Cursor(this);
221     },
222
223     
224     getCurrentNodeElement: function() {
225         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
226     },
227
228     getCurrentTextElement: function() {
229         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
230     },
231
232
233
234     setCurrentElement: function(element, params) {
235         if(!(element instanceof documentElement.DocumentElement)) {
236             element = utils.findCanvasElement(element);
237         }
238
239         params = _.extend({caretTo: 'end'}, params);
240         var findFirstDirectTextChild = function(e, nodeToLand) {
241             var byBrowser = this.getCursor().getPosition().element;
242             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
243                 return byBrowser;
244             }
245             var children = e.children();
246             for(var i = 0; i < children.length; i++) {
247                 if(children[i] instanceof documentElement.DocumentTextElement) {
248                     return children[i];
249                 }
250             }
251             return null;
252         }.bind(this);
253         var _markAsCurrent = function(element) {
254             if(element instanceof documentElement.DocumentTextElement) {
255                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
256                 element.dom().addClass('current-text-element');
257             } else {
258                 this.wrapper.find('.current-node-element').removeClass('current-node-element');
259                 element._container().addClass('current-node-element');
260                 this.publisher('currentElementChanged', element);
261             }
262         }.bind(this);
263
264
265         var isTextElement = element instanceof documentElement.DocumentTextElement,
266             nodeElementToLand = isTextElement ? element.parent() : element,
267             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
268             currentTextElement = this.getCurrentTextElement(),
269             currentNodeElement = this.getCurrentNodeElement();
270
271         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
272             this.wrapper.find('.current-text-element').removeClass('current-text-element');
273         }
274
275         if(textElementToLand) {
276             _markAsCurrent(textElementToLand);
277             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
278                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
279             }
280             if(!(textElementToLand.sameNode(currentTextElement))) {
281                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
282             }
283         } else {
284             document.getSelection().removeAllRanges();
285         }
286
287         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
288             _markAsCurrent(nodeElementToLand);
289
290             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
291         }
292     },
293
294     _moveCaretToTextElement: function(element, where) {
295         var range = document.createRange(),
296             node = element.dom().contents()[0];
297
298         if(typeof where !== 'number') {
299             range.selectNodeContents(node);
300         } else {
301             range.setStart(node, where);
302         }
303         
304         if(where !== 'whole') {
305             var collapseArg = true;
306             if(where === 'end') {
307                 collapseArg = false;
308             }
309             range.collapse(collapseArg);
310         }
311         var selection = document.getSelection();
312
313         selection.removeAllRanges();
314         selection.addRange(range);
315         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
316     },
317
318     setCursorPosition: function(position) {
319         if(position.element) {
320             this._moveCaretToTextElement(position.element, position.offset);
321         }
322     }
323 });
324
325
326 var Cursor = function(canvas) {
327     this.canvas = canvas;
328 };
329
330 $.extend(Cursor.prototype, {
331     isSelecting: function() {
332         var selection = window.getSelection();
333         return !selection.isCollapsed;
334     },
335     isSelectingWithinElement: function() {
336         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
337     },
338     isWithinElement: function() {
339         return !this.isSelecting() || this.isSelectingWithinElement();
340     },
341     isSelectingSiblings: function() {
342         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
343     },
344     getPosition: function() {
345         return this.getSelectionAnchor();
346     },
347     getSelectionStart: function() {
348         return this.getSelectionBoundry('start');
349     },
350     getSelectionEnd: function() {
351         return this.getSelectionBoundry('end');
352     },
353     getSelectionAnchor: function() {
354         return this.getSelectionBoundry('anchor');
355     },
356     getSelectionFocus: function() {
357         return this.getSelectionBoundry('focus');
358     },
359     getSelectionBoundry: function(which) {
360         /* globals window */
361         var selection = window.getSelection(),
362             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
363             focusElement = this.canvas.getDocumentElement(selection.focusNode);
364         
365         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
366             return {};
367         }
368
369         if(which === 'anchor') {
370             return {
371                 element: anchorElement,
372                 offset: selection.anchorOffset,
373                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
374                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
375             };
376         }
377         if(which === 'focus') {
378             return {
379                 element: focusElement,
380                 offset: selection.focusOffset,
381                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
382                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
383             };
384         }
385         
386         var getPlaceData = function(anchorFirst) {
387             var element, offset;
388             if(anchorFirst) {
389                 if(which === 'start') {
390                     element = anchorElement;
391                     offset = selection.anchorOffset;
392                 }
393                 else if(which === 'end') {
394                     element = focusElement;
395                     offset = selection.focusOffset;
396                 }
397             } else {
398                 if(which === 'start') {
399                     element = focusElement;
400                     offset = selection.focusOffset;
401                 }
402                 else if(which === 'end') {
403                     element = anchorElement;
404                     offset = selection.anchorOffset;
405                 }
406             }
407             return {element: element, offset: offset};
408         };
409
410         var anchorFirst, placeData, parent;
411
412         if(anchorElement.parent().sameNode(focusElement.parent())) {
413             parent = anchorElement.parent();
414             if(selection.anchorNode === selection.focusNode) {
415                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
416             } else {
417                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
418             }
419             placeData = getPlaceData(anchorFirst);
420         } else {
421             /*jshint bitwise: false*/
422             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
423             placeData = getPlaceData(anchorFirst);
424         }
425
426         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
427         return {
428             element: placeData.element,
429             offset: placeData.offset,
430             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
431             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
432         };
433     }
434 });
435
436 return {
437     fromXMLDocument: function(wlxmlDocument, publisher) {
438         return new Canvas(wlxmlDocument, publisher);
439     }
440 };
441
442 });