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