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