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