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