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/genericElement'
12 ], function($, _, Backbone, logging, wlxml, documentElement, keyboard, utils, wlxmlListener, 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')
59 var ElementsRegister = function() {
61 '': ElementsRegister.createCanvasElementType(genericElement, documentElement.DocumentNodeElement)
65 _.extend(ElementsRegister, {
66 createCanvasElementType: function(elementPrototype, inheritFrom) {
67 var Constructor = function() {
69 this.super = inheritFrom.prototype;
71 inheritFrom.apply(this, Array.prototype.slice.call(arguments, 0));
74 Constructor.prototype = Object.create(inheritFrom.prototype);
75 _.extend(Constructor.prototype, elementPrototype);
79 _.extend(ElementsRegister.prototype, {
80 register: function(klass, elementPrototype) {
81 this._register[klass] = ElementsRegister.createCanvasElementType(elementPrototype, this.getFactoryFor(''));
83 getFactoryFor: function(klass) {
85 wlxml.getClassHierarchy(klass).reverse().some(function(klass) {
86 Factory = this._register[klass];
97 var Canvas = function(wlxmlDocument, elements) {
98 this.elementsRegister = new ElementsRegister();
99 (elements || []).forEach(function(elementDesc) {
100 this.elementsRegister.register(elementDesc.klass, elementDesc.element);
102 this.eventBus = _.extend({}, Backbone.Events);
103 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
104 this.wlxmlListener = wlxmlListener.create(this);
105 this.loadWlxmlDocument(wlxmlDocument);
106 this.setupEventHandling();
107 this.textHandler = new TextHandler(this);
110 $.extend(Canvas.prototype, Backbone.Events, {
112 loadWlxmlDocument: function(wlxmlDocument) {
117 this.wlxmlListener.listenTo(wlxmlDocument);
118 this.wlxmlDocument = wlxmlDocument;
122 createElement: function(wlxmlNode) {
124 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
125 Factory = documentElement.DocumentTextElement
127 if(wlxmlNode.getClass() === 'p') {
130 Factory = this.elementsRegister.getFactoryFor(wlxmlNode.getClass());
132 return new Factory(wlxmlNode, this);
135 getDocumentElement: function(htmlElement) {
136 /* globals HTMLElement, Text */
137 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
140 var $element = $(htmlElement);
141 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
142 return $element.data('canvas-element');
145 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
146 $element = $element.parent();
149 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
150 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
151 return $element.data('canvas-element');
155 reloadRoot: function() {
156 this.rootElement = this.createElement(this.wlxmlDocument.root);
157 this.wrapper.empty();
158 this.wrapper.append(this.rootElement.dom());
161 setupEventHandling: function() {
164 this.wrapper.on('keyup keydown keypress', function(e) {
165 keyboard.handleKey(e, canvas);
168 this.wrapper.on('mouseup', function() {
169 canvas.triggerSelectionChanged();
173 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
174 mouseDown = e.target;
177 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
179 if(e.originalEvent.detail === 3) {
181 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
183 if(mouseDown === e.target) {
184 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
189 this.wrapper.on('paste', function(e) {
192 var clipboardData = e.originalEvent.clipboardData;
193 if(!clipboardData || !clipboardData.getData) {
194 return; // TODO: alert
197 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
198 cursor = canvas.getCursor(),
199 element = cursor.getPosition().element,
202 if(element && cursor.isWithinElement()) {
203 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
204 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
205 element.setText(lhs+text+rhs);
206 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
208 /* jshint noempty:false */
213 /* globals MutationObserver */
214 var observer = new MutationObserver(function(mutations) {
215 mutations.forEach(function(mutation) {
216 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
217 observer.disconnect();
218 if(mutation.target.data === '') {
219 mutation.target.data = utils.unicode.ZWS;
221 else if(mutation.oldValue === utils.unicode.ZWS) {
222 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
223 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
225 observer.observe(canvas.wrapper[0], config);
227 var textElement = canvas.getDocumentElement(mutation.target),
228 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
230 //textElement.data('wlxmlNode').setText(toSet);
231 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
232 if(textElement.wlxmlNode.getText() !== toSet) {
233 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
238 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
239 observer.observe(this.wrapper[0], config);
242 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
243 var el = canvas.getDocumentElement(e.currentTarget);
248 if(el instanceof documentElement.DocumentTextElement) {
251 el.toggleLabel(true);
253 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
254 var el = canvas.getDocumentElement(e.currentTarget);
259 if(el instanceof documentElement.DocumentTextElement) {
262 el.toggleLabel(false);
265 this.eventBus.on('elementToggled', function(toggle, element) {
267 canvas.setCurrentElement(element.getPreviousTextElement());
277 return this.rootElement;
280 toggleElementHighlight: function(node, toggle) {
281 var element = utils.findCanvasElement(node);
282 element.toggleHighlight(toggle);
285 getCursor: function() {
286 return new Cursor(this);
290 getCurrentNodeElement: function() {
291 var htmlElement = this.wrapper.find('.current-node-element').parent()[0];
293 return this.getDocumentElement(htmlElement);
297 getCurrentTextElement: function() {
298 var htmlElement = this.wrapper.find('.current-text-element')[0];
300 return this.getDocumentElement(htmlElement);
304 contains: function(element) {
305 return element.dom().parents().index(this.wrapper) !== -1;
308 triggerSelectionChanged: function() {
309 this.trigger('selectionChanged', this.getSelection());
312 getSelection: function() {
313 return new Selection(this);
316 setCurrentElement: function(element, params) {
318 logger.debug('Invalid element passed to setCurrentElement: ' + element);
322 if(!(element instanceof documentElement.DocumentElement)) {
323 element = utils.findCanvasElement(element);
326 if(!element || !this.contains(element)) {
327 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
331 params = _.extend({caretTo: 'end'}, params);
332 var findFirstDirectTextChild = function(e, nodeToLand) {
333 var byBrowser = this.getCursor().getPosition().element;
334 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
337 var children = e.children();
338 for(var i = 0; i < children.length; i++) {
339 if(children[i] instanceof documentElement.DocumentTextElement) {
345 var _markAsCurrent = function(element) {
346 if(element instanceof documentElement.DocumentTextElement) {
347 this.wrapper.find('.current-text-element').removeClass('current-text-element');
348 element.dom().addClass('current-text-element');
350 this.wrapper.find('.current-node-element').removeClass('current-node-element');
351 element._container().addClass('current-node-element');
356 var isTextElement = element instanceof documentElement.DocumentTextElement,
357 nodeElementToLand = isTextElement ? element.parent() : element,
358 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
359 currentTextElement = this.getCurrentTextElement(),
360 currentNodeElement = this.getCurrentNodeElement();
362 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
363 this.wrapper.find('.current-text-element').removeClass('current-text-element');
366 if(textElementToLand) {
367 _markAsCurrent(textElementToLand);
368 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
369 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
372 document.getSelection().removeAllRanges();
375 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
376 _markAsCurrent(nodeElementToLand);
378 this.triggerSelectionChanged();
381 _moveCaretToTextElement: function(element, where) {
382 var range = document.createRange(),
383 node = element.dom().contents()[0];
385 if(typeof where !== 'number') {
386 range.selectNodeContents(node);
388 range.setStart(node, Math.min(node.data.length, where));
391 if(where !== 'whole') {
392 var collapseArg = true;
393 if(where === 'end') {
396 range.collapse(collapseArg);
398 var selection = document.getSelection();
400 selection.removeAllRanges();
401 selection.addRange(range);
402 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
405 setCursorPosition: function(position) {
406 if(position.element) {
407 this._moveCaretToTextElement(position.element, position.offset);
411 findCanvasElement: function(node) {
412 return utils.findCanvasElement(node);
415 toggleGrid: function() {
416 this.wrapper.toggleClass('grid-on');
417 this.trigger('changed');
419 isGridToggled: function() {
420 return this.wrapper.hasClass('grid-on');
425 var isText = function(node) {
426 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
429 var Selection = function(canvas) {
430 this.canvas = canvas;
431 var nativeSelection = this.nativeSelection = window.getSelection();
432 Object.defineProperty(this, 'type', {
434 if(nativeSelection.focusNode) {
435 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
438 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
439 return 'textSelection';
442 if(canvas.getCurrentNodeElement()) {
449 $.extend(Selection.prototype, {
450 toDocumentFragment: function() {
451 var doc = this.canvas.wlxmlDocument,
452 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
453 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
454 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
455 focusNode = focusElement ? focusElement.wlxmlNode : null;
456 if(this.type === 'caret') {
457 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
459 if(this.type === 'textSelection') {
460 if(anchorNode.isSiblingOf(focusNode)) {
461 return doc.createFragment(doc.TextRangeFragment, {
463 offset1: this.nativeSelection.anchorOffset,
465 offset2: this.nativeSelection.focusOffset,
469 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
470 return doc.createFragment(doc.RangeFragment, {
471 node1: siblingParents.node1,
472 node2: siblingParents.node2
476 if(this.type === 'node') {
477 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
480 sameAs: function(other) {
485 var Cursor = function(canvas) {
486 this.canvas = canvas;
487 this.selection = window.getSelection();
490 $.extend(Cursor.prototype, {
491 sameAs: function(other) {
497 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
498 same = same && this.selection[prop] === other.selection[prop];
500 return true; // break
506 isSelecting: function() {
507 var selection = window.getSelection();
508 return !selection.isCollapsed;
510 isSelectingWithinElement: function() {
511 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
513 isWithinElement: function() {
514 return !this.isSelecting() || this.isSelectingWithinElement();
516 isSelectingSiblings: function() {
517 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
519 getPosition: function() {
520 return this.getSelectionAnchor();
522 getSelectionStart: function() {
523 return this.getSelectionBoundry('start');
525 getSelectionEnd: function() {
526 return this.getSelectionBoundry('end');
528 getSelectionAnchor: function() {
529 return this.getSelectionBoundry('anchor');
531 getSelectionFocus: function() {
532 return this.getSelectionBoundry('focus');
534 getSelectionBoundry: function(which) {
536 var selection = window.getSelection(),
537 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
538 focusElement = this.canvas.getDocumentElement(selection.focusNode);
540 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
544 if(which === 'anchor') {
546 element: anchorElement,
547 offset: selection.anchorOffset,
548 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
549 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
552 if(which === 'focus') {
554 element: focusElement,
555 offset: selection.focusOffset,
556 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
557 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
561 var getPlaceData = function(anchorFirst) {
564 if(which === 'start') {
565 element = anchorElement;
566 offset = selection.anchorOffset;
568 else if(which === 'end') {
569 element = focusElement;
570 offset = selection.focusOffset;
573 if(which === 'start') {
574 element = focusElement;
575 offset = selection.focusOffset;
577 else if(which === 'end') {
578 element = anchorElement;
579 offset = selection.anchorOffset;
582 return {element: element, offset: offset};
585 var anchorFirst, placeData, parent;
587 if(anchorElement.parent().sameNode(focusElement.parent())) {
588 parent = anchorElement.parent();
589 if(selection.anchorNode === selection.focusNode) {
590 anchorFirst = selection.anchorOffset <= selection.focusOffset;
592 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
594 placeData = getPlaceData(anchorFirst);
596 /*jshint bitwise: false*/
597 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
598 placeData = getPlaceData(anchorFirst);
601 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
603 element: placeData.element,
604 offset: placeData.offset,
605 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
606 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
612 fromXMLDocument: function(wlxmlDocument, elements) {
613 return new Canvas(wlxmlDocument, elements);