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