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