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