smartxml: node.setAttr tests
[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.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 = canvas.createNodeElement({
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                 });
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                     canvas.setCurrentElement(element.getPreviousTextElement());
195                 }
196             })
197
198         } else {
199             this.d = null;
200         }
201     },
202
203     view: function() {
204         return this.wrapper;
205     },
206
207     doc: function() {
208         if(this.d === null)
209             return null;
210         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
211     },
212
213     createNodeElement: function(params) {
214         return documentElement.DocumentNodeElement.create(params, this);
215     },
216
217     wrapText: function(params) {
218         params = _.extend({textNodeIdx: 0}, params);
219         if(typeof params.textNodeIdx === 'number')
220             params.textNodeIdx = [params.textNodeIdx];
221         
222         var childrenInside = params.inside.children(),
223             idx1 = Math.min.apply(Math, params.textNodeIdx),
224             idx2 = Math.max.apply(Math, params.textNodeIdx),
225             textNode1 = childrenInside[idx1],
226             textNode2 = childrenInside[idx2],
227             sameNode = textNode1.sameNode(textNode2),
228             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
229             prefixInside = textNode1.getText().substr(params.offsetStart),
230             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
231             suffixOutside = textNode2.getText().substr(params.offsetEnd)
232         ;
233         
234         var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
235         textNode1.after(wrapperElement);
236         textNode1.detach();
237         
238         if(prefixOutside.length > 0)
239             wrapperElement.before({text:prefixOutside});
240         if(sameNode) {
241             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
242             wrapperElement.append({text: core});
243         } else {
244             textNode2.detach();
245             if(prefixInside.length > 0)
246                 wrapperElement.append({text: prefixInside});
247             for(var i = idx1 + 1; i < idx2; i++) {
248                 wrapperElement.append(childrenInside[i]);
249             }
250             if(suffixInside.length > 0)
251                 wrapperElement.append({text: suffixInside});
252         }
253         if(suffixOutside.length > 0)
254             wrapperElement.after({text: suffixOutside});
255         return wrapperElement;
256     },
257
258     wrapElements: function(params) {
259         if(!(params.element1.parent().sameNode(params.element2.parent())))
260             return;
261
262         var parent = params.element1.parent(),
263             parentChildren = parent.children(),
264             wrapper = this.createNodeElement({
265                 tag: params._with.tag,
266                 klass: params._with.klass}),
267             idx1 = parent.childIndex(params.element1),
268             idx2 = parent.childIndex(params.element2);
269
270         if(idx1 > idx2) {
271             var tmp = idx1;
272             idx1 = idx2;
273             idx2 = tmp;
274         }
275
276         var insertingMethod, insertingTarget;
277         if(idx1 === 0) {
278             insertingMethod = 'prepend';
279             insertingTarget = parent;
280         } else {
281             insertingMethod = 'after';
282             insertingTarget = parentChildren[idx1-1];
283         }
284
285         for(var i = idx1; i <= idx2; i++) {
286             wrapper.append(parentChildren[i].detach());
287         }
288
289         insertingTarget[insertingMethod](wrapper);
290         return wrapper;
291     },
292
293     getSiblingParents: function(params) {
294         var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
295             parents2 = [params.element2].concat(params.element2.parents()).reverse(),
296             noSiblingParents = null;
297
298         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
299             return noSiblingParents;
300
301         var i;
302         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
303             if(parents1[i].sameNode(parents2[i]))
304                 continue;
305             break;
306         }
307         return {element1: parents1[i], element2: parents2[i]};
308     },
309
310     getDocumentElement: function(from) {
311         if(from instanceof HTMLElement || from instanceof Text) {
312            return documentElement.DocumentElement.fromHTMLElement(from, this);
313         }
314     },
315     getCursor: function() {
316         return new Cursor(this);
317     },
318
319     list: {},
320
321     
322     getCurrentNodeElement: function() {
323         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
324     },
325
326     getCurrentTextElement: function() {
327         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
328     },
329
330
331
332     setCurrentElement: function(element, params) {
333         params = _.extend({caretTo: 'end'}, params);
334         var findFirstDirectTextChild = function(e, nodeToLand) {
335             var byBrowser = this.getCursor().getPosition().element;
336             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
337                 return byBrowser;
338             var children = e.children();
339             for(var i = 0; i < children.length; i++) {
340                 if(children[i] instanceof documentElement.DocumentTextElement)
341                     return children[i];
342             }
343             return null;
344         }.bind(this);
345         var _markAsCurrent = function(element) {
346             if(element instanceof documentElement.DocumentTextElement) {
347                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
348                 element.dom().addClass('current-text-element');
349             } else {
350                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
351                 element._container().addClass('current-node-element');
352                 this.publisher('currentElementChanged', element);
353             }
354         }.bind(this);
355
356
357         var isTextElement = element instanceof documentElement.DocumentTextElement,
358             nodeElementToLand = isTextElement ? element.parent() : element,
359             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
360             currentTextElement = this.getCurrentTextElement(),
361             currentNodeElement = this.getCurrentNodeElement();
362
363         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
364             this.wrapper.find('.current-text-element').removeClass('current-text-element');
365
366         if(textElementToLand) {
367             _markAsCurrent(textElementToLand);
368             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
369                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
370             if(!(textElementToLand.sameNode(currentTextElement)))
371                 this.publisher('currentTextElementSet', textElementToLand);
372         } else {
373             document.getSelection().removeAllRanges();
374         }
375
376         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
377             _markAsCurrent(nodeElementToLand);
378
379             this.publisher('currentNodeElementSet', nodeElementToLand);
380         }
381     },
382
383     _moveCaretToTextElement: function(element, where) {
384         var range = document.createRange(),
385             node = element.dom().contents()[0];
386
387         if(typeof where !== 'number') {
388             range.selectNodeContents(node);
389         } else {
390             range.setStart(node, where);
391         }
392         
393         var collapseArg = true;
394         if(where === 'end')
395             collapseArg = false;
396         range.collapse(collapseArg);
397         
398         var selection = document.getSelection();
399
400         selection.removeAllRanges();
401         selection.addRange(range);
402         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
403     },
404
405     setCursorPosition: function(position) {
406         if(position.element)
407             this._moveCaretToTextElement(position.element, position.offset);
408     },
409
410     toXML: function() {
411         var parent = $('<div>'),
412             parts = this.doc().toXML(0);
413         parent.append(parts);
414         return parent.html();
415     }
416 });
417
418 $.extend(Canvas.prototype.list, {
419     create: function(params) {
420         if(!(params.element1.parent().sameNode(params.element2.parent())))
421             return false;
422             
423         var parent = params.element1.parent(),
424             canvas = params.element1.canvas;
425         
426         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
427             var tmp = params.element1;
428             params.element1 = params.element2;
429             params.element2 = tmp;
430         }
431         
432         var elementsToWrap = [];
433         
434         var place = 'before';
435         parent.children().some(function(element) {
436             var _e = element;
437             if(element.sameNode(params.element1))
438                 place = 'inside';
439             if(place === 'inside') {
440                 if(element instanceof documentElement.DocumentTextElement) {
441                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
442                     if(element.children()[0].sameNode(params.element1))
443                         params.element1 = element;
444                 }
445                 element.setWlxmlClass('item');
446                 elementsToWrap.push(element);
447             }
448             if(_e.sameNode(params.element2))
449                 return true;
450         });
451         
452         var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
453         var toret;
454         if(parent.is('list')) {
455             var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
456             item.exec('toggleBullet', false);
457             toret = listElement.parent();
458         } else {
459             toret = listElement;
460         }  
461         
462         params.element1.before(toret);
463         
464         elementsToWrap.forEach(function(element) {
465             element.detach();
466             listElement.append(element);
467         });
468     },
469     extractItems: function(params) {
470         params = _.extend({merge: true}, params);
471         var list = params.element1.parent();
472         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
473             return false;
474
475         var idx1 = list.childIndex(params.element1),
476             idx2 = list.childIndex(params.element2),
477             precedingItems = [],
478             extractedItems = [],
479             succeedingItems = [],
480             items = list.children(),
481             listIsNested = list.parent().getWlxmlClass() === 'item',
482             canvas = params.element1.canvas,
483             i;
484
485         if(idx1 > idx2) {
486             var tmp = idx1; idx1 = idx2; idx2 = tmp;
487         }
488
489         items.forEach(function(item, idx) {
490             if(idx < idx1)
491                 precedingItems.push(item);
492             else if(idx >= idx1 && idx <= idx2) {
493                 extractedItems.push(item);
494             }
495             else {
496                 succeedingItems.push(item);
497             }
498         });
499
500         var reference = listIsNested ? list.parent() : list;
501         if(succeedingItems.length === 0) {
502             var reference_orig = reference;
503             extractedItems.forEach(function(item) {
504                 reference.after(item);
505                 reference = item;
506                 if(!listIsNested)
507                     item.setWlxmlClass(null);
508             });
509             if(precedingItems.length === 0)
510                 reference_orig.detach();
511         } else if(precedingItems.length === 0) {
512             extractedItems.forEach(function(item) {
513                 reference.before(item);
514                 if(!listIsNested)
515                     item.setWlxmlClass(null);
516             });
517         } else {
518             extractedItems.forEach(function(item) {
519                 reference.after(item);
520                 if(!listIsNested)
521                     item.setWlxmlClass(null);
522                 reference = item;
523             });
524             var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
525                 toAdd = secondList;
526             
527             if(listIsNested) {
528                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
529             }
530             succeedingItems.forEach(function(item) {
531                 secondList.append(item);
532             });
533
534             reference.after(toAdd);
535         }
536         if(!params.merge && listIsNested) {
537             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
538         }
539         return true;
540     },
541     areItemsOfTheSameList: function(params) {
542         var e1 = params.element1,
543             e2 = params.element2;
544         return e1.parent().sameNode(e2.parent())
545             && e1.parent().is('list');
546     }
547 });
548
549
550 var Cursor = function(canvas) {
551     this.canvas = canvas;
552 };
553
554 $.extend(Cursor.prototype, {
555     isSelecting: function() {
556         var selection = window.getSelection();
557         return !selection.isCollapsed;
558     },
559     isSelectingWithinElement: function() {
560         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
561     },
562     isSelectingSiblings: function() {
563         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
564     },
565     getPosition: function() {
566         return this.getSelectionAnchor();
567     },
568     getSelectionStart: function() {
569         return this.getSelectionBoundry('start');
570     },
571     getSelectionEnd: function() {
572         return this.getSelectionBoundry('end');
573     },
574     getSelectionAnchor: function() {
575         return this.getSelectionBoundry('anchor');
576     },
577     getSelectionFocus: function() {
578         return this.getSelectionBoundry('focus');
579     },
580     getSelectionBoundry: function(which) {
581         var selection = window.getSelection(),
582             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
583             focusElement = this.canvas.getDocumentElement(selection.focusNode);
584         
585         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
586             return {};
587
588         if(which === 'anchor') {
589             return {
590                 element: anchorElement,
591                 offset: selection.anchorOffset,
592                 offsetAtBeginning: selection.anchorOffset === 0,
593                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
594             };
595         }
596         if(which === 'focus') {
597             return {
598                 element: focusElement,
599                 offset: selection.focusOffset,
600                 offsetAtBeginning: selection.focusOffset === 0,
601                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
602             };
603         }
604         
605         var element,
606             offset;
607
608         if(anchorElement.parent().sameNode(focusElement.parent())) {
609             var parent = anchorElement.parent(),
610                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
611             if(anchorFirst) {
612                 if(which === 'start') {
613                     element = anchorElement;
614                     offset = selection.anchorOffset
615                 }
616                 else if(which === 'end') {
617                     element = focusElement,
618                     offset = selection.focusOffset
619                 }
620             } else {
621                 if(which === 'start') {
622                     element = focusElement,
623                     offset = selection.focusOffset
624                 }
625                 else if(which === 'end') {
626                     element = anchorElement;
627                     offset = selection.anchorOffset
628                 }
629             }
630         } else {
631             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
632             if(which === 'start') {
633                 element = anchorElement;
634                 offset = selection.anchorOffset
635             } else {
636                 element = focusElement;
637                 offset = selection.focusOffset
638             }
639         }
640
641         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
642         return {
643             element: element,
644             offset: offset,
645             offsetAtBeginning: offset === 0,
646             offsetAtEnd: nodeLen === offset
647         }
648     }
649 })
650
651 return {
652     fromXML: function(xml, publisher) {
653         return new Canvas(xml, publisher);
654     }
655 };
656
657 });