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 'modules/documentCanvas/canvas/nullElement',
13 'modules/documentCanvas/canvas/gutter',
14 'libs/text!./canvas.html'
15 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement, gutter, canvasTemplate) {
18 /* global document:false, window:false, Node:false, gettext */
20 var logger = logging.getLogger('canvas');
22 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
23 $.extend(TextHandler.prototype, {
24 handle: function(node, text) {
25 this.setText(text, node);
30 // if(this.node.sameNode(node)) {
38 _ping: _.throttle(function(text) {
43 if(this.buffer !== null) {
44 this.setText(this.buffer, this.node);
48 setText: function(text, node) {
49 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
50 node.document.transaction(function() {
54 description: gettext('Changing text')
63 var Canvas = function(wlxmlDocument, elements) {
64 this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
67 {tag: 'section', klass: null, prototype: genericElement},
68 {tag: 'div', klass: null, prototype: genericElement},
69 {tag: 'header', klass: null, prototype: genericElement},
70 {tag: 'span', klass: null, prototype: genericElement},
71 {tag: 'aside', klass: null, prototype: genericElement}
72 ].concat(elements || []);
74 (elements).forEach(function(elementDesc) {
75 this.elementsRegister.register(elementDesc);
77 this.eventBus = _.extend({}, Backbone.Events);
79 this.dom = $(canvasTemplate);
80 this.rootWrapper = this.dom.find('.root-wrapper');
83 this.gutter = gutter.create();
84 this.gutterView = new gutter.GutterView(this.gutter);
85 this.dom.find('.view-row').append(this.gutterView.dom);
87 this.wlxmlListener = wlxmlListener.create(this);
88 this.loadWlxmlDocument(wlxmlDocument);
89 this.setupEventHandling();
90 this.textHandler = new TextHandler(this);
93 $.extend(Canvas.prototype, Backbone.Events, {
95 getElementOffset: function(element) {
96 return element.dom.offset().top - this.dom.offset().top;
99 loadWlxmlDocument: function(wlxmlDocument) {
104 this.wlxmlListener.listenTo(wlxmlDocument);
105 this.wlxmlDocument = wlxmlDocument;
109 createElement: function(wlxmlNode) {
111 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
112 Factory = documentElement.DocumentTextElement;
114 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
116 return new Factory(wlxmlNode, this);
119 getDocumentElement: function(htmlElement) {
120 /* globals HTMLElement, Text */
121 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
124 var $element = $(htmlElement);
125 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
126 return $element.data('canvas-element');
129 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
130 $element = $element.parent();
133 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
134 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
135 return $element.data('canvas-element');
139 reloadRoot: function() {
140 this.rootElement = this.createElement(this.wlxmlDocument.root);
141 this.rootWrapper.empty();
142 this.rootWrapper.append(this.rootElement.dom);
145 setupEventHandling: function() {
148 this.rootWrapper.on('keyup keydown keypress', function(e) {
149 keyboard.handleKey(e, canvas);
152 this.rootWrapper.on('mouseup', function() {
153 canvas.triggerSelectionChanged();
157 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
158 mouseDown = e.target;
161 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
163 if(e.originalEvent.detail === 3) {
165 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
167 if(mouseDown === e.target) {
168 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
173 this.rootWrapper.on('paste', function(e) {
176 var clipboardData = e.originalEvent.clipboardData;
177 if(!clipboardData || !clipboardData.getData) {
178 return; // TODO: alert
181 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
182 cursor = canvas.getCursor(),
183 element = cursor.getPosition().element,
186 if(element && cursor.isWithinElement()) {
187 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
188 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
189 element.setText(lhs+text+rhs);
190 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
192 /* jshint noempty:false */
197 /* globals MutationObserver */
198 var observer = new MutationObserver(function(mutations) {
199 mutations.forEach(function(mutation) {
200 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
201 observer.disconnect();
202 if(mutation.target.data === '') {
203 mutation.target.data = utils.unicode.ZWS;
205 else if(mutation.oldValue === utils.unicode.ZWS) {
206 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
207 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
209 observer.observe(canvas.dom[0], config);
211 var textElement = canvas.getDocumentElement(mutation.target),
212 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
214 //textElement.data('wlxmlNode').setText(toSet);
215 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
216 if(textElement.wlxmlNode.getText() !== toSet) {
217 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
222 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
223 observer.observe(this.rootWrapper[0], config);
226 var hoverHandler = function(e) {
227 var el = canvas.getDocumentElement(e.currentTarget),
236 if(el instanceof documentElement.DocumentTextElement) {
239 el.updateState({exposed:expose[e.type]});
242 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
243 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
245 this.eventBus.on('elementToggled', function(toggle, element) {
247 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
257 return this.rootElement;
260 toggleElementHighlight: function(node, toggle) {
261 var element = utils.getElementForNode(node);
262 element.updateState({exposed: toggle});
265 getCursor: function() {
266 return new Cursor(this);
270 getCurrentNodeElement: function() {
271 return this.currentNodeElement;
274 getCurrentTextElement: function() {
275 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
277 return this.getDocumentElement(htmlElement);
281 getPreviousTextElement: function(relativeToElement, includeInvisible) {
282 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
285 getNextTextElement: function(relativeToElement, includeInvisible) {
286 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
289 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
290 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
291 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
292 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
295 contains: function(element) {
296 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
299 triggerSelectionChanged: function() {
300 this.trigger('selectionChanged', this.getSelection());
301 var s = this.getSelection(),
302 f = s.toDocumentFragment();
303 if(f && f instanceof f.RangeFragment) {
304 if(this.currentNodeElement) {
305 this.currentNodeElement.updateState({active: false});
306 this.currentNodeElement = null;
311 getSelection: function() {
312 return new Selection(this);
315 select: function(fragment) {
316 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
317 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
318 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
320 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
322 this.setCurrentElement(fragment.node, params);
324 logger.debug('Fragment not supported');
328 setCurrentElement: function(element, params) {
330 logger.debug('Invalid element passed to setCurrentElement: ' + element);
334 if(!(element instanceof documentElement.DocumentElement)) {
335 element = utils.getElementForNode(element);
338 if(!element || !this.contains(element)) {
339 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
343 params = _.extend({caretTo: 'end'}, params);
344 var findFirstDirectTextChild = function(e, nodeToLand) {
345 var byBrowser = this.getCursor().getPosition().element;
346 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
349 return e.getVerticallyFirstTextElement();
351 var _markAsCurrent = function(element) {
352 if(element instanceof documentElement.DocumentTextElement) {
353 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
354 element.dom.addClass('current-text-element');
356 if(this.currentNodeElement) {
357 this.currentNodeElement.updateState({active: false});
359 element.updateState({active: true});
360 this.currentNodeElement = element;
365 var isTextElement = element instanceof documentElement.DocumentTextElement,
366 nodeElementToLand = isTextElement ? element.parent() : element,
367 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
368 currentTextElement = this.getCurrentTextElement(),
369 currentNodeElement = this.getCurrentNodeElement();
371 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
372 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
375 if(textElementToLand) {
376 _markAsCurrent(textElementToLand);
377 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
378 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
381 document.getSelection().removeAllRanges();
384 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
385 _markAsCurrent(nodeElementToLand);
387 this.triggerSelectionChanged();
390 _moveCaretToTextElement: function(element, where) {
391 var range = document.createRange(),
392 node = element.dom.contents()[0];
394 if(typeof where !== 'number') {
395 range.selectNodeContents(node);
397 range.setStart(node, Math.min(node.data.length, where));
400 if(where !== 'whole') {
401 var collapseArg = true;
402 if(where === 'end') {
405 range.collapse(collapseArg);
407 var selection = document.getSelection();
409 selection.removeAllRanges();
410 selection.addRange(range);
411 this.rootWrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
414 setCursorPosition: function(position) {
415 if(position.element) {
416 this._moveCaretToTextElement(position.element, position.offset);
420 toggleGrid: function() {
421 this.rootWrapper.toggleClass('grid-on');
422 this.trigger('changed');
424 isGridToggled: function() {
425 return this.rootWrapper.hasClass('grid-on');
430 var isText = function(node) {
431 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
434 var Selection = function(canvas) {
435 this.canvas = canvas;
436 var nativeSelection = this.nativeSelection = window.getSelection();
437 Object.defineProperty(this, 'type', {
439 if(nativeSelection.focusNode) {
440 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
443 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
444 return 'textSelection';
447 if(canvas.getCurrentNodeElement()) {
454 $.extend(Selection.prototype, {
455 toDocumentFragment: function() {
456 var doc = this.canvas.wlxmlDocument,
457 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
458 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
459 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
460 focusNode = focusElement ? focusElement.wlxmlNode : null;
461 if(this.type === 'caret') {
462 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
464 if(this.type === 'textSelection') {
465 if(anchorNode.isSiblingOf(focusNode)) {
466 return doc.createFragment(doc.TextRangeFragment, {
468 offset1: this.nativeSelection.anchorOffset,
470 offset2: this.nativeSelection.focusOffset,
474 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
475 return doc.createFragment(doc.RangeFragment, {
476 node1: siblingParents.node1,
477 node2: siblingParents.node2
481 if(this.type === 'node') {
482 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
485 sameAs: function(other) {
490 var Cursor = function(canvas) {
491 this.canvas = canvas;
492 this.selection = window.getSelection();
495 $.extend(Cursor.prototype, {
496 sameAs: function(other) {
502 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
503 same = same && this.selection[prop] === other.selection[prop];
505 return true; // break
511 isSelecting: function() {
512 var selection = window.getSelection();
513 return !selection.isCollapsed;
515 isSelectingWithinElement: function() {
516 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
518 isWithinElement: function() {
519 return !this.isSelecting() || this.isSelectingWithinElement();
521 isSelectingSiblings: function() {
522 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
524 getPosition: function() {
525 return this.getSelectionAnchor();
527 getSelectionStart: function() {
528 return this.getSelectionBoundry('start');
530 getSelectionEnd: function() {
531 return this.getSelectionBoundry('end');
533 getSelectionAnchor: function() {
534 return this.getSelectionBoundry('anchor');
536 getSelectionFocus: function() {
537 return this.getSelectionBoundry('focus');
539 getSelectionBoundry: function(which) {
541 var selection = window.getSelection(),
542 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
543 focusElement = this.canvas.getDocumentElement(selection.focusNode);
545 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
549 if(which === 'anchor') {
551 element: anchorElement,
552 offset: selection.anchorOffset,
553 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
554 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
557 if(which === 'focus') {
559 element: focusElement,
560 offset: selection.focusOffset,
561 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
562 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
566 var getPlaceData = function(anchorFirst) {
569 if(which === 'start') {
570 element = anchorElement;
571 offset = selection.anchorOffset;
573 else if(which === 'end') {
574 element = focusElement;
575 offset = selection.focusOffset;
578 if(which === 'start') {
579 element = focusElement;
580 offset = selection.focusOffset;
582 else if(which === 'end') {
583 element = anchorElement;
584 offset = selection.anchorOffset;
587 return {element: element, offset: offset};
590 var anchorFirst, placeData, parent;
592 if(anchorElement.parent().sameNode(focusElement.parent())) {
593 parent = anchorElement.parent();
594 if(selection.anchorNode === selection.focusNode) {
595 anchorFirst = selection.anchorOffset <= selection.focusOffset;
597 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
599 placeData = getPlaceData(anchorFirst);
601 /*jshint bitwise: false*/
602 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
603 placeData = getPlaceData(anchorFirst);
606 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
608 element: placeData.element,
609 offset: placeData.offset,
610 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
611 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
617 fromXMLDocument: function(wlxmlDocument, elements) {
618 return new Canvas(wlxmlDocument, elements);