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