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 'modules/documentCanvas/canvas/elementsRegister',
11 'modules/documentCanvas/canvas/genericElement',
12 'modules/documentCanvas/canvas/nullElement',
13 'modules/documentCanvas/canvas/gutter',
14 'libs/text!./canvas.html'
15 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement, gutter, canvasTemplate) {
18 /* global document:false, window:false, Node:false, gettext */
20 var logger = logging.getLogger('canvas');
22 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
23 $.extend(TextHandler.prototype, {
24 handle: function(node, text) {
25 this.setText(text, node);
30 // if(this.node.sameNode(node)) {
38 _ping: _.throttle(function(text) {
43 if(this.buffer !== null) {
44 this.setText(this.buffer, this.node);
48 setText: function(text, node) {
49 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
50 node.document.transaction(function() {
54 description: gettext('Changing text')
63 var Canvas = function(wlxmlDocument, elements, metadata) {
64 this.metadata = metadata || {};
65 this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
68 {tag: 'section', klass: null, prototype: genericElement},
69 {tag: 'div', klass: null, prototype: genericElement},
70 {tag: 'header', klass: null, prototype: genericElement},
71 {tag: 'span', klass: null, prototype: genericElement},
72 {tag: 'aside', klass: null, prototype: genericElement}
73 ].concat(elements || []);
75 (elements).forEach(function(elementDesc) {
76 this.elementsRegister.register(elementDesc);
78 this.eventBus = _.extend({}, Backbone.Events);
80 this.dom = $(canvasTemplate);
81 this.rootWrapper = this.dom.find('.root-wrapper');
84 this.gutter = gutter.create();
85 this.gutterView = new gutter.GutterView(this.gutter);
86 this.dom.find('.view-row').append(this.gutterView.dom);
88 this.wlxmlListener = wlxmlListener.create(this);
89 this.loadWlxmlDocument(wlxmlDocument);
90 this.setupEventHandling();
91 this.textHandler = new TextHandler(this);
94 $.extend(Canvas.prototype, Backbone.Events, {
96 getElementOffset: function(element) {
97 return element.dom.offset().top - this.dom.offset().top;
100 loadWlxmlDocument: function(wlxmlDocument) {
105 this.wlxmlListener.listenTo(wlxmlDocument);
106 this.wlxmlDocument = wlxmlDocument;
110 createElement: function(wlxmlNode) {
112 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
113 Factory = documentElement.DocumentTextElement;
115 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
117 return new Factory(wlxmlNode, this);
120 getDocumentElement: function(htmlElement) {
121 /* globals HTMLElement, Text */
122 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
125 var $element = $(htmlElement);
126 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
127 return $element.data('canvas-element');
130 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
131 $element = $element.parent();
134 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
135 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
136 return $element.data('canvas-element');
140 reloadRoot: function() {
141 if(this.rootElement) {
142 this.rootElement.detach();
144 this.rootElement = this.createElement(this.wlxmlDocument.root);
145 this.rootWrapper.append(this.rootElement.dom);
148 setupEventHandling: function() {
151 this.rootWrapper.on('keyup keydown keypress', function(e) {
152 keyboard.handleKey(e, canvas);
155 this.rootWrapper.on('mouseup', function() {
156 canvas.triggerSelectionChanged();
160 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
161 mouseDown = e.target;
162 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
165 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
166 var position, element;
168 if(e.originalEvent.detail === 3) {
170 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
172 if(mouseDown === e.target) {
173 element = canvas.getDocumentElement(e.target);
174 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
175 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
176 canvas.setCurrentElement(element);
180 if(window.getSelection().isCollapsed) {
181 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
182 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
188 this.rootWrapper.on('paste', function(e) {
191 var clipboardData = e.originalEvent.clipboardData;
192 if(!clipboardData || !clipboardData.getData) {
193 return; // TODO: alert
196 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
197 cursor = canvas.getCursor(),
198 element = cursor.getPosition().element,
201 if(element && cursor.isWithinElement()) {
202 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
203 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
204 element.setText(lhs+text+rhs);
205 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
207 /* jshint noempty:false */
212 /* globals MutationObserver */
213 var observer = new MutationObserver(function(mutations) {
214 mutations.forEach(function(mutation) {
215 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
216 observer.disconnect();
217 if(mutation.target.data === '') {
218 mutation.target.data = utils.unicode.ZWS;
220 else if(mutation.oldValue === utils.unicode.ZWS) {
221 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
222 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
224 observer.observe(canvas.dom[0], config);
226 var textElement = canvas.getDocumentElement(mutation.target),
227 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
229 //textElement.data('wlxmlNode').setText(toSet);
230 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
231 if(textElement.wlxmlNode.getText() !== toSet) {
232 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
237 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
238 observer.observe(this.rootWrapper[0], config);
241 var hoverHandler = function(e) {
242 var el = canvas.getDocumentElement(e.currentTarget),
251 if(el instanceof documentElement.DocumentTextElement) {
254 el.updateState({exposed:expose[e.type]});
257 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
258 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
260 this.eventBus.on('elementToggled', function(toggle, element) {
262 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
272 return this.rootElement;
275 toggleElementHighlight: function(node, toggle) {
276 var element = utils.getElementForNode(node);
277 element.updateState({exposed: toggle});
280 getCursor: function() {
281 return new Cursor(this);
285 getCurrentNodeElement: function() {
286 return this.currentNodeElement;
289 getCurrentTextElement: function() {
290 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
292 return this.getDocumentElement(htmlElement);
296 getPreviousTextElement: function(relativeToElement, includeInvisible) {
297 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
300 getNextTextElement: function(relativeToElement, includeInvisible) {
301 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
304 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
305 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
306 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
307 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
310 contains: function(element) {
311 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
314 triggerSelectionChanged: function() {
315 this.trigger('selectionChanged', this.getSelection());
316 var s = this.getSelection(),
317 f = s.toDocumentFragment();
318 if(f && f instanceof f.RangeFragment) {
319 if(this.currentNodeElement) {
320 this.currentNodeElement.updateState({active: false});
321 this.currentNodeElement = null;
326 getSelection: function() {
327 return new Selection(this);
330 select: function(fragment) {
331 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
332 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
333 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
335 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
337 this.setCurrentElement(fragment.node, params);
339 logger.debug('Fragment not supported');
343 setCurrentElement: function(element, params) {
345 logger.debug('Invalid element passed to setCurrentElement: ' + element);
349 if(!(element instanceof documentElement.DocumentElement)) {
350 element = utils.getElementForNode(element);
353 if(!element || !this.contains(element)) {
354 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
358 params = _.extend({caretTo: 'end'}, params);
359 var findFirstDirectTextChild = function(e, nodeToLand) {
360 var byBrowser = this.getCursor().getPosition().element;
361 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
364 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
366 var _markAsCurrent = function(element) {
367 if(element instanceof documentElement.DocumentTextElement) {
368 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
369 element.dom.addClass('current-text-element');
371 if(this.currentNodeElement) {
372 this.currentNodeElement.updateState({active: false});
374 element.updateState({active: true});
375 this.currentNodeElement = element;
380 var isTextElement = element instanceof documentElement.DocumentTextElement,
381 nodeElementToLand = isTextElement ? element.parent() : element,
382 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
383 currentTextElement = this.getCurrentTextElement(),
384 currentNodeElement = this.getCurrentNodeElement();
386 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
387 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
390 if(textElementToLand) {
391 _markAsCurrent(textElementToLand);
392 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
393 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
396 document.getSelection().removeAllRanges();
399 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
400 _markAsCurrent(nodeElementToLand);
402 this.triggerSelectionChanged();
405 _moveCaretToTextElement: function(element, where) {
406 var range = document.createRange(),
407 node = element.dom.contents()[0];
409 if(typeof where !== 'number') {
410 range.selectNodeContents(node);
412 range.setStart(node, Math.min(node.data.length, where));
415 if(where !== 'whole') {
416 var collapseArg = true;
417 if(where === 'end') {
420 range.collapse(collapseArg);
422 var selection = document.getSelection();
424 $(node).parent().attr('contenteditable', true);
425 selection.removeAllRanges();
426 selection.addRange(range);
427 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
430 setCursorPosition: function(position) {
431 if(position.element) {
432 this._moveCaretToTextElement(position.element, position.offset);
438 var isText = function(node) {
439 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
442 var Selection = function(canvas) {
443 this.canvas = canvas;
444 var nativeSelection = this.nativeSelection = window.getSelection();
445 Object.defineProperty(this, 'type', {
447 if(nativeSelection.focusNode) {
448 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
451 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
452 return 'textSelection';
455 if(canvas.getCurrentNodeElement()) {
462 $.extend(Selection.prototype, {
463 toDocumentFragment: function() {
464 var doc = this.canvas.wlxmlDocument,
465 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
466 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
467 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
468 focusNode = focusElement ? focusElement.wlxmlNode : null;
469 if(this.type === 'caret') {
470 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
472 if(this.type === 'textSelection') {
473 if(!anchorNode || !focusNode) {
476 if(anchorNode.isSiblingOf(focusNode)) {
477 return doc.createFragment(doc.TextRangeFragment, {
479 offset1: this.nativeSelection.anchorOffset,
481 offset2: this.nativeSelection.focusOffset,
485 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
486 return doc.createFragment(doc.RangeFragment, {
487 node1: siblingParents.node1,
488 node2: siblingParents.node2
492 if(this.type === 'node') {
493 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
496 sameAs: function(other) {
501 var Cursor = function(canvas) {
502 this.canvas = canvas;
503 this.selection = window.getSelection();
506 $.extend(Cursor.prototype, {
507 sameAs: function(other) {
513 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
514 same = same && this.selection[prop] === other.selection[prop];
516 return true; // break
522 isSelecting: function() {
523 var selection = window.getSelection();
524 return !selection.isCollapsed;
526 isSelectingWithinElement: function() {
527 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
529 isWithinElement: function() {
530 return !this.isSelecting() || this.isSelectingWithinElement();
532 isSelectingSiblings: function() {
533 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
535 getPosition: function() {
536 return this.getSelectionAnchor();
538 getSelectionStart: function() {
539 return this.getSelectionBoundry('start');
541 getSelectionEnd: function() {
542 return this.getSelectionBoundry('end');
544 getSelectionAnchor: function() {
545 return this.getSelectionBoundry('anchor');
547 getSelectionFocus: function() {
548 return this.getSelectionBoundry('focus');
550 getSelectionBoundry: function(which) {
552 var selection = window.getSelection(),
553 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
554 focusElement = this.canvas.getDocumentElement(selection.focusNode);
556 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
560 if(which === 'anchor') {
562 element: anchorElement,
563 offset: selection.anchorOffset,
564 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
565 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
568 if(which === 'focus') {
570 element: focusElement,
571 offset: selection.focusOffset,
572 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
573 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
577 var getPlaceData = function(anchorFirst) {
580 if(which === 'start') {
581 element = anchorElement;
582 offset = selection.anchorOffset;
584 else if(which === 'end') {
585 element = focusElement;
586 offset = selection.focusOffset;
589 if(which === 'start') {
590 element = focusElement;
591 offset = selection.focusOffset;
593 else if(which === 'end') {
594 element = anchorElement;
595 offset = selection.anchorOffset;
598 return {element: element, offset: offset};
601 var anchorFirst, placeData, parent;
603 if(anchorElement.parent().sameNode(focusElement.parent())) {
604 parent = anchorElement.parent();
605 if(selection.anchorNode === selection.focusNode) {
606 anchorFirst = selection.anchorOffset <= selection.focusOffset;
608 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
610 placeData = getPlaceData(anchorFirst);
612 /*jshint bitwise: false*/
613 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
614 placeData = getPlaceData(anchorFirst);
617 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
619 element: placeData.element,
620 offset: placeData.offset,
621 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
622 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
628 fromXMLDocument: function(wlxmlDocument, elements, metadata) {
629 return new Canvas(wlxmlDocument, elements, metadata);