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();
178 (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()
179 || selection.type == 'nodeSelection')) {
180 keyboard.handleKeyEvent(keyEvent, selection);
184 createAction: function(fqName, config) {
185 return this.sandbox.createAction(fqName, config);
188 setupEventHandling: function() {
191 /* globals document */
192 $(document.body).on('keydown', function(e) {
193 canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
196 this.rootWrapper.on('mouseup', function() {
197 canvas.triggerSelectionChanged();
201 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
202 mouseDown = e.target;
203 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
206 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
207 var position, element;
209 if(e.originalEvent.detail === 3) {
211 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
213 if(mouseDown === e.target) {
214 element = canvas.getDocumentElement(e.target);
215 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
216 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
217 canvas.setCurrentElement(element);
221 if(window.getSelection().isCollapsed) {
222 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
223 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
229 this.rootWrapper.on('contextmenu', function(e) {
230 var el = canvas.getDocumentElement(e.target);
237 this.showContextMenu(el, {x: e.clientX, y: e.clientY});
240 this.rootWrapper.on('paste', function(e) {
243 var clipboardData = e.originalEvent.clipboardData;
244 if(!clipboardData || !clipboardData.getData) {
245 return; // TODO: alert
248 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
249 cursor = canvas.getCursor(),
250 element = cursor.getPosition().element,
253 if(element && cursor.isWithinElement()) {
254 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
255 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
256 element.setText(lhs+text+rhs);
257 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
259 /* jshint noempty:false */
264 /* globals MutationObserver */
265 var observer = new MutationObserver(function(mutations) {
266 mutations.forEach(function(mutation) {
267 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
268 observer.disconnect();
269 if(mutation.target.data === '') {
270 mutation.target.data = utils.unicode.ZWS;
272 else if(mutation.oldValue === utils.unicode.ZWS) {
273 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
274 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
276 observer.observe(canvas.dom[0], config);
278 var textElement = canvas.getDocumentElement(mutation.target),
279 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
281 //textElement.data('wlxmlNode').setText(toSet);
282 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
283 if(textElement.wlxmlNode.getText() !== toSet) {
284 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
289 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
290 observer.observe(this.rootWrapper[0], config);
293 var hoverHandler = function(e) {
294 var el = canvas.getDocumentElement(e.currentTarget),
303 if(el instanceof documentElement.DocumentTextElement) {
306 el.updateState({exposed:expose[e.type]});
309 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
310 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
312 this.eventBus.on('elementToggled', function(toggle, element) {
314 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
324 return this.rootElement;
327 toggleElementHighlight: function(node, toggle) {
328 var element = utils.getElementForNode(node);
329 element.updateState({exposed: toggle});
332 getCursor: function() {
333 return new Cursor(this);
337 getCurrentNodeElement: function() {
338 return this.currentNodeElement;
341 getCurrentTextElement: function() {
342 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
344 return this.getDocumentElement(htmlElement);
348 getPreviousTextElement: function(relativeToElement, includeInvisible) {
349 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
352 getNextTextElement: function(relativeToElement, includeInvisible) {
353 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
356 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
357 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
358 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
359 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
362 contains: function(element) {
363 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
366 triggerSelectionChanged: function() {
367 var s = this.getSelection(),
372 this.trigger('selectionChanged', s);
373 f = s.toDocumentFragment();
375 if(f && f instanceof f.RangeFragment) {
376 if(this.currentNodeElement) {
377 this.currentNodeElement.updateState({active: false});
378 this.currentNodeElement = null;
383 getSelection: function() {
384 return selection.fromNativeSelection(this);
387 select: function(fragment) {
388 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
389 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
390 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
392 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
394 this.setCurrentElement(fragment.node, params);
396 logger.debug('Fragment not supported');
400 setSelection: function(selection) {
401 this.select(this, selection.toDocumentFragment());
404 createSelection: function(params) {
405 return selection.fromParams(this, params);
407 setCurrentElement: function(element, params) {
409 logger.debug('Invalid element passed to setCurrentElement: ' + element);
413 if(!(element instanceof documentElement.DocumentElement)) {
414 element = utils.getElementForNode(element);
417 if(!element || !this.contains(element)) {
418 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
422 params = _.extend({caretTo: 'end'}, params);
423 var findFirstDirectTextChild = function(e, nodeToLand) {
424 var byBrowser = this.getCursor().getPosition().element;
425 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
428 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
430 var _markAsCurrent = function(element) {
431 if(element instanceof documentElement.DocumentTextElement) {
432 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
433 element.dom.addClass('current-text-element');
435 if(this.currentNodeElement) {
436 this.currentNodeElement.updateState({active: false});
438 element.updateState({active: true});
439 this.currentNodeElement = element;
444 var isTextElement = element instanceof documentElement.DocumentTextElement,
445 nodeElementToLand = isTextElement ? element.parent() : element,
446 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
447 currentTextElement = this.getCurrentTextElement(),
448 currentNodeElement = this.getCurrentNodeElement();
450 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
451 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
454 if(textElementToLand) {
455 _markAsCurrent(textElementToLand);
456 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
457 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
460 document.getSelection().removeAllRanges();
463 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
464 _markAsCurrent(nodeElementToLand);
466 this.triggerSelectionChanged();
469 _moveCaretToTextElement: function(element, where) {
470 var range = document.createRange(),
471 node = element.dom.contents()[0];
473 if(typeof where !== 'number') {
474 range.selectNodeContents(node);
476 range.setStart(node, Math.min(node.data.length, where));
479 if(where !== 'whole') {
480 var collapseArg = true;
481 if(where === 'end') {
484 range.collapse(collapseArg);
486 var selection = document.getSelection();
488 $(node).parent().attr('contenteditable', true);
489 selection.removeAllRanges();
490 selection.addRange(range);
491 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
494 setCursorPosition: function(position) {
495 if(position.element) {
496 this._moveCaretToTextElement(position.element, position.offset);
499 showContextMenu: function(element, coors) {
500 var menu = new Menu();
503 (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
504 element = element.parent();
506 if(menu.actions.length) {
507 menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
508 this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
514 var Cursor = function(canvas) {
515 this.canvas = canvas;
516 this.selection = window.getSelection();
519 $.extend(Cursor.prototype, {
520 sameAs: function(other) {
526 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
527 same = same && this.selection[prop] === other.selection[prop];
529 return true; // break
535 isSelecting: function() {
536 var selection = window.getSelection();
537 return !selection.isCollapsed;
539 isSelectingWithinElement: function() {
540 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
542 isWithinElement: function() {
543 return !this.isSelecting() || this.isSelectingWithinElement();
545 isSelectingSiblings: function() {
546 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
548 getPosition: function() {
549 return this.getSelectionAnchor();
551 getSelectionStart: function() {
552 return this.getSelectionBoundry('start');
554 getSelectionEnd: function() {
555 return this.getSelectionBoundry('end');
557 getSelectionAnchor: function() {
558 return this.getSelectionBoundry('anchor');
560 getSelectionFocus: function() {
561 return this.getSelectionBoundry('focus');
563 getSelectionBoundry: function(which) {
565 var selection = window.getSelection(),
566 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
567 focusElement = this.canvas.getDocumentElement(selection.focusNode);
569 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
573 if(which === 'anchor') {
575 element: anchorElement,
576 offset: selection.anchorOffset,
577 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
578 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
581 if(which === 'focus') {
583 element: focusElement,
584 offset: selection.focusOffset,
585 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
586 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
590 var getPlaceData = function(anchorFirst) {
593 if(which === 'start') {
594 element = anchorElement;
595 offset = selection.anchorOffset;
597 else if(which === 'end') {
598 element = focusElement;
599 offset = selection.focusOffset;
602 if(which === 'start') {
603 element = focusElement;
604 offset = selection.focusOffset;
606 else if(which === 'end') {
607 element = anchorElement;
608 offset = selection.anchorOffset;
611 return {element: element, offset: offset};
614 var anchorFirst, placeData, parent;
616 if(anchorElement.parent().sameNode(focusElement.parent())) {
617 parent = anchorElement.parent();
618 if(selection.anchorNode === selection.focusNode) {
619 anchorFirst = selection.anchorOffset <= selection.focusOffset;
621 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
623 placeData = getPlaceData(anchorFirst);
625 /*jshint bitwise: false*/
626 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
627 placeData = getPlaceData(anchorFirst);
630 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
632 element: placeData.element,
633 offset: placeData.offset,
634 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
635 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
641 fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
642 return new Canvas(wlxmlDocument, elements, metadata, sandbox);