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