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