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) {
 
  12 /* global document:false, window:false, Node:false */
 
  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);
 
  23         // if(this.node.sameNode(node)) {
 
  31     _ping: _.throttle(function(text) {
 
  36         if(this.buffer !== null) {
 
  37             this.setText(this.buffer, this.node);
 
  41     setText: function(text, node) {
 
  42         //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
 
  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);
 
  60 $.extend(Canvas.prototype, {
 
  62     loadWlxmlDocument: function(wlxmlDocument) {
 
  67         this.wlxmlListener.listenTo(wlxmlDocument);
 
  68         this.wlxmlDocument = wlxmlDocument;
 
  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);
 
  77         this.wrapper.append(canvasDOM);
 
  78         this.d = this.wrapper.children(0);
 
  81     generateCanvasDOM: function(wlxmlNode) {
 
  82         var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
 
  86     setupEventHandling: function() {
 
  88         this.wrapper.on('keyup keydown keypress', function(e) {
 
  89             keyboard.handleKey(e, this);
 
  92         this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
 
  94             canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
 
  97         this.wrapper.on('paste', function(e) {
 
 100             var clipboardData = e.originalEvent.clipboardData;
 
 101             if(!clipboardData || !clipboardData.getData) {
 
 102                 return; // TODO: alert
 
 105             var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
 
 106                 cursor = canvas.getCursor(),
 
 107                 element = cursor.getPosition().element,
 
 110             if(element && cursor.isWithinElement()) {
 
 111                 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
 
 112                 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
 
 113                 element.setText(lhs+text+rhs);
 
 114                 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
 
 116                 /* jshint noempty:false */
 
 121         /* globals MutationObserver */
 
 122         var observer = new MutationObserver(function(mutations) {
 
 123             mutations.forEach(function(mutation) {
 
 124                 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
 
 125                     observer.disconnect();
 
 126                     if(mutation.target.data === '') {
 
 127                         mutation.target.data = utils.unicode.ZWS;
 
 129                     else if(mutation.oldValue === utils.unicode.ZWS) {
 
 130                         mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
 
 131                         canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
 
 133                     observer.observe(canvas.wrapper[0], config);
 
 134                     canvas.publisher('contentChanged');
 
 136                     var textElement = canvas.getDocumentElement(mutation.target),
 
 137                         toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
 
 139                     //textElement.data('wlxmlNode').setText(toSet);
 
 140                     //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
 
 141                     if(textElement.data('wlxmlNode').getText() !== toSet) {
 
 142                         canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
 
 147         var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
 
 148         observer.observe(this.wrapper[0], config);
 
 151         this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
 
 152             var el = canvas.getDocumentElement(e.currentTarget);
 
 157             if(el instanceof documentElement.DocumentTextElement) {
 
 160             el.toggleLabel(true);
 
 162         this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
 
 163             var el = canvas.getDocumentElement(e.currentTarget);
 
 168             if(el instanceof documentElement.DocumentTextElement) {
 
 171             el.toggleLabel(false);
 
 174         this.eventBus.on('elementToggled', function(toggle, element) {
 
 176                 canvas.setCurrentElement(element.getPreviousTextElement());
 
 186         if(this.d === null) {
 
 189         return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
 
 192     toggleElementHighlight: function(node, toggle) {
 
 193         var element = utils.findCanvasElement(node);
 
 194         element.toggleHighlight(toggle);
 
 197     createNodeElement: function(params) {
 
 198         return documentElement.DocumentNodeElement.create(params, this);
 
 201     getDocumentElement: function(from) {
 
 202         /* globals HTMLElement, Text */
 
 203         if(from instanceof HTMLElement || from instanceof Text) {
 
 204            return documentElement.DocumentElement.fromHTMLElement(from, this);
 
 207     getCursor: function() {
 
 208         return new Cursor(this);
 
 212     getCurrentNodeElement: function() {
 
 213         return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
 
 216     getCurrentTextElement: function() {
 
 217         return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
 
 222     setCurrentElement: function(element, params) {
 
 223         if(!(element instanceof documentElement.DocumentElement)) {
 
 224             element = utils.findCanvasElement(element);
 
 227         params = _.extend({caretTo: 'end'}, params);
 
 228         var findFirstDirectTextChild = function(e, nodeToLand) {
 
 229             var byBrowser = this.getCursor().getPosition().element;
 
 230             if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
 
 233             var children = e.children();
 
 234             for(var i = 0; i < children.length; i++) {
 
 235                 if(children[i] instanceof documentElement.DocumentTextElement) {
 
 241         var _markAsCurrent = function(element) {
 
 242             if(element instanceof documentElement.DocumentTextElement) {
 
 243                 this.wrapper.find('.current-text-element').removeClass('current-text-element');
 
 244                 element.dom().addClass('current-text-element');
 
 246                 this.wrapper.find('.current-node-element').removeClass('current-node-element');
 
 247                 element._container().addClass('current-node-element');
 
 248                 this.publisher('currentElementChanged', element);
 
 253         var isTextElement = element instanceof documentElement.DocumentTextElement,
 
 254             nodeElementToLand = isTextElement ? element.parent() : element,
 
 255             textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
 
 256             currentTextElement = this.getCurrentTextElement(),
 
 257             currentNodeElement = this.getCurrentNodeElement();
 
 259         if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
 
 260             this.wrapper.find('.current-text-element').removeClass('current-text-element');
 
 263         if(textElementToLand) {
 
 264             _markAsCurrent(textElementToLand);
 
 265             if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
 
 266                 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
 
 268             if(!(textElementToLand.sameNode(currentTextElement))) {
 
 269                 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
 
 272             document.getSelection().removeAllRanges();
 
 275         if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
 
 276             _markAsCurrent(nodeElementToLand);
 
 278             this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
 
 282     _moveCaretToTextElement: function(element, where) {
 
 283         var range = document.createRange(),
 
 284             node = element.dom().contents()[0];
 
 286         if(typeof where !== 'number') {
 
 287             range.selectNodeContents(node);
 
 289             range.setStart(node, where);
 
 292         var collapseArg = true;
 
 293         if(where === 'end') {
 
 296         range.collapse(collapseArg);
 
 298         var selection = document.getSelection();
 
 300         selection.removeAllRanges();
 
 301         selection.addRange(range);
 
 302         this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
 
 305     setCursorPosition: function(position) {
 
 306         if(position.element) {
 
 307             this._moveCaretToTextElement(position.element, position.offset);
 
 313 var Cursor = function(canvas) {
 
 314     this.canvas = canvas;
 
 317 $.extend(Cursor.prototype, {
 
 318     isSelecting: function() {
 
 319         var selection = window.getSelection();
 
 320         return !selection.isCollapsed;
 
 322     isSelectingWithinElement: function() {
 
 323         return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
 
 325     isWithinElement: function() {
 
 326         return !this.isSelecting() || this.isSelectingWithinElement();
 
 328     isSelectingSiblings: function() {
 
 329         return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
 
 331     getPosition: function() {
 
 332         return this.getSelectionAnchor();
 
 334     getSelectionStart: function() {
 
 335         return this.getSelectionBoundry('start');
 
 337     getSelectionEnd: function() {
 
 338         return this.getSelectionBoundry('end');
 
 340     getSelectionAnchor: function() {
 
 341         return this.getSelectionBoundry('anchor');
 
 343     getSelectionFocus: function() {
 
 344         return this.getSelectionBoundry('focus');
 
 346     getSelectionBoundry: function(which) {
 
 348         var selection = window.getSelection(),
 
 349             anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
 
 350             focusElement = this.canvas.getDocumentElement(selection.focusNode);
 
 352         if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
 
 356         if(which === 'anchor') {
 
 358                 element: anchorElement,
 
 359                 offset: selection.anchorOffset,
 
 360                 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
 
 361                 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
 
 364         if(which === 'focus') {
 
 366                 element: focusElement,
 
 367                 offset: selection.focusOffset,
 
 368                 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
 
 369                 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
 
 373         var getPlaceData = function(anchorFirst) {
 
 376                 if(which === 'start') {
 
 377                     element = anchorElement;
 
 378                     offset = selection.anchorOffset;
 
 380                 else if(which === 'end') {
 
 381                     element = focusElement;
 
 382                     offset = selection.focusOffset;
 
 385                 if(which === 'start') {
 
 386                     element = focusElement;
 
 387                     offset = selection.focusOffset;
 
 389                 else if(which === 'end') {
 
 390                     element = anchorElement;
 
 391                     offset = selection.anchorOffset;
 
 394             return {element: element, offset: offset};
 
 397         var anchorFirst, placeData, parent;
 
 399         if(anchorElement.parent().sameNode(focusElement.parent())) {
 
 400             parent = anchorElement.parent();
 
 401             if(selection.anchorNode === selection.focusNode) {
 
 402                 anchorFirst = selection.anchorOffset <= selection.focusOffset;
 
 404                 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
 
 406             placeData = getPlaceData(anchorFirst);
 
 408             /*jshint bitwise: false*/
 
 409             anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
 
 410             placeData = getPlaceData(anchorFirst);
 
 413         var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
 
 415             element: placeData.element,
 
 416             offset: placeData.offset,
 
 417             offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
 
 418             offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
 
 424     fromXMLDocument: function(wlxmlDocument, publisher) {
 
 425         return new Canvas(wlxmlDocument, publisher);