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