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 = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
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) {
116 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
117 Factory = documentElement.DocumentTextElement;
119 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
121 return new Factory(wlxmlNode, this);
124 getDocumentElement: function(htmlElement) {
125 /* globals HTMLElement, Text */
126 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
129 var $element = $(htmlElement);
130 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
131 return $element.data('canvas-element');
134 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
135 $element = $element.parent();
138 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
139 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
140 return $element.data('canvas-element');
144 reloadRoot: function() {
145 if(this.rootElement) {
146 this.rootElement.detach();
148 this.rootElement = this.createElement(this.wlxmlDocument.root);
149 this.rootWrapper.append(this.rootElement.dom);
152 triggerKeyEvent: function(keyEvent, selection) {
153 selection = selection || this.getSelection();
154 if(selection && (selection.type === 'caret' || selection.type === 'textSelection') && selection.toDocumentFragment().isValid()) {
155 keyboard.handleKeyEvent(keyEvent, selection);
159 createAction: function(fqName, config) {
160 return this.sandbox.createAction(fqName, config);
163 setupEventHandling: function() {
166 /* globals document */
167 $(document.body).on('keydown', function(e) {
168 canvas.triggerKeyEvent(keyEvent.fromNativeEvent(e));
171 this.rootWrapper.on('mouseup', function() {
172 canvas.triggerSelectionChanged();
176 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
177 mouseDown = e.target;
178 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
181 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
182 var position, element;
184 if(e.originalEvent.detail === 3) {
186 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
188 if(mouseDown === e.target) {
189 element = canvas.getDocumentElement(e.target);
190 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
191 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
192 canvas.setCurrentElement(element);
196 if(window.getSelection().isCollapsed) {
197 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
198 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
204 this.rootWrapper.on('contextmenu', function(e) {
205 var el = canvas.getDocumentElement(e.target);
212 this.showContextMenu(el, {x: e.clientX, y: e.clientY});
215 this.rootWrapper.on('paste', function(e) {
218 var clipboardData = e.originalEvent.clipboardData;
219 if(!clipboardData || !clipboardData.getData) {
220 return; // TODO: alert
223 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
224 cursor = canvas.getCursor(),
225 element = cursor.getPosition().element,
228 if(element && cursor.isWithinElement()) {
229 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
230 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
231 element.setText(lhs+text+rhs);
232 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
234 /* jshint noempty:false */
239 /* globals MutationObserver */
240 var observer = new MutationObserver(function(mutations) {
241 mutations.forEach(function(mutation) {
242 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
243 observer.disconnect();
244 if(mutation.target.data === '') {
245 mutation.target.data = utils.unicode.ZWS;
247 else if(mutation.oldValue === utils.unicode.ZWS) {
248 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
249 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
251 observer.observe(canvas.dom[0], config);
253 var textElement = canvas.getDocumentElement(mutation.target),
254 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
256 //textElement.data('wlxmlNode').setText(toSet);
257 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
258 if(textElement.wlxmlNode.getText() !== toSet) {
259 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
264 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
265 observer.observe(this.rootWrapper[0], config);
268 var hoverHandler = function(e) {
269 var el = canvas.getDocumentElement(e.currentTarget),
278 if(el instanceof documentElement.DocumentTextElement) {
281 el.updateState({exposed:expose[e.type]});
284 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
285 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
287 this.eventBus.on('elementToggled', function(toggle, element) {
289 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
299 return this.rootElement;
302 toggleElementHighlight: function(node, toggle) {
303 var element = utils.getElementForNode(node);
304 element.updateState({exposed: toggle});
307 getCursor: function() {
308 return new Cursor(this);
312 getCurrentNodeElement: function() {
313 return this.currentNodeElement;
316 getCurrentTextElement: function() {
317 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
319 return this.getDocumentElement(htmlElement);
323 getPreviousTextElement: function(relativeToElement, includeInvisible) {
324 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
327 getNextTextElement: function(relativeToElement, includeInvisible) {
328 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
331 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
332 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
333 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
334 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
337 contains: function(element) {
338 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
341 triggerSelectionChanged: function() {
342 var s = this.getSelection(),
347 this.trigger('selectionChanged', s);
348 f = s.toDocumentFragment();
350 if(f && f instanceof f.RangeFragment) {
351 if(this.currentNodeElement) {
352 this.currentNodeElement.updateState({active: false});
353 this.currentNodeElement = null;
358 getSelection: function() {
359 return selection.fromNativeSelection(this);
362 select: function(fragment) {
363 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
364 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
365 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
367 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
369 this.setCurrentElement(fragment.node, params);
371 logger.debug('Fragment not supported');
375 setSelection: function(selection) {
376 this.select(this, selection.toDocumentFragment());
379 createSelection: function(params) {
380 return selection.fromParams(this, params);
382 setCurrentElement: function(element, params) {
384 logger.debug('Invalid element passed to setCurrentElement: ' + element);
388 if(!(element instanceof documentElement.DocumentElement)) {
389 element = utils.getElementForNode(element);
392 if(!element || !this.contains(element)) {
393 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
397 params = _.extend({caretTo: 'end'}, params);
398 var findFirstDirectTextChild = function(e, nodeToLand) {
399 var byBrowser = this.getCursor().getPosition().element;
400 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
403 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
405 var _markAsCurrent = function(element) {
406 if(element instanceof documentElement.DocumentTextElement) {
407 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
408 element.dom.addClass('current-text-element');
410 if(this.currentNodeElement) {
411 this.currentNodeElement.updateState({active: false});
413 element.updateState({active: true});
414 this.currentNodeElement = element;
419 var isTextElement = element instanceof documentElement.DocumentTextElement,
420 nodeElementToLand = isTextElement ? element.parent() : element,
421 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
422 currentTextElement = this.getCurrentTextElement(),
423 currentNodeElement = this.getCurrentNodeElement();
425 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
426 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
429 if(textElementToLand) {
430 _markAsCurrent(textElementToLand);
431 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
432 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
435 document.getSelection().removeAllRanges();
438 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
439 _markAsCurrent(nodeElementToLand);
441 this.triggerSelectionChanged();
444 _moveCaretToTextElement: function(element, where) {
445 var range = document.createRange(),
446 node = element.dom.contents()[0];
448 if(typeof where !== 'number') {
449 range.selectNodeContents(node);
451 range.setStart(node, Math.min(node.data.length, where));
454 if(where !== 'whole') {
455 var collapseArg = true;
456 if(where === 'end') {
459 range.collapse(collapseArg);
461 var selection = document.getSelection();
463 $(node).parent().attr('contenteditable', true);
464 selection.removeAllRanges();
465 selection.addRange(range);
466 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
469 setCursorPosition: function(position) {
470 if(position.element) {
471 this._moveCaretToTextElement(position.element, position.offset);
474 showContextMenu: function(element, coors) {
475 var menu = new Menu();
478 (element.contextMenuActions || []).forEach(menu.addAction.bind(menu));
479 element = element.parent();
481 if(menu.actions.length) {
482 menu.updateContextParam('fragment', this.getSelection().toDocumentFragment());
483 this.sandbox.showContextMenu(menu, {x: coors.x, y: coors.y});
489 var Cursor = function(canvas) {
490 this.canvas = canvas;
491 this.selection = window.getSelection();
494 $.extend(Cursor.prototype, {
495 sameAs: function(other) {
501 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
502 same = same && this.selection[prop] === other.selection[prop];
504 return true; // break
510 isSelecting: function() {
511 var selection = window.getSelection();
512 return !selection.isCollapsed;
514 isSelectingWithinElement: function() {
515 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
517 isWithinElement: function() {
518 return !this.isSelecting() || this.isSelectingWithinElement();
520 isSelectingSiblings: function() {
521 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
523 getPosition: function() {
524 return this.getSelectionAnchor();
526 getSelectionStart: function() {
527 return this.getSelectionBoundry('start');
529 getSelectionEnd: function() {
530 return this.getSelectionBoundry('end');
532 getSelectionAnchor: function() {
533 return this.getSelectionBoundry('anchor');
535 getSelectionFocus: function() {
536 return this.getSelectionBoundry('focus');
538 getSelectionBoundry: function(which) {
540 var selection = window.getSelection(),
541 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
542 focusElement = this.canvas.getDocumentElement(selection.focusNode);
544 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
548 if(which === 'anchor') {
550 element: anchorElement,
551 offset: selection.anchorOffset,
552 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
553 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
556 if(which === 'focus') {
558 element: focusElement,
559 offset: selection.focusOffset,
560 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
561 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
565 var getPlaceData = function(anchorFirst) {
568 if(which === 'start') {
569 element = anchorElement;
570 offset = selection.anchorOffset;
572 else if(which === 'end') {
573 element = focusElement;
574 offset = selection.focusOffset;
577 if(which === 'start') {
578 element = focusElement;
579 offset = selection.focusOffset;
581 else if(which === 'end') {
582 element = anchorElement;
583 offset = selection.anchorOffset;
586 return {element: element, offset: offset};
589 var anchorFirst, placeData, parent;
591 if(anchorElement.parent().sameNode(focusElement.parent())) {
592 parent = anchorElement.parent();
593 if(selection.anchorNode === selection.focusNode) {
594 anchorFirst = selection.anchorOffset <= selection.focusOffset;
596 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
598 placeData = getPlaceData(anchorFirst);
600 /*jshint bitwise: false*/
601 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
602 placeData = getPlaceData(anchorFirst);
605 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
607 element: placeData.element,
608 offset: placeData.offset,
609 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
610 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
616 fromXMLDocument: function(wlxmlDocument, elements, metadata, sandbox) {
617 return new Canvas(wlxmlDocument, elements, metadata, sandbox);