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 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener, ElementsRegister, genericElement, nullElement) {
16 /* global document:false, window:false, Node:false, gettext */
18 var logger = logging.getLogger('canvas');
20 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
21 $.extend(TextHandler.prototype, {
22 handle: function(node, text) {
23 this.setText(text, node);
28 // if(this.node.sameNode(node)) {
36 _ping: _.throttle(function(text) {
41 if(this.buffer !== null) {
42 this.setText(this.buffer, this.node);
46 setText: function(text, node) {
47 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
48 node.document.transaction(function() {
52 description: gettext('Changing text')
61 var Canvas = function(wlxmlDocument, elements) {
62 this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
65 {tag: 'section', klass: null, prototype: genericElement},
66 {tag: 'div', klass: null, prototype: genericElement},
67 {tag: 'header', klass: null, prototype: genericElement},
68 {tag: 'span', klass: null, prototype: genericElement},
69 {tag: 'aside', klass: null, prototype: genericElement}
70 ].concat(elements || []);
72 (elements).forEach(function(elementDesc) {
73 this.elementsRegister.register(elementDesc);
75 this.eventBus = _.extend({}, Backbone.Events);
76 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
77 this.wlxmlListener = wlxmlListener.create(this);
78 this.loadWlxmlDocument(wlxmlDocument);
79 this.setupEventHandling();
80 this.textHandler = new TextHandler(this);
83 $.extend(Canvas.prototype, Backbone.Events, {
85 loadWlxmlDocument: function(wlxmlDocument) {
90 this.wlxmlListener.listenTo(wlxmlDocument);
91 this.wlxmlDocument = wlxmlDocument;
95 createElement: function(wlxmlNode) {
97 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
98 Factory = documentElement.DocumentTextElement;
100 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
102 return new Factory(wlxmlNode, this);
105 getDocumentElement: function(htmlElement) {
106 /* globals HTMLElement, Text */
107 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
110 var $element = $(htmlElement);
111 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
112 return $element.data('canvas-element');
115 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
116 $element = $element.parent();
119 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
120 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
121 return $element.data('canvas-element');
125 reloadRoot: function() {
126 this.rootElement = this.createElement(this.wlxmlDocument.root);
127 this.wrapper.empty();
128 this.wrapper.append(this.rootElement.dom);
131 setupEventHandling: function() {
134 this.wrapper.on('keyup keydown keypress', function(e) {
135 keyboard.handleKey(e, canvas);
138 this.wrapper.on('mouseup', function() {
139 canvas.triggerSelectionChanged();
143 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
144 mouseDown = e.target;
147 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
149 if(e.originalEvent.detail === 3) {
151 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
153 if(mouseDown === e.target) {
154 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
159 this.wrapper.on('paste', function(e) {
162 var clipboardData = e.originalEvent.clipboardData;
163 if(!clipboardData || !clipboardData.getData) {
164 return; // TODO: alert
167 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
168 cursor = canvas.getCursor(),
169 element = cursor.getPosition().element,
172 if(element && cursor.isWithinElement()) {
173 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
174 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
175 element.setText(lhs+text+rhs);
176 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
178 /* jshint noempty:false */
183 /* globals MutationObserver */
184 var observer = new MutationObserver(function(mutations) {
185 mutations.forEach(function(mutation) {
186 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
187 observer.disconnect();
188 if(mutation.target.data === '') {
189 mutation.target.data = utils.unicode.ZWS;
191 else if(mutation.oldValue === utils.unicode.ZWS) {
192 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
193 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
195 observer.observe(canvas.wrapper[0], config);
197 var textElement = canvas.getDocumentElement(mutation.target),
198 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
200 //textElement.data('wlxmlNode').setText(toSet);
201 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
202 if(textElement.wlxmlNode.getText() !== toSet) {
203 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
208 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
209 observer.observe(this.wrapper[0], config);
212 var hoverHandler = function(e) {
213 var el = canvas.getDocumentElement(e.currentTarget),
222 if(el instanceof documentElement.DocumentTextElement) {
225 el.updateState({exposed:expose[e.type]});
228 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
229 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
231 this.eventBus.on('elementToggled', function(toggle, element) {
233 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
243 return this.rootElement;
246 toggleElementHighlight: function(node, toggle) {
247 var element = utils.getElementForNode(node);
248 element.updateState({exposed: toggle});
251 getCursor: function() {
252 return new Cursor(this);
256 getCurrentNodeElement: function() {
257 return this.currentNodeElement;
260 getCurrentTextElement: function() {
261 var htmlElement = this.wrapper.find('.current-text-element')[0];
263 return this.getDocumentElement(htmlElement);
267 getPreviousTextElement: function(relativeToElement, includeInvisible) {
268 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
271 getNextTextElement: function(relativeToElement, includeInvisible) {
272 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
275 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
276 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
277 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
278 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
281 contains: function(element) {
282 return element && element.dom && element.dom.parents().index(this.wrapper) !== -1;
285 triggerSelectionChanged: function() {
286 this.trigger('selectionChanged', this.getSelection());
287 var s = this.getSelection(),
288 f = s.toDocumentFragment();
289 if(f && f instanceof f.RangeFragment) {
290 if(this.currentNodeElement) {
291 this.currentNodeElement.updateState({active: false});
292 this.currentNodeElement = null;
297 getSelection: function() {
298 return new Selection(this);
301 select: function(fragment) {
302 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
303 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
304 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
306 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
308 this.setCurrentElement(fragment.node, params);
310 logger.debug('Fragment not supported');
314 setCurrentElement: function(element, params) {
316 logger.debug('Invalid element passed to setCurrentElement: ' + element);
320 if(!(element instanceof documentElement.DocumentElement)) {
321 element = utils.getElementForNode(element);
324 if(!element || !this.contains(element)) {
325 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
329 params = _.extend({caretTo: 'end'}, params);
330 var findFirstDirectTextChild = function(e, nodeToLand) {
331 var byBrowser = this.getCursor().getPosition().element;
332 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
335 return e.getVerticallyFirstTextElement();
337 var _markAsCurrent = function(element) {
338 if(element instanceof documentElement.DocumentTextElement) {
339 this.wrapper.find('.current-text-element').removeClass('current-text-element');
340 element.dom.addClass('current-text-element');
342 if(this.currentNodeElement) {
343 this.currentNodeElement.updateState({active: false});
345 element.updateState({active: true});
346 this.currentNodeElement = element;
351 var isTextElement = element instanceof documentElement.DocumentTextElement,
352 nodeElementToLand = isTextElement ? element.parent() : element,
353 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
354 currentTextElement = this.getCurrentTextElement(),
355 currentNodeElement = this.getCurrentNodeElement();
357 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
358 this.wrapper.find('.current-text-element').removeClass('current-text-element');
361 if(textElementToLand) {
362 _markAsCurrent(textElementToLand);
363 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
364 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
367 document.getSelection().removeAllRanges();
370 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
371 _markAsCurrent(nodeElementToLand);
373 this.triggerSelectionChanged();
376 _moveCaretToTextElement: function(element, where) {
377 var range = document.createRange(),
378 node = element.dom.contents()[0];
380 if(typeof where !== 'number') {
381 range.selectNodeContents(node);
383 range.setStart(node, Math.min(node.data.length, where));
386 if(where !== 'whole') {
387 var collapseArg = true;
388 if(where === 'end') {
391 range.collapse(collapseArg);
393 var selection = document.getSelection();
395 selection.removeAllRanges();
396 selection.addRange(range);
397 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
400 setCursorPosition: function(position) {
401 if(position.element) {
402 this._moveCaretToTextElement(position.element, position.offset);
406 toggleGrid: function() {
407 this.wrapper.toggleClass('grid-on');
408 this.trigger('changed');
410 isGridToggled: function() {
411 return this.wrapper.hasClass('grid-on');
416 var isText = function(node) {
417 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
420 var Selection = function(canvas) {
421 this.canvas = canvas;
422 var nativeSelection = this.nativeSelection = window.getSelection();
423 Object.defineProperty(this, 'type', {
425 if(nativeSelection.focusNode) {
426 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
429 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
430 return 'textSelection';
433 if(canvas.getCurrentNodeElement()) {
440 $.extend(Selection.prototype, {
441 toDocumentFragment: function() {
442 var doc = this.canvas.wlxmlDocument,
443 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
444 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
445 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
446 focusNode = focusElement ? focusElement.wlxmlNode : null;
447 if(this.type === 'caret') {
448 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
450 if(this.type === 'textSelection') {
451 if(anchorNode.isSiblingOf(focusNode)) {
452 return doc.createFragment(doc.TextRangeFragment, {
454 offset1: this.nativeSelection.anchorOffset,
456 offset2: this.nativeSelection.focusOffset,
460 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
461 return doc.createFragment(doc.RangeFragment, {
462 node1: siblingParents.node1,
463 node2: siblingParents.node2
467 if(this.type === 'node') {
468 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
471 sameAs: function(other) {
476 var Cursor = function(canvas) {
477 this.canvas = canvas;
478 this.selection = window.getSelection();
481 $.extend(Cursor.prototype, {
482 sameAs: function(other) {
488 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
489 same = same && this.selection[prop] === other.selection[prop];
491 return true; // break
497 isSelecting: function() {
498 var selection = window.getSelection();
499 return !selection.isCollapsed;
501 isSelectingWithinElement: function() {
502 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
504 isWithinElement: function() {
505 return !this.isSelecting() || this.isSelectingWithinElement();
507 isSelectingSiblings: function() {
508 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
510 getPosition: function() {
511 return this.getSelectionAnchor();
513 getSelectionStart: function() {
514 return this.getSelectionBoundry('start');
516 getSelectionEnd: function() {
517 return this.getSelectionBoundry('end');
519 getSelectionAnchor: function() {
520 return this.getSelectionBoundry('anchor');
522 getSelectionFocus: function() {
523 return this.getSelectionBoundry('focus');
525 getSelectionBoundry: function(which) {
527 var selection = window.getSelection(),
528 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
529 focusElement = this.canvas.getDocumentElement(selection.focusNode);
531 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
535 if(which === 'anchor') {
537 element: anchorElement,
538 offset: selection.anchorOffset,
539 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
540 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
543 if(which === 'focus') {
545 element: focusElement,
546 offset: selection.focusOffset,
547 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
548 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
552 var getPlaceData = function(anchorFirst) {
555 if(which === 'start') {
556 element = anchorElement;
557 offset = selection.anchorOffset;
559 else if(which === 'end') {
560 element = focusElement;
561 offset = selection.focusOffset;
564 if(which === 'start') {
565 element = focusElement;
566 offset = selection.focusOffset;
568 else if(which === 'end') {
569 element = anchorElement;
570 offset = selection.anchorOffset;
573 return {element: element, offset: offset};
576 var anchorFirst, placeData, parent;
578 if(anchorElement.parent().sameNode(focusElement.parent())) {
579 parent = anchorElement.parent();
580 if(selection.anchorNode === selection.focusNode) {
581 anchorFirst = selection.anchorOffset <= selection.focusOffset;
583 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
585 placeData = getPlaceData(anchorFirst);
587 /*jshint bitwise: false*/
588 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
589 placeData = getPlaceData(anchorFirst);
592 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
594 element: placeData.element,
595 offset: placeData.offset,
596 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
597 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
603 fromXMLDocument: function(wlxmlDocument, elements) {
604 return new Canvas(wlxmlDocument, elements);