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 getElementOffset: function(element) {
101 return element.dom.offset().top - this.dom.offset().top;
104 loadWlxmlDocument: function(wlxmlDocument) {
109 this.wlxmlListener.listenTo(wlxmlDocument);
110 this.wlxmlDocument = wlxmlDocument;
114 createElement: function(wlxmlNode, register, useRoot) {
116 register = register || this.elementsRegister;
117 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
118 Factory = documentElement.DocumentTextElement;
120 Factory = register.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
122 if(!Factory && useRoot) {
123 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
125 Factory = documentElement.DocumentNodeElement;
130 return new Factory(wlxmlNode, this);
134 createElementsRegister: function() {
135 return new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
138 getDocumentElement: function(htmlElement) {
139 /* globals HTMLElement, Text */
140 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
143 var $element = $(htmlElement);
144 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
145 return $element.data('canvas-element');
148 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
149 $element = $element.parent();
152 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
153 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
154 return $element.data('canvas-element');
158 reloadRoot: function() {
159 if(this.rootElement) {
160 this.rootElement.detach();
162 this.rootElement = this.createElement(this.wlxmlDocument.root);
163 this.rootWrapper.append(this.rootElement.dom);
166 triggerKeyEvent: function(keyEvent, selection) {
167 selection = selection || this.getSelection();
168 if(selection && (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()) {
169 keyboard.handleKeyEvent(keyEvent, selection);
173 createAction: function(fqName, config) {
174 return this.sandbox.createAction(fqName, config);
177 setupEventHandling: function() {
180 /* globals document */
181 $(document.body).on('keydown', function(e) {
182 canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
185 this.rootWrapper.on('mouseup', function() {
186 canvas.triggerSelectionChanged();
190 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
191 mouseDown = e.target;
192 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
195 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
196 var position, element;
198 if(e.originalEvent.detail === 3) {
200 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
202 if(mouseDown === e.target) {
203 element = canvas.getDocumentElement(e.target);
204 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
205 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
206 canvas.setCurrentElement(element);
210 if(window.getSelection().isCollapsed) {
211 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
212 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
218 this.rootWrapper.on('contextmenu', function(e) {
219 var el = canvas.getDocumentElement(e.target);
226 this.showContextMenu(el, {x: e.clientX, y: e.clientY});
229 this.rootWrapper.on('paste', function(e) {
232 var clipboardData = e.originalEvent.clipboardData;
233 if(!clipboardData || !clipboardData.getData) {
234 return; // TODO: alert
237 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
238 cursor = canvas.getCursor(),
239 element = cursor.getPosition().element,
242 if(element && cursor.isWithinElement()) {
243 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
244 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
245 element.setText(lhs+text+rhs);
246 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
248 /* jshint noempty:false */
253 /* globals MutationObserver */
254 var observer = new MutationObserver(function(mutations) {
255 mutations.forEach(function(mutation) {
256 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
257 observer.disconnect();
258 if(mutation.target.data === '') {
259 mutation.target.data = utils.unicode.ZWS;
261 else if(mutation.oldValue === utils.unicode.ZWS) {
262 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
263 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
265 observer.observe(canvas.dom[0], config);
267 var textElement = canvas.getDocumentElement(mutation.target),
268 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
270 //textElement.data('wlxmlNode').setText(toSet);
271 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
272 if(textElement.wlxmlNode.getText() !== toSet) {
273 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
278 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
279 observer.observe(this.rootWrapper[0], config);
282 var hoverHandler = function(e) {
283 var el = canvas.getDocumentElement(e.currentTarget),
292 if(el instanceof documentElement.DocumentTextElement) {
295 el.updateState({exposed:expose[e.type]});
298 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
299 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
301 this.eventBus.on('elementToggled', function(toggle, element) {
303 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
313 return this.rootElement;
316 toggleElementHighlight: function(node, toggle) {
317 var element = utils.getElementForNode(node);
318 element.updateState({exposed: toggle});
321 getCursor: function() {
322 return new Cursor(this);
326 getCurrentNodeElement: function() {
327 return this.currentNodeElement;
330 getCurrentTextElement: function() {
331 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
333 return this.getDocumentElement(htmlElement);
337 getPreviousTextElement: function(relativeToElement, includeInvisible) {
338 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
341 getNextTextElement: function(relativeToElement, includeInvisible) {
342 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
345 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
346 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
347 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
348 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
351 contains: function(element) {
352 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
355 triggerSelectionChanged: function() {
356 var s = this.getSelection(),
361 this.trigger('selectionChanged', s);
362 f = s.toDocumentFragment();
364 if(f && f instanceof f.RangeFragment) {
365 if(this.currentNodeElement) {
366 this.currentNodeElement.updateState({active: false});
367 this.currentNodeElement = null;
372 getSelection: function() {
373 return selection.fromNativeSelection(this);
376 select: function(fragment) {
377 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
378 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
379 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
381 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
383 this.setCurrentElement(fragment.node, params);
385 logger.debug('Fragment not supported');
389 setSelection: function(selection) {
390 this.select(this, selection.toDocumentFragment());
393 createSelection: function(params) {
394 return selection.fromParams(this, params);
396 setCurrentElement: function(element, params) {
398 logger.debug('Invalid element passed to setCurrentElement: ' + element);
402 if(!(element instanceof documentElement.DocumentElement)) {
403 element = utils.getElementForNode(element);
406 if(!element || !this.contains(element)) {
407 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
411 params = _.extend({caretTo: 'end'}, params);
412 var findFirstDirectTextChild = function(e, nodeToLand) {
413 var byBrowser = this.getCursor().getPosition().element;
414 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
417 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
419 var _markAsCurrent = function(element) {
420 if(element instanceof documentElement.DocumentTextElement) {
421 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
422 element.dom.addClass('current-text-element');
424 if(this.currentNodeElement) {
425 this.currentNodeElement.updateState({active: false});
427 element.updateState({active: true});
428 this.currentNodeElement = element;
433 var isTextElement = element instanceof documentElement.DocumentTextElement,
434 nodeElementToLand = isTextElement ? element.parent() : element,
435 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
436 currentTextElement = this.getCurrentTextElement(),
437 currentNodeElement = this.getCurrentNodeElement();
439 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
440 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
443 if(textElementToLand) {
444 _markAsCurrent(textElementToLand);
445 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
446 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
449 document.getSelection().removeAllRanges();
452 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
453 _markAsCurrent(nodeElementToLand);
455 this.triggerSelectionChanged();
458 _moveCaretToTextElement: function(element, where) {
459 var range = document.createRange(),
460 node = element.dom.contents()[0];
462 if(typeof where !== 'number') {
463 range.selectNodeContents(node);
465 range.setStart(node, Math.min(node.data.length, where));
468 if(where !== 'whole') {
469 var collapseArg = true;
470 if(where === 'end') {
473 range.collapse(collapseArg);
475 var selection = document.getSelection();
477 $(node).parent().attr('contenteditable', true);
478 selection.removeAllRanges();
479 selection.addRange(range);
480 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
483 setCursorPosition: function(position) {
484 if(position.element) {
485 this._moveCaretToTextElement(position.element, position.offset);
488 showContextMenu: function(element, coors) {
489 var menu = new Menu();
492 (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
493 element = element.parent();
495 if(menu.actions.length) {
496 menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
497 this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
503 var Cursor = function(canvas) {
504 this.canvas = canvas;
505 this.selection = window.getSelection();
508 $.extend(Cursor.prototype, {
509 sameAs: function(other) {
515 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
516 same = same && this.selection[prop] === other.selection[prop];
518 return true; // break
524 isSelecting: function() {
525 var selection = window.getSelection();
526 return !selection.isCollapsed;
528 isSelectingWithinElement: function() {
529 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
531 isWithinElement: function() {
532 return !this.isSelecting() || this.isSelectingWithinElement();
534 isSelectingSiblings: function() {
535 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
537 getPosition: function() {
538 return this.getSelectionAnchor();
540 getSelectionStart: function() {
541 return this.getSelectionBoundry('start');
543 getSelectionEnd: function() {
544 return this.getSelectionBoundry('end');
546 getSelectionAnchor: function() {
547 return this.getSelectionBoundry('anchor');
549 getSelectionFocus: function() {
550 return this.getSelectionBoundry('focus');
552 getSelectionBoundry: function(which) {
554 var selection = window.getSelection(),
555 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
556 focusElement = this.canvas.getDocumentElement(selection.focusNode);
558 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
562 if(which === 'anchor') {
564 element: anchorElement,
565 offset: selection.anchorOffset,
566 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
567 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
570 if(which === 'focus') {
572 element: focusElement,
573 offset: selection.focusOffset,
574 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
575 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
579 var getPlaceData = function(anchorFirst) {
582 if(which === 'start') {
583 element = anchorElement;
584 offset = selection.anchorOffset;
586 else if(which === 'end') {
587 element = focusElement;
588 offset = selection.focusOffset;
591 if(which === 'start') {
592 element = focusElement;
593 offset = selection.focusOffset;
595 else if(which === 'end') {
596 element = anchorElement;
597 offset = selection.anchorOffset;
600 return {element: element, offset: offset};
603 var anchorFirst, placeData, parent;
605 if(anchorElement.parent().sameNode(focusElement.parent())) {
606 parent = anchorElement.parent();
607 if(selection.anchorNode === selection.focusNode) {
608 anchorFirst = selection.anchorOffset <= selection.focusOffset;
610 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
612 placeData = getPlaceData(anchorFirst);
614 /*jshint bitwise: false*/
615 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
616 placeData = getPlaceData(anchorFirst);
619 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
621 element: placeData.element,
622 offset: placeData.offset,
623 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
624 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
630 fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
631 return new Canvas(wlxmlDocument, elements, metadata, sandbox);