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