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