45c7fe21db77db580678707e5bff2aade9d6f5de
[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) {
10     this.loadWlxml(wlxml);
11 };
12
13 $.extend(Canvas.prototype, {
14
15     loadWlxml: function(wlxml) {
16         var d = wlxml ? $($.trim(wlxml)) : null;
17         if(d) {
18             this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
19             this.wrapper.append(d);
20             
21             this.wrapper.find('*').replaceWith(function() {
22                 var currentTag = $(this);
23                 if(currentTag.attr('wlxml-tag'))
24                     return;
25                 var element = documentElement.DocumentNodeElement.createDOM({
26                     tag: currentTag.prop('tagName').toLowerCase(),
27                     klass: currentTag.attr('class')
28                 });
29
30                 element.append(currentTag.contents());
31                 return element;
32             });
33
34             this.wrapper.find(':not(iframe)').addBack().contents()
35                 .filter(function() {return this.nodeType === Node.TEXT_NODE})
36                 .each(function() {
37
38                     var el = $(this);
39                     
40                     // TODO: use DocumentElement API
41                     var spanParent = el.parent().attr('wlxml-tag') === 'span',
42                         spanBefore = el.prev().length > 0  && $(el.prev()[0]).attr('wlxml-tag') === 'span',
43                         spanAfter = el.next().length > 0 && $(el.next()[0]).attr('wlxml-tag') === 'span';
44                         
45                     if(spanParent || spanBefore || spanAfter) {
46                         var startSpace = /\s/g.test(this.data.substr(0,1));
47                         var endSpace = /\s/g.test(this.data.substr(-1)) && this.data.length > 1;
48                         var trimmed = $.trim(this.data);
49                         this.data = (startSpace && (spanParent || spanBefore) ? ' ' : '')
50                                     + trimmed
51                                     + (endSpace && (spanParent || spanAfter) ? ' ' : '');
52
53                     } else {
54                         var oldLength = this.data.length;
55                         this.data = $.trim(this.data);
56                         if(this.data.length === 0 && oldLength > 0 && el.parent().contents().length === 1)
57                             this.data = ' ';
58                         if(this.data.length === 0) {
59                             $(this).remove();
60                             return true; // continue
61                         }
62                     }
63
64                     var element = documentElement.DocumentTextElement.create({text: this.data});
65                     $(this).replaceWith(element.dom());
66                 });
67             
68             this.d = this.wrapper.children(0);
69         } else {
70             this.d = null;
71         }
72     },
73
74     view: function() {
75         return this.wrapper;
76     },
77
78     doc: function() {
79         if(this.d === null)
80             return null;
81         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
82     },
83
84     wrapText: function(params) {
85         params = _.extend({textNodeIdx: 0}, params);
86         if(typeof params.textNodeIdx === 'number')
87             params.textNodeIdx = [params.textNodeIdx];
88         
89         var childrenInside = params.inside.children(),
90             idx1 = Math.min.apply(Math, params.textNodeIdx),
91             idx2 = Math.max.apply(Math, params.textNodeIdx),
92             textNode1 = childrenInside[idx1],
93             textNode2 = childrenInside[idx2],
94             sameNode = textNode1.sameNode(textNode2),
95             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
96             prefixInside = textNode1.getText().substr(params.offsetStart),
97             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
98             suffixOutside = textNode2.getText().substr(params.offsetEnd)
99         ;
100         
101         var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
102         textNode1.after(wrapperElement);
103         textNode1.detach();
104         
105         if(prefixOutside.length > 0)
106             wrapperElement.before({text:prefixOutside});
107         if(sameNode) {
108             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
109             wrapperElement.append({text: core});
110         } else {
111             textNode2.detach();
112             if(prefixInside.length > 0)
113                 wrapperElement.append({text: prefixInside});
114             for(var i = idx1 + 1; i < idx2; i++) {
115                 wrapperElement.append(childrenInside[i]);
116             }
117             if(suffixInside.length > 0)
118                 wrapperElement.append({text: suffixInside});
119         }
120         if(suffixOutside.length > 0)
121             wrapperElement.after({text: suffixOutside});
122         return wrapperElement;
123     },
124     getDocumentElement: function(from) {
125         if(from instanceof HTMLElement || from instanceof Text) {
126            return documentElement.DocumentElement.fromHTMLElement(from, this);
127         }
128     },
129     getCursor: function() {
130         return new Cursor(this);
131     },
132
133     list: {},
134     
135 });
136
137 $.extend(Canvas.prototype.list, {
138     create: function(params) {
139         if(!(params.element1.parent().sameNode(params.element2.parent())))
140             return false;
141             
142         var parent = params.element1.parent();
143         
144         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
145             var tmp = params.element1;
146             params.element1 = params.element2;
147             params.element2 = tmp;
148         }
149         
150         var elementsToWrap = [];
151         
152         var place = 'before';
153         var canvas = this;
154         parent.children().some(function(element) {
155             var _e = element;
156             if(element.sameNode(params.element1))
157                 place = 'inside';
158             if(place === 'inside') {
159                 if(element instanceof documentElement.DocumentTextElement) {
160                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
161                     if(element.children()[0].sameNode(params.element1))
162                         params.element1 = element;
163                 }
164                 element.setWlxmlClass('item');
165                 elementsToWrap.push(element);
166             }
167             if(_e.sameNode(params.element2))
168                 return true;
169         });
170         
171         var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
172         
173         var toret;
174         if(parent.is('list')) {
175             listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
176             toret = listElement.parent();
177         } else {
178             toret = listElement;
179         }  
180         
181         params.element1.before(toret);
182         
183         elementsToWrap.forEach(function(element) {
184             element.detach();
185             listElement.append(element);
186         });
187     },
188     extractItems: function(params) {
189         params = _.extend({merge: true}, params);
190         var list = params.element1.parent();
191         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
192             return false;
193
194         var idx1 = list.childIndex(params.element1),
195             idx2 = list.childIndex(params.element2),
196             precedingItems = [],
197             extractedItems = [],
198             succeedingItems = [],
199             items = list.children(),
200             listIsNested = list.parent().getWlxmlClass() === 'item',
201             i;
202
203         if(idx1 > idx2) {
204             var tmp = idx1; idx1 = idx2; idx2 = tmp;
205         }
206
207         items.forEach(function(item, idx) {
208             if(idx < idx1)
209                 precedingItems.push(item);
210             else if(idx >= idx1 && idx <= idx2) {
211                 extractedItems.push(item);
212             }
213             else {
214                 succeedingItems.push(item);
215             }
216         });
217
218         var reference = listIsNested ? list.parent() : list;
219         if(succeedingItems.length === 0) {
220             var reference_orig = reference;
221             extractedItems.forEach(function(item) {
222                 reference.after(item);
223                 reference = item;
224                 if(!listIsNested)
225                     item.setWlxmlClass(null);
226             });
227             if(precedingItems.length === 0)
228                 reference_orig.detach();
229         } else if(precedingItems.length === 0) {
230             extractedItems.forEach(function(item) {
231                 reference.before(item);
232                 if(!listIsNested)
233                     item.setWlxmlClass(null);
234             });
235         } else {
236             extractedItems.forEach(function(item) {
237                 reference.after(item);
238                 if(!listIsNested)
239                     item.setWlxmlClass(null);
240                 reference = item;
241             });
242             var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
243                 toAdd = secondList;
244             
245             if(listIsNested) {
246                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
247             }
248             succeedingItems.forEach(function(item) {
249                 secondList.append(item);
250             });
251
252             reference.after(toAdd);
253         }
254         if(!params.merge && listIsNested) {
255             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
256         }
257         return true;
258     },
259     areItemsOfTheSameList: function(params) {
260         var e1 = params.element1,
261             e2 = params.element2;
262         return e1.parent().sameNode(e2.parent())
263             && e1.parent().is('list');
264     }
265 });
266
267
268 var Cursor = function(canvas) {
269     this.canvas = canvas;
270 };
271
272 $.extend(Cursor.prototype, {
273     isSelecting: function() {
274         var selection = window.getSelection();
275         return !selection.isCollapsed;
276     },
277     isSelectingWithinElement: function() {
278         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
279     },
280     isSelectingSiblings: function() {
281         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
282     },
283     getPosition: function() {
284         return this.getSelectionAnchor();
285     },
286     getSelectionStart: function() {
287         return this.getSelectionBoundry('start');
288     },
289     getSelectionEnd: function() {
290         return this.getSelectionBoundry('end');
291     },
292     getSelectionAnchor: function() {
293         return this.getSelectionBoundry('anchor');
294     },
295     getSelectionBoundry: function(which) {
296         var selection = window.getSelection(),
297             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
298             focusElement = this.canvas.getDocumentElement(selection.focusNode);
299         
300         if(which === 'anchor') {
301             return {
302                 element: anchorElement,
303                 offset: selection.anchorOffset
304             };
305         }
306         
307         var element,
308             offset;
309
310         if(anchorElement.parent().sameNode(focusElement.parent())) {
311             var parent = anchorElement.parent(),
312                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
313             if(anchorFirst) {
314                 if(which === 'start') {
315                     element = anchorElement;
316                     offset = selection.anchorOffset;
317                 }
318                 else if(which === 'end') {
319                     element = focusElement,
320                     offset = selection.focusOffset;
321                 }
322             } else {
323                 if(which === 'start') {
324                     element = focusElement,
325                     offset = selection.focusOffset
326                 }
327                 else if(which === 'end') {
328                     element = anchorElement;
329                     offset = selection.anchorOffset;
330                 }
331             }
332         } else {
333             // TODO: Handle order
334             if(which === 'start') {
335                 element = anchorElement;
336                 offset = selection.anchorOffset
337             } else {
338                 element = focusElement;
339                 offset = selection.focusOffset
340             }
341         }
342
343         return {
344             element: element,
345             offset: offset
346         }
347     }
348 })
349
350 return {
351     fromXML: function(xml) {
352         return new Canvas(xml);
353     }
354 };
355
356 });