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(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);
423 toggleGrid: function() {
424 this.rootWrapper.toggleClass('grid-on');
425 this.trigger('changed');
427 isGridToggled: function() {
428 return this.rootWrapper.hasClass('grid-on');
433 var isText = function(node) {
434 return node && node.nodeType === Node.TEXT_NODE && $(node.parentNode).is('[document-text-element]');
437 var Selection = function(canvas) {
438 this.canvas = canvas;
439 var nativeSelection = this.nativeSelection = window.getSelection();
440 Object.defineProperty(this, 'type', {
442 if(nativeSelection.focusNode) {
443 if(nativeSelection.isCollapsed && isText(nativeSelection.focusNode)) {
446 if(isText(nativeSelection.focusNode) && isText(nativeSelection.anchorNode)) {
447 return 'textSelection';
450 if(canvas.getCurrentNodeElement()) {
457 $.extend(Selection.prototype, {
458 toDocumentFragment: function() {
459 var doc = this.canvas.wlxmlDocument,
460 anchorElement = this.canvas.getDocumentElement(this.nativeSelection.anchorNode),
461 focusElement = this.canvas.getDocumentElement(this.nativeSelection.focusNode),
462 anchorNode = anchorElement ? anchorElement.wlxmlNode : null,
463 focusNode = focusElement ? focusElement.wlxmlNode : null;
464 if(this.type === 'caret') {
465 return doc.createFragment(doc.CaretFragment, {node: anchorNode, offset: this.nativeSelection.anchorOffset});
467 if(this.type === 'textSelection') {
468 if(anchorNode.isSiblingOf(focusNode)) {
469 return doc.createFragment(doc.TextRangeFragment, {
471 offset1: this.nativeSelection.anchorOffset,
473 offset2: this.nativeSelection.focusOffset,
477 var siblingParents = doc.getSiblingParents({node1: anchorNode, node2: focusNode});
478 return doc.createFragment(doc.RangeFragment, {
479 node1: siblingParents.node1,
480 node2: siblingParents.node2
484 if(this.type === 'node') {
485 return doc.createFragment(doc.NodeFragment, {node: this.canvas.getCurrentNodeElement().wlxmlNode});
488 sameAs: function(other) {
493 var Cursor = function(canvas) {
494 this.canvas = canvas;
495 this.selection = window.getSelection();
498 $.extend(Cursor.prototype, {
499 sameAs: function(other) {
505 ['focusNode', 'focusOffset', 'anchorNode', 'anchorOffset'].some(function(prop) {
506 same = same && this.selection[prop] === other.selection[prop];
508 return true; // break
514 isSelecting: function() {
515 var selection = window.getSelection();
516 return !selection.isCollapsed;
518 isSelectingWithinElement: function() {
519 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
521 isWithinElement: function() {
522 return !this.isSelecting() || this.isSelectingWithinElement();
524 isSelectingSiblings: function() {
525 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
527 getPosition: function() {
528 return this.getSelectionAnchor();
530 getSelectionStart: function() {
531 return this.getSelectionBoundry('start');
533 getSelectionEnd: function() {
534 return this.getSelectionBoundry('end');
536 getSelectionAnchor: function() {
537 return this.getSelectionBoundry('anchor');
539 getSelectionFocus: function() {
540 return this.getSelectionBoundry('focus');
542 getSelectionBoundry: function(which) {
544 var selection = window.getSelection(),
545 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
546 focusElement = this.canvas.getDocumentElement(selection.focusNode);
548 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
552 if(which === 'anchor') {
554 element: anchorElement,
555 offset: selection.anchorOffset,
556 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
557 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
560 if(which === 'focus') {
562 element: focusElement,
563 offset: selection.focusOffset,
564 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
565 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
569 var getPlaceData = function(anchorFirst) {
572 if(which === 'start') {
573 element = anchorElement;
574 offset = selection.anchorOffset;
576 else if(which === 'end') {
577 element = focusElement;
578 offset = selection.focusOffset;
581 if(which === 'start') {
582 element = focusElement;
583 offset = selection.focusOffset;
585 else if(which === 'end') {
586 element = anchorElement;
587 offset = selection.anchorOffset;
590 return {element: element, offset: offset};
593 var anchorFirst, placeData, parent;
595 if(anchorElement.parent().sameNode(focusElement.parent())) {
596 parent = anchorElement.parent();
597 if(selection.anchorNode === selection.focusNode) {
598 anchorFirst = selection.anchorOffset <= selection.focusOffset;
600 anchorFirst = (parent.getFirst(anchorElement, focusElement) === anchorElement);
602 placeData = getPlaceData(anchorFirst);
604 /*jshint bitwise: false*/
605 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
606 placeData = getPlaceData(anchorFirst);
609 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
611 element: placeData.element,
612 offset: placeData.offset,
613 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
614 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
620 fromXMLDocument: function(wlxmlDocument, elements, metadata) {
621 return new Canvas(wlxmlDocument, elements, metadata);