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