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