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