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 this.rootWrapper.on('keyup keydown keypress', function(e) {
152 keyboard.handleKey(e, canvas);
155 this.rootWrapper.on('mouseup', function() {
156 canvas.triggerSelectionChanged();
160 this.rootWrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
161 mouseDown = e.target;
164 this.rootWrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
166 if(e.originalEvent.detail === 3) {
168 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
170 if(mouseDown === e.target) {
171 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
176 this.rootWrapper.on('paste', function(e) {
179 var clipboardData = e.originalEvent.clipboardData;
180 if(!clipboardData || !clipboardData.getData) {
181 return; // TODO: alert
184 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
185 cursor = canvas.getCursor(),
186 element = cursor.getPosition().element,
189 if(element && cursor.isWithinElement()) {
190 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
191 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
192 element.setText(lhs+text+rhs);
193 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
195 /* jshint noempty:false */
200 /* globals MutationObserver */
201 var observer = new MutationObserver(function(mutations) {
202 mutations.forEach(function(mutation) {
203 if(canvas.dom[0].contains(mutation.target) && documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
204 observer.disconnect();
205 if(mutation.target.data === '') {
206 mutation.target.data = utils.unicode.ZWS;
208 else if(mutation.oldValue === utils.unicode.ZWS) {
209 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
210 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
212 observer.observe(canvas.dom[0], config);
214 var textElement = canvas.getDocumentElement(mutation.target),
215 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
217 //textElement.data('wlxmlNode').setText(toSet);
218 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
219 if(textElement.wlxmlNode.getText() !== toSet) {
220 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
225 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
226 observer.observe(this.rootWrapper[0], config);
229 var hoverHandler = function(e) {
230 var el = canvas.getDocumentElement(e.currentTarget),
239 if(el instanceof documentElement.DocumentTextElement) {
242 el.updateState({exposed:expose[e.type]});
245 this.rootWrapper.on('mouseover', '[document-node-element], [document-text-element]', hoverHandler);
246 this.rootWrapper.on('mouseout', '[document-node-element], [document-text-element]', hoverHandler);
248 this.eventBus.on('elementToggled', function(toggle, element) {
250 canvas.setCurrentElement(canvas.getPreviousTextElement(element));
260 return this.rootElement;
263 toggleElementHighlight: function(node, toggle) {
264 var element = utils.getElementForNode(node);
265 element.updateState({exposed: toggle});
268 getCursor: function() {
269 return new Cursor(this);
273 getCurrentNodeElement: function() {
274 return this.currentNodeElement;
277 getCurrentTextElement: function() {
278 var htmlElement = this.rootWrapper.find('.current-text-element')[0];
280 return this.getDocumentElement(htmlElement);
284 getPreviousTextElement: function(relativeToElement, includeInvisible) {
285 return this.getNearestTextElement('above', relativeToElement, includeInvisible);
288 getNextTextElement: function(relativeToElement, includeInvisible) {
289 return this.getNearestTextElement('below', relativeToElement, includeInvisible);
292 getNearestTextElement: function(direction, relativeToElement, includeInvisible) {
293 includeInvisible = includeInvisible !== undefined ? includeInvisible : false;
294 var selector = '[document-text-element]' + (includeInvisible ? '' : ':visible');
295 return this.getDocumentElement(utils.nearestInDocumentOrder(selector, direction, relativeToElement.dom[0]));
298 contains: function(element) {
299 return element && element.dom && element.dom.parents().index(this.rootWrapper) !== -1;
302 triggerSelectionChanged: function() {
303 this.trigger('selectionChanged', this.getSelection());
304 var s = this.getSelection(),
305 f = s.toDocumentFragment();
306 if(f && f instanceof f.RangeFragment) {
307 if(this.currentNodeElement) {
308 this.currentNodeElement.updateState({active: false});
309 this.currentNodeElement = null;
314 getSelection: function() {
315 return new Selection(this);
318 select: function(fragment) {
319 if(fragment instanceof this.wlxmlDocument.RangeFragment) {
320 this.setCurrentElement(fragment.endNode, {caretTo: fragment.endOffset});
321 } else if(fragment instanceof this.wlxmlDocument.NodeFragment) {
323 caretTo: fragment instanceof this.wlxmlDocument.CaretFragment ? fragment.offset : 'start'
325 this.setCurrentElement(fragment.node, params);
327 logger.debug('Fragment not supported');
331 setCurrentElement: function(element, params) {
333 logger.debug('Invalid element passed to setCurrentElement: ' + element);
337 if(!(element instanceof documentElement.DocumentElement)) {
338 element = utils.getElementForNode(element);
341 if(!element || !this.contains(element)) {
342 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
346 params = _.extend({caretTo: 'end'}, params);
347 var findFirstDirectTextChild = function(e, nodeToLand) {
348 var byBrowser = this.getCursor().getPosition().element;
349 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
352 return _.isFunction(e.getVerticallyFirstTextElement) ? e.getVerticallyFirstTextElement({considerChildren: false}) : null;
354 var _markAsCurrent = function(element) {
355 if(element instanceof documentElement.DocumentTextElement) {
356 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
357 element.dom.addClass('current-text-element');
359 if(this.currentNodeElement) {
360 this.currentNodeElement.updateState({active: false});
362 element.updateState({active: true});
363 this.currentNodeElement = element;
368 var isTextElement = element instanceof documentElement.DocumentTextElement,
369 nodeElementToLand = isTextElement ? element.parent() : element,
370 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
371 currentTextElement = this.getCurrentTextElement(),
372 currentNodeElement = this.getCurrentNodeElement();
374 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
375 this.rootWrapper.find('.current-text-element').removeClass('current-text-element');
378 if(textElementToLand) {
379 _markAsCurrent(textElementToLand);
380 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
381 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
384 document.getSelection().removeAllRanges();
387 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
388 _markAsCurrent(nodeElementToLand);
390 this.triggerSelectionChanged();
393 _moveCaretToTextElement: function(element, where) {
394 var range = document.createRange(),
395 node = element.dom.contents()[0];
397 if(typeof where !== 'number') {
398 range.selectNodeContents(node);
400 range.setStart(node, Math.min(node.data.length, where));
403 if(where !== 'whole') {
404 var collapseArg = true;
405 if(where === 'end') {
408 range.collapse(collapseArg);
410 var selection = document.getSelection();
412 selection.removeAllRanges();
413 selection.addRange(range);
414 this.rootWrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
417 setCursorPosition: function(position) {
418 if(position.element) {
419 this._moveCaretToTextElement(position.element, position.offset);
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 || !focusNode) {
463 if(anchorNode.isSiblingOf(focusNode)) {
464 return doc.createFragment(doc.TextRangeFragment, {
466 offset1: this.nativeSelection.anchorOffset,
468 offset2: this.nativeSelection.focusOffset,
472 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
473 return doc.createFragment(doc.RangeFragment, {
474 node1: siblingParents.node1,
475 node2: siblingParents.node2
479 if(this.type === 'node') {
480 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
483 sameAs: function(other) {
488 var Cursor = function(canvas) {
489 this.canvas = canvas;
490 this.selection = window.getSelection();
493 $.extend(Cursor.prototype, {
494 sameAs: function(other) {
500 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
501 same = same && this.selection[prop] === other.selection[prop];
503 return true; // break
509 isSelecting: function() {
510 var selection = window.getSelection();
511 return !selection.isCollapsed;
513 isSelectingWithinElement: function() {
514 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
516 isWithinElement: function() {
517 return !this.isSelecting() || this.isSelectingWithinElement();
519 isSelectingSiblings: function() {
520 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
522 getPosition: function() {
523 return this.getSelectionAnchor();
525 getSelectionStart: function() {
526 return this.getSelectionBoundry('start');
528 getSelectionEnd: function() {
529 return this.getSelectionBoundry('end');
531 getSelectionAnchor: function() {
532 return this.getSelectionBoundry('anchor');
534 getSelectionFocus: function() {
535 return this.getSelectionBoundry('focus');
537 getSelectionBoundry: function(which) {
539 var selection = window.getSelection(),
540 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
541 focusElement = this.canvas.getDocumentElement(selection.focusNode);
543 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
547 if(which === 'anchor') {
549 element: anchorElement,
550 offset: selection.anchorOffset,
551 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
552 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
555 if(which === 'focus') {
557 element: focusElement,
558 offset: selection.focusOffset,
559 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
560 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
564 var getPlaceData = function(anchorFirst) {
567 if(which === 'start') {
568 element = anchorElement;
569 offset = selection.anchorOffset;
571 else if(which === 'end') {
572 element = focusElement;
573 offset = selection.focusOffset;
576 if(which === 'start') {
577 element = focusElement;
578 offset = selection.focusOffset;
580 else if(which === 'end') {
581 element = anchorElement;
582 offset = selection.anchorOffset;
585 return {element: element, offset: offset};
588 var anchorFirst, placeData, parent;
590 if(anchorElement.parent().sameNode(focusElement.parent())) {
591 parent = anchorElement.parent();
592 if(selection.anchorNode === selection.focusNode) {
593 anchorFirst = selection.anchorOffset <= selection.focusOffset;
595 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
597 placeData = getPlaceData(anchorFirst);
599 /*jshint bitwise: false*/
600 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
601 placeData = getPlaceData(anchorFirst);
604 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
606 element: placeData.element,
607 offset: placeData.offset,
608 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
609 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
615 fromXMLDocument: function(wlxmlDocument, elements, metadata) {
616 return new Canvas(wlxmlDocument, elements, metadata);