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) {
168 if(e.originalEvent.detail === 3) {
170 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
172 if(mouseDown === e.target) {
173 if(window.getSelection().isCollapsed) {
174 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
175 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
181 this.rootWrapper.on('paste', function(e) {
184 var clipboardData = e.originalEvent.clipboardData;
185 if(!clipboardData || !clipboardData.getData) {
186 return; // TODO: alert
189 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
190 cursor = canvas.getCursor(),
191 element = cursor.getPosition().element,
194 if(element && cursor.isWithinElement()) {
195 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
196 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
197 element.setText(lhs+text+rhs);
198 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
200 /* jshint noempty:false */
205 /* globals MutationObserver */
206 var observer = new MutationObserver(function(mutations) {
207 mutations.forEach(function(mutation) {
208 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
209 observer.disconnect();
210 if(mutation.target.data === '') {
211 mutation.target.data = utils.unicode.ZWS;
213 else if(mutation.oldValue === utils.unicode.ZWS) {
214 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
215 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
217 observer.observe(canvas.dom[0], config);
219 var textElement = canvas.getDocumentElement(mutation.target),
220 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
222 //textElement.data('wlxmlNode').setText(toSet);
223 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
224 if(textElement.wlxmlNode.getText() !== toSet) {
225 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
230 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
231 observer.observe(this.rootWrapper[0], config);
234 var hoverHandler = function(e) {
235 var el = canvas.getDocumentElement(e.currentTarget),
244 if(el instanceof documentElement.DocumentTextElement) {
247 el.updateState({exposed:expose[e.type]});
250 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
251 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
253 this.eventBus.on('elementToggled', function(toggle, element) {
255 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
265 return this.rootElement;
268 toggleElementHighlight: function(node, toggle) {
269 var element = utils.getElementForNode(node);
270 element.updateState({exposed: toggle});
273 getCursor: function() {
274 return new Cursor(this);
278 getCurrentNodeElement: function() {
279 return this.currentNodeElement;
282 getCurrentTextElement: function() {
283 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
285 return this.getDocumentElement(htmlElement);
289 getPreviousTextElement: function(relativeToElement, includeInvisible) {
290 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
293 getNextTextElement: function(relativeToElement, includeInvisible) {
294 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
297 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
298 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
299 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
300 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
303 contains: function(element) {
304 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
307 triggerSelectionChanged: function() {
308 this.trigger('selectionChanged', this.getSelection());
309 var s = this.getSelection(),
310 f = s.toDocumentFragment();
311 if(f && f instanceof f.RangeFragment) {
312 if(this.currentNodeElement) {
313 this.currentNodeElement.updateState({active: false});
314 this.currentNodeElement = null;
319 getSelection: function() {
320 return new Selection(this);
323 select: function(fragment) {
324 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
325 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
326 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
328 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
330 this.setCurrentElement(fragment.node, params);
332 logger.debug('Fragment not supported');
336 setCurrentElement: function(element, params) {
338 logger.debug('Invalid element passed to setCurrentElement: ' + element);
342 if(!(element instanceof documentElement.DocumentElement)) {
343 element = utils.getElementForNode(element);
346 if(!element || !this.contains(element)) {
347 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
351 params = _.extend({caretTo: 'end'}, params);
352 var findFirstDirectTextChild = function(e, nodeToLand) {
353 var byBrowser = this.getCursor().getPosition().element;
354 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
357 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
359 var _markAsCurrent = function(element) {
360 if(element instanceof documentElement.DocumentTextElement) {
361 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
362 element.dom.addClass('current-text-element');
364 if(this.currentNodeElement) {
365 this.currentNodeElement.updateState({active: false});
367 element.updateState({active: true});
368 this.currentNodeElement = element;
373 var isTextElement = element instanceof documentElement.DocumentTextElement,
374 nodeElementToLand = isTextElement ? element.parent() : element,
375 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
376 currentTextElement = this.getCurrentTextElement(),
377 currentNodeElement = this.getCurrentNodeElement();
379 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
380 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
383 if(textElementToLand) {
384 _markAsCurrent(textElementToLand);
385 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
386 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
389 document.getSelection().removeAllRanges();
392 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
393 _markAsCurrent(nodeElementToLand);
395 this.triggerSelectionChanged();
398 _moveCaretToTextElement: function(element, where) {
399 var range = document.createRange(),
400 node = element.dom.contents()[0];
402 if(typeof where !== 'number') {
403 range.selectNodeContents(node);
405 range.setStart(node, Math.min(node.data.length, where));
408 if(where !== 'whole') {
409 var collapseArg = true;
410 if(where === 'end') {
413 range.collapse(collapseArg);
415 var selection = document.getSelection();
417 $(node).parent().attr('contenteditable', true);
418 selection.removeAllRanges();
419 selection.addRange(range);
420 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
423 setCursorPosition: function(position) {
424 if(position.element) {
425 this._moveCaretToTextElement(position.element, position.offset);
431 var isText = function(node) {
432 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
435 var Selection = function(canvas) {
436 this.canvas = canvas;
437 var nativeSelection = this.nativeSelection = window.getSelection();
438 Object.defineProperty(this, 'type', {
440 if(nativeSelection.focusNode) {
441 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
444 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
445 return 'textSelection';
448 if(canvas.getCurrentNodeElement()) {
455 $.extend(Selection.prototype, {
456 toDocumentFragment: function() {
457 var doc = this.canvas.wlxmlDocument,
458 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
459 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
460 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
461 focusNode = focusElement ? focusElement.wlxmlNode : null;
462 if(this.type === 'caret') {
463 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
465 if(this.type === 'textSelection') {
466 if(!anchorNode || !focusNode) {
469 if(anchorNode.isSiblingOf(focusNode)) {
470 return doc.createFragment(doc.TextRangeFragment, {
472 offset1: this.nativeSelection.anchorOffset,
474 offset2: this.nativeSelection.focusOffset,
478 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
479 return doc.createFragment(doc.RangeFragment, {
480 node1: siblingParents.node1,
481 node2: siblingParents.node2
485 if(this.type === 'node') {
486 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
489 sameAs: function(other) {
494 var Cursor = function(canvas) {
495 this.canvas = canvas;
496 this.selection = window.getSelection();
499 $.extend(Cursor.prototype, {
500 sameAs: function(other) {
506 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
507 same = same && this.selection[prop] === other.selection[prop];
509 return true; // break
515 isSelecting: function() {
516 var selection = window.getSelection();
517 return !selection.isCollapsed;
519 isSelectingWithinElement: function() {
520 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
522 isWithinElement: function() {
523 return !this.isSelecting() || this.isSelectingWithinElement();
525 isSelectingSiblings: function() {
526 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
528 getPosition: function() {
529 return this.getSelectionAnchor();
531 getSelectionStart: function() {
532 return this.getSelectionBoundry('start');
534 getSelectionEnd: function() {
535 return this.getSelectionBoundry('end');
537 getSelectionAnchor: function() {
538 return this.getSelectionBoundry('anchor');
540 getSelectionFocus: function() {
541 return this.getSelectionBoundry('focus');
543 getSelectionBoundry: function(which) {
545 var selection = window.getSelection(),
546 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
547 focusElement = this.canvas.getDocumentElement(selection.focusNode);
549 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
553 if(which === 'anchor') {
555 element: anchorElement,
556 offset: selection.anchorOffset,
557 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
558 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
561 if(which === 'focus') {
563 element: focusElement,
564 offset: selection.focusOffset,
565 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
566 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
570 var getPlaceData = function(anchorFirst) {
573 if(which === 'start') {
574 element = anchorElement;
575 offset = selection.anchorOffset;
577 else if(which === 'end') {
578 element = focusElement;
579 offset = selection.focusOffset;
582 if(which === 'start') {
583 element = focusElement;
584 offset = selection.focusOffset;
586 else if(which === 'end') {
587 element = anchorElement;
588 offset = selection.anchorOffset;
591 return {element: element, offset: offset};
594 var anchorFirst, placeData, parent;
596 if(anchorElement.parent().sameNode(focusElement.parent())) {
597 parent = anchorElement.parent();
598 if(selection.anchorNode === selection.focusNode) {
599 anchorFirst = selection.anchorOffset <= selection.focusOffset;
601 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
603 placeData = getPlaceData(anchorFirst);
605 /*jshint bitwise: false*/
606 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
607 placeData = getPlaceData(anchorFirst);
610 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
612 element: placeData.element,
613 offset: placeData.offset,
614 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
615 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
621 fromXMLDocument: function(wlxmlDocument, elements, metadata) {
622 return new Canvas(wlxmlDocument, elements, metadata);