b0d461bbbaa2ce7ab3f50db0092657f25b020944
[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     toggleElementHighlight: function(node, toggle) {
114         var element = utils.findCanvasElement(node);
115         element.toggleHighlight(toggle);
116     },
117
118     createNodeElement: function(params) {
119         return documentElement.DocumentNodeElement.create(params, this);
120     },
121
122     wrapText: function(params) {
123         params = _.extend({textNodeIdx: 0}, params);
124         if(typeof params.textNodeIdx === 'number')
125             params.textNodeIdx = [params.textNodeIdx];
126         
127         var childrenInside = params.inside.children(),
128             idx1 = Math.min.apply(Math, params.textNodeIdx),
129             idx2 = Math.max.apply(Math, params.textNodeIdx),
130             textNode1 = childrenInside[idx1],
131             textNode2 = childrenInside[idx2],
132             sameNode = textNode1.sameNode(textNode2),
133             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
134             prefixInside = textNode1.getText().substr(params.offsetStart),
135             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
136             suffixOutside = textNode2.getText().substr(params.offsetEnd)
137         ;
138         
139         var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
140         textNode1.after(wrapperElement);
141         textNode1.detach();
142         
143         if(prefixOutside.length > 0)
144             wrapperElement.before({text:prefixOutside});
145         if(sameNode) {
146             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
147             wrapperElement.append({text: core});
148         } else {
149             textNode2.detach();
150             if(prefixInside.length > 0)
151                 wrapperElement.append({text: prefixInside});
152             for(var i = idx1 + 1; i < idx2; i++) {
153                 wrapperElement.append(childrenInside[i]);
154             }
155             if(suffixInside.length > 0)
156                 wrapperElement.append({text: suffixInside});
157         }
158         if(suffixOutside.length > 0)
159             wrapperElement.after({text: suffixOutside});
160         return wrapperElement;
161     },
162
163     wrapElements: function(params) {
164         if(!(params.element1.parent().sameNode(params.element2.parent())))
165             return;
166
167         var parent = params.element1.parent(),
168             parentChildren = parent.children(),
169             wrapper = this.createNodeElement({
170                 tag: params._with.tag,
171                 klass: params._with.klass}),
172             idx1 = parent.childIndex(params.element1),
173             idx2 = parent.childIndex(params.element2);
174
175         if(idx1 > idx2) {
176             var tmp = idx1;
177             idx1 = idx2;
178             idx2 = tmp;
179         }
180
181         var insertingMethod, insertingTarget;
182         if(idx1 === 0) {
183             insertingMethod = 'prepend';
184             insertingTarget = parent;
185         } else {
186             insertingMethod = 'after';
187             insertingTarget = parentChildren[idx1-1];
188         }
189
190         for(var i = idx1; i <= idx2; i++) {
191             wrapper.append(parentChildren[i].detach());
192         }
193
194         insertingTarget[insertingMethod](wrapper);
195         return wrapper;
196     },
197
198     getSiblingParents: function(params) {
199         var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
200             parents2 = [params.element2].concat(params.element2.parents()).reverse(),
201             noSiblingParents = null;
202
203         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
204             return noSiblingParents;
205
206         var i;
207         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
208             if(parents1[i].sameNode(parents2[i]))
209                 continue;
210             break;
211         }
212         return {element1: parents1[i], element2: parents2[i]};
213     },
214
215     getDocumentElement: function(from) {
216         if(from instanceof HTMLElement || from instanceof Text) {
217            return documentElement.DocumentElement.fromHTMLElement(from, this);
218         }
219     },
220     getCursor: function() {
221         return new Cursor(this);
222     },
223
224     list: {},
225
226     
227     getCurrentNodeElement: function() {
228         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
229     },
230
231     getCurrentTextElement: function() {
232         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
233     },
234
235
236
237     setCurrentElement: function(element, params) {
238         if(!(element instanceof documentElement.DocumentElement)) {
239             element = utils.findCanvasElement(element);
240         }
241
242         params = _.extend({caretTo: 'end'}, params);
243         var findFirstDirectTextChild = function(e, nodeToLand) {
244             var byBrowser = this.getCursor().getPosition().element;
245             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
246                 return byBrowser;
247             var children = e.children();
248             for(var i = 0; i < children.length; i++) {
249                 if(children[i] instanceof documentElement.DocumentTextElement)
250                     return children[i];
251             }
252             return null;
253         }.bind(this);
254         var _markAsCurrent = function(element) {
255             if(element instanceof documentElement.DocumentTextElement) {
256                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
257                 element.dom().addClass('current-text-element');
258             } else {
259                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
260                 element._container().addClass('current-node-element');
261                 this.publisher('currentElementChanged', element);
262             }
263         }.bind(this);
264
265
266         var isTextElement = element instanceof documentElement.DocumentTextElement,
267             nodeElementToLand = isTextElement ? element.parent() : element,
268             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
269             currentTextElement = this.getCurrentTextElement(),
270             currentNodeElement = this.getCurrentNodeElement();
271
272         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
273             this.wrapper.find('.current-text-element').removeClass('current-text-element');
274
275         if(textElementToLand) {
276             _markAsCurrent(textElementToLand);
277             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
278                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
279             if(!(textElementToLand.sameNode(currentTextElement)))
280                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
281         } else {
282             document.getSelection().removeAllRanges();
283         }
284
285         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
286             _markAsCurrent(nodeElementToLand);
287
288             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
289         }
290     },
291
292     _moveCaretToTextElement: function(element, where) {
293         var range = document.createRange(),
294             node = element.dom().contents()[0];
295
296         if(typeof where !== 'number') {
297             range.selectNodeContents(node);
298         } else {
299             range.setStart(node, where);
300         }
301         
302         var collapseArg = true;
303         if(where === 'end')
304             collapseArg = false;
305         range.collapse(collapseArg);
306         
307         var selection = document.getSelection();
308
309         selection.removeAllRanges();
310         selection.addRange(range);
311         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
312     },
313
314     setCursorPosition: function(position) {
315         if(position.element)
316             this._moveCaretToTextElement(position.element, position.offset);
317     },
318
319     toXML: function() {
320         var parent = $('<div>'),
321             parts = this.doc().toXML(0);
322         parent.append(parts);
323         return parent.html();
324     }
325 });
326
327 $.extend(Canvas.prototype.list, {
328     create: function(params) {
329         if(!(params.element1.parent().sameNode(params.element2.parent())))
330             return false;
331             
332         var parent = params.element1.parent(),
333             canvas = params.element1.canvas;
334         
335         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
336             var tmp = params.element1;
337             params.element1 = params.element2;
338             params.element2 = tmp;
339         }
340         
341         var elementsToWrap = [];
342         
343         var place = 'before';
344         parent.children().some(function(element) {
345             var _e = element;
346             if(element.sameNode(params.element1))
347                 place = 'inside';
348             if(place === 'inside') {
349                 if(element instanceof documentElement.DocumentTextElement) {
350                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
351                     if(element.children()[0].sameNode(params.element1))
352                         params.element1 = element;
353                 }
354                 element.setWlxmlClass('item');
355                 elementsToWrap.push(element);
356             }
357             if(_e.sameNode(params.element2))
358                 return true;
359         });
360         
361         var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
362         var toret;
363         if(parent.is('list')) {
364             var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
365             item.exec('toggleBullet', false);
366             toret = listElement.parent();
367         } else {
368             toret = listElement;
369         }  
370         
371         params.element1.before(toret);
372         
373         elementsToWrap.forEach(function(element) {
374             element.detach();
375             listElement.append(element);
376         });
377     },
378     extractItems: function(params) {
379         params = _.extend({merge: true}, params);
380         var list = params.element1.parent();
381         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
382             return false;
383
384         var idx1 = list.childIndex(params.element1),
385             idx2 = list.childIndex(params.element2),
386             precedingItems = [],
387             extractedItems = [],
388             succeedingItems = [],
389             items = list.children(),
390             listIsNested = list.parent().getWlxmlClass() === 'item',
391             canvas = params.element1.canvas,
392             i;
393
394         if(idx1 > idx2) {
395             var tmp = idx1; idx1 = idx2; idx2 = tmp;
396         }
397
398         items.forEach(function(item, idx) {
399             if(idx < idx1)
400                 precedingItems.push(item);
401             else if(idx >= idx1 && idx <= idx2) {
402                 extractedItems.push(item);
403             }
404             else {
405                 succeedingItems.push(item);
406             }
407         });
408
409         var reference = listIsNested ? list.parent() : list;
410         if(succeedingItems.length === 0) {
411             var reference_orig = reference;
412             extractedItems.forEach(function(item) {
413                 reference.after(item);
414                 reference = item;
415                 if(!listIsNested)
416                     item.setWlxmlClass(null);
417             });
418             if(precedingItems.length === 0)
419                 reference_orig.detach();
420         } else if(precedingItems.length === 0) {
421             extractedItems.forEach(function(item) {
422                 reference.before(item);
423                 if(!listIsNested)
424                     item.setWlxmlClass(null);
425             });
426         } else {
427             extractedItems.forEach(function(item) {
428                 reference.after(item);
429                 if(!listIsNested)
430                     item.setWlxmlClass(null);
431                 reference = item;
432             });
433             var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
434                 toAdd = secondList;
435             
436             if(listIsNested) {
437                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
438             }
439             succeedingItems.forEach(function(item) {
440                 secondList.append(item);
441             });
442
443             reference.after(toAdd);
444         }
445         if(!params.merge && listIsNested) {
446             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
447         }
448         return true;
449     },
450     areItemsOfTheSameList: function(params) {
451         var e1 = params.element1,
452             e2 = params.element2;
453         return e1.parent().sameNode(e2.parent())
454             && e1.parent().is('list');
455     }
456 });
457
458
459 var Cursor = function(canvas) {
460     this.canvas = canvas;
461 };
462
463 $.extend(Cursor.prototype, {
464     isSelecting: function() {
465         var selection = window.getSelection();
466         return !selection.isCollapsed;
467     },
468     isSelectingWithinElement: function() {
469         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
470     },
471     isSelectingSiblings: function() {
472         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
473     },
474     getPosition: function() {
475         return this.getSelectionAnchor();
476     },
477     getSelectionStart: function() {
478         return this.getSelectionBoundry('start');
479     },
480     getSelectionEnd: function() {
481         return this.getSelectionBoundry('end');
482     },
483     getSelectionAnchor: function() {
484         return this.getSelectionBoundry('anchor');
485     },
486     getSelectionFocus: function() {
487         return this.getSelectionBoundry('focus');
488     },
489     getSelectionBoundry: function(which) {
490         var selection = window.getSelection(),
491             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
492             focusElement = this.canvas.getDocumentElement(selection.focusNode);
493         
494         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
495             return {};
496
497         if(which === 'anchor') {
498             return {
499                 element: anchorElement,
500                 offset: selection.anchorOffset,
501                 offsetAtBeginning: selection.anchorOffset === 0,
502                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
503             };
504         }
505         if(which === 'focus') {
506             return {
507                 element: focusElement,
508                 offset: selection.focusOffset,
509                 offsetAtBeginning: selection.focusOffset === 0,
510                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
511             };
512         }
513         
514         var element,
515             offset;
516
517         if(anchorElement.parent().sameNode(focusElement.parent())) {
518             var parent = anchorElement.parent(),
519                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
520             if(anchorFirst) {
521                 if(which === 'start') {
522                     element = anchorElement;
523                     offset = selection.anchorOffset
524                 }
525                 else if(which === 'end') {
526                     element = focusElement,
527                     offset = selection.focusOffset
528                 }
529             } else {
530                 if(which === 'start') {
531                     element = focusElement,
532                     offset = selection.focusOffset
533                 }
534                 else if(which === 'end') {
535                     element = anchorElement;
536                     offset = selection.anchorOffset
537                 }
538             }
539         } else {
540             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
541             if(which === 'start') {
542                 element = anchorElement;
543                 offset = selection.anchorOffset
544             } else {
545                 element = focusElement;
546                 offset = selection.focusOffset
547             }
548         }
549
550         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
551         return {
552             element: element,
553             offset: offset,
554             offsetAtBeginning: offset === 0,
555             offsetAtEnd: nodeLen === offset
556         }
557     }
558 })
559
560 return {
561     fromXMLDocument: function(wlxmlDocument, publisher) {
562         return new Canvas(wlxmlDocument, publisher);
563     }
564 };
565
566 });