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, genericElement);
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 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
212 var el = canvas.getDocumentElement(e.currentTarget);
217 if(el instanceof documentElement.DocumentTextElement) {
220 el.toggleLabel(true);
222 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
223 var el = canvas.getDocumentElement(e.currentTarget);
228 if(el instanceof documentElement.DocumentTextElement) {
231 el.toggleLabel(false);
234 this.eventBus.on('elementToggled', function(toggle, element) {
236 canvas.setCurrentElement(element.getPreviousTextElement());
246 return this.rootElement;
249 toggleElementHighlight: function(node, toggle) {
250 var element = utils.findCanvasElement(node);
251 element.toggleHighlight(toggle);
254 getCursor: function() {
255 return new Cursor(this);
259 getCurrentNodeElement: function() {
260 var htmlElement = this.wrapper.find('.current-node-element').parent()[0];
262 return this.getDocumentElement(htmlElement);
266 getCurrentTextElement: function() {
267 var htmlElement = this.wrapper.find('.current-text-element')[0];
269 return this.getDocumentElement(htmlElement);
273 contains: function(element) {
274 return element.dom().parents().index(this.wrapper) !== -1;
277 triggerSelectionChanged: function() {
278 this.trigger('selectionChanged', this.getSelection());
281 getSelection: function() {
282 return new Selection(this);
285 setCurrentElement: function(element, params) {
287 logger.debug('Invalid element passed to setCurrentElement: ' + element);
291 if(!(element instanceof documentElement.DocumentElement)) {
292 element = utils.findCanvasElement(element);
295 if(!element || !this.contains(element)) {
296 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
300 params = _.extend({caretTo: 'end'}, params);
301 var findFirstDirectTextChild = function(e, nodeToLand) {
302 var byBrowser = this.getCursor().getPosition().element;
303 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
306 var children = e.children();
307 for(var i = 0; i < children.length; i++) {
308 if(children[i] instanceof documentElement.DocumentTextElement) {
314 var _markAsCurrent = function(element) {
315 if(element instanceof documentElement.DocumentTextElement) {
316 this.wrapper.find('.current-text-element').removeClass('current-text-element');
317 element.dom().addClass('current-text-element');
319 this.wrapper.find('.current-node-element').removeClass('current-node-element');
320 element._container().addClass('current-node-element');
325 var isTextElement = element instanceof documentElement.DocumentTextElement,
326 nodeElementToLand = isTextElement ? element.parent() : element,
327 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
328 currentTextElement = this.getCurrentTextElement(),
329 currentNodeElement = this.getCurrentNodeElement();
331 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
332 this.wrapper.find('.current-text-element').removeClass('current-text-element');
335 if(textElementToLand) {
336 _markAsCurrent(textElementToLand);
337 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
338 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
341 document.getSelection().removeAllRanges();
344 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
345 _markAsCurrent(nodeElementToLand);
347 this.triggerSelectionChanged();
350 _moveCaretToTextElement: function(element, where) {
351 var range = document.createRange(),
352 node = element.dom().contents()[0];
354 if(typeof where !== 'number') {
355 range.selectNodeContents(node);
357 range.setStart(node, Math.min(node.data.length, where));
360 if(where !== 'whole') {
361 var collapseArg = true;
362 if(where === 'end') {
365 range.collapse(collapseArg);
367 var selection = document.getSelection();
369 selection.removeAllRanges();
370 selection.addRange(range);
371 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
374 setCursorPosition: function(position) {
375 if(position.element) {
376 this._moveCaretToTextElement(position.element, position.offset);
380 findCanvasElement: function(node) {
381 return utils.findCanvasElement(node);
384 toggleGrid: function() {
385 this.wrapper.toggleClass('grid-on');
386 this.trigger('changed');
388 isGridToggled: function() {
389 return this.wrapper.hasClass('grid-on');
394 var isText = function(node) {
395 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
398 var Selection = function(canvas) {
399 this.canvas = canvas;
400 var nativeSelection = this.nativeSelection = window.getSelection();
401 Object.defineProperty(this, 'type', {
403 if(nativeSelection.focusNode) {
404 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
407 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
408 return 'textSelection';
411 if(canvas.getCurrentNodeElement()) {
418 $.extend(Selection.prototype, {
419 toDocumentFragment: function() {
420 var doc = this.canvas.wlxmlDocument,
421 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
422 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
423 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
424 focusNode = focusElement ? focusElement.wlxmlNode : null;
425 if(this.type === 'caret') {
426 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
428 if(this.type === 'textSelection') {
429 if(anchorNode.isSiblingOf(focusNode)) {
430 return doc.createFragment(doc.TextRangeFragment, {
432 offset1: this.nativeSelection.anchorOffset,
434 offset2: this.nativeSelection.focusOffset,
438 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
439 return doc.createFragment(doc.RangeFragment, {
440 node1: siblingParents.node1,
441 node2: siblingParents.node2
445 if(this.type === 'node') {
446 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
449 sameAs: function(other) {
454 var Cursor = function(canvas) {
455 this.canvas = canvas;
456 this.selection = window.getSelection();
459 $.extend(Cursor.prototype, {
460 sameAs: function(other) {
466 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
467 same = same && this.selection[prop] === other.selection[prop];
469 return true; // break
475 isSelecting: function() {
476 var selection = window.getSelection();
477 return !selection.isCollapsed;
479 isSelectingWithinElement: function() {
480 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
482 isWithinElement: function() {
483 return !this.isSelecting() || this.isSelectingWithinElement();
485 isSelectingSiblings: function() {
486 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
488 getPosition: function() {
489 return this.getSelectionAnchor();
491 getSelectionStart: function() {
492 return this.getSelectionBoundry('start');
494 getSelectionEnd: function() {
495 return this.getSelectionBoundry('end');
497 getSelectionAnchor: function() {
498 return this.getSelectionBoundry('anchor');
500 getSelectionFocus: function() {
501 return this.getSelectionBoundry('focus');
503 getSelectionBoundry: function(which) {
505 var selection = window.getSelection(),
506 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
507 focusElement = this.canvas.getDocumentElement(selection.focusNode);
509 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
513 if(which === 'anchor') {
515 element: anchorElement,
516 offset: selection.anchorOffset,
517 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
518 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
521 if(which === 'focus') {
523 element: focusElement,
524 offset: selection.focusOffset,
525 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
526 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
530 var getPlaceData = function(anchorFirst) {
533 if(which === 'start') {
534 element = anchorElement;
535 offset = selection.anchorOffset;
537 else if(which === 'end') {
538 element = focusElement;
539 offset = selection.focusOffset;
542 if(which === 'start') {
543 element = focusElement;
544 offset = selection.focusOffset;
546 else if(which === 'end') {
547 element = anchorElement;
548 offset = selection.anchorOffset;
551 return {element: element, offset: offset};
554 var anchorFirst, placeData, parent;
556 if(anchorElement.parent().sameNode(focusElement.parent())) {
557 parent = anchorElement.parent();
558 if(selection.anchorNode === selection.focusNode) {
559 anchorFirst = selection.anchorOffset <= selection.focusOffset;
561 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
563 placeData = getPlaceData(anchorFirst);
565 /*jshint bitwise: false*/
566 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
567 placeData = getPlaceData(anchorFirst);
570 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
572 element: placeData.element,
573 offset: placeData.offset,
574 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
575 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
581 fromXMLDocument: function(wlxmlDocument, elements) {
582 return new Canvas(wlxmlDocument, elements);