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