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