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