empty text nodes after spans
[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 'views/menu/menu',
7 'modules/documentCanvas/canvas/documentElement',
8 'modules/documentCanvas/canvas/keyboard',
9 'modules/documentCanvas/canvas/utils',
10 'modules/documentCanvas/canvas/wlxmlListener',
11 'modules/documentCanvas/canvas/elementsRegister',
12 'modules/documentCanvas/canvas/genericElement',
13 'modules/documentCanvas/canvas/nullElement',
14 'modules/documentCanvas/canvas/gutter',
15 'modules/documentCanvas/canvas/selection',
16 'modules/documentCanvas/canvas/keyEvent',
17 'libs/text!./canvas.html'
18 ], function($, _, Backbone, logging, Menu, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement, gutter, selection, keyEvent, canvasTemplate) {
19
20 'use strict';
21 /* global document:false, window:false, Node:false, gettext */
22
23 var logger = logging.getLogger('canvas');
24
25 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
26 $.extend(TextHandler.prototype, {
27     handle: function(node, text) {
28         this.setText(text, node);
29         // return;
30         // if(!this.node) {
31         //     this.node = node;
32         // }
33         // if(this.node.sameNode(node)) {
34         //     this._ping(text);
35         // } else {
36         //     this.flush();
37         //     this.node = node;
38         //     this._ping(text);
39         // }
40     },
41     _ping: _.throttle(function(text) {
42         this.buffer = text;
43         this.flush();
44     }, 1000),
45     flush: function() {
46         if(this.buffer !== null) {
47             this.setText(this.buffer, this.node);
48             this.buffer = null;
49         }
50     },
51     setText: function(text, node) {
52         //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
53         node.document.transaction(function() {
54             node.setText(text);
55         }, {
56             metadata:{
57                 description: gettext('Changing text')
58             }
59         });
60
61     }
62
63 });
64
65
66 var Canvas = function(wlxmlDocument, elements, metadata, sandbox) {
67     this.metadata = metadata || {};
68     this.sandbox = sandbox;
69     this.elementsRegister = this.createElementsRegister();
70
71     elements = [
72         {tag: 'section', klass: null, prototype: genericElement},
73         {tag: 'div', klass: null, prototype: genericElement},
74         {tag: 'header', klass: null, prototype: genericElement},
75         {tag: 'span', klass: null, prototype: genericElement},
76         {tag: 'aside', klass: null, prototype: genericElement}
77     ].concat(elements || []);
78
79     (elements).forEach(function(elementDesc) {
80         this.elementsRegister.register(elementDesc);
81     }.bind(this));
82     this.eventBus = _.extend({}, Backbone.Events);
83     
84     this.dom = $(canvasTemplate);
85     this.rootWrapper = this.dom.find('.root-wrapper');
86     
87
88     this.gutter = gutter.create();
89     this.gutterView = new gutter.GutterView(this.gutter);
90     this.dom.find('.view-row').append(this.gutterView.dom);
91     
92     this.wlxmlListener = wlxmlListener.create(this);
93     this.loadWlxmlDocument(wlxmlDocument);
94     this.setupEventHandling();
95     this.textHandler = new TextHandler(this);
96 };
97
98 $.extend(Canvas.prototype, Backbone.Events, {
99
100     createElementType: function(elementPrototype) {
101         /* TODO: reconcile this with ElementsRegister behavior */
102         var Constructor = function() {
103             documentElement.DocumentNodeElement.apply(this, Array.prototype.slice.call(arguments, 0));
104         };
105         Constructor.prototype = elementPrototype;
106         return Constructor;
107     },
108
109     getElementOffset: function(element) {
110         return element.dom.offset().top - this.dom.offset().top;
111     },
112
113     loadWlxmlDocument: function(wlxmlDocument) {
114         if(!wlxmlDocument) {
115             return false;
116         }
117
118         this.wlxmlListener.listenTo(wlxmlDocument);
119         this.wlxmlDocument = wlxmlDocument;
120         this.reloadRoot();
121     },
122
123     createElement: function(wlxmlNode, register, useRoot) {
124         var Factory;
125         register = register || this.elementsRegister;
126         if(wlxmlNode.nodeType === Node.TEXT_NODE) {
127             Factory = documentElement.DocumentTextElement;
128         } else {
129             Factory = register.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
130         }
131         if(!Factory && useRoot) {
132             Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
133             if(!Factory) {
134                 Factory = documentElement.DocumentNodeElement;
135             }
136         }
137
138         if(Factory) {
139             return new Factory(wlxmlNode, this);
140         }
141     },
142
143     createElementsRegister: function() {
144         return new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
145     },
146
147     getDocumentElement: function(htmlElement) {
148         /* globals HTMLElement, Text */
149         if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
150             return null;
151         }
152         var $element = $(htmlElement);
153         if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
154             return $element.data('canvas-element');
155         }
156
157         if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
158             $element = $element.parent();
159         }
160
161         if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
162             //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
163             return $element.data('canvas-element');
164         }
165     },
166
167     reloadRoot: function() {
168         if(this.rootElement) {
169             this.rootElement.detach();
170         }
171         this.rootElement = this.createElement(this.wlxmlDocument.root);
172         this.rootWrapper.append(this.rootElement.dom);
173     },
174
175     triggerKeyEvent: function(keyEvent, selection) {
176         selection = selection || this.getSelection();
177         if(selection && (
178             (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()
179             || selection.type == 'nodeSelection')) {
180             keyboard.handleKeyEvent(keyEvent, selection);
181         }
182     },
183
184     createAction: function(fqName, config) {
185         return this.sandbox.createAction(fqName, config);
186     },
187
188     setupEventHandling: function() {
189         var canvas = this;
190
191         /* globals document */
192         $(document.body).on('keydown', function(e) {
193             canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
194         });
195
196         this.rootWrapper.on('mouseup', function() {
197             canvas.triggerSelectionChanged();
198         });
199
200         var mouseDown;
201         this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
202             mouseDown = e.target;
203             canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
204         });
205
206         this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
207             var position, element;
208             e.stopPropagation();
209             if(e.originalEvent.detail === 3) {
210                 e.preventDefault();
211                 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
212             } else {
213                 if(mouseDown === e.target) {
214                     element = canvas.getDocumentElement(e.target);
215                     if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
216                         if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
217                             canvas.setCurrentElement(element);
218                             return;
219                         }
220                     }
221                     if(window.getSelection().isCollapsed) {
222                         position = utils.caretPositionFromPoint(e.clientX, e.clientY);
223                         canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
224                     }
225                 }
226             }
227         });
228
229         this.rootWrapper.on('contextmenu', function(e) {
230             var el = canvas.getDocumentElement(e.target);
231             
232             if(!el) {
233                 return;
234             }
235
236             e.preventDefault();
237             this.showContextMenu(el, {x: e.clientX, y: e.clientY});
238         }.bind(this));
239
240         this.rootWrapper.on('paste', function(e) {
241             e.preventDefault();
242
243             var clipboardData = e.originalEvent.clipboardData;
244             if(!clipboardData || !clipboardData.getData) {
245                 return; // TODO: alert
246             }
247
248             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
249                 cursor = canvas.getCursor(),
250                 element = cursor.getPosition().element,
251                 lhs, rhs;
252             
253             if(element && cursor.isWithinElement()) {
254                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
255                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
256                 element.setText(lhs+text+rhs);
257                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
258             } else {
259                 /* jshint noempty:false */
260                 // TODO: alert
261             }
262         });
263
264         /* globals MutationObserver */
265         var observer = new MutationObserver(function(mutations) {
266             mutations.forEach(function(mutation) {
267                 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
268                     observer.disconnect();
269                     if(mutation.target.data === '') {
270                         mutation.target.data = utils.unicode.ZWS;
271                     }
272                     if(mutation.target.data === mutation.oldValue) {
273                         return; // shouldn't happen, but better be safe
274                     }
275                     if(mutation.oldValue === utils.unicode.ZWS) {
276                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
277                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
278                     }
279                     observer.observe(canvas.dom[0], config);
280
281                     var textElement = canvas.getDocumentElement(mutation.target),
282                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
283
284                     //textElement.data('wlxmlNode').setText(toSet);
285                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
286                     if(textElement.wlxmlNode.getText() !== toSet) {
287                         canvas.textHandler.handle(textElement.wlxmlNode, toSet);
288                     }
289                 }
290             });
291         });
292         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
293         observer.observe(this.rootWrapper[0], config);
294
295
296         var hoverHandler = function(e) {
297             var el = canvas.getDocumentElement(e.currentTarget),
298                 expose = {
299                     mouseover: true,
300                     mouseout: false
301                 };
302             if(!el) {
303                 return;
304             }
305             e.stopPropagation();
306             if(el instanceof documentElement.DocumentTextElement) {
307                 el = el.parent();
308             }
309             el.updateState({exposed:expose[e.type]});
310         };
311
312         this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
313         this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
314
315         this.eventBus.on('elementToggled', function(toggle, element) {
316             if(!toggle) {
317                 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
318             }
319         });
320     },
321
322     view: function() {
323         return this.dom;
324     },
325
326     doc: function() {
327         return this.rootElement;
328     },
329
330     toggleElementHighlight: function(node, toggle) {
331         var element = utils.getElementForNode(node);
332         element.updateState({exposed: toggle});
333     },
334
335     getCursor: function() {
336         return new Cursor(this);
337     },
338
339     
340     getCurrentNodeElement: function() {
341         return this.currentNodeElement;
342     },
343
344     getCurrentTextElement: function() {
345         var htmlElement = this.rootWrapper.find('.current-text-element')[0];
346         if(htmlElement) {
347             return this.getDocumentElement(htmlElement);
348         }
349     },
350
351     getPreviousTextElement: function(relativeToElement, includeInvisible) {
352         return this.getNearestTextElement('above', relativeToElement, includeInvisible);
353     },
354
355     getNextTextElement: function(relativeToElement, includeInvisible) {
356         return this.getNearestTextElement('below', relativeToElement, includeInvisible);
357     },
358
359     getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
360         includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
361         var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
362         return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
363     },
364
365     contains: function(element) {
366         return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
367     },
368
369     triggerSelectionChanged: function() {
370         var s = this.getSelection(),
371             f;
372         if(!s) {
373             return;
374         }
375         this.trigger('selectionChanged', s);
376         f = s.toDocumentFragment();
377
378         if(f && f instanceof f.RangeFragment) {
379             if(this.currentNodeElement) {
380                 this.currentNodeElement.updateState({active: false});
381                 this.currentNodeElement = null;
382             }
383         }
384     },
385
386     getSelection: function() {
387         return selection.fromNativeSelection(this);
388     },
389
390     select: function(fragment) {
391         if(fragment instanceof this.wlxmlDocument.RangeFragment) {
392             this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
393         } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
394             var params = {
395                 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
396             };
397             this.setCurrentElement(fragment.node, params);
398         } else {
399             logger.debug('Fragment not supported');
400         }
401     },
402
403     setSelection: function(selection) {
404         this.select(this, selection.toDocumentFragment());
405     },
406
407     createSelection: function(params) {
408         return selection.fromParams(this, params);
409     },
410     setCurrentElement: function(element, params) {
411         if(!element) {
412             logger.debug('Invalid element passed to setCurrentElement: ' + element);
413             return;
414         }
415
416         if(!(element instanceof documentElement.DocumentElement)) {
417             element = utils.getElementForNode(element);
418         }
419
420         if(!element || !this.contains(element)) {
421             logger.warning('Cannot set current element: element doesn\'t exist on canvas');
422             return;
423         }
424
425         params = _.extend({caretTo: 'end'}, params);
426         var findFirstDirectTextChild = function(e, nodeToLand) {
427             var byBrowser = this.getCursor().getPosition().element;
428             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
429                 return byBrowser;
430             }
431             return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
432         }.bind(this);
433         var _markAsCurrent = function(element) {
434             if(element instanceof documentElement.DocumentTextElement) {
435                 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
436                 element.dom.addClass('current-text-element');
437             } else {
438                 if(this.currentNodeElement) {
439                     this.currentNodeElement.updateState({active: false});
440                 }
441                 element.updateState({active: true});
442                 this.currentNodeElement = element;
443             }
444         }.bind(this);
445
446
447         var isTextElement = element instanceof documentElement.DocumentTextElement,
448             nodeElementToLand = isTextElement ? element.parent() : element,
449             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
450             currentTextElement = this.getCurrentTextElement(),
451             currentNodeElement = this.getCurrentNodeElement();
452
453         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
454             this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
455         }
456
457         if(textElementToLand) {
458             _markAsCurrent(textElementToLand);
459             if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
460                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
461             }
462         } else {
463             document.getSelection().removeAllRanges();
464         }
465
466         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
467             _markAsCurrent(nodeElementToLand);
468         }
469         this.triggerSelectionChanged();
470     },
471
472     _moveCaretToTextElement: function(element, where) {
473         var range = document.createRange(),
474             node = element.dom.contents()[0];
475
476         if(typeof where !== 'number') {
477             range.selectNodeContents(node);
478         } else {
479             range.setStart(node, Math.min(node.data.length, where));
480         }
481         
482         if(where !== 'whole') {
483             var collapseArg = true;
484             if(where === 'end') {
485                 collapseArg = false;
486             }
487             range.collapse(collapseArg);
488         }
489         var selection = document.getSelection();
490
491         $(node).parent().attr('contenteditable', true);
492         selection.removeAllRanges();
493         selection.addRange(range);
494         $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
495     },
496
497     setCursorPosition: function(position) {
498         if(position.element) {
499             this._moveCaretToTextElement(position.element, position.offset);
500         }
501     },
502     showContextMenu: function(element, coors) {
503         var menu = new Menu();
504
505         while(element) {
506             (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
507             element = element.parent();
508         }
509         if(menu.actions.length) {
510             menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
511             this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
512         }
513     }
514 });
515
516
517 var Cursor = function(canvas) {
518     this.canvas = canvas;
519     this.selection = window.getSelection();
520 };
521
522 $.extend(Cursor.prototype, {
523     sameAs: function(other) {
524         var same = true;
525         if(!other) {
526             return false;
527         }
528
529         ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
530             same = same && this.selection[prop] === other.selection[prop];
531             if(!same) {
532                 return true; // break
533             }
534         }.bind(this));
535
536         return same;
537     },
538     isSelecting: function() {
539         var selection = window.getSelection();
540         return !selection.isCollapsed;
541     },
542     isSelectingWithinElement: function() {
543         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
544     },
545     isWithinElement: function() {
546         return !this.isSelecting() || this.isSelectingWithinElement();
547     },
548     isSelectingSiblings: function() {
549         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
550     },
551     getPosition: function() {
552         return this.getSelectionAnchor();
553     },
554     getSelectionStart: function() {
555         return this.getSelectionBoundary('start');
556     },
557     getSelectionEnd: function() {
558         return this.getSelectionBoundary('end');
559     },
560     getSelectionAnchor: function() {
561         return this.getSelectionBoundary('anchor');
562     },
563     getSelectionFocus: function() {
564         return this.getSelectionBoundary('focus');
565     },
566     getSelectionBoundary: function(which) {
567         /* globals window */
568         var selection = window.getSelection(),
569             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
570             focusElement = this.canvas.getDocumentElement(selection.focusNode);
571         
572         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
573             return {};
574         }
575
576         if(which === 'anchor') {
577             return {
578                 element: anchorElement,
579                 offset: selection.anchorOffset,
580                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
581                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
582             };
583         }
584         if(which === 'focus') {
585             return {
586                 element: focusElement,
587                 offset: selection.focusOffset,
588                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
589                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
590             };
591         }
592         
593         var getPlaceData = function(anchorFirst) {
594             var element, offset;
595             if(anchorFirst) {
596                 if(which === 'start') {
597                     element = anchorElement;
598                     offset = selection.anchorOffset;
599                 }
600                 else if(which === 'end') {
601                     element = focusElement;
602                     offset = selection.focusOffset;
603                 }
604             } else {
605                 if(which === 'start') {
606                     element = focusElement;
607                     offset = selection.focusOffset;
608                 }
609                 else if(which === 'end') {
610                     element = anchorElement;
611                     offset = selection.anchorOffset;
612                 }
613             }
614             return {element: element, offset: offset};
615         };
616
617         var anchorFirst, placeData, parent;
618
619         if(anchorElement.parent().sameNode(focusElement.parent())) {
620             parent = anchorElement.parent();
621             if(selection.anchorNode === selection.focusNode) {
622                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
623             } else {
624                 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
625             }
626             placeData = getPlaceData(anchorFirst);
627         } else {
628             /*jshint bitwise: false*/
629             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
630             placeData = getPlaceData(anchorFirst);
631         }
632
633         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
634         return {
635             element: placeData.element,
636             offset: placeData.offset,
637             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
638             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
639         };
640     }
641 });
642
643 return {
644     fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
645         return new Canvas(wlxmlDocument, elements, metadata, sandbox);
646     }
647 };
648
649 });