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