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 reloadRoot: function() {
168 if(this.rootElement) {
169 this.rootElement.detach();
171 this.rootElement = this.createElement(this.wlxmlDocument.root);
172 this.rootWrapper.append(this.rootElement.dom);
175 triggerKeyEvent: function(keyEvent, selection) {
176 selection = selection || this.getSelection();
177 if(selection && (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()) {
178 keyboard.handleKeyEvent(keyEvent, selection);
182 createAction: function(fqName, config) {
183 return this.sandbox.createAction(fqName, config);
186 setupEventHandling: function() {
189 /* globals document */
190 $(document.body).on('keydown', function(e) {
191 canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
194 this.rootWrapper.on('mouseup', function() {
195 canvas.triggerSelectionChanged();
199 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
200 mouseDown = e.target;
201 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
204 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
205 var position, element;
207 if(e.originalEvent.detail === 3) {
209 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
211 if(mouseDown === e.target) {
212 element = canvas.getDocumentElement(e.target);
213 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
214 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
215 canvas.setCurrentElement(element);
219 if(window.getSelection().isCollapsed) {
220 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
221 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
227 this.rootWrapper.on('contextmenu', function(e) {
228 var el = canvas.getDocumentElement(e.target);
235 this.showContextMenu(el, {x: e.clientX, y: e.clientY});
238 this.rootWrapper.on('paste', function(e) {
241 var clipboardData = e.originalEvent.clipboardData;
242 if(!clipboardData || !clipboardData.getData) {
243 return; // TODO: alert
246 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
247 cursor = canvas.getCursor(),
248 element = cursor.getPosition().element,
251 if(element && cursor.isWithinElement()) {
252 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
253 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
254 element.setText(lhs+text+rhs);
255 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
257 /* jshint noempty:false */
262 /* globals MutationObserver */
263 var observer = new MutationObserver(function(mutations) {
264 mutations.forEach(function(mutation) {
265 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
266 observer.disconnect();
267 if(mutation.target.data === '') {
268 mutation.target.data = utils.unicode.ZWS;
270 else if(mutation.oldValue === utils.unicode.ZWS) {
271 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
272 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
274 observer.observe(canvas.dom[0], config);
276 var textElement = canvas.getDocumentElement(mutation.target),
277 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
279 //textElement.data('wlxmlNode').setText(toSet);
280 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
281 if(textElement.wlxmlNode.getText() !== toSet) {
282 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
287 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
288 observer.observe(this.rootWrapper[0], config);
291 var hoverHandler = function(e) {
292 var el = canvas.getDocumentElement(e.currentTarget),
301 if(el instanceof documentElement.DocumentTextElement) {
304 el.updateState({exposed:expose[e.type]});
307 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
308 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
310 this.eventBus.on('elementToggled', function(toggle, element) {
312 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
322 return this.rootElement;
325 toggleElementHighlight: function(node, toggle) {
326 var element = utils.getElementForNode(node);
327 element.updateState({exposed: toggle});
330 getCursor: function() {
331 return new Cursor(this);
335 getCurrentNodeElement: function() {
336 return this.currentNodeElement;
339 getCurrentTextElement: function() {
340 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
342 return this.getDocumentElement(htmlElement);
346 getPreviousTextElement: function(relativeToElement, includeInvisible) {
347 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
350 getNextTextElement: function(relativeToElement, includeInvisible) {
351 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
354 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
355 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
356 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
357 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
360 contains: function(element) {
361 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
364 triggerSelectionChanged: function() {
365 var s = this.getSelection(),
370 this.trigger('selectionChanged', s);
371 f = s.toDocumentFragment();
373 if(f && f instanceof f.RangeFragment) {
374 if(this.currentNodeElement) {
375 this.currentNodeElement.updateState({active: false});
376 this.currentNodeElement = null;
381 getSelection: function() {
382 return selection.fromNativeSelection(this);
385 select: function(fragment) {
386 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
387 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
388 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
390 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
392 this.setCurrentElement(fragment.node, params);
394 logger.debug('Fragment not supported');
398 setSelection: function(selection) {
399 this.select(this, selection.toDocumentFragment());
402 createSelection: function(params) {
403 return selection.fromParams(this, params);
405 setCurrentElement: function(element, params) {
407 logger.debug('Invalid element passed to setCurrentElement: ' + element);
411 if(!(element instanceof documentElement.DocumentElement)) {
412 element = utils.getElementForNode(element);
415 if(!element || !this.contains(element)) {
416 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
420 params = _.extend({caretTo: 'end'}, params);
421 var findFirstDirectTextChild = function(e, nodeToLand) {
422 var byBrowser = this.getCursor().getPosition().element;
423 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
426 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
428 var _markAsCurrent = function(element) {
429 if(element instanceof documentElement.DocumentTextElement) {
430 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
431 element.dom.addClass('current-text-element');
433 if(this.currentNodeElement) {
434 this.currentNodeElement.updateState({active: false});
436 element.updateState({active: true});
437 this.currentNodeElement = element;
442 var isTextElement = element instanceof documentElement.DocumentTextElement,
443 nodeElementToLand = isTextElement ? element.parent() : element,
444 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
445 currentTextElement = this.getCurrentTextElement(),
446 currentNodeElement = this.getCurrentNodeElement();
448 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
449 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
452 if(textElementToLand) {
453 _markAsCurrent(textElementToLand);
454 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
455 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
458 document.getSelection().removeAllRanges();
461 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
462 _markAsCurrent(nodeElementToLand);
464 this.triggerSelectionChanged();
467 _moveCaretToTextElement: function(element, where) {
468 var range = document.createRange(),
469 node = element.dom.contents()[0];
471 if(typeof where !== 'number') {
472 range.selectNodeContents(node);
474 range.setStart(node, Math.min(node.data.length, where));
477 if(where !== 'whole') {
478 var collapseArg = true;
479 if(where === 'end') {
482 range.collapse(collapseArg);
484 var selection = document.getSelection();
486 $(node).parent().attr('contenteditable', true);
487 selection.removeAllRanges();
488 selection.addRange(range);
489 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
492 setCursorPosition: function(position) {
493 if(position.element) {
494 this._moveCaretToTextElement(position.element, position.offset);
497 showContextMenu: function(element, coors) {
498 var menu = new Menu();
501 (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
502 element = element.parent();
504 if(menu.actions.length) {
505 menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
506 this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
512 var Cursor = function(canvas) {
513 this.canvas = canvas;
514 this.selection = window.getSelection();
517 $.extend(Cursor.prototype, {
518 sameAs: function(other) {
524 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
525 same = same && this.selection[prop] === other.selection[prop];
527 return true; // break
533 isSelecting: function() {
534 var selection = window.getSelection();
535 return !selection.isCollapsed;
537 isSelectingWithinElement: function() {
538 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
540 isWithinElement: function() {
541 return !this.isSelecting() || this.isSelectingWithinElement();
543 isSelectingSiblings: function() {
544 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
546 getPosition: function() {
547 return this.getSelectionAnchor();
549 getSelectionStart: function() {
550 return this.getSelectionBoundry('start');
552 getSelectionEnd: function() {
553 return this.getSelectionBoundry('end');
555 getSelectionAnchor: function() {
556 return this.getSelectionBoundry('anchor');
558 getSelectionFocus: function() {
559 return this.getSelectionBoundry('focus');
561 getSelectionBoundry: function(which) {
563 var selection = window.getSelection(),
564 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
565 focusElement = this.canvas.getDocumentElement(selection.focusNode);
567 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
571 if(which === 'anchor') {
573 element: anchorElement,
574 offset: selection.anchorOffset,
575 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
576 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
579 if(which === 'focus') {
581 element: focusElement,
582 offset: selection.focusOffset,
583 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
584 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
588 var getPlaceData = function(anchorFirst) {
591 if(which === 'start') {
592 element = anchorElement;
593 offset = selection.anchorOffset;
595 else if(which === 'end') {
596 element = focusElement;
597 offset = selection.focusOffset;
600 if(which === 'start') {
601 element = focusElement;
602 offset = selection.focusOffset;
604 else if(which === 'end') {
605 element = anchorElement;
606 offset = selection.anchorOffset;
609 return {element: element, offset: offset};
612 var anchorFirst, placeData, parent;
614 if(anchorElement.parent().sameNode(focusElement.parent())) {
615 parent = anchorElement.parent();
616 if(selection.anchorNode === selection.focusNode) {
617 anchorFirst = selection.anchorOffset <= selection.focusOffset;
619 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
621 placeData = getPlaceData(anchorFirst);
623 /*jshint bitwise: false*/
624 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
625 placeData = getPlaceData(anchorFirst);
628 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
630 element: placeData.element,
631 offset: placeData.offset,
632 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
633 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
639 fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
640 return new Canvas(wlxmlDocument, elements, metadata, sandbox);