5 'fnpjs/logging/logging',
7 'modules/documentCanvas/canvas/documentElement',
8 'modules/documentCanvas/canvas/keyboard',
9 'modules/documentCanvas/canvas/utils',
10 'modules/documentCanvas/canvas/wlxmlListener',
11 'modules/documentCanvas/canvas/elementsRegister',
12 'modules/documentCanvas/canvas/genericElement',
13 'modules/documentCanvas/canvas/nullElement',
14 'modules/documentCanvas/canvas/gutter',
15 'modules/documentCanvas/canvas/selection',
16 'modules/documentCanvas/canvas/keyEvent',
17 'libs/text!./canvas.html'
18 ], function($, _, Backbone, logging, Menu, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement, gutter, selection, keyEvent, canvasTemplate) {
21 /* global document:false, window:false, Node:false, gettext */
23 var logger = logging.getLogger('canvas');
25 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
26 $.extend(TextHandler.prototype, {
27 handle: function(node, text) {
28 this.setText(text, node);
33 // if(this.node.sameNode(node)) {
41 _ping: _.throttle(function(text) {
46 if(this.buffer !== null) {
47 this.setText(this.buffer, this.node);
51 setText: function(text, node) {
52 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
53 node.document.transaction(function() {
57 description: gettext('Changing text')
66 var Canvas = function(wlxmlDocument, elements, metadata, sandbox) {
67 this.metadata = metadata || {};
68 this.sandbox = sandbox;
69 this.elementsRegister = this.createElementsRegister();
72 {tag: 'section', klass: null, prototype: genericElement},
73 {tag: 'div', klass: null, prototype: genericElement},
74 {tag: 'header', klass: null, prototype: genericElement},
75 {tag: 'span', klass: null, prototype: genericElement},
76 {tag: 'aside', klass: null, prototype: genericElement}
77 ].concat(elements || []);
79 (elements).forEach(function(elementDesc) {
80 this.elementsRegister.register(elementDesc);
82 this.eventBus = _.extend({}, Backbone.Events);
84 this.dom = $(canvasTemplate);
85 this.rootWrapper = this.dom.find('.root-wrapper');
88 this.gutter = gutter.create();
89 this.gutterView = new gutter.GutterView(this.gutter);
90 this.dom.find('.view-row').append(this.gutterView.dom);
92 this.wlxmlListener = wlxmlListener.create(this);
93 this.loadWlxmlDocument(wlxmlDocument);
94 this.setupEventHandling();
95 this.textHandler = new TextHandler(this);
98 $.extend(Canvas.prototype, Backbone.Events, {
100 createElementType: function(elementPrototype) {
101 /* TODO: reconcile this with ElementsRegister behavior */
102 var Constructor = function() {
103 documentElement.DocumentNodeElement.apply(this, Array.prototype.slice.call(arguments, 0));
105 Constructor.prototype = elementPrototype;
109 getElementOffset: function(element) {
110 return element.dom.offset().top - this.dom.offset().top;
113 loadWlxmlDocument: function(wlxmlDocument) {
118 this.wlxmlListener.listenTo(wlxmlDocument);
119 this.wlxmlDocument = wlxmlDocument;
123 createElement: function(wlxmlNode, register, useRoot) {
125 register = register || this.elementsRegister;
126 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
127 Factory = documentElement.DocumentTextElement;
129 Factory = register.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
131 if(!Factory && useRoot) {
132 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
134 Factory = documentElement.DocumentNodeElement;
139 return new Factory(wlxmlNode, this);
143 createElementsRegister: function() {
144 return new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
147 getDocumentElement: function(htmlElement) {
148 /* globals HTMLElement, Text */
149 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
152 var $element = $(htmlElement);
153 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
154 return $element.data('canvas-element');
157 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
158 $element = $element.parent();
161 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
162 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
163 return $element.data('canvas-element');
167 if($element.parent().data('canvas-element')) {
168 return $element.parent().data('canvas-element');
172 reloadRoot: function() {
173 if(this.rootElement) {
174 this.rootElement.detach();
176 this.rootElement = this.createElement(this.wlxmlDocument.root);
177 this.rootWrapper.append(this.rootElement.dom);
180 triggerKeyEvent: function(keyEvent, selection) {
181 selection = selection || this.getSelection();
183 (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()
184 || selection.type == 'nodeSelection')) {
185 keyboard.handleKeyEvent(keyEvent, selection);
189 createAction: function(fqName, config) {
190 return this.sandbox.createAction(fqName, config);
193 setupEventHandling: function() {
196 /* globals document */
197 $(document.body).on('keydown', function(e) {
198 canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
201 this.rootWrapper.on('mouseup', function() {
202 canvas.triggerSelectionChanged();
206 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
207 mouseDown = e.target;
208 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
211 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
212 var position, element;
214 if(e.originalEvent.detail === 3) {
216 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
218 if(mouseDown === e.target) {
219 element = canvas.getDocumentElement(e.target);
220 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
221 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
222 canvas.setCurrentElement(element);
226 if(window.getSelection().isCollapsed) {
227 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
228 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
234 this.rootWrapper.on('contextmenu', function(e) {
235 var el = canvas.getDocumentElement(e.target);
242 this.showContextMenu(el, {x: e.clientX, y: e.clientY});
245 this.rootWrapper.on('paste', function(e) {
248 var clipboardData = e.originalEvent.clipboardData;
249 if(!clipboardData || !clipboardData.getData) {
250 return; // TODO: alert
253 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
254 cursor = canvas.getCursor(),
255 element = cursor.getPosition().element,
258 if(element && cursor.isWithinElement()) {
259 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
260 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
261 element.setText(lhs+text+rhs);
262 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
264 /* jshint noempty:false */
269 /* globals MutationObserver */
270 var observer = new MutationObserver(function(mutations) {
271 mutations.forEach(function(mutation) {
272 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
273 observer.disconnect();
274 if(mutation.target.data === '') {
275 mutation.target.data = utils.unicode.ZWS;
277 if(mutation.target.data === mutation.oldValue) {
278 return; // shouldn't happen, but better be safe
280 if(mutation.oldValue === utils.unicode.ZWS) {
281 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
282 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
284 observer.observe(canvas.dom[0], config);
286 var textElement = canvas.getDocumentElement(mutation.target),
287 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
289 //textElement.data('wlxmlNode').setText(toSet);
290 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
291 if(textElement.wlxmlNode.getText() !== toSet) {
292 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
297 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
298 observer.observe(this.rootWrapper[0], config);
301 var hoverHandler = function(e) {
302 var el = canvas.getDocumentElement(e.currentTarget),
311 if(el instanceof documentElement.DocumentTextElement) {
314 el.updateState({exposed:expose[e.type]});
317 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
318 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
320 this.eventBus.on('elementToggled', function(toggle, element) {
322 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
332 return this.rootElement;
335 toggleElementHighlight: function(node, toggle) {
336 var element = utils.getElementForNode(node);
337 element.updateState({exposed: toggle});
340 getCursor: function() {
341 return new Cursor(this);
345 getCurrentNodeElement: function() {
346 return this.currentNodeElement;
349 getCurrentTextElement: function() {
350 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
352 return this.getDocumentElement(htmlElement);
356 getPreviousTextElement: function(relativeToElement, includeInvisible) {
357 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
360 getNextTextElement: function(relativeToElement, includeInvisible) {
361 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
364 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
365 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
366 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
367 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
370 contains: function(element) {
371 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
374 triggerSelectionChanged: function() {
375 var s = this.getSelection(),
380 this.trigger('selectionChanged', s);
381 f = s.toDocumentFragment();
383 if(f && f instanceof f.RangeFragment) {
384 if(this.currentNodeElement) {
385 this.currentNodeElement.updateState({active: false});
386 this.currentNodeElement = null;
391 getSelection: function() {
392 return selection.fromNativeSelection(this);
395 select: function(fragment) {
396 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
397 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
398 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
400 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
402 this.setCurrentElement(fragment.node, params);
404 logger.debug('Fragment not supported');
408 setSelection: function(selection) {
409 this.select(this, selection.toDocumentFragment());
412 createSelection: function(params) {
413 return selection.fromParams(this, params);
415 setCurrentElement: function(element, params) {
417 logger.debug('Invalid element passed to setCurrentElement: ' + element);
421 if(!(element instanceof documentElement.DocumentElement)) {
422 element = utils.getElementForNode(element);
425 if(!element || !this.contains(element)) {
426 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
430 params = _.extend({caretTo: 'end'}, params);
431 var findFirstDirectTextChild = function(e, nodeToLand) {
432 var byBrowser = this.getCursor().getPosition().element;
433 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
436 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
438 var _markAsCurrent = function(element) {
439 if(element instanceof documentElement.DocumentTextElement) {
440 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
441 element.dom.addClass('current-text-element');
443 if(this.currentNodeElement) {
444 this.currentNodeElement.updateState({active: false});
446 element.updateState({active: true});
447 this.currentNodeElement = element;
452 var isTextElement = element instanceof documentElement.DocumentTextElement,
453 nodeElementToLand = isTextElement ? element.parent() : element,
454 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
455 currentTextElement = this.getCurrentTextElement(),
456 currentNodeElement = this.getCurrentNodeElement();
458 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
459 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
462 if(textElementToLand) {
463 _markAsCurrent(textElementToLand);
464 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
465 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
468 document.getSelection().removeAllRanges();
471 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
472 _markAsCurrent(nodeElementToLand);
474 this.triggerSelectionChanged();
477 _moveCaretToTextElement: function(element, where) {
478 var range = document.createRange(),
479 node = element.dom.contents()[0];
481 if(typeof where !== 'number') {
482 range.selectNodeContents(node);
484 range.setStart(node, Math.min(node.data.length, where));
487 if(where !== 'whole') {
488 var collapseArg = true;
489 if(where === 'end') {
492 range.collapse(collapseArg);
494 var selection = document.getSelection();
496 $(node).parent().attr('contenteditable', true);
497 selection.removeAllRanges();
498 selection.addRange(range);
499 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
502 setCursorPosition: function(position) {
503 if(position.element) {
504 this._moveCaretToTextElement(position.element, position.offset);
507 showContextMenu: function(element, coors) {
508 var menu = new Menu();
511 (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
512 element = element.parent();
514 if(menu.actions.length) {
515 menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
516 this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
522 var Cursor = function(canvas) {
523 this.canvas = canvas;
524 this.selection = window.getSelection();
527 $.extend(Cursor.prototype, {
528 sameAs: function(other) {
534 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
535 same = same && this.selection[prop] === other.selection[prop];
537 return true; // break
543 isSelecting: function() {
544 var selection = window.getSelection();
545 return !selection.isCollapsed;
547 isSelectingWithinElement: function() {
548 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
550 isWithinElement: function() {
551 return !this.isSelecting() || this.isSelectingWithinElement();
553 isSelectingSiblings: function() {
554 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
556 getPosition: function() {
557 return this.getSelectionAnchor();
559 getSelectionStart: function() {
560 return this.getSelectionBoundary('start');
562 getSelectionEnd: function() {
563 return this.getSelectionBoundary('end');
565 getSelectionAnchor: function() {
566 return this.getSelectionBoundary('anchor');
568 getSelectionFocus: function() {
569 return this.getSelectionBoundary('focus');
571 getSelectionBoundary: function(which) {
573 var selection = window.getSelection(),
574 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
575 focusElement = this.canvas.getDocumentElement(selection.focusNode);
577 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
581 if(which === 'anchor') {
583 element: anchorElement,
584 offset: selection.anchorOffset,
585 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
586 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
589 if(which === 'focus') {
591 element: focusElement,
592 offset: selection.focusOffset,
593 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
594 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
598 var getPlaceData = function(anchorFirst) {
601 if(which === 'start') {
602 element = anchorElement;
603 offset = selection.anchorOffset;
605 else if(which === 'end') {
606 element = focusElement;
607 offset = selection.focusOffset;
610 if(which === 'start') {
611 element = focusElement;
612 offset = selection.focusOffset;
614 else if(which === 'end') {
615 element = anchorElement;
616 offset = selection.anchorOffset;
619 return {element: element, offset: offset};
622 var anchorFirst, placeData, parent;
624 if(anchorElement.parent().sameNode(focusElement.parent())) {
625 parent = anchorElement.parent();
626 if(selection.anchorNode === selection.focusNode) {
627 anchorFirst = selection.anchorOffset <= selection.focusOffset;
629 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
631 placeData = getPlaceData(anchorFirst);
633 /*jshint bitwise: false*/
634 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
635 placeData = getPlaceData(anchorFirst);
638 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
640 element: placeData.element,
641 offset: placeData.offset,
642 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
643 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
649 fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
650 return new Canvas(wlxmlDocument, elements, metadata, sandbox);