editor: removing unused code
[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     getDocumentElement: function(from) {
211         /* globals HTMLElement, Text */
212         if(from instanceof HTMLElement || from instanceof Text) {
213            return documentElement.DocumentElement.fromHTMLElement(from, this);
214         }
215     },
216     getCursor: function() {
217         return new Cursor(this);
218     },
219
220     
221     getCurrentNodeElement: function() {
222         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
223     },
224
225     getCurrentTextElement: function() {
226         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
227     },
228
229     contains: function(element) {
230         return element.dom().parents().index(this.wrapper) !== -1;
231     },
232
233     setCurrentElement: function(element, params) {
234         if(!(element instanceof documentElement.DocumentElement)) {
235             element = utils.findCanvasElement(element);
236         }
237
238         if(!element || !this.contains(element)) {
239             logger.warning('Cannot set current element: element doesn\'t exist on canvas');
240             return;
241         }
242
243         params = _.extend({caretTo: 'end'}, params);
244         var findFirstDirectTextChild = function(e, nodeToLand) {
245             var byBrowser = this.getCursor().getPosition().element;
246             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
247                 return byBrowser;
248             }
249             var children = e.children();
250             for(var i = 0; i < children.length; i++) {
251                 if(children[i] instanceof documentElement.DocumentTextElement) {
252                     return children[i];
253                 }
254             }
255             return null;
256         }.bind(this);
257         var _markAsCurrent = function(element) {
258             if(element instanceof documentElement.DocumentTextElement) {
259                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
260                 element.dom().addClass('current-text-element');
261             } else {
262                 this.wrapper.find('.current-node-element').removeClass('current-node-element');
263                 element._container().addClass('current-node-element');
264             }
265         }.bind(this);
266
267
268         var isTextElement = element instanceof documentElement.DocumentTextElement,
269             nodeElementToLand = isTextElement ? element.parent() : element,
270             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
271             currentTextElement = this.getCurrentTextElement(),
272             currentNodeElement = this.getCurrentNodeElement();
273
274         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
275             this.wrapper.find('.current-text-element').removeClass('current-text-element');
276         }
277
278         if(textElementToLand) {
279             _markAsCurrent(textElementToLand);
280             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
281                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
282             }
283             if(!(textElementToLand.sameNode(currentTextElement))) {
284                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
285             }
286         } else {
287             document.getSelection().removeAllRanges();
288         }
289
290         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
291             _markAsCurrent(nodeElementToLand);
292
293             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
294         }
295     },
296
297     _moveCaretToTextElement: function(element, where) {
298         var range = document.createRange(),
299             node = element.dom().contents()[0];
300
301         if(typeof where !== 'number') {
302             range.selectNodeContents(node);
303         } else {
304             range.setStart(node, where);
305         }
306         
307         if(where !== 'whole') {
308             var collapseArg = true;
309             if(where === 'end') {
310                 collapseArg = false;
311             }
312             range.collapse(collapseArg);
313         }
314         var selection = document.getSelection();
315
316         selection.removeAllRanges();
317         selection.addRange(range);
318         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
319     },
320
321     setCursorPosition: function(position) {
322         if(position.element) {
323             this._moveCaretToTextElement(position.element, position.offset);
324         }
325     }
326 });
327
328
329 var Cursor = function(canvas) {
330     this.canvas = canvas;
331 };
332
333 $.extend(Cursor.prototype, {
334     isSelecting: function() {
335         var selection = window.getSelection();
336         return !selection.isCollapsed;
337     },
338     isSelectingWithinElement: function() {
339         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
340     },
341     isWithinElement: function() {
342         return !this.isSelecting() || this.isSelectingWithinElement();
343     },
344     isSelectingSiblings: function() {
345         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
346     },
347     getPosition: function() {
348         return this.getSelectionAnchor();
349     },
350     getSelectionStart: function() {
351         return this.getSelectionBoundry('start');
352     },
353     getSelectionEnd: function() {
354         return this.getSelectionBoundry('end');
355     },
356     getSelectionAnchor: function() {
357         return this.getSelectionBoundry('anchor');
358     },
359     getSelectionFocus: function() {
360         return this.getSelectionBoundry('focus');
361     },
362     getSelectionBoundry: function(which) {
363         /* globals window */
364         var selection = window.getSelection(),
365             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
366             focusElement = this.canvas.getDocumentElement(selection.focusNode);
367         
368         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
369             return {};
370         }
371
372         if(which === 'anchor') {
373             return {
374                 element: anchorElement,
375                 offset: selection.anchorOffset,
376                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
377                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
378             };
379         }
380         if(which === 'focus') {
381             return {
382                 element: focusElement,
383                 offset: selection.focusOffset,
384                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
385                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
386             };
387         }
388         
389         var getPlaceData = function(anchorFirst) {
390             var element, offset;
391             if(anchorFirst) {
392                 if(which === 'start') {
393                     element = anchorElement;
394                     offset = selection.anchorOffset;
395                 }
396                 else if(which === 'end') {
397                     element = focusElement;
398                     offset = selection.focusOffset;
399                 }
400             } else {
401                 if(which === 'start') {
402                     element = focusElement;
403                     offset = selection.focusOffset;
404                 }
405                 else if(which === 'end') {
406                     element = anchorElement;
407                     offset = selection.anchorOffset;
408                 }
409             }
410             return {element: element, offset: offset};
411         };
412
413         var anchorFirst, placeData, parent;
414
415         if(anchorElement.parent().sameNode(focusElement.parent())) {
416             parent = anchorElement.parent();
417             if(selection.anchorNode === selection.focusNode) {
418                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
419             } else {
420                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
421             }
422             placeData = getPlaceData(anchorFirst);
423         } else {
424             /*jshint bitwise: false*/
425             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
426             placeData = getPlaceData(anchorFirst);
427         }
428
429         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
430         return {
431             element: placeData.element,
432             offset: placeData.offset,
433             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
434             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
435         };
436     }
437 });
438
439 return {
440     fromXMLDocument: function(wlxmlDocument, publisher) {
441         return new Canvas(wlxmlDocument, publisher);
442     }
443 };
444
445 });