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, metadata) {
64 this.metadata = metadata || {};
65 this.elementsRegister = new ElementsRegister(documentElement.DocumentNodeElement, nullElement);
68 {tag: 'section', klass: null, prototype: genericElement},
69 {tag: 'div', klass: null, prototype: genericElement},
70 {tag: 'header', klass: null, prototype: genericElement},
71 {tag: 'span', klass: null, prototype: genericElement},
72 {tag: 'aside', klass: null, prototype: genericElement}
73 ].concat(elements || []);
75 (elements).forEach(function(elementDesc) {
76 this.elementsRegister.register(elementDesc);
78 this.eventBus = _.extend({}, Backbone.Events);
80 this.dom = $(canvasTemplate);
81 this.rootWrapper = this.dom.find('.root-wrapper');
84 this.gutter = gutter.create();
85 this.gutterView = new gutter.GutterView(this.gutter);
86 this.dom.find('.view-row').append(this.gutterView.dom);
88 this.wlxmlListener = wlxmlListener.create(this);
89 this.loadWlxmlDocument(wlxmlDocument);
90 this.setupEventHandling();
91 this.textHandler = new TextHandler(this);
94 $.extend(Canvas.prototype, Backbone.Events, {
96 getElementOffset: function(element) {
97 return element.dom.offset().top - this.dom.offset().top;
100 loadWlxmlDocument: function(wlxmlDocument) {
105 this.wlxmlListener.listenTo(wlxmlDocument);
106 this.wlxmlDocument = wlxmlDocument;
110 createElement: function(wlxmlNode) {
112 if(wlxmlNode.nodeType === Node.TEXT_NODE) {
113 Factory = documentElement.DocumentTextElement;
115 Factory = this.elementsRegister.getElement({tag: wlxmlNode.getTagName(), klass: wlxmlNode.getClass()});
117 return new Factory(wlxmlNode, this);
120 getDocumentElement: function(htmlElement) {
121 /* globals HTMLElement, Text */
122 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
125 var $element = $(htmlElement);
126 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
127 return $element.data('canvas-element');
130 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
131 $element = $element.parent();
134 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
135 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
136 return $element.data('canvas-element');
140 reloadRoot: function() {
141 if(this.rootElement) {
142 this.rootElement.detach();
144 this.rootElement = this.createElement(this.wlxmlDocument.root);
145 this.rootWrapper.append(this.rootElement.dom);
148 setupEventHandling: function() {
151 /* globals document */
152 $(document.body).on('keydown', function(e) {
153 var cursor = canvas.getCursor();
154 if(cursor.isSelecting() || Object.keys(cursor.getPosition()).length) {
155 keyboard.handleKey(e, canvas);
159 this.rootWrapper.on('mouseup', function() {
160 canvas.triggerSelectionChanged();
164 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
165 mouseDown = e.target;
166 canvas.rootWrapper.find('[contenteditable]').attr('contenteditable', null);
169 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
170 var position, element;
172 if(e.originalEvent.detail === 3) {
174 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
176 if(mouseDown === e.target) {
177 element = canvas.getDocumentElement(e.target);
178 if(element && element.wlxmlNode.nodeType === Node.ELEMENT_NODE) {
179 if(element.getVerticallyFirstTextElement && !element.getVerticallyFirstTextElement({considerChildren: false})) {
180 canvas.setCurrentElement(element);
184 if(window.getSelection().isCollapsed) {
185 position = utils.caretPositionFromPoint(e.clientX, e.clientY);
186 canvas.setCurrentElement(canvas.getDocumentElement(position.textNode), {caretTo: position.offset});
192 this.rootWrapper.on('paste', function(e) {
195 var clipboardData = e.originalEvent.clipboardData;
196 if(!clipboardData || !clipboardData.getData) {
197 return; // TODO: alert
200 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
201 cursor = canvas.getCursor(),
202 element = cursor.getPosition().element,
205 if(element && cursor.isWithinElement()) {
206 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
207 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
208 element.setText(lhs+text+rhs);
209 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
211 /* jshint noempty:false */
216 /* globals MutationObserver */
217 var observer = new MutationObserver(function(mutations) {
218 mutations.forEach(function(mutation) {
219 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
220 observer.disconnect();
221 if(mutation.target.data === '') {
222 mutation.target.data = utils.unicode.ZWS;
224 else if(mutation.oldValue === utils.unicode.ZWS) {
225 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
226 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
228 observer.observe(canvas.dom[0], config);
230 var textElement = canvas.getDocumentElement(mutation.target),
231 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
233 //textElement.data('wlxmlNode').setText(toSet);
234 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
235 if(textElement.wlxmlNode.getText() !== toSet) {
236 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
241 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
242 observer.observe(this.rootWrapper[0], config);
245 var hoverHandler = function(e) {
246 var el = canvas.getDocumentElement(e.currentTarget),
255 if(el instanceof documentElement.DocumentTextElement) {
258 el.updateState({exposed:expose[e.type]});
261 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
262 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
264 this.eventBus.on('elementToggled', function(toggle, element) {
266 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
276 return this.rootElement;
279 toggleElementHighlight: function(node, toggle) {
280 var element = utils.getElementForNode(node);
281 element.updateState({exposed: toggle});
284 getCursor: function() {
285 return new Cursor(this);
289 getCurrentNodeElement: function() {
290 return this.currentNodeElement;
293 getCurrentTextElement: function() {
294 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
296 return this.getDocumentElement(htmlElement);
300 getPreviousTextElement: function(relativeToElement, includeInvisible) {
301 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
304 getNextTextElement: function(relativeToElement, includeInvisible) {
305 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
308 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
309 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
310 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
311 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
314 contains: function(element) {
315 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
318 triggerSelectionChanged: function() {
319 this.trigger('selectionChanged', this.getSelection());
320 var s = this.getSelection(),
321 f = s.toDocumentFragment();
322 if(f && f instanceof f.RangeFragment) {
323 if(this.currentNodeElement) {
324 this.currentNodeElement.updateState({active: false});
325 this.currentNodeElement = null;
330 getSelection: function() {
331 return new Selection(this);
334 select: function(fragment) {
335 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
336 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
337 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
339 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
341 this.setCurrentElement(fragment.node, params);
343 logger.debug('Fragment not supported');
347 setCurrentElement: function(element, params) {
349 logger.debug('Invalid element passed to setCurrentElement: ' + element);
353 if(!(element instanceof documentElement.DocumentElement)) {
354 element = utils.getElementForNode(element);
357 if(!element || !this.contains(element)) {
358 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
362 params = _.extend({caretTo: 'end'}, params);
363 var findFirstDirectTextChild = function(e, nodeToLand) {
364 var byBrowser = this.getCursor().getPosition().element;
365 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
368 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
370 var _markAsCurrent = function(element) {
371 if(element instanceof documentElement.DocumentTextElement) {
372 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
373 element.dom.addClass('current-text-element');
375 if(this.currentNodeElement) {
376 this.currentNodeElement.updateState({active: false});
378 element.updateState({active: true});
379 this.currentNodeElement = element;
384 var isTextElement = element instanceof documentElement.DocumentTextElement,
385 nodeElementToLand = isTextElement ? element.parent() : element,
386 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
387 currentTextElement = this.getCurrentTextElement(),
388 currentNodeElement = this.getCurrentNodeElement();
390 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
391 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
394 if(textElementToLand) {
395 _markAsCurrent(textElementToLand);
396 if((params.caretTo || params.caretTo === 0) || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
397 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
400 document.getSelection().removeAllRanges();
403 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
404 _markAsCurrent(nodeElementToLand);
406 this.triggerSelectionChanged();
409 _moveCaretToTextElement: function(element, where) {
410 var range = document.createRange(),
411 node = element.dom.contents()[0];
413 if(typeof where !== 'number') {
414 range.selectNodeContents(node);
416 range.setStart(node, Math.min(node.data.length, where));
419 if(where !== 'whole') {
420 var collapseArg = true;
421 if(where === 'end') {
424 range.collapse(collapseArg);
426 var selection = document.getSelection();
428 $(node).parent().attr('contenteditable', true);
429 selection.removeAllRanges();
430 selection.addRange(range);
431 $(node).parent().focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
434 setCursorPosition: function(position) {
435 if(position.element) {
436 this._moveCaretToTextElement(position.element, position.offset);
442 var isText = function(node) {
443 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
446 var Selection = function(canvas) {
447 this.canvas = canvas;
448 var nativeSelection = this.nativeSelection = window.getSelection();
449 Object.defineProperty(this, 'type', {
451 if(nativeSelection.focusNode) {
452 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
455 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
456 return 'textSelection';
459 if(canvas.getCurrentNodeElement()) {
466 $.extend(Selection.prototype, {
467 toDocumentFragment: function() {
468 var doc = this.canvas.wlxmlDocument,
469 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
470 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
471 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
472 focusNode = focusElement ? focusElement.wlxmlNode : null;
473 if(this.type === 'caret') {
474 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
476 if(this.type === 'textSelection') {
477 if(!anchorNode || !focusNode) {
480 if(anchorNode.isSiblingOf(focusNode)) {
481 return doc.createFragment(doc.TextRangeFragment, {
483 offset1: this.nativeSelection.anchorOffset,
485 offset2: this.nativeSelection.focusOffset,
489 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
490 return doc.createFragment(doc.RangeFragment, {
491 node1: siblingParents.node1,
492 node2: siblingParents.node2
496 if(this.type === 'node') {
497 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
500 sameAs: function(other) {
505 var Cursor = function(canvas) {
506 this.canvas = canvas;
507 this.selection = window.getSelection();
510 $.extend(Cursor.prototype, {
511 sameAs: function(other) {
517 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
518 same = same && this.selection[prop] === other.selection[prop];
520 return true; // break
526 isSelecting: function() {
527 var selection = window.getSelection();
528 return !selection.isCollapsed;
530 isSelectingWithinElement: function() {
531 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
533 isWithinElement: function() {
534 return !this.isSelecting() || this.isSelectingWithinElement();
536 isSelectingSiblings: function() {
537 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
539 getPosition: function() {
540 return this.getSelectionAnchor();
542 getSelectionStart: function() {
543 return this.getSelectionBoundry('start');
545 getSelectionEnd: function() {
546 return this.getSelectionBoundry('end');
548 getSelectionAnchor: function() {
549 return this.getSelectionBoundry('anchor');
551 getSelectionFocus: function() {
552 return this.getSelectionBoundry('focus');
554 getSelectionBoundry: function(which) {
556 var selection = window.getSelection(),
557 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
558 focusElement = this.canvas.getDocumentElement(selection.focusNode);
560 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
564 if(which === 'anchor') {
566 element: anchorElement,
567 offset: selection.anchorOffset,
568 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
569 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
572 if(which === 'focus') {
574 element: focusElement,
575 offset: selection.focusOffset,
576 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
577 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
581 var getPlaceData = function(anchorFirst) {
584 if(which === 'start') {
585 element = anchorElement;
586 offset = selection.anchorOffset;
588 else if(which === 'end') {
589 element = focusElement;
590 offset = selection.focusOffset;
593 if(which === 'start') {
594 element = focusElement;
595 offset = selection.focusOffset;
597 else if(which === 'end') {
598 element = anchorElement;
599 offset = selection.anchorOffset;
602 return {element: element, offset: offset};
605 var anchorFirst, placeData, parent;
607 if(anchorElement.parent().sameNode(focusElement.parent())) {
608 parent = anchorElement.parent();
609 if(selection.anchorNode === selection.focusNode) {
610 anchorFirst = selection.anchorOffset <= selection.focusOffset;
612 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
614 placeData = getPlaceData(anchorFirst);
616 /*jshint bitwise: false*/
617 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
618 placeData = getPlaceData(anchorFirst);
621 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
623 element: placeData.element,
624 offset: placeData.offset,
625 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
626 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
632 fromXMLDocument: function(wlxmlDocument, elements, metadata) {
633 return new Canvas(wlxmlDocument, elements, metadata);