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