2 'libs/jquery-1.9.1.min',
5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/utils'
7 ], function($, _, Backbone, documentElement, utils) {
11 var Canvas = function(wlxml, publisher) {
12 this.eventBus = _.extend({}, Backbone.Events);
13 this.loadWlxml(wlxml);
14 this.publisher = publisher ? publisher : function() {};
17 $.extend(Canvas.prototype, {
19 loadWlxml: function(wlxml) {
20 var d = wlxml ? $($.trim(wlxml)) : null;
22 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
23 this.wrapper.append(d);
26 this.wrapper.find('*').replaceWith(function() {
27 var currentTag = $(this);
28 if(currentTag.attr('wlxml-tag'))
31 var meta = {}, others = {};
32 for(var i = 0; i < this.attributes.length; i++) {
33 var attr = this.attributes[i];
34 if(attr.name.substr(0, 5) === 'meta-')
35 meta[attr.name.substr(5)] = attr.value;
36 else if(attr.name !== 'class')
37 others[attr.name] = attr.value;
40 var element = documentElement.DocumentNodeElement.create({
41 tag: currentTag.prop('tagName').toLowerCase(),
42 klass: currentTag.attr('class'),
45 rawChildren: currentTag.contents()
48 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
49 element.data(attr, '');
54 var FIRST_CONTENT_INDEX = 0;
56 // @@ TODO - refactor!
57 var getNode = function(element) {
58 return element.children('[document-element-content]');
61 this.wrapper.find(':not(iframe)').addBack().contents()
62 .filter(function() {return this.nodeType === Node.TEXT_NODE})
65 // TODO: use DocumentElement API
68 text = {original: el.text(), trimmed: $.trim(el.text())},
69 elParent = el.parent(),
70 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
71 hasSpanBefore = el.prev().length > 0 && getNode($(el.prev()[0])).attr('wlxml-tag') === 'span',
72 hasSpanAfter = el.next().length > 0 && getNode($(el.next()[0])).attr('wlxml-tag') === 'span';
74 if(el.parent().hasClass('canvas-widget'))
75 return true; // continue
77 var addInfo = function(toAdd, where) {
78 var parentContents = elParent.contents(),
79 idx = parentContents.index(el[0]),
80 prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
81 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
84 if(where === 'above') {
85 target = prev ? $(prev) : elParent.parent();
86 key = prev ? 'orig-after' : 'orig-begin';
87 } else if(where === 'below') {
88 target = next ? $(next) : elParent.parent();
89 key = next ? 'orig-before' : 'orig-end';
90 } else { throw new Object;}
92 target.data(key, toAdd);
95 text.transformed = text.trimmed;
97 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
98 var startSpace = /\s/g.test(text.original.substr(0,1)),
99 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
100 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
102 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
104 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
105 text.transformed = ' ';
108 if(!text.transformed) {
109 addInfo(text.original, 'below');
111 return true; // continue
114 if(text.transformed !== text.original) {
116 addInfo(text.original, 'below');
118 var startingMatch = text.original.match(/^\s+/g),
119 endingMatch = text.original.match(/\s+$/g),
120 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
121 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
123 if(endingWhiteSpace) {
124 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
125 endingWhiteSpace = endingWhiteSpace.substr(1);
126 addInfo(endingWhiteSpace, 'below');
129 if(startingWhiteSpace) {
130 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
131 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
132 addInfo(startingWhiteSpace, 'above');
137 var element = documentElement.DocumentTextElement.create({text: text.transformed});
138 el.replaceWith(element.dom());
141 this.d = this.wrapper.children(0);
143 this.wrapper.on('keydown', function(e) {
146 var cursor = canvas.getCursor();
147 if(!cursor.isSelecting()) {
148 var position = cursor.getPosition(),
149 element = position.element;
151 if(!(element.parent().parent())) {
152 return false; // top level element is unsplittable
155 var elements = position.element.split({offset: position.offset}),
159 if(position.offsetAtBeginning)
160 newEmpty = elements.first;
161 else if(position.offsetAtEnd)
162 newEmpty = elements.second;
164 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
165 canvas.setCurrentElement(goto);
182 this.wrapper.on('keyup', function(e) {
183 if(e.which >= 37 && e.which <= 40) {
184 var element = canvas.getCursor().getPosition().element,
189 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
196 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
198 canvas.setCurrentElement(element, {caretTo: caretTo});
202 this.wrapper.on('keydown', function(e) {
203 var cursor = canvas.getCursor(),
204 position = canvas.getCursor().getPosition(),
205 element = position.element;
206 if(e.which >= 37 && e.which <= 40) {
208 if(element && (element instanceof documentElement.DocumentTextElement)) {
209 if(element.isEmpty()) {
210 var direction, caretTo;
211 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
218 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
219 canvas.setCurrentElement(element, {caretTo: caretTo});
221 var txt = element.dom().contents()[0].data;
222 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
224 canvas._moveCaretToTextElement(element, position.offset-2);
226 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
228 canvas._moveCaretToTextElement(element, position.offset+2);
236 var selectsWholeTextElement = function() {
237 if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd)
242 if(e.which === KEYS.X && e.ctrlKey && selectsWholeTextElement()) {
246 if(e.which === KEYS.BACKSPACE || e.which === KEYS.DELETE) {
247 if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
252 var cursorAtOperationEdge = position.offsetAtBeginning;
253 if(e.which === KEYS.DELETE) {
254 cursorAtOperationEdge = position.offsetAtEnd;
257 if(element.getText().length === 1 || selectsWholeTextElement()) {
261 else if(element.isEmpty()) {
263 var direction = 'above',
266 if(e.which === KEYS.DELETE) {
273 var parent = element.parent(),
274 grandParent = parent ? parent.parent() : null,
276 if(parent.children().length === 1) {
277 if(grandParent && grandParent.children().length === 1) {
278 goto = grandParent.append({text: ''});
280 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
284 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
287 canvas.setCurrentElement(goto, {caretTo: caretTo});
289 else if(cursorAtOperationEdge) {
296 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
298 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
301 var observer = new MutationObserver(function(mutations) {
302 mutations.forEach(function(mutation) {
303 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
304 mutation.target.data = utils.unicode.ZWS;
307 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
308 observer.observe(this.d[0], config);
311 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
312 var el = canvas.getDocumentElement(e.currentTarget);
316 if(el instanceof documentElement.DocumentTextElement)
318 el.toggleLabel(true);
320 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
321 var el = canvas.getDocumentElement(e.currentTarget);
325 if(el instanceof documentElement.DocumentTextElement)
327 el.toggleLabel(false);
330 this.eventBus.on('elementToggled', function(toggle, element) {
332 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
333 canvas.setCurrentElement(element);
349 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
352 wrapText: function(params) {
353 params = _.extend({textNodeIdx: 0}, params);
354 if(typeof params.textNodeIdx === 'number')
355 params.textNodeIdx = [params.textNodeIdx];
357 var childrenInside = params.inside.children(),
358 idx1 = Math.min.apply(Math, params.textNodeIdx),
359 idx2 = Math.max.apply(Math, params.textNodeIdx),
360 textNode1 = childrenInside[idx1],
361 textNode2 = childrenInside[idx2],
362 sameNode = textNode1.sameNode(textNode2),
363 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
364 prefixInside = textNode1.getText().substr(params.offsetStart),
365 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
366 suffixOutside = textNode2.getText().substr(params.offsetEnd)
369 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
370 textNode1.after(wrapperElement);
373 if(prefixOutside.length > 0)
374 wrapperElement.before({text:prefixOutside});
376 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
377 wrapperElement.append({text: core});
380 if(prefixInside.length > 0)
381 wrapperElement.append({text: prefixInside});
382 for(var i = idx1 + 1; i < idx2; i++) {
383 wrapperElement.append(childrenInside[i]);
385 if(suffixInside.length > 0)
386 wrapperElement.append({text: suffixInside});
388 if(suffixOutside.length > 0)
389 wrapperElement.after({text: suffixOutside});
390 return wrapperElement;
393 wrapElements: function(params) {
394 if(!(params.element1.parent().sameNode(params.element2.parent())))
397 var parent = params.element1.parent(),
398 parentChildren = parent.children(),
399 wrapper = documentElement.DocumentNodeElement.create({
400 tag: params._with.tag,
401 klass: params._with.klass}),
402 idx1 = parent.childIndex(params.element1),
403 idx2 = parent.childIndex(params.element2);
411 var insertingMethod, insertingTarget;
413 insertingMethod = 'prepend';
414 insertingTarget = parent;
416 insertingMethod = 'after';
417 insertingTarget = parentChildren[idx1-1];
420 for(var i = idx1; i <= idx2; i++) {
421 wrapper.append(parentChildren[i].detach());
424 insertingTarget[insertingMethod](wrapper);
428 getSiblingParents: function(params) {
429 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
430 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
431 noSiblingParents = null;
433 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
434 return noSiblingParents;
437 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
438 if(parents1[i].sameNode(parents2[i]))
442 return {element1: parents1[i], element2: parents2[i]};
445 getDocumentElement: function(from) {
446 if(from instanceof HTMLElement || from instanceof Text) {
447 return documentElement.DocumentElement.fromHTMLElement(from, this);
450 getCursor: function() {
451 return new Cursor(this);
457 getCurrentNodeElement: function() {
458 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
461 getCurrentTextElement: function() {
462 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
467 setCurrentElement: function(element, params) {
468 params = _.extend({caretTo: 'end'}, params);
469 var findFirstDirectTextChild = function(e, nodeToLand) {
470 var byBrowser = this.getCursor().getPosition().element;
471 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
473 var children = e.children();
474 for(var i = 0; i < children.length; i++) {
475 if(children[i] instanceof documentElement.DocumentTextElement)
480 var _markAsCurrent = function(element) {
481 if(element instanceof documentElement.DocumentTextElement) {
482 this.wrapper.find('.current-text-element').removeClass('current-text-element');
483 element.dom().addClass('current-text-element');
485 this.wrapper.find('.current-node-element').removeClass('current-node-element')
486 element._container().addClass('current-node-element');
487 this.publisher('currentElementChanged', element);
492 var isTextElement = element instanceof documentElement.DocumentTextElement,
493 nodeElementToLand = isTextElement ? element.parent() : element,
494 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
495 currentTextElement = this.getCurrentTextElement(),
496 currentNodeElement = this.getCurrentNodeElement();
498 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
499 this.wrapper.find('.current-text-element').removeClass('current-text-element');
501 if(textElementToLand) {
502 _markAsCurrent(textElementToLand);
503 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
504 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
505 if(!(textElementToLand.sameNode(currentTextElement)))
506 this.publisher('currentTextElementSet', textElementToLand);
508 document.getSelection().removeAllRanges();
511 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
512 _markAsCurrent(nodeElementToLand);
514 this.publisher('currentNodeElementSet', nodeElementToLand);
518 _moveCaretToTextElement: function(element, where) {
519 var range = document.createRange(),
520 node = element.dom().contents()[0];
522 if(typeof where !== 'number') {
523 range.selectNodeContents(node);
525 range.setStart(node, where);
528 var collapseArg = true;
531 range.collapse(collapseArg);
533 var selection = document.getSelection();
535 selection.removeAllRanges();
536 selection.addRange(range);
537 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
540 setCursorPosition: function(position) {
542 this._moveCaretToTextElement(position.element, position.offset);
546 var parent = $('<div>'),
547 parts = this.doc().toXML(0);
548 parent.append(parts);
549 return parent.html();
553 $.extend(Canvas.prototype.list, {
554 create: function(params) {
555 if(!(params.element1.parent().sameNode(params.element2.parent())))
558 var parent = params.element1.parent();
560 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
561 var tmp = params.element1;
562 params.element1 = params.element2;
563 params.element2 = tmp;
566 var elementsToWrap = [];
568 var place = 'before';
570 parent.children().some(function(element) {
572 if(element.sameNode(params.element1))
574 if(place === 'inside') {
575 if(element instanceof documentElement.DocumentTextElement) {
576 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
577 if(element.children()[0].sameNode(params.element1))
578 params.element1 = element;
580 element.setWlxmlClass('item');
581 elementsToWrap.push(element);
583 if(_e.sameNode(params.element2))
587 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
590 if(parent.is('list')) {
591 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
592 toret = listElement.parent();
597 params.element1.before(toret);
599 elementsToWrap.forEach(function(element) {
601 listElement.append(element);
604 extractItems: function(params) {
605 params = _.extend({merge: true}, params);
606 var list = params.element1.parent();
607 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
610 var idx1 = list.childIndex(params.element1),
611 idx2 = list.childIndex(params.element2),
614 succeedingItems = [],
615 items = list.children(),
616 listIsNested = list.parent().getWlxmlClass() === 'item',
620 var tmp = idx1; idx1 = idx2; idx2 = tmp;
623 items.forEach(function(item, idx) {
625 precedingItems.push(item);
626 else if(idx >= idx1 && idx <= idx2) {
627 extractedItems.push(item);
630 succeedingItems.push(item);
634 var reference = listIsNested ? list.parent() : list;
635 if(succeedingItems.length === 0) {
636 var reference_orig = reference;
637 extractedItems.forEach(function(item) {
638 reference.after(item);
641 item.setWlxmlClass(null);
643 if(precedingItems.length === 0)
644 reference_orig.detach();
645 } else if(precedingItems.length === 0) {
646 extractedItems.forEach(function(item) {
647 reference.before(item);
649 item.setWlxmlClass(null);
652 extractedItems.forEach(function(item) {
653 reference.after(item);
655 item.setWlxmlClass(null);
658 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
662 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
664 succeedingItems.forEach(function(item) {
665 secondList.append(item);
668 reference.after(toAdd);
670 if(!params.merge && listIsNested) {
671 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
675 areItemsOfTheSameList: function(params) {
676 var e1 = params.element1,
677 e2 = params.element2;
678 return e1.parent().sameNode(e2.parent())
679 && e1.parent().is('list');
684 var Cursor = function(canvas) {
685 this.canvas = canvas;
688 $.extend(Cursor.prototype, {
689 isSelecting: function() {
690 var selection = window.getSelection();
691 return !selection.isCollapsed;
693 isSelectingWithinElement: function() {
694 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
696 isSelectingSiblings: function() {
697 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
699 getPosition: function() {
700 return this.getSelectionAnchor();
702 getSelectionStart: function() {
703 return this.getSelectionBoundry('start');
705 getSelectionEnd: function() {
706 return this.getSelectionBoundry('end');
708 getSelectionAnchor: function() {
709 return this.getSelectionBoundry('anchor');
711 getSelectionFocus: function() {
712 return this.getSelectionBoundry('focus');
714 getSelectionBoundry: function(which) {
715 var selection = window.getSelection(),
716 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
717 focusElement = this.canvas.getDocumentElement(selection.focusNode);
719 var getOffset = function(where) {
721 if(where === 'anchor') {
722 node = selection.anchorNode;
723 toret = selection.anchorOffset;
725 node = selection.focusNode;
726 toret = selection.focusOffset;
729 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
731 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
736 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
739 if(which === 'anchor') {
741 element: anchorElement,
742 offset: getOffset('anchor'),
743 offsetAtBeginning: getOffset('anchor') === 0,
744 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
747 if(which === 'focus') {
749 element: focusElement,
750 offset: getOffset('focus'),
751 offsetAtBeginning: getOffset('focus') === 0,
752 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
759 if(anchorElement.parent().sameNode(focusElement.parent())) {
760 var parent = anchorElement.parent(),
761 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
763 if(which === 'start') {
764 element = anchorElement;
765 offset = getOffset('anchor')
767 else if(which === 'end') {
768 element = focusElement,
769 offset = getOffset('focus')
772 if(which === 'start') {
773 element = focusElement,
774 offset = getOffset('focus')
776 else if(which === 'end') {
777 element = anchorElement;
778 offset = getOffset('anchor')
782 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
783 if(which === 'start') {
784 element = anchorElement;
785 offset = getOffset('anchor')
787 element = focusElement;
788 offset = getOffset('focus')
792 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
796 offsetAtBeginning: offset === 0,
797 offsetAtEnd: nodeLen === offset
803 fromXML: function(xml, publisher) {
804 return new Canvas(xml, publisher);