integration wip: handle backspace/delete
[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     toXML: function() {
322         var parent = $('<div>'),
323             parts = this.doc().toXML(0);
324         parent.append(parts);
325         return parent.html();
326     }
327 });
328
329 $.extend(Canvas.prototype.list, {
330     create: function(params) {
331         if(!(params.element1.parent().sameNode(params.element2.parent())))
332             return false;
333             
334         var parent = params.element1.parent(),
335             canvas = params.element1.canvas;
336         
337         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
338             var tmp = params.element1;
339             params.element1 = params.element2;
340             params.element2 = tmp;
341         }
342         
343         var elementsToWrap = [];
344         
345         var place = 'before';
346         parent.children().some(function(element) {
347             var _e = element;
348             if(element.sameNode(params.element1))
349                 place = 'inside';
350             if(place === 'inside') {
351                 if(element instanceof documentElement.DocumentTextElement) {
352                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
353                     if(element.children()[0].sameNode(params.element1))
354                         params.element1 = element;
355                 }
356                 element.setWlxmlClass('item');
357                 elementsToWrap.push(element);
358             }
359             if(_e.sameNode(params.element2))
360                 return true;
361         });
362         
363         var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
364         var toret;
365         if(parent.is('list')) {
366             var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
367             item.exec('toggleBullet', false);
368             toret = listElement.parent();
369         } else {
370             toret = listElement;
371         }  
372         
373         params.element1.before(toret);
374         
375         elementsToWrap.forEach(function(element) {
376             element.detach();
377             listElement.append(element);
378         });
379     },
380     extractItems: function(params) {
381         params = _.extend({merge: true}, params);
382         var list = params.element1.parent();
383         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
384             return false;
385
386         var idx1 = list.childIndex(params.element1),
387             idx2 = list.childIndex(params.element2),
388             precedingItems = [],
389             extractedItems = [],
390             succeedingItems = [],
391             items = list.children(),
392             listIsNested = list.parent().getWlxmlClass() === 'item',
393             canvas = params.element1.canvas,
394             i;
395
396         if(idx1 > idx2) {
397             var tmp = idx1; idx1 = idx2; idx2 = tmp;
398         }
399
400         items.forEach(function(item, idx) {
401             if(idx < idx1)
402                 precedingItems.push(item);
403             else if(idx >= idx1 && idx <= idx2) {
404                 extractedItems.push(item);
405             }
406             else {
407                 succeedingItems.push(item);
408             }
409         });
410
411         var reference = listIsNested ? list.parent() : list;
412         if(succeedingItems.length === 0) {
413             var reference_orig = reference;
414             extractedItems.forEach(function(item) {
415                 reference.after(item);
416                 reference = item;
417                 if(!listIsNested)
418                     item.setWlxmlClass(null);
419             });
420             if(precedingItems.length === 0)
421                 reference_orig.detach();
422         } else if(precedingItems.length === 0) {
423             extractedItems.forEach(function(item) {
424                 reference.before(item);
425                 if(!listIsNested)
426                     item.setWlxmlClass(null);
427             });
428         } else {
429             extractedItems.forEach(function(item) {
430                 reference.after(item);
431                 if(!listIsNested)
432                     item.setWlxmlClass(null);
433                 reference = item;
434             });
435             var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
436                 toAdd = secondList;
437             
438             if(listIsNested) {
439                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
440             }
441             succeedingItems.forEach(function(item) {
442                 secondList.append(item);
443             });
444
445             reference.after(toAdd);
446         }
447         if(!params.merge && listIsNested) {
448             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
449         }
450         return true;
451     },
452     areItemsOfTheSameList: function(params) {
453         var e1 = params.element1,
454             e2 = params.element2;
455         return e1.parent().sameNode(e2.parent())
456             && e1.parent().is('list');
457     }
458 });
459
460
461 var Cursor = function(canvas) {
462     this.canvas = canvas;
463 };
464
465 $.extend(Cursor.prototype, {
466     isSelecting: function() {
467         var selection = window.getSelection();
468         return !selection.isCollapsed;
469     },
470     isSelectingWithinElement: function() {
471         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
472     },
473     isSelectingSiblings: function() {
474         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
475     },
476     getPosition: function() {
477         return this.getSelectionAnchor();
478     },
479     getSelectionStart: function() {
480         return this.getSelectionBoundry('start');
481     },
482     getSelectionEnd: function() {
483         return this.getSelectionBoundry('end');
484     },
485     getSelectionAnchor: function() {
486         return this.getSelectionBoundry('anchor');
487     },
488     getSelectionFocus: function() {
489         return this.getSelectionBoundry('focus');
490     },
491     getSelectionBoundry: function(which) {
492         var selection = window.getSelection(),
493             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
494             focusElement = this.canvas.getDocumentElement(selection.focusNode);
495         
496         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
497             return {};
498
499         if(which === 'anchor') {
500             return {
501                 element: anchorElement,
502                 offset: selection.anchorOffset,
503                 offsetAtBeginning: selection.anchorOffset === 0,
504                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
505             };
506         }
507         if(which === 'focus') {
508             return {
509                 element: focusElement,
510                 offset: selection.focusOffset,
511                 offsetAtBeginning: selection.focusOffset === 0,
512                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
513             };
514         }
515         
516         var element,
517             offset;
518
519         if(anchorElement.parent().sameNode(focusElement.parent())) {
520             var parent = anchorElement.parent(),
521                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
522             if(anchorFirst) {
523                 if(which === 'start') {
524                     element = anchorElement;
525                     offset = selection.anchorOffset
526                 }
527                 else if(which === 'end') {
528                     element = focusElement,
529                     offset = selection.focusOffset
530                 }
531             } else {
532                 if(which === 'start') {
533                     element = focusElement,
534                     offset = selection.focusOffset
535                 }
536                 else if(which === 'end') {
537                     element = anchorElement;
538                     offset = selection.anchorOffset
539                 }
540             }
541         } else {
542             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
543             if(which === 'start') {
544                 element = anchorElement;
545                 offset = selection.anchorOffset
546             } else {
547                 element = focusElement;
548                 offset = selection.focusOffset
549             }
550         }
551
552         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
553         return {
554             element: element,
555             offset: offset,
556             offsetAtBeginning: offset === 0,
557             offsetAtEnd: nodeLen === offset
558         }
559     }
560 })
561
562 return {
563     fromXMLDocument: function(wlxmlDocument, publisher) {
564         return new Canvas(wlxmlDocument, publisher);
565     }
566 };
567
568 });