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();
182 if(selection && (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()) {
183 keyboard.handleKeyEvent(keyEvent, selection);
187 createAction: function(fqName, config) {
188 return this.sandbox.createAction(fqName, config);
191 setupEventHandling: function() {
194 /* globals document */
195 $(document.body).on('keydown', function(e) {
196 canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
199 this.rootWrapper.on('mouseup', function() {
200 canvas.triggerSelectionChanged();
204 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
205 mouseDown = e.target;
206 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
209 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
210 var position, element;
212 if(e.originalEvent.detail === 3) {
214 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
216 if(mouseDown === e.target) {
217 element = canvas.getDocumentElement(e.target);
218 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
219 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
220 canvas.setCurrentElement(element);
224 if(window.getSelection().isCollapsed) {
225 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
226 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
232 this.rootWrapper.on('contextmenu', function(e) {
233 var el = canvas.getDocumentElement(e.target);
240 this.showContextMenu(el, {x: e.clientX, y: e.clientY});
243 this.rootWrapper.on('paste', function(e) {
246 var clipboardData = e.originalEvent.clipboardData;
247 if(!clipboardData || !clipboardData.getData) {
248 return; // TODO: alert
251 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
252 cursor = canvas.getCursor(),
253 element = cursor.getPosition().element,
256 if(element && cursor.isWithinElement()) {
257 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
258 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
259 element.setText(lhs+text+rhs);
260 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
262 /* jshint noempty:false */
267 /* globals MutationObserver */
268 var observer = new MutationObserver(function(mutations) {
269 mutations.forEach(function(mutation) {
270 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
271 observer.disconnect();
272 if(mutation.target.data === '') {
273 mutation.target.data = utils.unicode.ZWS;
275 else if(mutation.oldValue === utils.unicode.ZWS) {
276 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
277 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
279 observer.observe(canvas.dom[0], config);
281 var textElement = canvas.getDocumentElement(mutation.target),
282 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
284 //textElement.data('wlxmlNode').setText(toSet);
285 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
286 if(textElement.wlxmlNode.getText() !== toSet) {
287 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
292 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
293 observer.observe(this.rootWrapper[0], config);
296 var hoverHandler = function(e) {
297 var el = canvas.getDocumentElement(e.currentTarget),
306 if(el instanceof documentElement.DocumentTextElement) {
309 el.updateState({exposed:expose[e.type]});
312 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
313 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
315 this.eventBus.on('elementToggled', function(toggle, element) {
317 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
327 return this.rootElement;
330 toggleElementHighlight: function(node, toggle) {
331 var element = utils.getElementForNode(node);
332 element.updateState({exposed: toggle});
335 getCursor: function() {
336 return new Cursor(this);
340 getCurrentNodeElement: function() {
341 return this.currentNodeElement;
344 getCurrentTextElement: function() {
345 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
347 return this.getDocumentElement(htmlElement);
351 getPreviousTextElement: function(relativeToElement, includeInvisible) {
352 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
355 getNextTextElement: function(relativeToElement, includeInvisible) {
356 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
359 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
360 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
361 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
362 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
365 contains: function(element) {
366 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
369 triggerSelectionChanged: function() {
370 var s = this.getSelection(),
375 this.trigger('selectionChanged', s);
376 f = s.toDocumentFragment();
378 if(f && f instanceof f.RangeFragment) {
379 if(this.currentNodeElement) {
380 this.currentNodeElement.updateState({active: false});
381 this.currentNodeElement = null;
386 getSelection: function() {
387 return selection.fromNativeSelection(this);
390 select: function(fragment) {
391 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
392 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
393 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
395 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
397 this.setCurrentElement(fragment.node, params);
399 logger.debug('Fragment not supported');
403 setSelection: function(selection) {
404 this.select(this, selection.toDocumentFragment());
407 createSelection: function(params) {
408 return selection.fromParams(this, params);
410 setCurrentElement: function(element, params) {
412 logger.debug('Invalid element passed to setCurrentElement: ' + element);
416 if(!(element instanceof documentElement.DocumentElement)) {
417 element = utils.getElementForNode(element);
420 if(!element || !this.contains(element)) {
421 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
425 params = _.extend({caretTo: 'end'}, params);
426 var findFirstDirectTextChild = function(e, nodeToLand) {
427 var byBrowser = this.getCursor().getPosition().element;
428 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
431 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
433 var _markAsCurrent = function(element) {
434 if(element instanceof documentElement.DocumentTextElement) {
435 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
436 element.dom.addClass('current-text-element');
438 if(this.currentNodeElement) {
439 this.currentNodeElement.updateState({active: false});
441 element.updateState({active: true});
442 this.currentNodeElement = element;
447 var isTextElement = element instanceof documentElement.DocumentTextElement,
448 nodeElementToLand = isTextElement ? element.parent() : element,
449 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
450 currentTextElement = this.getCurrentTextElement(),
451 currentNodeElement = this.getCurrentNodeElement();
453 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
454 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
457 if(textElementToLand) {
458 _markAsCurrent(textElementToLand);
459 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
460 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
463 document.getSelection().removeAllRanges();
466 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
467 _markAsCurrent(nodeElementToLand);
469 this.triggerSelectionChanged();
472 _moveCaretToTextElement: function(element, where) {
473 var range = document.createRange(),
474 node = element.dom.contents()[0];
476 if(typeof where !== 'number') {
477 range.selectNodeContents(node);
479 range.setStart(node, Math.min(node.data.length, where));
482 if(where !== 'whole') {
483 var collapseArg = true;
484 if(where === 'end') {
487 range.collapse(collapseArg);
489 var selection = document.getSelection();
491 $(node).parent().attr('contenteditable', true);
492 selection.removeAllRanges();
493 selection.addRange(range);
494 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
497 setCursorPosition: function(position) {
498 if(position.element) {
499 this._moveCaretToTextElement(position.element, position.offset);
502 showContextMenu: function(element, coors) {
503 var menu = new Menu();
506 (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
507 element = element.parent();
509 if(menu.actions.length) {
510 menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
511 this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
517 var Cursor = function(canvas) {
518 this.canvas = canvas;
519 this.selection = window.getSelection();
522 $.extend(Cursor.prototype, {
523 sameAs: function(other) {
529 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
530 same = same && this.selection[prop] === other.selection[prop];
532 return true; // break
538 isSelecting: function() {
539 var selection = window.getSelection();
540 return !selection.isCollapsed;
542 isSelectingWithinElement: function() {
543 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
545 isWithinElement: function() {
546 return !this.isSelecting() || this.isSelectingWithinElement();
548 isSelectingSiblings: function() {
549 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
551 getPosition: function() {
552 return this.getSelectionAnchor();
554 getSelectionStart: function() {
555 return this.getSelectionBoundry('start');
557 getSelectionEnd: function() {
558 return this.getSelectionBoundry('end');
560 getSelectionAnchor: function() {
561 return this.getSelectionBoundry('anchor');
563 getSelectionFocus: function() {
564 return this.getSelectionBoundry('focus');
566 getSelectionBoundry: function(which) {
568 var selection = window.getSelection(),
569 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
570 focusElement = this.canvas.getDocumentElement(selection.focusNode);
572 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
576 if(which === 'anchor') {
578 element: anchorElement,
579 offset: selection.anchorOffset,
580 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
581 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
584 if(which === 'focus') {
586 element: focusElement,
587 offset: selection.focusOffset,
588 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
589 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
593 var getPlaceData = function(anchorFirst) {
596 if(which === 'start') {
597 element = anchorElement;
598 offset = selection.anchorOffset;
600 else if(which === 'end') {
601 element = focusElement;
602 offset = selection.focusOffset;
605 if(which === 'start') {
606 element = focusElement;
607 offset = selection.focusOffset;
609 else if(which === 'end') {
610 element = anchorElement;
611 offset = selection.anchorOffset;
614 return {element: element, offset: offset};
617 var anchorFirst, placeData, parent;
619 if(anchorElement.parent().sameNode(focusElement.parent())) {
620 parent = anchorElement.parent();
621 if(selection.anchorNode === selection.focusNode) {
622 anchorFirst = selection.anchorOffset <= selection.focusOffset;
624 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
626 placeData = getPlaceData(anchorFirst);
628 /*jshint bitwise: false*/
629 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
630 placeData = getPlaceData(anchorFirst);
633 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
635 element: placeData.element,
636 offset: placeData.offset,
637 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
638 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
644 fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
645 return new Canvas(wlxmlDocument, elements, metadata, sandbox);