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