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