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) {
13 /* global document:false, window:false, Node:false */
15 var logger = logging.getLogger('canvas');
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);
25 // if(this.node.sameNode(node)) {
33 _ping: _.throttle(function(text) {
38 if(this.buffer !== null) {
39 this.setText(this.buffer, this.node);
43 setText: function(text, node) {
44 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
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);
62 $.extend(Canvas.prototype, {
64 loadWlxmlDocument: function(wlxmlDocument) {
69 this.wlxmlListener.listenTo(wlxmlDocument);
70 this.wlxmlDocument = wlxmlDocument;
74 createElement: function(wlxmlNode) {
75 var Factory = wlxmlNode.nodeType === Node.TEXT_NODE ? documentElement.DocumentTextElement : documentElement.DocumentNodeElement;
76 return new Factory(wlxmlNode, this);
79 getDocumentElement: function(htmlElement) {
80 /* globals HTMLElement, Text */
81 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
84 var $element = $(htmlElement);
85 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
86 return $element.data('canvas-element');
89 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
90 $element = $element.parent();
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');
99 reloadRoot: function() {
100 var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
101 //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
103 this.wrapper.empty();
104 this.wrapper.append(canvasDOM);
105 this.d = this.wrapper.children(0);
108 generateCanvasDOM: function(wlxmlNode) {
109 //var element = new documentElement.DocumentNodeElement(wlxmlNode, this);
110 //return element.dom();
111 return this.createElement(wlxmlNode).dom();
114 setupEventHandling: function() {
116 this.wrapper.on('keyup keydown keypress', function(e) {
117 keyboard.handleKey(e, this);
121 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
122 mouseDown = e.target;
125 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
127 if(e.originalEvent.detail === 3) {
129 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
131 if(mouseDown === e.target) {
132 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
137 this.wrapper.on('paste', function(e) {
140 var clipboardData = e.originalEvent.clipboardData;
141 if(!clipboardData || !clipboardData.getData) {
142 return; // TODO: alert
145 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
146 cursor = canvas.getCursor(),
147 element = cursor.getPosition().element,
150 if(element && cursor.isWithinElement()) {
151 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
152 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
153 element.setText(lhs+text+rhs);
154 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
156 /* jshint noempty:false */
161 /* globals MutationObserver */
162 var observer = new MutationObserver(function(mutations) {
163 mutations.forEach(function(mutation) {
164 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
165 observer.disconnect();
166 if(mutation.target.data === '') {
167 mutation.target.data = utils.unicode.ZWS;
169 else if(mutation.oldValue === utils.unicode.ZWS) {
170 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
171 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
173 observer.observe(canvas.wrapper[0], config);
175 var textElement = canvas.getDocumentElement(mutation.target),
176 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
178 //textElement.data('wlxmlNode').setText(toSet);
179 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
180 if(textElement.wlxmlNode.getText() !== toSet) {
181 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
186 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
187 observer.observe(this.wrapper[0], config);
190 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
191 var el = canvas.getDocumentElement(e.currentTarget);
196 if(el instanceof documentElement.DocumentTextElement) {
199 el.toggleLabel(true);
201 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
202 var el = canvas.getDocumentElement(e.currentTarget);
207 if(el instanceof documentElement.DocumentTextElement) {
210 el.toggleLabel(false);
213 this.eventBus.on('elementToggled', function(toggle, element) {
215 canvas.setCurrentElement(element.getPreviousTextElement());
225 if(this.d === null) {
228 return this.getDocumentElement(this.d[0]);
231 toggleElementHighlight: function(node, toggle) {
232 var element = utils.findCanvasElement(node);
233 element.toggleHighlight(toggle);
236 getCursor: function() {
237 return new Cursor(this);
241 getCurrentNodeElement: function() {
242 var htmlElement = this.wrapper.find('.current-node-element').parent()[0];
244 return this.getDocumentElement(htmlElement);
248 getCurrentTextElement: function() {
249 var htmlElement = this.wrapper.find('.current-text-element')[0];
251 return this.getDocumentElement(htmlElement);
255 contains: function(element) {
256 return element.dom().parents().index(this.wrapper) !== -1;
259 setCurrentElement: function(element, params) {
260 if(!(element instanceof documentElement.DocumentElement)) {
261 element = utils.findCanvasElement(element);
264 if(!element || !this.contains(element)) {
265 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
269 params = _.extend({caretTo: 'end'}, params);
270 var findFirstDirectTextChild = function(e, nodeToLand) {
271 var byBrowser = this.getCursor().getPosition().element;
272 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
275 var children = e.children();
276 for(var i = 0; i < children.length; i++) {
277 if(children[i] instanceof documentElement.DocumentTextElement) {
283 var _markAsCurrent = function(element) {
284 if(element instanceof documentElement.DocumentTextElement) {
285 this.wrapper.find('.current-text-element').removeClass('current-text-element');
286 element.dom().addClass('current-text-element');
288 this.wrapper.find('.current-node-element').removeClass('current-node-element');
289 element._container().addClass('current-node-element');
294 var isTextElement = element instanceof documentElement.DocumentTextElement,
295 nodeElementToLand = isTextElement ? element.parent() : element,
296 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
297 currentTextElement = this.getCurrentTextElement(),
298 currentNodeElement = this.getCurrentNodeElement();
300 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
301 this.wrapper.find('.current-text-element').removeClass('current-text-element');
304 if(textElementToLand) {
305 _markAsCurrent(textElementToLand);
306 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
307 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
309 if(!(textElementToLand.sameNode(currentTextElement))) {
310 this.publisher('currentTextElementSet', textElementToLand.wlxmlNode);
313 document.getSelection().removeAllRanges();
316 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
317 _markAsCurrent(nodeElementToLand);
319 this.publisher('currentNodeElementSet', nodeElementToLand.wlxmlNode);
323 _moveCaretToTextElement: function(element, where) {
324 var range = document.createRange(),
325 node = element.dom().contents()[0];
327 if(typeof where !== 'number') {
328 range.selectNodeContents(node);
330 range.setStart(node, where);
333 if(where !== 'whole') {
334 var collapseArg = true;
335 if(where === 'end') {
338 range.collapse(collapseArg);
340 var selection = document.getSelection();
342 selection.removeAllRanges();
343 selection.addRange(range);
344 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
347 setCursorPosition: function(position) {
348 if(position.element) {
349 this._moveCaretToTextElement(position.element, position.offset);
355 var Cursor = function(canvas) {
356 this.canvas = canvas;
359 $.extend(Cursor.prototype, {
360 isSelecting: function() {
361 var selection = window.getSelection();
362 return !selection.isCollapsed;
364 isSelectingWithinElement: function() {
365 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
367 isWithinElement: function() {
368 return !this.isSelecting() || this.isSelectingWithinElement();
370 isSelectingSiblings: function() {
371 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
373 getPosition: function() {
374 return this.getSelectionAnchor();
376 getSelectionStart: function() {
377 return this.getSelectionBoundry('start');
379 getSelectionEnd: function() {
380 return this.getSelectionBoundry('end');
382 getSelectionAnchor: function() {
383 return this.getSelectionBoundry('anchor');
385 getSelectionFocus: function() {
386 return this.getSelectionBoundry('focus');
388 getSelectionBoundry: function(which) {
390 var selection = window.getSelection(),
391 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
392 focusElement = this.canvas.getDocumentElement(selection.focusNode);
394 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
398 if(which === 'anchor') {
400 element: anchorElement,
401 offset: selection.anchorOffset,
402 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
403 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
406 if(which === 'focus') {
408 element: focusElement,
409 offset: selection.focusOffset,
410 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
411 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
415 var getPlaceData = function(anchorFirst) {
418 if(which === 'start') {
419 element = anchorElement;
420 offset = selection.anchorOffset;
422 else if(which === 'end') {
423 element = focusElement;
424 offset = selection.focusOffset;
427 if(which === 'start') {
428 element = focusElement;
429 offset = selection.focusOffset;
431 else if(which === 'end') {
432 element = anchorElement;
433 offset = selection.anchorOffset;
436 return {element: element, offset: offset};
439 var anchorFirst, placeData, parent;
441 if(anchorElement.parent().sameNode(focusElement.parent())) {
442 parent = anchorElement.parent();
443 if(selection.anchorNode === selection.focusNode) {
444 anchorFirst = selection.anchorOffset <= selection.focusOffset;
446 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
448 placeData = getPlaceData(anchorFirst);
450 /*jshint bitwise: false*/
451 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
452 placeData = getPlaceData(anchorFirst);
455 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
457 element: placeData.element,
458 offset: placeData.offset,
459 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
460 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
466 fromXMLDocument: function(wlxmlDocument, publisher) {
467 return new Canvas(wlxmlDocument, publisher);