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