editor: core plugin - edumed - first approach to all three choice exercises
[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
167     reloadRoot: function() {
168         if(this.rootElement) {
169             this.rootElement.detach();
170         }
171         this.rootElement = this.createElement(this.wlxmlDocument.root);
172         this.rootWrapper.append(this.rootElement.dom);
173     },
174
175     triggerKeyEvent: function(keyEvent, selection) {
176         selection = selection || this.getSelection();
177         if(selection && (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()) {
178             keyboard.handleKeyEvent(keyEvent, selection);
179         }
180     },
181
182     createAction: function(fqName, config) {
183         return this.sandbox.createAction(fqName, config);
184     },
185
186     setupEventHandling: function() {
187         var canvas = this;
188
189         /* globals document */
190         $(document.body).on('keydown', function(e) {
191             canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
192         });
193
194         this.rootWrapper.on('mouseup', function() {
195             canvas.triggerSelectionChanged();
196         });
197
198         var mouseDown;
199         this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
200             mouseDown = e.target;
201             canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
202         });
203
204         this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
205             var position, element;
206             e.stopPropagation();
207             if(e.originalEvent.detail === 3) {
208                 e.preventDefault();
209                 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
210             } else {
211                 if(mouseDown === e.target) {
212                     element = canvas.getDocumentElement(e.target);
213                     if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
214                         if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
215                             canvas.setCurrentElement(element);
216                             return;
217                         }
218                     }
219                     if(window.getSelection().isCollapsed) {
220                         position = utils.caretPositionFromPoint(e.clientX, e.clientY);
221                         canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
222                     }
223                 }
224             }
225         });
226
227         this.rootWrapper.on('contextmenu', function(e) {
228             var el = canvas.getDocumentElement(e.target);
229             
230             if(!el) {
231                 return;
232             }
233
234             e.preventDefault();
235             this.showContextMenu(el, {x: e.clientX, y: e.clientY});
236         }.bind(this));
237
238         this.rootWrapper.on('paste', function(e) {
239             e.preventDefault();
240
241             var clipboardData = e.originalEvent.clipboardData;
242             if(!clipboardData || !clipboardData.getData) {
243                 return; // TODO: alert
244             }
245
246             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
247                 cursor = canvas.getCursor(),
248                 element = cursor.getPosition().element,
249                 lhs, rhs;
250             
251             if(element && cursor.isWithinElement()) {
252                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
253                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
254                 element.setText(lhs+text+rhs);
255                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
256             } else {
257                 /* jshint noempty:false */
258                 // TODO: alert
259             }
260         });
261
262         /* globals MutationObserver */
263         var observer = new MutationObserver(function(mutations) {
264             mutations.forEach(function(mutation) {
265                 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
266                     observer.disconnect();
267                     if(mutation.target.data === '') {
268                         mutation.target.data = utils.unicode.ZWS;
269                     }
270                     else if(mutation.oldValue === utils.unicode.ZWS) {
271                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
272                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
273                     }
274                     observer.observe(canvas.dom[0], config);
275
276                     var textElement = canvas.getDocumentElement(mutation.target),
277                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
278
279                     //textElement.data('wlxmlNode').setText(toSet);
280                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
281                     if(textElement.wlxmlNode.getText() !== toSet) {
282                         canvas.textHandler.handle(textElement.wlxmlNode, toSet);
283                     }
284                 }
285             });
286         });
287         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
288         observer.observe(this.rootWrapper[0], config);
289
290
291         var hoverHandler = function(e) {
292             var el = canvas.getDocumentElement(e.currentTarget),
293                 expose = {
294                     mouseover: true,
295                     mouseout: false
296                 };
297             if(!el) {
298                 return;
299             }
300             e.stopPropagation();
301             if(el instanceof documentElement.DocumentTextElement) {
302                 el = el.parent();
303             }
304             el.updateState({exposed:expose[e.type]});
305         };
306
307         this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
308         this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
309
310         this.eventBus.on('elementToggled', function(toggle, element) {
311             if(!toggle) {
312                 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
313             }
314         });
315     },
316
317     view: function() {
318         return this.dom;
319     },
320
321     doc: function() {
322         return this.rootElement;
323     },
324
325     toggleElementHighlight: function(node, toggle) {
326         var element = utils.getElementForNode(node);
327         element.updateState({exposed: toggle});
328     },
329
330     getCursor: function() {
331         return new Cursor(this);
332     },
333
334     
335     getCurrentNodeElement: function() {
336         return this.currentNodeElement;
337     },
338
339     getCurrentTextElement: function() {
340         var htmlElement = this.rootWrapper.find('.current-text-element')[0];
341         if(htmlElement) {
342             return this.getDocumentElement(htmlElement);
343         }
344     },
345
346     getPreviousTextElement: function(relativeToElement, includeInvisible) {
347         return this.getNearestTextElement('above', relativeToElement, includeInvisible);
348     },
349
350     getNextTextElement: function(relativeToElement, includeInvisible) {
351         return this.getNearestTextElement('below', relativeToElement, includeInvisible);
352     },
353
354     getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
355         includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
356         var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
357         return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
358     },
359
360     contains: function(element) {
361         return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
362     },
363
364     triggerSelectionChanged: function() {
365         var s = this.getSelection(),
366             f;
367         if(!s) {
368             return;
369         }
370         this.trigger('selectionChanged', s);
371         f = s.toDocumentFragment();
372
373         if(f && f instanceof f.RangeFragment) {
374             if(this.currentNodeElement) {
375                 this.currentNodeElement.updateState({active: false});
376                 this.currentNodeElement = null;
377             }
378         }
379     },
380
381     getSelection: function() {
382         return selection.fromNativeSelection(this);
383     },
384
385     select: function(fragment) {
386         if(fragment instanceof this.wlxmlDocument.RangeFragment) {
387             this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
388         } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
389             var params = {
390                 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
391             };
392             this.setCurrentElement(fragment.node, params);
393         } else {
394             logger.debug('Fragment not supported');
395         }
396     },
397
398     setSelection: function(selection) {
399         this.select(this, selection.toDocumentFragment());
400     },
401
402     createSelection: function(params) {
403         return selection.fromParams(this, params);
404     },
405     setCurrentElement: function(element, params) {
406         if(!element) {
407             logger.debug('Invalid element passed to setCurrentElement: ' + element);
408             return;
409         }
410
411         if(!(element instanceof documentElement.DocumentElement)) {
412             element = utils.getElementForNode(element);
413         }
414
415         if(!element || !this.contains(element)) {
416             logger.warning('Cannot set current element: element doesn\'t exist on canvas');
417             return;
418         }
419
420         params = _.extend({caretTo: 'end'}, params);
421         var findFirstDirectTextChild = function(e, nodeToLand) {
422             var byBrowser = this.getCursor().getPosition().element;
423             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
424                 return byBrowser;
425             }
426             return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
427         }.bind(this);
428         var _markAsCurrent = function(element) {
429             if(element instanceof documentElement.DocumentTextElement) {
430                 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
431                 element.dom.addClass('current-text-element');
432             } else {
433                 if(this.currentNodeElement) {
434                     this.currentNodeElement.updateState({active: false});
435                 }
436                 element.updateState({active: true});
437                 this.currentNodeElement = element;
438             }
439         }.bind(this);
440
441
442         var isTextElement = element instanceof documentElement.DocumentTextElement,
443             nodeElementToLand = isTextElement ? element.parent() : element,
444             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
445             currentTextElement = this.getCurrentTextElement(),
446             currentNodeElement = this.getCurrentNodeElement();
447
448         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
449             this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
450         }
451
452         if(textElementToLand) {
453             _markAsCurrent(textElementToLand);
454             if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
455                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
456             }
457         } else {
458             document.getSelection().removeAllRanges();
459         }
460
461         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
462             _markAsCurrent(nodeElementToLand);
463         }
464         this.triggerSelectionChanged();
465     },
466
467     _moveCaretToTextElement: function(element, where) {
468         var range = document.createRange(),
469             node = element.dom.contents()[0];
470
471         if(typeof where !== 'number') {
472             range.selectNodeContents(node);
473         } else {
474             range.setStart(node, Math.min(node.data.length, where));
475         }
476         
477         if(where !== 'whole') {
478             var collapseArg = true;
479             if(where === 'end') {
480                 collapseArg = false;
481             }
482             range.collapse(collapseArg);
483         }
484         var selection = document.getSelection();
485
486         $(node).parent().attr('contenteditable', true);
487         selection.removeAllRanges();
488         selection.addRange(range);
489         $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
490     },
491
492     setCursorPosition: function(position) {
493         if(position.element) {
494             this._moveCaretToTextElement(position.element, position.offset);
495         }
496     },
497     showContextMenu: function(element, coors) {
498         var menu = new Menu();
499
500         while(element) {
501             (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
502             element = element.parent();
503         }
504         if(menu.actions.length) {
505             menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
506             this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
507         }
508     }
509 });
510
511
512 var Cursor = function(canvas) {
513     this.canvas = canvas;
514     this.selection = window.getSelection();
515 };
516
517 $.extend(Cursor.prototype, {
518     sameAs: function(other) {
519         var same = true;
520         if(!other) {
521             return false;
522         }
523
524         ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
525             same = same && this.selection[prop] === other.selection[prop];
526             if(!same) {
527                 return true; // break
528             }
529         }.bind(this));
530
531         return same;
532     },
533     isSelecting: function() {
534         var selection = window.getSelection();
535         return !selection.isCollapsed;
536     },
537     isSelectingWithinElement: function() {
538         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
539     },
540     isWithinElement: function() {
541         return !this.isSelecting() || this.isSelectingWithinElement();
542     },
543     isSelectingSiblings: function() {
544         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
545     },
546     getPosition: function() {
547         return this.getSelectionAnchor();
548     },
549     getSelectionStart: function() {
550         return this.getSelectionBoundry('start');
551     },
552     getSelectionEnd: function() {
553         return this.getSelectionBoundry('end');
554     },
555     getSelectionAnchor: function() {
556         return this.getSelectionBoundry('anchor');
557     },
558     getSelectionFocus: function() {
559         return this.getSelectionBoundry('focus');
560     },
561     getSelectionBoundry: function(which) {
562         /* globals window */
563         var selection = window.getSelection(),
564             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
565             focusElement = this.canvas.getDocumentElement(selection.focusNode);
566         
567         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
568             return {};
569         }
570
571         if(which === 'anchor') {
572             return {
573                 element: anchorElement,
574                 offset: selection.anchorOffset,
575                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
576                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
577             };
578         }
579         if(which === 'focus') {
580             return {
581                 element: focusElement,
582                 offset: selection.focusOffset,
583                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
584                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
585             };
586         }
587         
588         var getPlaceData = function(anchorFirst) {
589             var element, offset;
590             if(anchorFirst) {
591                 if(which === 'start') {
592                     element = anchorElement;
593                     offset = selection.anchorOffset;
594                 }
595                 else if(which === 'end') {
596                     element = focusElement;
597                     offset = selection.focusOffset;
598                 }
599             } else {
600                 if(which === 'start') {
601                     element = focusElement;
602                     offset = selection.focusOffset;
603                 }
604                 else if(which === 'end') {
605                     element = anchorElement;
606                     offset = selection.anchorOffset;
607                 }
608             }
609             return {element: element, offset: offset};
610         };
611
612         var anchorFirst, placeData, parent;
613
614         if(anchorElement.parent().sameNode(focusElement.parent())) {
615             parent = anchorElement.parent();
616             if(selection.anchorNode === selection.focusNode) {
617                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
618             } else {
619                 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
620             }
621             placeData = getPlaceData(anchorFirst);
622         } else {
623             /*jshint bitwise: false*/
624             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
625             placeData = getPlaceData(anchorFirst);
626         }
627
628         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
629         return {
630             element: placeData.element,
631             offset: placeData.offset,
632             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
633             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
634         };
635     }
636 });
637
638 return {
639     fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
640         return new Canvas(wlxmlDocument, elements, metadata, sandbox);
641     }
642 };
643
644 });