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