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