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