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