c72d886f3192e934030ca1c9c050303662876f15
[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                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
70
71                     textElement.data('wlxmlNode').setText(toSet);
72                 }
73             });
74         });
75         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
76         observer.observe(this.d[0], config);
77
78
79         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
80             var el = canvas.getDocumentElement(e.currentTarget);
81             if(!el)
82                 return;
83             e.stopPropagation();
84             if(el instanceof documentElement.DocumentTextElement)
85                 el = el.parent();
86             el.toggleLabel(true);
87         });
88         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
89             var el = canvas.getDocumentElement(e.currentTarget);
90             if(!el)
91                 return;
92             e.stopPropagation();
93             if(el instanceof documentElement.DocumentTextElement)
94                 el = el.parent();
95             el.toggleLabel(false);
96         });
97
98         this.eventBus.on('elementToggled', function(toggle, element) {
99             if(!toggle) {
100                 canvas.setCurrentElement(element.getPreviousTextElement());
101             }
102         });
103     },
104
105     view: function() {
106         return this.wrapper;
107     },
108
109     doc: function() {
110         if(this.d === null)
111             return null;
112         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
113     },
114
115     toggleElementHighlight: function(node, toggle) {
116         var element = utils.findCanvasElement(node);
117         element.toggleHighlight(toggle);
118     },
119
120     createNodeElement: function(params) {
121         return documentElement.DocumentNodeElement.create(params, this);
122     },
123
124     wrapText: function(params) {
125         params = _.extend({textNodeIdx: 0}, params);
126         if(typeof params.textNodeIdx === 'number')
127             params.textNodeIdx = [params.textNodeIdx];
128         
129         var childrenInside = params.inside.children(),
130             idx1 = Math.min.apply(Math, params.textNodeIdx),
131             idx2 = Math.max.apply(Math, params.textNodeIdx),
132             textNode1 = childrenInside[idx1],
133             textNode2 = childrenInside[idx2],
134             sameNode = textNode1.sameNode(textNode2),
135             prefixOutside = textNode1.getText().substr(0, params.offsetStart),
136             prefixInside = textNode1.getText().substr(params.offsetStart),
137             suffixInside = textNode2.getText().substr(0, params.offsetEnd),
138             suffixOutside = textNode2.getText().substr(params.offsetEnd)
139         ;
140         
141         var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
142         textNode1.after(wrapperElement);
143         textNode1.detach();
144         
145         if(prefixOutside.length > 0)
146             wrapperElement.before({text:prefixOutside});
147         if(sameNode) {
148             var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
149             wrapperElement.append({text: core});
150         } else {
151             textNode2.detach();
152             if(prefixInside.length > 0)
153                 wrapperElement.append({text: prefixInside});
154             for(var i = idx1 + 1; i < idx2; i++) {
155                 wrapperElement.append(childrenInside[i]);
156             }
157             if(suffixInside.length > 0)
158                 wrapperElement.append({text: suffixInside});
159         }
160         if(suffixOutside.length > 0)
161             wrapperElement.after({text: suffixOutside});
162         return wrapperElement;
163     },
164
165     wrapElements: function(params) {
166         if(!(params.element1.parent().sameNode(params.element2.parent())))
167             return;
168
169         var parent = params.element1.parent(),
170             parentChildren = parent.children(),
171             wrapper = this.createNodeElement({
172                 tag: params._with.tag,
173                 klass: params._with.klass}),
174             idx1 = parent.childIndex(params.element1),
175             idx2 = parent.childIndex(params.element2);
176
177         if(idx1 > idx2) {
178             var tmp = idx1;
179             idx1 = idx2;
180             idx2 = tmp;
181         }
182
183         var insertingMethod, insertingTarget;
184         if(idx1 === 0) {
185             insertingMethod = 'prepend';
186             insertingTarget = parent;
187         } else {
188             insertingMethod = 'after';
189             insertingTarget = parentChildren[idx1-1];
190         }
191
192         for(var i = idx1; i <= idx2; i++) {
193             wrapper.append(parentChildren[i].detach());
194         }
195
196         insertingTarget[insertingMethod](wrapper);
197         return wrapper;
198     },
199
200     getSiblingParents: function(params) {
201         var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
202             parents2 = [params.element2].concat(params.element2.parents()).reverse(),
203             noSiblingParents = null;
204
205         if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
206             return noSiblingParents;
207
208         var i;
209         for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
210             if(parents1[i].sameNode(parents2[i]))
211                 continue;
212             break;
213         }
214         return {element1: parents1[i], element2: parents2[i]};
215     },
216
217     getDocumentElement: function(from) {
218         if(from instanceof HTMLElement || from instanceof Text) {
219            return documentElement.DocumentElement.fromHTMLElement(from, this);
220         }
221     },
222     getCursor: function() {
223         return new Cursor(this);
224     },
225
226     list: {},
227
228     
229     getCurrentNodeElement: function() {
230         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
231     },
232
233     getCurrentTextElement: function() {
234         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
235     },
236
237
238
239     setCurrentElement: function(element, params) {
240         if(!(element instanceof documentElement.DocumentElement)) {
241             element = utils.findCanvasElement(element);
242         }
243
244         params = _.extend({caretTo: 'end'}, params);
245         var findFirstDirectTextChild = function(e, nodeToLand) {
246             var byBrowser = this.getCursor().getPosition().element;
247             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
248                 return byBrowser;
249             var children = e.children();
250             for(var i = 0; i < children.length; i++) {
251                 if(children[i] instanceof documentElement.DocumentTextElement)
252                     return children[i];
253             }
254             return null;
255         }.bind(this);
256         var _markAsCurrent = function(element) {
257             if(element instanceof documentElement.DocumentTextElement) {
258                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
259                 element.dom().addClass('current-text-element');
260             } else {
261                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
262                 element._container().addClass('current-node-element');
263                 this.publisher('currentElementChanged', element);
264             }
265         }.bind(this);
266
267
268         var isTextElement = element instanceof documentElement.DocumentTextElement,
269             nodeElementToLand = isTextElement ? element.parent() : element,
270             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
271             currentTextElement = this.getCurrentTextElement(),
272             currentNodeElement = this.getCurrentNodeElement();
273
274         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
275             this.wrapper.find('.current-text-element').removeClass('current-text-element');
276
277         if(textElementToLand) {
278             _markAsCurrent(textElementToLand);
279             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
280                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
281             if(!(textElementToLand.sameNode(currentTextElement)))
282                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
283         } else {
284             document.getSelection().removeAllRanges();
285         }
286
287         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
288             _markAsCurrent(nodeElementToLand);
289
290             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
291         }
292     },
293
294     _moveCaretToTextElement: function(element, where) {
295         var range = document.createRange(),
296             node = element.dom().contents()[0];
297
298         if(typeof where !== 'number') {
299             range.selectNodeContents(node);
300         } else {
301             range.setStart(node, where);
302         }
303         
304         var collapseArg = true;
305         if(where === 'end')
306             collapseArg = false;
307         range.collapse(collapseArg);
308         
309         var selection = document.getSelection();
310
311         selection.removeAllRanges();
312         selection.addRange(range);
313         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
314     },
315
316     setCursorPosition: function(position) {
317         if(position.element)
318             this._moveCaretToTextElement(position.element, position.offset);
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 });