3a662e903612f9247ed66f5518160c03c55c5b84
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
4 'libs/backbone',
5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/keyboard',
7 'modules/documentCanvas/canvas/utils',
8 'modules/documentCanvas/canvas/wlxmlListener'
9 ], function($, _, Backbone, documentElement, keyboard, utils, wlxmlListener) {
10     
11 'use strict';
12
13 var Canvas = function(wlxmlDocument, publisher) {
14     this.eventBus = _.extend({}, Backbone.Events);
15     this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
16     this.wlxmlListener = wlxmlListener.create(this);
17     this.loadWlxmlDocument(wlxmlDocument);
18     this.publisher = publisher ? publisher : function() {};
19 };
20
21 $.extend(Canvas.prototype, {
22
23     loadWlxmlDocument: function(wlxmlDocument) {
24         if(!wlxmlDocument) {
25             return false;
26         }
27
28         var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
29
30         this.wrapper.empty();
31         this.wrapper.append(canvasDOM);
32         this.d = this.wrapper.children(0);
33         this.setupEventHandling();
34
35         this.wlxmlListener.listenTo(wlxmlDocument);
36         this.wlxmlDocument = wlxmlDocument;
37     },
38
39     generateCanvasDOM: function(wlxmlNode) {
40         var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
41         return element.dom();
42     },
43
44     setupEventHandling: function() {
45         var canvas = this;
46         this.wrapper.on('keyup keydown keypress', function(e) {
47             keyboard.handleKey(e, this);
48         }.bind(this));
49
50         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
51             e.stopPropagation();
52             canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
53         });
54
55         var observer = new MutationObserver(function(mutations) {
56             mutations.forEach(function(mutation) {
57                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
58                     observer.disconnect();
59                     if(mutation.target.data === '')
60                         mutation.target.data = utils.unicode.ZWS;
61                     else if(mutation.oldValue === utils.unicode.ZWS) {
62                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
63                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
64                     }
65                     observer.observe(canvas.d[0], config);
66                     canvas.publisher('contentChanged');
67
68                     var textElement = canvas.getDocumentElement(mutation.target);
69                     textElement.data('wlxmlNode').setText(mutation.target.data);
70                 }
71             });
72         });
73         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
74         observer.observe(this.d[0], config);
75
76
77         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
78             var el = canvas.getDocumentElement(e.currentTarget);
79             if(!el)
80                 return;
81             e.stopPropagation();
82             if(el instanceof documentElement.DocumentTextElement)
83                 el = el.parent();
84             el.toggleLabel(true);
85         });
86         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
87             var el = canvas.getDocumentElement(e.currentTarget);
88             if(!el)
89                 return;
90             e.stopPropagation();
91             if(el instanceof documentElement.DocumentTextElement)
92                 el = el.parent();
93             el.toggleLabel(false);
94         });
95
96         this.eventBus.on('elementToggled', function(toggle, element) {
97             if(!toggle) {
98                 canvas.setCurrentElement(element.getPreviousTextElement());
99             }
100         });
101     },
102
103     view: function() {
104         return this.wrapper;
105     },
106
107     doc: function() {
108         if(this.d === null)
109             return null;
110         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
111     },
112
113     createNodeElement: function(params) {
114         return documentElement.DocumentNodeElement.create(params, this);
115     },
116
117     wrapText: function(params) {
118         params = _.extend({textNodeIdx: 0}, params);
119         if(typeof params.textNodeIdx === 'number')
120             params.textNodeIdx = [params.textNodeIdx];
121         
122         var childrenInside = params.inside.children(),
123             idx1 = Math.min.apply(Math, params.textNodeIdx),
124             idx2 = Math.max.apply(Math, params.textNodeIdx),
125             textNode1 = childrenInside[idx1],
126             textNode2 = childrenInside[idx2],
127             sameNode = textNode1.sameNode(textNode2),
128             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
129             prefixInside = textNode1.getText().substr(params.offsetStart),
130             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
131             suffixOutside = textNode2.getText().substr(params.offsetEnd)
132         ;
133         
134         var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
135         textNode1.after(wrapperElement);
136         textNode1.detach();
137         
138         if(prefixOutside.length > 0)
139             wrapperElement.before({text:prefixOutside});
140         if(sameNode) {
141             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
142             wrapperElement.append({text: core});
143         } else {
144             textNode2.detach();
145             if(prefixInside.length > 0)
146                 wrapperElement.append({text: prefixInside});
147             for(var i = idx1 + 1; i < idx2; i++) {
148                 wrapperElement.append(childrenInside[i]);
149             }
150             if(suffixInside.length > 0)
151                 wrapperElement.append({text: suffixInside});
152         }
153         if(suffixOutside.length > 0)
154             wrapperElement.after({text: suffixOutside});
155         return wrapperElement;
156     },
157
158     wrapElements: function(params) {
159         if(!(params.element1.parent().sameNode(params.element2.parent())))
160             return;
161
162         var parent = params.element1.parent(),
163             parentChildren = parent.children(),
164             wrapper = this.createNodeElement({
165                 tag: params._with.tag,
166                 klass: params._with.klass}),
167             idx1 = parent.childIndex(params.element1),
168             idx2 = parent.childIndex(params.element2);
169
170         if(idx1 > idx2) {
171             var tmp = idx1;
172             idx1 = idx2;
173             idx2 = tmp;
174         }
175
176         var insertingMethod, insertingTarget;
177         if(idx1 === 0) {
178             insertingMethod = 'prepend';
179             insertingTarget = parent;
180         } else {
181             insertingMethod = 'after';
182             insertingTarget = parentChildren[idx1-1];
183         }
184
185         for(var i = idx1; i <= idx2; i++) {
186             wrapper.append(parentChildren[i].detach());
187         }
188
189         insertingTarget[insertingMethod](wrapper);
190         return wrapper;
191     },
192
193     getSiblingParents: function(params) {
194         var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
195             parents2 = [params.element2].concat(params.element2.parents()).reverse(),
196             noSiblingParents = null;
197
198         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
199             return noSiblingParents;
200
201         var i;
202         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
203             if(parents1[i].sameNode(parents2[i]))
204                 continue;
205             break;
206         }
207         return {element1: parents1[i], element2: parents2[i]};
208     },
209
210     getDocumentElement: function(from) {
211         if(from instanceof HTMLElement || from instanceof Text) {
212            return documentElement.DocumentElement.fromHTMLElement(from, this);
213         }
214     },
215     getCursor: function() {
216         return new Cursor(this);
217     },
218
219     list: {},
220
221     
222     getCurrentNodeElement: function() {
223         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
224     },
225
226     getCurrentTextElement: function() {
227         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
228     },
229
230
231
232     setCurrentElement: function(element, params) {
233         params = _.extend({caretTo: 'end'}, params);
234         var findFirstDirectTextChild = function(e, nodeToLand) {
235             var byBrowser = this.getCursor().getPosition().element;
236             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
237                 return byBrowser;
238             var children = e.children();
239             for(var i = 0; i < children.length; i++) {
240                 if(children[i] instanceof documentElement.DocumentTextElement)
241                     return children[i];
242             }
243             return null;
244         }.bind(this);
245         var _markAsCurrent = function(element) {
246             if(element instanceof documentElement.DocumentTextElement) {
247                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
248                 element.dom().addClass('current-text-element');
249             } else {
250                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
251                 element._container().addClass('current-node-element');
252                 this.publisher('currentElementChanged', element);
253             }
254         }.bind(this);
255
256
257         var isTextElement = element instanceof documentElement.DocumentTextElement,
258             nodeElementToLand = isTextElement ? element.parent() : element,
259             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
260             currentTextElement = this.getCurrentTextElement(),
261             currentNodeElement = this.getCurrentNodeElement();
262
263         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
264             this.wrapper.find('.current-text-element').removeClass('current-text-element');
265
266         if(textElementToLand) {
267             _markAsCurrent(textElementToLand);
268             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
269                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
270             if(!(textElementToLand.sameNode(currentTextElement)))
271                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
272         } else {
273             document.getSelection().removeAllRanges();
274         }
275
276         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
277             _markAsCurrent(nodeElementToLand);
278
279             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
280         }
281     },
282
283     _moveCaretToTextElement: function(element, where) {
284         var range = document.createRange(),
285             node = element.dom().contents()[0];
286
287         if(typeof where !== 'number') {
288             range.selectNodeContents(node);
289         } else {
290             range.setStart(node, where);
291         }
292         
293         var collapseArg = true;
294         if(where === 'end')
295             collapseArg = false;
296         range.collapse(collapseArg);
297         
298         var selection = document.getSelection();
299
300         selection.removeAllRanges();
301         selection.addRange(range);
302         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
303     },
304
305     setCursorPosition: function(position) {
306         if(position.element)
307             this._moveCaretToTextElement(position.element, position.offset);
308     },
309
310     toXML: function() {
311         var parent = $('<div>'),
312             parts = this.doc().toXML(0);
313         parent.append(parts);
314         return parent.html();
315     }
316 });
317
318 $.extend(Canvas.prototype.list, {
319     create: function(params) {
320         if(!(params.element1.parent().sameNode(params.element2.parent())))
321             return false;
322             
323         var parent = params.element1.parent(),
324             canvas = params.element1.canvas;
325         
326         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
327             var tmp = params.element1;
328             params.element1 = params.element2;
329             params.element2 = tmp;
330         }
331         
332         var elementsToWrap = [];
333         
334         var place = 'before';
335         parent.children().some(function(element) {
336             var _e = element;
337             if(element.sameNode(params.element1))
338                 place = 'inside';
339             if(place === 'inside') {
340                 if(element instanceof documentElement.DocumentTextElement) {
341                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
342                     if(element.children()[0].sameNode(params.element1))
343                         params.element1 = element;
344                 }
345                 element.setWlxmlClass('item');
346                 elementsToWrap.push(element);
347             }
348             if(_e.sameNode(params.element2))
349                 return true;
350         });
351         
352         var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
353         var toret;
354         if(parent.is('list')) {
355             var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
356             item.exec('toggleBullet', false);
357             toret = listElement.parent();
358         } else {
359             toret = listElement;
360         }  
361         
362         params.element1.before(toret);
363         
364         elementsToWrap.forEach(function(element) {
365             element.detach();
366             listElement.append(element);
367         });
368     },
369     extractItems: function(params) {
370         params = _.extend({merge: true}, params);
371         var list = params.element1.parent();
372         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
373             return false;
374
375         var idx1 = list.childIndex(params.element1),
376             idx2 = list.childIndex(params.element2),
377             precedingItems = [],
378             extractedItems = [],
379             succeedingItems = [],
380             items = list.children(),
381             listIsNested = list.parent().getWlxmlClass() === 'item',
382             canvas = params.element1.canvas,
383             i;
384
385         if(idx1 > idx2) {
386             var tmp = idx1; idx1 = idx2; idx2 = tmp;
387         }
388
389         items.forEach(function(item, idx) {
390             if(idx < idx1)
391                 precedingItems.push(item);
392             else if(idx >= idx1 && idx <= idx2) {
393                 extractedItems.push(item);
394             }
395             else {
396                 succeedingItems.push(item);
397             }
398         });
399
400         var reference = listIsNested ? list.parent() : list;
401         if(succeedingItems.length === 0) {
402             var reference_orig = reference;
403             extractedItems.forEach(function(item) {
404                 reference.after(item);
405                 reference = item;
406                 if(!listIsNested)
407                     item.setWlxmlClass(null);
408             });
409             if(precedingItems.length === 0)
410                 reference_orig.detach();
411         } else if(precedingItems.length === 0) {
412             extractedItems.forEach(function(item) {
413                 reference.before(item);
414                 if(!listIsNested)
415                     item.setWlxmlClass(null);
416             });
417         } else {
418             extractedItems.forEach(function(item) {
419                 reference.after(item);
420                 if(!listIsNested)
421                     item.setWlxmlClass(null);
422                 reference = item;
423             });
424             var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
425                 toAdd = secondList;
426             
427             if(listIsNested) {
428                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
429             }
430             succeedingItems.forEach(function(item) {
431                 secondList.append(item);
432             });
433
434             reference.after(toAdd);
435         }
436         if(!params.merge && listIsNested) {
437             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
438         }
439         return true;
440     },
441     areItemsOfTheSameList: function(params) {
442         var e1 = params.element1,
443             e2 = params.element2;
444         return e1.parent().sameNode(e2.parent())
445             && e1.parent().is('list');
446     }
447 });
448
449
450 var Cursor = function(canvas) {
451     this.canvas = canvas;
452 };
453
454 $.extend(Cursor.prototype, {
455     isSelecting: function() {
456         var selection = window.getSelection();
457         return !selection.isCollapsed;
458     },
459     isSelectingWithinElement: function() {
460         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
461     },
462     isSelectingSiblings: function() {
463         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
464     },
465     getPosition: function() {
466         return this.getSelectionAnchor();
467     },
468     getSelectionStart: function() {
469         return this.getSelectionBoundry('start');
470     },
471     getSelectionEnd: function() {
472         return this.getSelectionBoundry('end');
473     },
474     getSelectionAnchor: function() {
475         return this.getSelectionBoundry('anchor');
476     },
477     getSelectionFocus: function() {
478         return this.getSelectionBoundry('focus');
479     },
480     getSelectionBoundry: function(which) {
481         var selection = window.getSelection(),
482             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
483             focusElement = this.canvas.getDocumentElement(selection.focusNode);
484         
485         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
486             return {};
487
488         if(which === 'anchor') {
489             return {
490                 element: anchorElement,
491                 offset: selection.anchorOffset,
492                 offsetAtBeginning: selection.anchorOffset === 0,
493                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
494             };
495         }
496         if(which === 'focus') {
497             return {
498                 element: focusElement,
499                 offset: selection.focusOffset,
500                 offsetAtBeginning: selection.focusOffset === 0,
501                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
502             };
503         }
504         
505         var element,
506             offset;
507
508         if(anchorElement.parent().sameNode(focusElement.parent())) {
509             var parent = anchorElement.parent(),
510                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
511             if(anchorFirst) {
512                 if(which === 'start') {
513                     element = anchorElement;
514                     offset = selection.anchorOffset
515                 }
516                 else if(which === 'end') {
517                     element = focusElement,
518                     offset = selection.focusOffset
519                 }
520             } else {
521                 if(which === 'start') {
522                     element = focusElement,
523                     offset = selection.focusOffset
524                 }
525                 else if(which === 'end') {
526                     element = anchorElement;
527                     offset = selection.anchorOffset
528                 }
529             }
530         } else {
531             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
532             if(which === 'start') {
533                 element = anchorElement;
534                 offset = selection.anchorOffset
535             } else {
536                 element = focusElement;
537                 offset = selection.focusOffset
538             }
539         }
540
541         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
542         return {
543             element: element,
544             offset: offset,
545             offsetAtBeginning: offset === 0,
546             offsetAtEnd: nodeLen === offset
547         }
548     }
549 })
550
551 return {
552     fromXMLDocument: function(wlxmlDocument, publisher) {
553         return new Canvas(wlxmlDocument, publisher);
554     }
555 };
556
557 });