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