editor: canvas - refactoring
[fnpeditor.git] / src / editor / modules / documentCanvas / canvas / canvas.js
1 define([
2 'libs/jquery',
3 'libs/underscore',
4 'libs/backbone',
5 'fnpjs/logging/logging',
6 'modules/documentCanvas/canvas/documentElement',
7 'modules/documentCanvas/canvas/keyboard',
8 'modules/documentCanvas/canvas/utils',
9 'modules/documentCanvas/canvas/wlxmlListener'
10 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener) {
11     
12 'use strict';
13 /* global document:false, window:false, Node:false */
14
15 var logger = logging.getLogger('canvas');
16
17 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
18 $.extend(TextHandler.prototype, {
19     handle: function(node, text) {
20         this.setText(text, node);
21         // return;
22         // if(!this.node) {
23         //     this.node = node;
24         // }
25         // if(this.node.sameNode(node)) {
26         //     this._ping(text);
27         // } else {
28         //     this.flush();
29         //     this.node = node;
30         //     this._ping(text);
31         // }
32     },
33     _ping: _.throttle(function(text) {
34         this.buffer = text;
35         this.flush();
36     }, 1000),
37     flush: function() {
38         if(this.buffer !== null) {
39             this.setText(this.buffer, this.node);
40             this.buffer = null;
41         }
42     },
43     setText: function(text, node) {
44         //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
45         node.setText(text);
46
47     }
48
49 });
50
51
52 var Canvas = function(wlxmlDocument, publisher) {
53     this.eventBus = _.extend({}, Backbone.Events);
54     this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
55     this.wlxmlListener = wlxmlListener.create(this);
56     this.loadWlxmlDocument(wlxmlDocument);
57     this.setupEventHandling();
58     this.publisher = publisher ? publisher : function() {};
59     this.textHandler = new TextHandler(this);
60 };
61
62 $.extend(Canvas.prototype, {
63
64     loadWlxmlDocument: function(wlxmlDocument) {
65         if(!wlxmlDocument) {
66             return false;
67         }
68
69         this.wlxmlListener.listenTo(wlxmlDocument);
70         this.wlxmlDocument = wlxmlDocument;
71         this.reloadRoot();
72     },
73
74     reloadRoot: function() {
75         var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
76         //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
77
78         this.wrapper.empty();
79         this.wrapper.append(canvasDOM);
80         this.d = this.wrapper.children(0);
81     },
82
83     generateCanvasDOM: function(wlxmlNode) {
84         var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
85         return element.dom();
86     },
87
88     setupEventHandling: function() {
89         var canvas = this;
90         this.wrapper.on('keyup keydown keypress', function(e) {
91             keyboard.handleKey(e, this);
92         }.bind(this));
93
94         var mouseDown;
95         this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
96             mouseDown = e.target;
97         });
98
99         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
100             e.stopPropagation();
101             if(e.originalEvent.detail === 3) {
102                 e.preventDefault();
103                 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
104             } else {
105                 if(mouseDown === e.target) {
106                     canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
107                 }
108             }
109         });
110
111         this.wrapper.on('paste', function(e) {
112             e.preventDefault();
113
114             var clipboardData = e.originalEvent.clipboardData;
115             if(!clipboardData || !clipboardData.getData) {
116                 return; // TODO: alert
117             }
118
119             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
120                 cursor = canvas.getCursor(),
121                 element = cursor.getPosition().element,
122                 lhs, rhs;
123             
124             if(element && cursor.isWithinElement()) {
125                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
126                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
127                 element.setText(lhs+text+rhs);
128                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
129             } else {
130                 /* jshint noempty:false */
131                 // TODO: alert
132             }
133         });
134
135         /* globals MutationObserver */
136         var observer = new MutationObserver(function(mutations) {
137             mutations.forEach(function(mutation) {
138                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
139                     observer.disconnect();
140                     if(mutation.target.data === '') {
141                         mutation.target.data = utils.unicode.ZWS;
142                     }
143                     else if(mutation.oldValue === utils.unicode.ZWS) {
144                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
145                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
146                     }
147                     observer.observe(canvas.wrapper[0], config);
148
149                     var textElement = canvas.getDocumentElement(mutation.target),
150                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
151
152                     //textElement.data('wlxmlNode').setText(toSet);
153                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
154                     if(textElement.data('wlxmlNode').getText() !== toSet) {
155                         canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
156                     }
157                 }
158             });
159         });
160         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
161         observer.observe(this.wrapper[0], config);
162
163
164         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
165             var el = canvas.getDocumentElement(e.currentTarget);
166             if(!el) {
167                 return;
168             }
169             e.stopPropagation();
170             if(el instanceof documentElement.DocumentTextElement) {
171                 el = el.parent();
172             }
173             el.toggleLabel(true);
174         });
175         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
176             var el = canvas.getDocumentElement(e.currentTarget);
177             if(!el) {
178                 return;
179             }
180             e.stopPropagation();
181             if(el instanceof documentElement.DocumentTextElement) {
182                 el = el.parent();
183             }
184             el.toggleLabel(false);
185         });
186
187         this.eventBus.on('elementToggled', function(toggle, element) {
188             if(!toggle) {
189                 canvas.setCurrentElement(element.getPreviousTextElement());
190             }
191         });
192     },
193
194     view: function() {
195         return this.wrapper;
196     },
197
198     doc: function() {
199         if(this.d === null) {
200             return null;
201         }
202         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
203     },
204
205     toggleElementHighlight: function(node, toggle) {
206         var element = utils.findCanvasElement(node);
207         element.toggleHighlight(toggle);
208     },
209
210     createNodeElement: function(params) {
211         return documentElement.DocumentNodeElement.create(params, this);
212     },
213
214     getDocumentElement: function(from) {
215         /* globals HTMLElement, Text */
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     
225     getCurrentNodeElement: function() {
226         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
227     },
228
229     getCurrentTextElement: function() {
230         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
231     },
232
233     contains: function(element) {
234         return element.dom().parents().index(this.wrapper) !== -1;
235     },
236
237     setCurrentElement: function(element, params) {
238         if(!(element instanceof documentElement.DocumentElement)) {
239             element = utils.findCanvasElement(element);
240         }
241
242         if(!element || !this.contains(element)) {
243             logger.warning('Cannot set current element: element doesn\'t exist on canvas');
244             return;
245         }
246
247         params = _.extend({caretTo: 'end'}, params);
248         var findFirstDirectTextChild = function(e, nodeToLand) {
249             var byBrowser = this.getCursor().getPosition().element;
250             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
251                 return byBrowser;
252             }
253             var children = e.children();
254             for(var i = 0; i < children.length; i++) {
255                 if(children[i] instanceof documentElement.DocumentTextElement) {
256                     return children[i];
257                 }
258             }
259             return null;
260         }.bind(this);
261         var _markAsCurrent = function(element) {
262             if(element instanceof documentElement.DocumentTextElement) {
263                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
264                 element.dom().addClass('current-text-element');
265             } else {
266                 this.wrapper.find('.current-node-element').removeClass('current-node-element');
267                 element._container().addClass('current-node-element');
268             }
269         }.bind(this);
270
271
272         var isTextElement = element instanceof documentElement.DocumentTextElement,
273             nodeElementToLand = isTextElement ? element.parent() : element,
274             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
275             currentTextElement = this.getCurrentTextElement(),
276             currentNodeElement = this.getCurrentNodeElement();
277
278         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
279             this.wrapper.find('.current-text-element').removeClass('current-text-element');
280         }
281
282         if(textElementToLand) {
283             _markAsCurrent(textElementToLand);
284             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
285                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
286             }
287             if(!(textElementToLand.sameNode(currentTextElement))) {
288                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
289             }
290         } else {
291             document.getSelection().removeAllRanges();
292         }
293
294         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
295             _markAsCurrent(nodeElementToLand);
296
297             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
298         }
299     },
300
301     _moveCaretToTextElement: function(element, where) {
302         var range = document.createRange(),
303             node = element.dom().contents()[0];
304
305         if(typeof where !== 'number') {
306             range.selectNodeContents(node);
307         } else {
308             range.setStart(node, where);
309         }
310         
311         if(where !== 'whole') {
312             var collapseArg = true;
313             if(where === 'end') {
314                 collapseArg = false;
315             }
316             range.collapse(collapseArg);
317         }
318         var selection = document.getSelection();
319
320         selection.removeAllRanges();
321         selection.addRange(range);
322         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
323     },
324
325     setCursorPosition: function(position) {
326         if(position.element) {
327             this._moveCaretToTextElement(position.element, position.offset);
328         }
329     }
330 });
331
332
333 var Cursor = function(canvas) {
334     this.canvas = canvas;
335 };
336
337 $.extend(Cursor.prototype, {
338     isSelecting: function() {
339         var selection = window.getSelection();
340         return !selection.isCollapsed;
341     },
342     isSelectingWithinElement: function() {
343         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
344     },
345     isWithinElement: function() {
346         return !this.isSelecting() || this.isSelectingWithinElement();
347     },
348     isSelectingSiblings: function() {
349         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
350     },
351     getPosition: function() {
352         return this.getSelectionAnchor();
353     },
354     getSelectionStart: function() {
355         return this.getSelectionBoundry('start');
356     },
357     getSelectionEnd: function() {
358         return this.getSelectionBoundry('end');
359     },
360     getSelectionAnchor: function() {
361         return this.getSelectionBoundry('anchor');
362     },
363     getSelectionFocus: function() {
364         return this.getSelectionBoundry('focus');
365     },
366     getSelectionBoundry: function(which) {
367         /* globals window */
368         var selection = window.getSelection(),
369             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
370             focusElement = this.canvas.getDocumentElement(selection.focusNode);
371         
372         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
373             return {};
374         }
375
376         if(which === 'anchor') {
377             return {
378                 element: anchorElement,
379                 offset: selection.anchorOffset,
380                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
381                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
382             };
383         }
384         if(which === 'focus') {
385             return {
386                 element: focusElement,
387                 offset: selection.focusOffset,
388                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
389                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
390             };
391         }
392         
393         var getPlaceData = function(anchorFirst) {
394             var element, offset;
395             if(anchorFirst) {
396                 if(which === 'start') {
397                     element = anchorElement;
398                     offset = selection.anchorOffset;
399                 }
400                 else if(which === 'end') {
401                     element = focusElement;
402                     offset = selection.focusOffset;
403                 }
404             } else {
405                 if(which === 'start') {
406                     element = focusElement;
407                     offset = selection.focusOffset;
408                 }
409                 else if(which === 'end') {
410                     element = anchorElement;
411                     offset = selection.anchorOffset;
412                 }
413             }
414             return {element: element, offset: offset};
415         };
416
417         var anchorFirst, placeData, parent;
418
419         if(anchorElement.parent().sameNode(focusElement.parent())) {
420             parent = anchorElement.parent();
421             if(selection.anchorNode === selection.focusNode) {
422                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
423             } else {
424                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
425             }
426             placeData = getPlaceData(anchorFirst);
427         } else {
428             /*jshint bitwise: false*/
429             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
430             placeData = getPlaceData(anchorFirst);
431         }
432
433         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
434         return {
435             element: placeData.element,
436             offset: placeData.offset,
437             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
438             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
439         };
440     }
441 });
442
443 return {
444     fromXMLDocument: function(wlxmlDocument, publisher) {
445         return new Canvas(wlxmlDocument, publisher);
446     }
447 };
448
449 });