f80e9612032c91556e7d7beec3470ce28ed1d7d3
[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 && 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', textElementToLand);
220         } else {
221             document.getSelection().removeAllRanges();
222         }
223
224         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
225             _markAsCurrent(nodeElementToLand);
226
227             this.publisher('currentNodeElementSet', nodeElementToLand);
228         }
229     },
230
231     _moveCaretToTextElement: function(element, where) {
232         var range = document.createRange(),
233             node = element.dom().contents()[0];
234
235         if(typeof where !== 'number') {
236             range.selectNodeContents(node);
237         } else {
238             range.setStart(node, where);
239         }
240         
241         var collapseArg = true;
242         if(where === 'end')
243             collapseArg = false;
244         range.collapse(collapseArg);
245         
246         var selection = document.getSelection();
247
248         selection.removeAllRanges();
249         selection.addRange(range);
250         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
251     },
252
253     setCursorPosition: function(position) {
254         if(position.element)
255             this._moveCaretToTextElement(position.element, position.offset);
256     }
257 });
258
259 $.extend(Canvas.prototype.list, {
260     create: function(params) {
261         if(!(params.element1.parent().sameNode(params.element2.parent())))
262             return false;
263             
264         var parent = params.element1.parent();
265         
266         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
267             var tmp = params.element1;
268             params.element1 = params.element2;
269             params.element2 = tmp;
270         }
271         
272         var elementsToWrap = [];
273         
274         var place = 'before';
275         var canvas = this;
276         parent.children().some(function(element) {
277             var _e = element;
278             if(element.sameNode(params.element1))
279                 place = 'inside';
280             if(place === 'inside') {
281                 if(element instanceof documentElement.DocumentTextElement) {
282                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
283                     if(element.children()[0].sameNode(params.element1))
284                         params.element1 = element;
285                 }
286                 element.setWlxmlClass('item');
287                 elementsToWrap.push(element);
288             }
289             if(_e.sameNode(params.element2))
290                 return true;
291         });
292         
293         var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
294         
295         var toret;
296         if(parent.is('list')) {
297             listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
298             toret = listElement.parent();
299         } else {
300             toret = listElement;
301         }  
302         
303         params.element1.before(toret);
304         
305         elementsToWrap.forEach(function(element) {
306             element.detach();
307             listElement.append(element);
308         });
309     },
310     extractItems: function(params) {
311         params = _.extend({merge: true}, params);
312         var list = params.element1.parent();
313         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
314             return false;
315
316         var idx1 = list.childIndex(params.element1),
317             idx2 = list.childIndex(params.element2),
318             precedingItems = [],
319             extractedItems = [],
320             succeedingItems = [],
321             items = list.children(),
322             listIsNested = list.parent().getWlxmlClass() === 'item',
323             i;
324
325         if(idx1 > idx2) {
326             var tmp = idx1; idx1 = idx2; idx2 = tmp;
327         }
328
329         items.forEach(function(item, idx) {
330             if(idx < idx1)
331                 precedingItems.push(item);
332             else if(idx >= idx1 && idx <= idx2) {
333                 extractedItems.push(item);
334             }
335             else {
336                 succeedingItems.push(item);
337             }
338         });
339
340         var reference = listIsNested ? list.parent() : list;
341         if(succeedingItems.length === 0) {
342             var reference_orig = reference;
343             extractedItems.forEach(function(item) {
344                 reference.after(item);
345                 reference = item;
346                 if(!listIsNested)
347                     item.setWlxmlClass(null);
348             });
349             if(precedingItems.length === 0)
350                 reference_orig.detach();
351         } else if(precedingItems.length === 0) {
352             extractedItems.forEach(function(item) {
353                 reference.before(item);
354                 if(!listIsNested)
355                     item.setWlxmlClass(null);
356             });
357         } else {
358             extractedItems.forEach(function(item) {
359                 reference.after(item);
360                 if(!listIsNested)
361                     item.setWlxmlClass(null);
362                 reference = item;
363             });
364             var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
365                 toAdd = secondList;
366             
367             if(listIsNested) {
368                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
369             }
370             succeedingItems.forEach(function(item) {
371                 secondList.append(item);
372             });
373
374             reference.after(toAdd);
375         }
376         if(!params.merge && listIsNested) {
377             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
378         }
379         return true;
380     },
381     areItemsOfTheSameList: function(params) {
382         var e1 = params.element1,
383             e2 = params.element2;
384         return e1.parent().sameNode(e2.parent())
385             && e1.parent().is('list');
386     }
387 });
388
389
390 var Cursor = function(canvas) {
391     this.canvas = canvas;
392 };
393
394 $.extend(Cursor.prototype, {
395     isSelecting: function() {
396         var selection = window.getSelection();
397         return !selection.isCollapsed;
398     },
399     isSelectingWithinElement: function() {
400         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
401     },
402     isSelectingSiblings: function() {
403         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
404     },
405     getPosition: function() {
406         return this.getSelectionAnchor();
407     },
408     getSelectionStart: function() {
409         return this.getSelectionBoundry('start');
410     },
411     getSelectionEnd: function() {
412         return this.getSelectionBoundry('end');
413     },
414     getSelectionAnchor: function() {
415         return this.getSelectionBoundry('anchor');
416     },
417     getSelectionBoundry: function(which) {
418         var selection = window.getSelection(),
419             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
420             focusElement = this.canvas.getDocumentElement(selection.focusNode);
421         
422         if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
423             return {};
424
425         if(which === 'anchor') {
426             return {
427                 element: anchorElement,
428                 offset: selection.anchorOffset
429             };
430         }
431         
432         var element,
433             offset;
434
435         if(anchorElement.parent().sameNode(focusElement.parent())) {
436             var parent = anchorElement.parent(),
437                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
438             if(anchorFirst) {
439                 if(which === 'start') {
440                     element = anchorElement;
441                     offset = selection.anchorOffset;
442                 }
443                 else if(which === 'end') {
444                     element = focusElement,
445                     offset = selection.focusOffset;
446                 }
447             } else {
448                 if(which === 'start') {
449                     element = focusElement,
450                     offset = selection.focusOffset
451                 }
452                 else if(which === 'end') {
453                     element = anchorElement;
454                     offset = selection.anchorOffset;
455                 }
456             }
457         } else {
458             // TODO: Handle order
459             if(which === 'start') {
460                 element = anchorElement;
461                 offset = selection.anchorOffset
462             } else {
463                 element = focusElement;
464                 offset = selection.focusOffset
465             }
466         }
467
468         return {
469             element: element,
470             offset: offset
471         }
472     }
473 })
474
475 return {
476     fromXML: function(xml, publisher) {
477         return new Canvas(xml, publisher);
478     }
479 };
480
481 });