Handle root node sent to findCanvasElementInParent
[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     getDocumentElement: function(from) {
125         if(from instanceof HTMLElement || from instanceof Text) {
126            return documentElement.DocumentElement.fromHTMLElement(from, this);
127         }
128     },
129     getCursor: function() {
130         return new Cursor(this);
131     },
132
133     list: {},
134
135     
136     getCurrentNodeElement: function() {
137         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
138     },
139
140     getCurrentTextElement: function() {
141         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
142     },
143
144
145
146     setCurrentElement: function(element, params) {
147         if(!(element instanceof documentElement.DocumentElement)) {
148             element = utils.findCanvasElement(element);
149         }
150
151         params = _.extend({caretTo: 'end'}, params);
152         var findFirstDirectTextChild = function(e, nodeToLand) {
153             var byBrowser = this.getCursor().getPosition().element;
154             if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
155                 return byBrowser;
156             var children = e.children();
157             for(var i = 0; i < children.length; i++) {
158                 if(children[i] instanceof documentElement.DocumentTextElement)
159                     return children[i];
160             }
161             return null;
162         }.bind(this);
163         var _markAsCurrent = function(element) {
164             if(element instanceof documentElement.DocumentTextElement) {
165                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
166                 element.dom().addClass('current-text-element');
167             } else {
168                 this.wrapper.find('.current-node-element').removeClass('current-node-element')
169                 element._container().addClass('current-node-element');
170                 this.publisher('currentElementChanged', element);
171             }
172         }.bind(this);
173
174
175         var isTextElement = element instanceof documentElement.DocumentTextElement,
176             nodeElementToLand = isTextElement ? element.parent() : element,
177             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
178             currentTextElement = this.getCurrentTextElement(),
179             currentNodeElement = this.getCurrentNodeElement();
180
181         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
182             this.wrapper.find('.current-text-element').removeClass('current-text-element');
183
184         if(textElementToLand) {
185             _markAsCurrent(textElementToLand);
186             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
187                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
188             if(!(textElementToLand.sameNode(currentTextElement)))
189                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
190         } else {
191             document.getSelection().removeAllRanges();
192         }
193
194         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
195             _markAsCurrent(nodeElementToLand);
196
197             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
198         }
199     },
200
201     _moveCaretToTextElement: function(element, where) {
202         var range = document.createRange(),
203             node = element.dom().contents()[0];
204
205         if(typeof where !== 'number') {
206             range.selectNodeContents(node);
207         } else {
208             range.setStart(node, where);
209         }
210         
211         var collapseArg = true;
212         if(where === 'end')
213             collapseArg = false;
214         range.collapse(collapseArg);
215         
216         var selection = document.getSelection();
217
218         selection.removeAllRanges();
219         selection.addRange(range);
220         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
221     },
222
223     setCursorPosition: function(position) {
224         if(position.element)
225             this._moveCaretToTextElement(position.element, position.offset);
226     }
227 });
228
229 $.extend(Canvas.prototype.list, {
230     create: function(params) {
231         if(!(params.element1.parent().sameNode(params.element2.parent())))
232             return false;
233             
234         var parent = params.element1.parent(),
235             canvas = params.element1.canvas;
236         
237         if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
238             var tmp = params.element1;
239             params.element1 = params.element2;
240             params.element2 = tmp;
241         }
242         
243         var elementsToWrap = [];
244         
245         var place = 'before';
246         parent.children().some(function(element) {
247             var _e = element;
248             if(element.sameNode(params.element1))
249                 place = 'inside';
250             if(place === 'inside') {
251                 if(element instanceof documentElement.DocumentTextElement) {
252                     element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
253                     if(element.children()[0].sameNode(params.element1))
254                         params.element1 = element;
255                 }
256                 element.setWlxmlClass('item');
257                 elementsToWrap.push(element);
258             }
259             if(_e.sameNode(params.element2))
260                 return true;
261         });
262         
263         var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
264         var toret;
265         if(parent.is('list')) {
266             var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
267             item.exec('toggleBullet', false);
268             toret = listElement.parent();
269         } else {
270             toret = listElement;
271         }  
272         
273         params.element1.before(toret);
274         
275         elementsToWrap.forEach(function(element) {
276             element.detach();
277             listElement.append(element);
278         });
279     },
280     extractItems: function(params) {
281         params = _.extend({merge: true}, params);
282         var list = params.element1.parent();
283         if(!list.is('list') || !(list.sameNode(params.element2.parent())))
284             return false;
285
286         var idx1 = list.childIndex(params.element1),
287             idx2 = list.childIndex(params.element2),
288             precedingItems = [],
289             extractedItems = [],
290             succeedingItems = [],
291             items = list.children(),
292             listIsNested = list.parent().getWlxmlClass() === 'item',
293             canvas = params.element1.canvas,
294             i;
295
296         if(idx1 > idx2) {
297             var tmp = idx1; idx1 = idx2; idx2 = tmp;
298         }
299
300         items.forEach(function(item, idx) {
301             if(idx < idx1)
302                 precedingItems.push(item);
303             else if(idx >= idx1 && idx <= idx2) {
304                 extractedItems.push(item);
305             }
306             else {
307                 succeedingItems.push(item);
308             }
309         });
310
311         var reference = listIsNested ? list.parent() : list;
312         if(succeedingItems.length === 0) {
313             var reference_orig = reference;
314             extractedItems.forEach(function(item) {
315                 reference.after(item);
316                 reference = item;
317                 if(!listIsNested)
318                     item.setWlxmlClass(null);
319             });
320             if(precedingItems.length === 0)
321                 reference_orig.detach();
322         } else if(precedingItems.length === 0) {
323             extractedItems.forEach(function(item) {
324                 reference.before(item);
325                 if(!listIsNested)
326                     item.setWlxmlClass(null);
327             });
328         } else {
329             extractedItems.forEach(function(item) {
330                 reference.after(item);
331                 if(!listIsNested)
332                     item.setWlxmlClass(null);
333                 reference = item;
334             });
335             var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
336                 toAdd = secondList;
337             
338             if(listIsNested) {
339                 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
340             }
341             succeedingItems.forEach(function(item) {
342                 secondList.append(item);
343             });
344
345             reference.after(toAdd);
346         }
347         if(!params.merge && listIsNested) {
348             return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
349         }
350         return true;
351     },
352     areItemsOfTheSameList: function(params) {
353         var e1 = params.element1,
354             e2 = params.element2;
355         return e1.parent().sameNode(e2.parent())
356             && e1.parent().is('list');
357     }
358 });
359
360
361 var Cursor = function(canvas) {
362     this.canvas = canvas;
363 };
364
365 $.extend(Cursor.prototype, {
366     isSelecting: function() {
367         var selection = window.getSelection();
368         return !selection.isCollapsed;
369     },
370     isSelectingWithinElement: function() {
371         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
372     },
373     isSelectingSiblings: function() {
374         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
375     },
376     getPosition: function() {
377         return this.getSelectionAnchor();
378     },
379     getSelectionStart: function() {
380         return this.getSelectionBoundry('start');
381     },
382     getSelectionEnd: function() {
383         return this.getSelectionBoundry('end');
384     },
385     getSelectionAnchor: function() {
386         return this.getSelectionBoundry('anchor');
387     },
388     getSelectionFocus: function() {
389         return this.getSelectionBoundry('focus');
390     },
391     getSelectionBoundry: function(which) {
392         var selection = window.getSelection(),
393             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
394             focusElement = this.canvas.getDocumentElement(selection.focusNode);
395         
396         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
397             return {};
398
399         if(which === 'anchor') {
400             return {
401                 element: anchorElement,
402                 offset: selection.anchorOffset,
403                 offsetAtBeginning: selection.anchorOffset === 0,
404                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
405             };
406         }
407         if(which === 'focus') {
408             return {
409                 element: focusElement,
410                 offset: selection.focusOffset,
411                 offsetAtBeginning: selection.focusOffset === 0,
412                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
413             };
414         }
415         
416         var element,
417             offset;
418
419         if(anchorElement.parent().sameNode(focusElement.parent())) {
420             var parent = anchorElement.parent(),
421                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
422             if(anchorFirst) {
423                 if(which === 'start') {
424                     element = anchorElement;
425                     offset = selection.anchorOffset
426                 }
427                 else if(which === 'end') {
428                     element = focusElement,
429                     offset = selection.focusOffset
430                 }
431             } else {
432                 if(which === 'start') {
433                     element = focusElement,
434                     offset = selection.focusOffset
435                 }
436                 else if(which === 'end') {
437                     element = anchorElement;
438                     offset = selection.anchorOffset
439                 }
440             }
441         } else {
442             // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
443             if(which === 'start') {
444                 element = anchorElement;
445                 offset = selection.anchorOffset
446             } else {
447                 element = focusElement;
448                 offset = selection.focusOffset
449             }
450         }
451
452         var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
453         return {
454             element: element,
455             offset: offset,
456             offsetAtBeginning: offset === 0,
457             offsetAtEnd: nodeLen === offset
458         }
459     }
460 })
461
462 return {
463     fromXMLDocument: function(wlxmlDocument, publisher) {
464         return new Canvas(wlxmlDocument, publisher);
465     }
466 };
467
468 });