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