integration fix: sourceEditor module
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
4 'libs/backbone',
5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/keyboard',
7 'modules/documentCanvas/canvas/utils'
8 ], function($, _, Backbone, documentElement, keyboard, utils) {
9     
10 'use strict';
11
12 var Canvas = function(wlxml, publisher) {
13     this.eventBus = _.extend({}, Backbone.Events);
14     this.loadWlxmlDocument(wlxml);
15     this.publisher = publisher ? publisher : function() {};
16 };
17
18 $.extend(Canvas.prototype, {
19
20     loadWlxmlDocument: function(wlxmlDocument) {
21         var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
22
23         this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
24         this.wrapper.append(canvasDOM);
25         this.d = this.wrapper.children(0);
26         this.setupEventHandling();
27     },
28
29     generateCanvasDOM: function(wlxmlNode) {
30         // var element = this.createNodeElement2({
31         //     tag: wlxmlNode.getTagName(),
32         //     klass: wlxmlNode.getClass(), //currentTag.attr('class'),
33         //     meta: wlxmlNode.getMetaAttributes(), //meta,
34         //     others: wlxmlNode.getOtherAttributes(), // ~ //others,
35         //     rawChildren: wlxmlNode.contents(),
36         //     prepopulateOnEmpty: true
37         // }); //->create2
38
39         var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
40
41
42         ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
43             element.data(attr, '');
44         });
45         return element.dom();
46     },
47
48     setupEventHandling: function() {
49         var canvas = this;
50         this.wrapper.on('keyup keydown keypress', function(e) {
51             keyboard.handleKey(e, this);
52         }.bind(this));
53
54         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
55             e.stopPropagation();
56             canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
57         });
58
59         var observer = new MutationObserver(function(mutations) {
60             mutations.forEach(function(mutation) {
61                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
62                     observer.disconnect();
63                     if(mutation.target.data === '')
64                         mutation.target.data = utils.unicode.ZWS;
65                     else if(mutation.oldValue === utils.unicode.ZWS) {
66                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
67                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
68                     }
69                     observer.observe(canvas.d[0], config);
70                     canvas.publisher('contentChanged');
71                 }
72             });
73         });
74         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
75         observer.observe(this.d[0], config);
76
77
78         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
79             var el = canvas.getDocumentElement(e.currentTarget);
80             if(!el)
81                 return;
82             e.stopPropagation();
83             if(el instanceof documentElement.DocumentTextElement)
84                 el = el.parent();
85             el.toggleLabel(true);
86         });
87         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
88             var el = canvas.getDocumentElement(e.currentTarget);
89             if(!el)
90                 return;
91             e.stopPropagation();
92             if(el instanceof documentElement.DocumentTextElement)
93                 el = el.parent();
94             el.toggleLabel(false);
95         });
96
97         this.eventBus.on('elementToggled', function(toggle, element) {
98             if(!toggle) {
99                 canvas.setCurrentElement(element.getPreviousTextElement());
100             }
101         });
102     },
103
104     view: function() {
105         return this.wrapper;
106     },
107
108     doc: function() {
109         if(this.d === null)
110             return null;
111         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
112     },
113
114     createNodeElement: function(params) {
115         return documentElement.DocumentNodeElement.create(params, this);
116     },
117
118     wrapText: function(params) {
119         params = _.extend({textNodeIdx: 0}, params);
120         if(typeof params.textNodeIdx === 'number')
121             params.textNodeIdx = [params.textNodeIdx];
122         
123         var childrenInside = params.inside.children(),
124             idx1 = Math.min.apply(Math, params.textNodeIdx),
125             idx2 = Math.max.apply(Math, params.textNodeIdx),
126             textNode1 = childrenInside[idx1],
127             textNode2 = childrenInside[idx2],
128             sameNode = textNode1.sameNode(textNode2),
129             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
130             prefixInside = textNode1.getText().substr(params.offsetStart),
131             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
132             suffixOutside = textNode2.getText().substr(params.offsetEnd)
133         ;
134         
135         var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
136         textNode1.after(wrapperElement);
137         textNode1.detach();
138         
139         if(prefixOutside.length > 0)
140             wrapperElement.before({text:prefixOutside});
141         if(sameNode) {
142             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
143             wrapperElement.append({text: core});
144         } else {
145             textNode2.detach();
146             if(prefixInside.length > 0)
147                 wrapperElement.append({text: prefixInside});
148             for(var i = idx1 + 1; i < idx2; i++) {
149                 wrapperElement.append(childrenInside[i]);
150             }
151             if(suffixInside.length > 0)
152                 wrapperElement.append({text: suffixInside});
153         }
154         if(suffixOutside.length > 0)
155             wrapperElement.after({text: suffixOutside});
156         return wrapperElement;
157     },
158
159     wrapElements: function(params) {
160         if(!(params.element1.parent().sameNode(params.element2.parent())))
161             return;
162
163         var parent = params.element1.parent(),
164             parentChildren = parent.children(),
165             wrapper = this.createNodeElement({
166                 tag: params._with.tag,
167                 klass: params._with.klass}),
168             idx1 = parent.childIndex(params.element1),
169             idx2 = parent.childIndex(params.element2);
170
171         if(idx1 > idx2) {
172             var tmp = idx1;
173             idx1 = idx2;
174             idx2 = tmp;
175         }
176
177         var insertingMethod, insertingTarget;
178         if(idx1 === 0) {
179             insertingMethod = 'prepend';
180             insertingTarget = parent;
181         } else {
182             insertingMethod = 'after';
183             insertingTarget = parentChildren[idx1-1];
184         }
185
186         for(var i = idx1; i <= idx2; i++) {
187             wrapper.append(parentChildren[i].detach());
188         }
189
190         insertingTarget[insertingMethod](wrapper);
191         return wrapper;
192     },
193
194     getSiblingParents: function(params) {
195         var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
196             parents2 = [params.element2].concat(params.element2.parents()).reverse(),
197             noSiblingParents = null;
198
199         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
200             return noSiblingParents;
201
202         var i;
203         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
204             if(parents1[i].sameNode(parents2[i]))
205                 continue;
206             break;
207         }
208         return {element1: parents1[i], element2: parents2[i]};
209     },
210
211     getDocumentElement: function(from) {
212         if(from instanceof HTMLElement || from instanceof Text) {
213            return documentElement.DocumentElement.fromHTMLElement(from, this);
214         }
215     },
216     getCursor: function() {
217         return new Cursor(this);
218     },
219
220     list: {},
221
222     
223     getCurrentNodeElement: function() {
224         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
225     },
226
227     getCurrentTextElement: function() {
228         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
229     },
230
231
232
233     setCurrentElement: function(element, params) {
234         params = _.extend({caretTo: 'end'}, params);
235         var findFirstDirectTextChild = function(e, nodeToLand) {
236             var byBrowser = this.getCursor().getPosition().element;
237             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
238                 return byBrowser;
239             var children = e.children();
240             for(var i = 0; i < children.length; i++) {
241                 if(children[i] instanceof documentElement.DocumentTextElement)
242                     return children[i];
243             }
244             return null;
245         }.bind(this);
246         var _markAsCurrent = function(element) {
247             if(element instanceof documentElement.DocumentTextElement) {
248                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
249                 element.dom().addClass('current-text-element');
250             } else {
251                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
252                 element._container().addClass('current-node-element');
253                 this.publisher('currentElementChanged', element);
254             }
255         }.bind(this);
256
257
258         var isTextElement = element instanceof documentElement.DocumentTextElement,
259             nodeElementToLand = isTextElement ? element.parent() : element,
260             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
261             currentTextElement = this.getCurrentTextElement(),
262             currentNodeElement = this.getCurrentNodeElement();
263
264         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
265             this.wrapper.find('.current-text-element').removeClass('current-text-element');
266
267         if(textElementToLand) {
268             _markAsCurrent(textElementToLand);
269             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
270                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
271             if(!(textElementToLand.sameNode(currentTextElement)))
272                 this.publisher('currentTextElementSet', textElementToLand);
273         } else {
274             document.getSelection().removeAllRanges();
275         }
276
277         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
278             _markAsCurrent(nodeElementToLand);
279
280             this.publisher('currentNodeElementSet', nodeElementToLand);
281         }
282     },
283
284     _moveCaretToTextElement: function(element, where) {
285         var range = document.createRange(),
286             node = element.dom().contents()[0];
287
288         if(typeof where !== 'number') {
289             range.selectNodeContents(node);
290         } else {
291             range.setStart(node, where);
292         }
293         
294         var collapseArg = true;
295         if(where === 'end')
296             collapseArg = false;
297         range.collapse(collapseArg);
298         
299         var selection = document.getSelection();
300
301         selection.removeAllRanges();
302         selection.addRange(range);
303         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
304     },
305
306     setCursorPosition: function(position) {
307         if(position.element)
308             this._moveCaretToTextElement(position.element, position.offset);
309     },
310
311     toXML: function() {
312         var parent = $('<div>'),
313             parts = this.doc().toXML(0);
314         parent.append(parts);
315         return parent.html();
316     }
317 });
318
319 $.extend(Canvas.prototype.list, {
320     create: function(params) {
321         if(!(params.element1.parent().sameNode(params.element2.parent())))
322             return false;
323             
324         var parent = params.element1.parent(),
325             canvas = params.element1.canvas;
326         
327         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
328             var tmp = params.element1;
329             params.element1 = params.element2;
330             params.element2 = tmp;
331         }
332         
333         var elementsToWrap = [];
334         
335         var place = 'before';
336         parent.children().some(function(element) {
337             var _e = element;
338             if(element.sameNode(params.element1))
339                 place = 'inside';
340             if(place === 'inside') {
341                 if(element instanceof documentElement.DocumentTextElement) {
342                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
343                     if(element.children()[0].sameNode(params.element1))
344                         params.element1 = element;
345                 }
346                 element.setWlxmlClass('item');
347                 elementsToWrap.push(element);
348             }
349             if(_e.sameNode(params.element2))
350                 return true;
351         });
352         
353         var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
354         var toret;
355         if(parent.is('list')) {
356             var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
357             item.exec('toggleBullet', false);
358             toret = listElement.parent();
359         } else {
360             toret = listElement;
361         }  
362         
363         params.element1.before(toret);
364         
365         elementsToWrap.forEach(function(element) {
366             element.detach();
367             listElement.append(element);
368         });
369     },
370     extractItems: function(params) {
371         params = _.extend({merge: true}, params);
372         var list = params.element1.parent();
373         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
374             return false;
375
376         var idx1 = list.childIndex(params.element1),
377             idx2 = list.childIndex(params.element2),
378             precedingItems = [],
379             extractedItems = [],
380             succeedingItems = [],
381             items = list.children(),
382             listIsNested = list.parent().getWlxmlClass() === 'item',
383             canvas = params.element1.canvas,
384             i;
385
386         if(idx1 > idx2) {
387             var tmp = idx1; idx1 = idx2; idx2 = tmp;
388         }
389
390         items.forEach(function(item, idx) {
391             if(idx < idx1)
392                 precedingItems.push(item);
393             else if(idx >= idx1 && idx <= idx2) {
394                 extractedItems.push(item);
395             }
396             else {
397                 succeedingItems.push(item);
398             }
399         });
400
401         var reference = listIsNested ? list.parent() : list;
402         if(succeedingItems.length === 0) {
403             var reference_orig = reference;
404             extractedItems.forEach(function(item) {
405                 reference.after(item);
406                 reference = item;
407                 if(!listIsNested)
408                     item.setWlxmlClass(null);
409             });
410             if(precedingItems.length === 0)
411                 reference_orig.detach();
412         } else if(precedingItems.length === 0) {
413             extractedItems.forEach(function(item) {
414                 reference.before(item);
415                 if(!listIsNested)
416                     item.setWlxmlClass(null);
417             });
418         } else {
419             extractedItems.forEach(function(item) {
420                 reference.after(item);
421                 if(!listIsNested)
422                     item.setWlxmlClass(null);
423                 reference = item;
424             });
425             var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
426                 toAdd = secondList;
427             
428             if(listIsNested) {
429                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
430             }
431             succeedingItems.forEach(function(item) {
432                 secondList.append(item);
433             });
434
435             reference.after(toAdd);
436         }
437         if(!params.merge && listIsNested) {
438             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
439         }
440         return true;
441     },
442     areItemsOfTheSameList: function(params) {
443         var e1 = params.element1,
444             e2 = params.element2;
445         return e1.parent().sameNode(e2.parent())
446             && e1.parent().is('list');
447     }
448 });
449
450
451 var Cursor = function(canvas) {
452     this.canvas = canvas;
453 };
454
455 $.extend(Cursor.prototype, {
456     isSelecting: function() {
457         var selection = window.getSelection();
458         return !selection.isCollapsed;
459     },
460     isSelectingWithinElement: function() {
461         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
462     },
463     isSelectingSiblings: function() {
464         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
465     },
466     getPosition: function() {
467         return this.getSelectionAnchor();
468     },
469     getSelectionStart: function() {
470         return this.getSelectionBoundry('start');
471     },
472     getSelectionEnd: function() {
473         return this.getSelectionBoundry('end');
474     },
475     getSelectionAnchor: function() {
476         return this.getSelectionBoundry('anchor');
477     },
478     getSelectionFocus: function() {
479         return this.getSelectionBoundry('focus');
480     },
481     getSelectionBoundry: function(which) {
482         var selection = window.getSelection(),
483             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
484             focusElement = this.canvas.getDocumentElement(selection.focusNode);
485         
486         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
487             return {};
488
489         if(which === 'anchor') {
490             return {
491                 element: anchorElement,
492                 offset: selection.anchorOffset,
493                 offsetAtBeginning: selection.anchorOffset === 0,
494                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
495             };
496         }
497         if(which === 'focus') {
498             return {
499                 element: focusElement,
500                 offset: selection.focusOffset,
501                 offsetAtBeginning: selection.focusOffset === 0,
502                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
503             };
504         }
505         
506         var element,
507             offset;
508
509         if(anchorElement.parent().sameNode(focusElement.parent())) {
510             var parent = anchorElement.parent(),
511                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
512             if(anchorFirst) {
513                 if(which === 'start') {
514                     element = anchorElement;
515                     offset = selection.anchorOffset
516                 }
517                 else if(which === 'end') {
518                     element = focusElement,
519                     offset = selection.focusOffset
520                 }
521             } else {
522                 if(which === 'start') {
523                     element = focusElement,
524                     offset = selection.focusOffset
525                 }
526                 else if(which === 'end') {
527                     element = anchorElement;
528                     offset = selection.anchorOffset
529                 }
530             }
531         } else {
532             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
533             if(which === 'start') {
534                 element = anchorElement;
535                 offset = selection.anchorOffset
536             } else {
537                 element = focusElement;
538                 offset = selection.focusOffset
539             }
540         }
541
542         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
543         return {
544             element: element,
545             offset: offset,
546             offsetAtBeginning: offset === 0,
547             offsetAtEnd: nodeLen === offset
548         }
549     }
550 })
551
552 return {
553     fromXML: function(wlxmlNode, publisher) {
554         return new Canvas(wlxmlNode, publisher);
555     }
556 };
557
558 });