5 'fnpjs/logging/logging',
6 'modules/documentCanvas/canvas/documentElement',
7 'modules/documentCanvas/canvas/keyboard',
8 'modules/documentCanvas/canvas/utils',
9 'modules/documentCanvas/canvas/wlxmlListener',
10 'modules/documentCanvas/canvas/elementsRegister',
11 'modules/documentCanvas/canvas/genericElement',
12 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement) {
15 /* global document:false, window:false, Node:false, gettext */
17 var logger = logging.getLogger('canvas');
19 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
20 $.extend(TextHandler.prototype, {
21 handle: function(node, text) {
22 this.setText(text, node);
27 // if(this.node.sameNode(node)) {
35 _ping: _.throttle(function(text) {
40 if(this.buffer !== null) {
41 this.setText(this.buffer, this.node);
45 setText: function(text, node) {
46 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
47 node.document.transaction(function() {
51 description: gettext('Changing text')
60 var Canvas = function(wlxmlDocument, elements) {
61 this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement);
64 {tag: 'section', klass: null, prototype: genericElement},
65 {tag: 'div', klass: null, prototype: genericElement},
66 {tag: 'header', klass: null, prototype: genericElement},
67 {tag: 'span', klass: null, prototype: genericElement},
68 {tag: 'aside', klass: null, prototype: genericElement}
69 ].concat(elements || []);
71 (elements).forEach(function(elementDesc) {
72 this.elementsRegister.register(elementDesc);
74 this.eventBus = _.extend({}, Backbone.Events);
75 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
76 this.wlxmlListener = wlxmlListener.create(this);
77 this.loadWlxmlDocument(wlxmlDocument);
78 this.setupEventHandling();
79 this.textHandler = new TextHandler(this);
82 $.extend(Canvas.prototype, Backbone.Events, {
84 loadWlxmlDocument: function(wlxmlDocument) {
89 this.wlxmlListener.listenTo(wlxmlDocument);
90 this.wlxmlDocument = wlxmlDocument;
94 createElement: function(wlxmlNode) {
96 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
97 Factory = documentElement.DocumentTextElement;
99 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
101 return new Factory(wlxmlNode, this);
104 getDocumentElement: function(htmlElement) {
105 /* globals HTMLElement, Text */
106 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
109 var $element = $(htmlElement);
110 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
111 return $element.data('canvas-element');
114 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
115 $element = $element.parent();
118 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
119 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
120 return $element.data('canvas-element');
124 reloadRoot: function() {
125 this.rootElement = this.createElement(this.wlxmlDocument.root);
126 this.wrapper.empty();
127 this.wrapper.append(this.rootElement.dom);
130 setupEventHandling: function() {
133 this.wrapper.on('keyup keydown keypress', function(e) {
134 keyboard.handleKey(e, canvas);
137 this.wrapper.on('mouseup', function() {
138 canvas.triggerSelectionChanged();
142 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
143 mouseDown = e.target;
146 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
148 if(e.originalEvent.detail === 3) {
150 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
152 if(mouseDown === e.target) {
153 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
158 this.wrapper.on('paste', function(e) {
161 var clipboardData = e.originalEvent.clipboardData;
162 if(!clipboardData || !clipboardData.getData) {
163 return; // TODO: alert
166 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
167 cursor = canvas.getCursor(),
168 element = cursor.getPosition().element,
171 if(element && cursor.isWithinElement()) {
172 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
173 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
174 element.setText(lhs+text+rhs);
175 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
177 /* jshint noempty:false */
182 /* globals MutationObserver */
183 var observer = new MutationObserver(function(mutations) {
184 mutations.forEach(function(mutation) {
185 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
186 observer.disconnect();
187 if(mutation.target.data === '') {
188 mutation.target.data = utils.unicode.ZWS;
190 else if(mutation.oldValue === utils.unicode.ZWS) {
191 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
192 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
194 observer.observe(canvas.wrapper[0], config);
196 var textElement = canvas.getDocumentElement(mutation.target),
197 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
199 //textElement.data('wlxmlNode').setText(toSet);
200 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
201 if(textElement.wlxmlNode.getText() !== toSet) {
202 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
207 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
208 observer.observe(this.wrapper[0], config);
211 var hoverHandler = function(e) {
212 var el = canvas.getDocumentElement(e.currentTarget),
221 if(el instanceof documentElement.DocumentTextElement) {
224 el.updateState({exposed:expose[e.type]});
227 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
228 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
230 this.eventBus.on('elementToggled', function(toggle, element) {
232 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
242 return this.rootElement;
245 toggleElementHighlight: function(node, toggle) {
246 var element = utils.getElementForNode(node);
247 element.updateState({exposed: toggle});
250 getCursor: function() {
251 return new Cursor(this);
255 getCurrentNodeElement: function() {
256 return this.currentNodeElement;
259 getCurrentTextElement: function() {
260 var htmlElement = this.wrapper.find('.current-text-element')[0];
262 return this.getDocumentElement(htmlElement);
266 getPreviousTextElement: function(relativeToElement, includeInvisible) {
267 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
270 getNextTextElement: function(relativeToElement, includeInvisible) {
271 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
274 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
275 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
276 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
277 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
280 contains: function(element) {
281 return element.dom.parents().index(this.wrapper) !== -1;
284 triggerSelectionChanged: function() {
285 this.trigger('selectionChanged', this.getSelection());
286 var s = this.getSelection(),
287 f = s.toDocumentFragment();
288 if(f && f instanceof f.RangeFragment) {
289 if(this.currentNodeElement) {
290 this.currentNodeElement.updateState({active: false});
291 this.currentNodeElement = null;
296 getSelection: function() {
297 return new Selection(this);
300 select: function(fragment) {
301 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
302 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
303 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
305 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
307 this.setCurrentElement(fragment.node, params);
309 logger.debug('Fragment not supported');
313 setCurrentElement: function(element, params) {
315 logger.debug('Invalid element passed to setCurrentElement: ' + element);
319 if(!(element instanceof documentElement.DocumentElement)) {
320 element = utils.getElementForNode(element);
323 if(!element || !this.contains(element)) {
324 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
328 params = _.extend({caretTo: 'end'}, params);
329 var findFirstDirectTextChild = function(e, nodeToLand) {
330 var byBrowser = this.getCursor().getPosition().element;
331 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
334 return e.getVerticallyFirstTextElement();
336 var _markAsCurrent = function(element) {
337 if(element instanceof documentElement.DocumentTextElement) {
338 this.wrapper.find('.current-text-element').removeClass('current-text-element');
339 element.dom.addClass('current-text-element');
341 if(this.currentNodeElement) {
342 this.currentNodeElement.updateState({active: false});
344 element.updateState({active: true});
345 this.currentNodeElement = element;
350 var isTextElement = element instanceof documentElement.DocumentTextElement,
351 nodeElementToLand = isTextElement ? element.parent() : element,
352 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
353 currentTextElement = this.getCurrentTextElement(),
354 currentNodeElement = this.getCurrentNodeElement();
356 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
357 this.wrapper.find('.current-text-element').removeClass('current-text-element');
360 if(textElementToLand) {
361 _markAsCurrent(textElementToLand);
362 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
363 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
366 document.getSelection().removeAllRanges();
369 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
370 _markAsCurrent(nodeElementToLand);
372 this.triggerSelectionChanged();
375 _moveCaretToTextElement: function(element, where) {
376 var range = document.createRange(),
377 node = element.dom.contents()[0];
379 if(typeof where !== 'number') {
380 range.selectNodeContents(node);
382 range.setStart(node, Math.min(node.data.length, where));
385 if(where !== 'whole') {
386 var collapseArg = true;
387 if(where === 'end') {
390 range.collapse(collapseArg);
392 var selection = document.getSelection();
394 selection.removeAllRanges();
395 selection.addRange(range);
396 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
399 setCursorPosition: function(position) {
400 if(position.element) {
401 this._moveCaretToTextElement(position.element, position.offset);
405 toggleGrid: function() {
406 this.wrapper.toggleClass('grid-on');
407 this.trigger('changed');
409 isGridToggled: function() {
410 return this.wrapper.hasClass('grid-on');
415 var isText = function(node) {
416 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
419 var Selection = function(canvas) {
420 this.canvas = canvas;
421 var nativeSelection = this.nativeSelection = window.getSelection();
422 Object.defineProperty(this, 'type', {
424 if(nativeSelection.focusNode) {
425 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
428 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
429 return 'textSelection';
432 if(canvas.getCurrentNodeElement()) {
439 $.extend(Selection.prototype, {
440 toDocumentFragment: function() {
441 var doc = this.canvas.wlxmlDocument,
442 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
443 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
444 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
445 focusNode = focusElement ? focusElement.wlxmlNode : null;
446 if(this.type === 'caret') {
447 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
449 if(this.type === 'textSelection') {
450 if(anchorNode.isSiblingOf(focusNode)) {
451 return doc.createFragment(doc.TextRangeFragment, {
453 offset1: this.nativeSelection.anchorOffset,
455 offset2: this.nativeSelection.focusOffset,
459 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
460 return doc.createFragment(doc.RangeFragment, {
461 node1: siblingParents.node1,
462 node2: siblingParents.node2
466 if(this.type === 'node') {
467 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
470 sameAs: function(other) {
475 var Cursor = function(canvas) {
476 this.canvas = canvas;
477 this.selection = window.getSelection();
480 $.extend(Cursor.prototype, {
481 sameAs: function(other) {
487 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
488 same = same && this.selection[prop] === other.selection[prop];
490 return true; // break
496 isSelecting: function() {
497 var selection = window.getSelection();
498 return !selection.isCollapsed;
500 isSelectingWithinElement: function() {
501 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
503 isWithinElement: function() {
504 return !this.isSelecting() || this.isSelectingWithinElement();
506 isSelectingSiblings: function() {
507 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
509 getPosition: function() {
510 return this.getSelectionAnchor();
512 getSelectionStart: function() {
513 return this.getSelectionBoundry('start');
515 getSelectionEnd: function() {
516 return this.getSelectionBoundry('end');
518 getSelectionAnchor: function() {
519 return this.getSelectionBoundry('anchor');
521 getSelectionFocus: function() {
522 return this.getSelectionBoundry('focus');
524 getSelectionBoundry: function(which) {
526 var selection = window.getSelection(),
527 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
528 focusElement = this.canvas.getDocumentElement(selection.focusNode);
530 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
534 if(which === 'anchor') {
536 element: anchorElement,
537 offset: selection.anchorOffset,
538 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
539 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
542 if(which === 'focus') {
544 element: focusElement,
545 offset: selection.focusOffset,
546 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
547 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
551 var getPlaceData = function(anchorFirst) {
554 if(which === 'start') {
555 element = anchorElement;
556 offset = selection.anchorOffset;
558 else if(which === 'end') {
559 element = focusElement;
560 offset = selection.focusOffset;
563 if(which === 'start') {
564 element = focusElement;
565 offset = selection.focusOffset;
567 else if(which === 'end') {
568 element = anchorElement;
569 offset = selection.anchorOffset;
572 return {element: element, offset: offset};
575 var anchorFirst, placeData, parent;
577 if(anchorElement.parent().sameNode(focusElement.parent())) {
578 parent = anchorElement.parent();
579 if(selection.anchorNode === selection.focusNode) {
580 anchorFirst = selection.anchorOffset <= selection.focusOffset;
582 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
584 placeData = getPlaceData(anchorFirst);
586 /*jshint bitwise: false*/
587 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
588 placeData = getPlaceData(anchorFirst);
591 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
593 element: placeData.element,
594 offset: placeData.offset,
595 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
596 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
602 fromXMLDocument: function(wlxmlDocument, elements) {
603 return new Canvas(wlxmlDocument, elements);