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) {
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.textHandler = new TextHandler(this);
61 $.extend(Canvas.prototype, Backbone.Events, {
63 loadWlxmlDocument: function(wlxmlDocument) {
68 this.wlxmlListener.listenTo(wlxmlDocument);
69 this.wlxmlDocument = wlxmlDocument;
73 createElement: function(wlxmlNode) {
74 var Factory = wlxmlNode.nodeType === Node.TEXT_NODE ? documentElement.DocumentTextElement : documentElement.DocumentNodeElement;
75 return new Factory(wlxmlNode, this);
78 getDocumentElement: function(htmlElement) {
79 /* globals HTMLElement, Text */
80 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
83 var $element = $(htmlElement);
84 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
85 return $element.data('canvas-element');
88 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
89 $element = $element.parent();
92 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
93 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
94 return $element.data('canvas-element');
98 reloadRoot: function() {
99 this.rootElement = this.createElement(this.wlxmlDocument.root);
100 this.wrapper.empty();
101 this.wrapper.append(this.rootElement.dom());
104 setupEventHandling: function() {
107 this.wrapper.on('keyup keydown keypress', function(e) {
108 keyboard.handleKey(e, canvas);
111 this.wrapper.on('mouseup', function() {
112 canvas.triggerSelectionChanged();
116 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
117 mouseDown = e.target;
120 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
122 if(e.originalEvent.detail === 3) {
124 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
126 if(mouseDown === e.target) {
127 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
132 this.wrapper.on('paste', function(e) {
135 var clipboardData = e.originalEvent.clipboardData;
136 if(!clipboardData || !clipboardData.getData) {
137 return; // TODO: alert
140 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
141 cursor = canvas.getCursor(),
142 element = cursor.getPosition().element,
145 if(element && cursor.isWithinElement()) {
146 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
147 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
148 element.setText(lhs+text+rhs);
149 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
151 /* jshint noempty:false */
156 /* globals MutationObserver */
157 var observer = new MutationObserver(function(mutations) {
158 mutations.forEach(function(mutation) {
159 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
160 observer.disconnect();
161 if(mutation.target.data === '') {
162 mutation.target.data = utils.unicode.ZWS;
164 else if(mutation.oldValue === utils.unicode.ZWS) {
165 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
166 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
168 observer.observe(canvas.wrapper[0], config);
170 var textElement = canvas.getDocumentElement(mutation.target),
171 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
173 //textElement.data('wlxmlNode').setText(toSet);
174 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
175 if(textElement.wlxmlNode.getText() !== toSet) {
176 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
181 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
182 observer.observe(this.wrapper[0], config);
185 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
186 var el = canvas.getDocumentElement(e.currentTarget);
191 if(el instanceof documentElement.DocumentTextElement) {
194 el.toggleLabel(true);
196 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
197 var el = canvas.getDocumentElement(e.currentTarget);
202 if(el instanceof documentElement.DocumentTextElement) {
205 el.toggleLabel(false);
208 this.eventBus.on('elementToggled', function(toggle, element) {
210 canvas.setCurrentElement(element.getPreviousTextElement());
220 return this.rootElement;
223 toggleElementHighlight: function(node, toggle) {
224 var element = utils.findCanvasElement(node);
225 element.toggleHighlight(toggle);
228 getCursor: function() {
229 return new Cursor(this);
233 getCurrentNodeElement: function() {
234 var htmlElement = this.wrapper.find('.current-node-element').parent()[0];
236 return this.getDocumentElement(htmlElement);
240 getCurrentTextElement: function() {
241 var htmlElement = this.wrapper.find('.current-text-element')[0];
243 return this.getDocumentElement(htmlElement);
247 contains: function(element) {
248 return element.dom().parents().index(this.wrapper) !== -1;
251 triggerSelectionChanged: function() {
252 this.trigger('selectionChanged', this.getSelection());
255 getSelection: function() {
256 return new Selection(this);
259 setCurrentElement: function(element, params) {
261 logger.debug('Invalid element passed to setCurrentElement: ' + element);
265 if(!(element instanceof documentElement.DocumentElement)) {
266 element = utils.findCanvasElement(element);
269 if(!element || !this.contains(element)) {
270 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
274 params = _.extend({caretTo: 'end'}, params);
275 var findFirstDirectTextChild = function(e, nodeToLand) {
276 var byBrowser = this.getCursor().getPosition().element;
277 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
280 var children = e.children();
281 for(var i = 0; i < children.length; i++) {
282 if(children[i] instanceof documentElement.DocumentTextElement) {
288 var _markAsCurrent = function(element) {
289 if(element instanceof documentElement.DocumentTextElement) {
290 this.wrapper.find('.current-text-element').removeClass('current-text-element');
291 element.dom().addClass('current-text-element');
293 this.wrapper.find('.current-node-element').removeClass('current-node-element');
294 element._container().addClass('current-node-element');
299 var isTextElement = element instanceof documentElement.DocumentTextElement,
300 nodeElementToLand = isTextElement ? element.parent() : element,
301 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
302 currentTextElement = this.getCurrentTextElement(),
303 currentNodeElement = this.getCurrentNodeElement();
305 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
306 this.wrapper.find('.current-text-element').removeClass('current-text-element');
309 if(textElementToLand) {
310 _markAsCurrent(textElementToLand);
311 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
312 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
315 document.getSelection().removeAllRanges();
318 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
319 _markAsCurrent(nodeElementToLand);
321 this.triggerSelectionChanged();
324 _moveCaretToTextElement: function(element, where) {
325 var range = document.createRange(),
326 node = element.dom().contents()[0];
328 if(typeof where !== 'number') {
329 range.selectNodeContents(node);
331 range.setStart(node, Math.min(node.data.length, where));
334 if(where !== 'whole') {
335 var collapseArg = true;
336 if(where === 'end') {
339 range.collapse(collapseArg);
341 var selection = document.getSelection();
343 selection.removeAllRanges();
344 selection.addRange(range);
345 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
348 setCursorPosition: function(position) {
349 if(position.element) {
350 this._moveCaretToTextElement(position.element, position.offset);
354 findCanvasElement: function(node) {
355 return utils.findCanvasElement(node);
358 toggleGrid: function() {
359 this.wrapper.toggleClass('grid-on');
360 this.trigger('changed');
362 isGridToggled: function() {
363 return this.wrapper.hasClass('grid-on');
368 var isText = function(node) {
369 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
372 var Selection = function(canvas) {
373 this.canvas = canvas;
374 var nativeSelection = this.nativeSelection = window.getSelection();
375 Object.defineProperty(this, 'type', {
377 if(nativeSelection.focusNode) {
378 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
381 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
382 return 'textSelection';
385 if(canvas.getCurrentNodeElement()) {
392 $.extend(Selection.prototype, {
393 toDocumentFragment: function() {
394 var doc = this.canvas.wlxmlDocument,
395 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
396 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
397 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
398 focusNode = focusElement ? focusElement.wlxmlNode : null;
399 if(this.type === 'caret') {
400 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
402 if(this.type === 'textSelection') {
403 if(anchorNode.isSiblingOf(focusNode)) {
404 return doc.createFragment(doc.TextRangeFragment, {
406 offset1: this.nativeSelection.anchorOffset,
408 offset2: this.nativeSelection.focusOffset,
412 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
413 return doc.createFragment(doc.RangeFragment, {
414 node1: siblingParents.node1,
415 node2: siblingParents.node2
419 if(this.type === 'node') {
420 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
423 sameAs: function(other) {
428 var Cursor = function(canvas) {
429 this.canvas = canvas;
430 this.selection = window.getSelection();
433 $.extend(Cursor.prototype, {
434 sameAs: function(other) {
440 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
441 same = same && this.selection[prop] === other.selection[prop];
443 return true; // break
449 isSelecting: function() {
450 var selection = window.getSelection();
451 return !selection.isCollapsed;
453 isSelectingWithinElement: function() {
454 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
456 isWithinElement: function() {
457 return !this.isSelecting() || this.isSelectingWithinElement();
459 isSelectingSiblings: function() {
460 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
462 getPosition: function() {
463 return this.getSelectionAnchor();
465 getSelectionStart: function() {
466 return this.getSelectionBoundry('start');
468 getSelectionEnd: function() {
469 return this.getSelectionBoundry('end');
471 getSelectionAnchor: function() {
472 return this.getSelectionBoundry('anchor');
474 getSelectionFocus: function() {
475 return this.getSelectionBoundry('focus');
477 getSelectionBoundry: function(which) {
479 var selection = window.getSelection(),
480 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
481 focusElement = this.canvas.getDocumentElement(selection.focusNode);
483 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
487 if(which === 'anchor') {
489 element: anchorElement,
490 offset: selection.anchorOffset,
491 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
492 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
495 if(which === 'focus') {
497 element: focusElement,
498 offset: selection.focusOffset,
499 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
500 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
504 var getPlaceData = function(anchorFirst) {
507 if(which === 'start') {
508 element = anchorElement;
509 offset = selection.anchorOffset;
511 else if(which === 'end') {
512 element = focusElement;
513 offset = selection.focusOffset;
516 if(which === 'start') {
517 element = focusElement;
518 offset = selection.focusOffset;
520 else if(which === 'end') {
521 element = anchorElement;
522 offset = selection.anchorOffset;
525 return {element: element, offset: offset};
528 var anchorFirst, placeData, parent;
530 if(anchorElement.parent().sameNode(focusElement.parent())) {
531 parent = anchorElement.parent();
532 if(selection.anchorNode === selection.focusNode) {
533 anchorFirst = selection.anchorOffset <= selection.focusOffset;
535 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
537 placeData = getPlaceData(anchorFirst);
539 /*jshint bitwise: false*/
540 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
541 placeData = getPlaceData(anchorFirst);
544 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
546 element: placeData.element,
547 offset: placeData.offset,
548 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
549 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
555 fromXMLDocument: function(wlxmlDocument) {
556 return new Canvas(wlxmlDocument);