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 'modules/documentCanvas/canvas/selection',
15 'libs/text!./canvas.html'
16 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement, gutter, selection, canvasTemplate) {
19 /* global document:false, window:false, Node:false, gettext */
21 var logger = logging.getLogger('canvas');
23 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
24 $.extend(TextHandler.prototype, {
25 handle: function(node, text) {
26 this.setText(text, node);
31 // if(this.node.sameNode(node)) {
39 _ping: _.throttle(function(text) {
44 if(this.buffer !== null) {
45 this.setText(this.buffer, this.node);
49 setText: function(text, node) {
50 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
51 node.document.transaction(function() {
55 description: gettext('Changing text')
64 var Canvas = function(wlxmlDocument, elements, metadata) {
65 this.metadata = metadata || {};
66 this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
69 {tag: 'section', klass: null, prototype: genericElement},
70 {tag: 'div', klass: null, prototype: genericElement},
71 {tag: 'header', klass: null, prototype: genericElement},
72 {tag: 'span', klass: null, prototype: genericElement},
73 {tag: 'aside', klass: null, prototype: genericElement}
74 ].concat(elements || []);
76 (elements).forEach(function(elementDesc) {
77 this.elementsRegister.register(elementDesc);
79 this.eventBus = _.extend({}, Backbone.Events);
81 this.dom = $(canvasTemplate);
82 this.rootWrapper = this.dom.find('.root-wrapper');
85 this.gutter = gutter.create();
86 this.gutterView = new gutter.GutterView(this.gutter);
87 this.dom.find('.view-row').append(this.gutterView.dom);
89 this.wlxmlListener = wlxmlListener.create(this);
90 this.loadWlxmlDocument(wlxmlDocument);
91 this.setupEventHandling();
92 this.textHandler = new TextHandler(this);
95 $.extend(Canvas.prototype, Backbone.Events, {
97 getElementOffset: function(element) {
98 return element.dom.offset().top - this.dom.offset().top;
101 loadWlxmlDocument: function(wlxmlDocument) {
106 this.wlxmlListener.listenTo(wlxmlDocument);
107 this.wlxmlDocument = wlxmlDocument;
111 createElement: function(wlxmlNode) {
113 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
114 Factory = documentElement.DocumentTextElement;
116 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
118 return new Factory(wlxmlNode, this);
121 getDocumentElement: function(htmlElement) {
122 /* globals HTMLElement, Text */
123 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
126 var $element = $(htmlElement);
127 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
128 return $element.data('canvas-element');
131 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
132 $element = $element.parent();
135 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
136 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
137 return $element.data('canvas-element');
141 reloadRoot: function() {
142 if(this.rootElement) {
143 this.rootElement.detach();
145 this.rootElement = this.createElement(this.wlxmlDocument.root);
146 this.rootWrapper.append(this.rootElement.dom);
150 triggerKeyEvent: function(keyEvent, selection) {
151 selection = selection || this.getSelection();
152 if(selection && (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()) {
153 keyboard.handleKeyEvent(keyEvent, selection);
157 setupEventHandling: function() {
160 /* globals document */
161 $(document.body).on('keydown', function(e) {
162 var cursor = canvas.getCursor();
163 if(cursor.isSelecting() || Object.keys(cursor.getPosition()).length) {
164 keyboard.handleKey(e, canvas);
168 this.rootWrapper.on('mouseup', function() {
169 canvas.triggerSelectionChanged();
173 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
174 mouseDown = e.target;
175 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
178 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
179 var position, element;
181 if(e.originalEvent.detail === 3) {
183 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
185 if(mouseDown === e.target) {
186 element = canvas.getDocumentElement(e.target);
187 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
188 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
189 canvas.setCurrentElement(element);
193 if(window.getSelection().isCollapsed) {
194 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
195 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
201 this.rootWrapper.on('paste', function(e) {
204 var clipboardData = e.originalEvent.clipboardData;
205 if(!clipboardData || !clipboardData.getData) {
206 return; // TODO: alert
209 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
210 cursor = canvas.getCursor(),
211 element = cursor.getPosition().element,
214 if(element && cursor.isWithinElement()) {
215 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
216 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
217 element.setText(lhs+text+rhs);
218 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
220 /* jshint noempty:false */
225 /* globals MutationObserver */
226 var observer = new MutationObserver(function(mutations) {
227 mutations.forEach(function(mutation) {
228 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
229 observer.disconnect();
230 if(mutation.target.data === '') {
231 mutation.target.data = utils.unicode.ZWS;
233 else if(mutation.oldValue === utils.unicode.ZWS) {
234 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
235 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
237 observer.observe(canvas.dom[0], config);
239 var textElement = canvas.getDocumentElement(mutation.target),
240 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
242 //textElement.data('wlxmlNode').setText(toSet);
243 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
244 if(textElement.wlxmlNode.getText() !== toSet) {
245 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
250 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
251 observer.observe(this.rootWrapper[0], config);
254 var hoverHandler = function(e) {
255 var el = canvas.getDocumentElement(e.currentTarget),
264 if(el instanceof documentElement.DocumentTextElement) {
267 el.updateState({exposed:expose[e.type]});
270 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
271 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
273 this.eventBus.on('elementToggled', function(toggle, element) {
275 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
285 return this.rootElement;
288 toggleElementHighlight: function(node, toggle) {
289 var element = utils.getElementForNode(node);
290 element.updateState({exposed: toggle});
293 getCursor: function() {
294 return new Cursor(this);
298 getCurrentNodeElement: function() {
299 return this.currentNodeElement;
302 getCurrentTextElement: function() {
303 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
305 return this.getDocumentElement(htmlElement);
309 getPreviousTextElement: function(relativeToElement, includeInvisible) {
310 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
313 getNextTextElement: function(relativeToElement, includeInvisible) {
314 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
317 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
318 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
319 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
320 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
323 contains: function(element) {
324 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
327 triggerSelectionChanged: function() {
328 var s = this.getSelection(),
333 this.trigger('selectionChanged', s);
334 f = s.toDocumentFragment();
336 if(f && f instanceof f.RangeFragment) {
337 if(this.currentNodeElement) {
338 this.currentNodeElement.updateState({active: false});
339 this.currentNodeElement = null;
344 getSelection: function() {
345 return selection.fromNativeSelection(this);
348 select: function(fragment) {
349 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
350 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
351 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
353 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
355 this.setCurrentElement(fragment.node, params);
357 logger.debug('Fragment not supported');
361 setSelection: function(selection) {
362 this.select(this, selection.toDocumentFragment());
365 createSelection: function(params) {
366 return selection.fromParams(this, params);
368 setCurrentElement: function(element, params) {
370 logger.debug('Invalid element passed to setCurrentElement: ' + element);
374 if(!(element instanceof documentElement.DocumentElement)) {
375 element = utils.getElementForNode(element);
378 if(!element || !this.contains(element)) {
379 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
383 params = _.extend({caretTo: 'end'}, params);
384 var findFirstDirectTextChild = function(e, nodeToLand) {
385 var byBrowser = this.getCursor().getPosition().element;
386 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
389 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
391 var _markAsCurrent = function(element) {
392 if(element instanceof documentElement.DocumentTextElement) {
393 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
394 element.dom.addClass('current-text-element');
396 if(this.currentNodeElement) {
397 this.currentNodeElement.updateState({active: false});
399 element.updateState({active: true});
400 this.currentNodeElement = element;
405 var isTextElement = element instanceof documentElement.DocumentTextElement,
406 nodeElementToLand = isTextElement ? element.parent() : element,
407 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
408 currentTextElement = this.getCurrentTextElement(),
409 currentNodeElement = this.getCurrentNodeElement();
411 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
412 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
415 if(textElementToLand) {
416 _markAsCurrent(textElementToLand);
417 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
418 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
421 document.getSelection().removeAllRanges();
424 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
425 _markAsCurrent(nodeElementToLand);
427 this.triggerSelectionChanged();
430 _moveCaretToTextElement: function(element, where) {
431 var range = document.createRange(),
432 node = element.dom.contents()[0];
434 if(typeof where !== 'number') {
435 range.selectNodeContents(node);
437 range.setStart(node, Math.min(node.data.length, where));
440 if(where !== 'whole') {
441 var collapseArg = true;
442 if(where === 'end') {
445 range.collapse(collapseArg);
447 var selection = document.getSelection();
449 $(node).parent().attr('contenteditable', true);
450 selection.removeAllRanges();
451 selection.addRange(range);
452 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
455 setCursorPosition: function(position) {
456 if(position.element) {
457 this._moveCaretToTextElement(position.element, position.offset);
463 var Cursor = function(canvas) {
464 this.canvas = canvas;
465 this.selection = window.getSelection();
468 $.extend(Cursor.prototype, {
469 sameAs: function(other) {
475 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
476 same = same && this.selection[prop] === other.selection[prop];
478 return true; // break
484 isSelecting: function() {
485 var selection = window.getSelection();
486 return !selection.isCollapsed;
488 isSelectingWithinElement: function() {
489 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
491 isWithinElement: function() {
492 return !this.isSelecting() || this.isSelectingWithinElement();
494 isSelectingSiblings: function() {
495 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
497 getPosition: function() {
498 return this.getSelectionAnchor();
500 getSelectionStart: function() {
501 return this.getSelectionBoundry('start');
503 getSelectionEnd: function() {
504 return this.getSelectionBoundry('end');
506 getSelectionAnchor: function() {
507 return this.getSelectionBoundry('anchor');
509 getSelectionFocus: function() {
510 return this.getSelectionBoundry('focus');
512 getSelectionBoundry: function(which) {
514 var selection = window.getSelection(),
515 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
516 focusElement = this.canvas.getDocumentElement(selection.focusNode);
518 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
522 if(which === 'anchor') {
524 element: anchorElement,
525 offset: selection.anchorOffset,
526 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
527 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
530 if(which === 'focus') {
532 element: focusElement,
533 offset: selection.focusOffset,
534 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
535 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
539 var getPlaceData = function(anchorFirst) {
542 if(which === 'start') {
543 element = anchorElement;
544 offset = selection.anchorOffset;
546 else if(which === 'end') {
547 element = focusElement;
548 offset = selection.focusOffset;
551 if(which === 'start') {
552 element = focusElement;
553 offset = selection.focusOffset;
555 else if(which === 'end') {
556 element = anchorElement;
557 offset = selection.anchorOffset;
560 return {element: element, offset: offset};
563 var anchorFirst, placeData, parent;
565 if(anchorElement.parent().sameNode(focusElement.parent())) {
566 parent = anchorElement.parent();
567 if(selection.anchorNode === selection.focusNode) {
568 anchorFirst = selection.anchorOffset <= selection.focusOffset;
570 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
572 placeData = getPlaceData(anchorFirst);
574 /*jshint bitwise: false*/
575 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
576 placeData = getPlaceData(anchorFirst);
579 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
581 element: placeData.element,
582 offset: placeData.offset,
583 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
584 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
590 fromXMLDocument: function(wlxmlDocument, elements, metadata) {
591 return new Canvas(wlxmlDocument, elements, metadata);