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