05c109cd837eaac9c13691f5c4c195f904894284
[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(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 e.getVerticallyFirstTextElement();
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     toggleGrid: function() {
424         this.rootWrapper.toggleClass('grid-on');
425         this.trigger('changed');
426     },
427     isGridToggled: function() {
428         return this.rootWrapper.hasClass('grid-on');
429     }
430 });
431
432
433 var isText = function(node) {
434     return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
435 };
436
437 var Selection = function(canvas) {
438     this.canvas = canvas;
439     var nativeSelection = this.nativeSelection = window.getSelection();
440     Object.defineProperty(this, 'type', {
441         get: function() {
442             if(nativeSelection.focusNode) {
443                 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
444                     return 'caret';
445                 }
446                 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
447                     return 'textSelection';
448                 }
449             }
450             if(canvas.getCurrentNodeElement()) {
451                 return 'node';
452             }
453         }
454     });
455 };
456
457 $.extend(Selection.prototype, {
458     toDocumentFragment: function() {
459         var doc = this.canvas.wlxmlDocument,
460             anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
461             focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
462             anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
463             focusNode = focusElement ? focusElement.wlxmlNode : null;
464         if(this.type === 'caret') {
465             return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
466         }
467         if(this.type === 'textSelection') {
468             if(anchorNode.isSiblingOf(focusNode)) {
469                 return doc.createFragment(doc.TextRangeFragment, {
470                     node1: anchorNode,
471                     offset1: this.nativeSelection.anchorOffset,
472                     node2: focusNode,
473                     offset2: this.nativeSelection.focusOffset,
474                 });
475             }
476             else {
477                 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
478                 return doc.createFragment(doc.RangeFragment, {
479                     node1: siblingParents.node1,
480                     node2: siblingParents.node2
481                 });
482             }
483         }
484         if(this.type === 'node') {
485             return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
486         }
487     },
488     sameAs: function(other) {
489         void(other);
490     }
491 });
492
493 var Cursor = function(canvas) {
494     this.canvas = canvas;
495     this.selection = window.getSelection();
496 };
497
498 $.extend(Cursor.prototype, {
499     sameAs: function(other) {
500         var same = true;
501         if(!other) {
502             return false;
503         }
504
505         ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
506             same = same && this.selection[prop] === other.selection[prop];
507             if(!same) {
508                 return true; // break
509             }
510         }.bind(this));
511
512         return same;
513     },
514     isSelecting: function() {
515         var selection = window.getSelection();
516         return !selection.isCollapsed;
517     },
518     isSelectingWithinElement: function() {
519         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
520     },
521     isWithinElement: function() {
522         return !this.isSelecting() || this.isSelectingWithinElement();
523     },
524     isSelectingSiblings: function() {
525         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
526     },
527     getPosition: function() {
528         return this.getSelectionAnchor();
529     },
530     getSelectionStart: function() {
531         return this.getSelectionBoundry('start');
532     },
533     getSelectionEnd: function() {
534         return this.getSelectionBoundry('end');
535     },
536     getSelectionAnchor: function() {
537         return this.getSelectionBoundry('anchor');
538     },
539     getSelectionFocus: function() {
540         return this.getSelectionBoundry('focus');
541     },
542     getSelectionBoundry: function(which) {
543         /* globals window */
544         var selection = window.getSelection(),
545             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
546             focusElement = this.canvas.getDocumentElement(selection.focusNode);
547         
548         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
549             return {};
550         }
551
552         if(which === 'anchor') {
553             return {
554                 element: anchorElement,
555                 offset: selection.anchorOffset,
556                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
557                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
558             };
559         }
560         if(which === 'focus') {
561             return {
562                 element: focusElement,
563                 offset: selection.focusOffset,
564                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
565                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
566             };
567         }
568         
569         var getPlaceData = function(anchorFirst) {
570             var element, offset;
571             if(anchorFirst) {
572                 if(which === 'start') {
573                     element = anchorElement;
574                     offset = selection.anchorOffset;
575                 }
576                 else if(which === 'end') {
577                     element = focusElement;
578                     offset = selection.focusOffset;
579                 }
580             } else {
581                 if(which === 'start') {
582                     element = focusElement;
583                     offset = selection.focusOffset;
584                 }
585                 else if(which === 'end') {
586                     element = anchorElement;
587                     offset = selection.anchorOffset;
588                 }
589             }
590             return {element: element, offset: offset};
591         };
592
593         var anchorFirst, placeData, parent;
594
595         if(anchorElement.parent().sameNode(focusElement.parent())) {
596             parent = anchorElement.parent();
597             if(selection.anchorNode === selection.focusNode) {
598                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
599             } else {
600                 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
601             }
602             placeData = getPlaceData(anchorFirst);
603         } else {
604             /*jshint bitwise: false*/
605             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
606             placeData = getPlaceData(anchorFirst);
607         }
608
609         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
610         return {
611             element: placeData.element,
612             offset: placeData.offset,
613             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
614             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
615         };
616     }
617 });
618
619 return {
620     fromXMLDocument: function(wlxmlDocument, elements, metadata) {
621         return new Canvas(wlxmlDocument, elements, metadata);
622     }
623 };
624
625 });