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