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(),
46 prepopulateOnEmpty: true
49 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
50 element.data(attr, '');
55 var FIRST_CONTENT_INDEX = 0;
57 // @@ TODO - refactor!
58 var getNode = function(element) {
59 return element.children('[document-element-content]');
62 this.wrapper.find(':not(iframe)').addBack().contents()
63 .filter(function() {return this.nodeType === Node.TEXT_NODE})
66 // TODO: use DocumentElement API
69 text = {original: el.text(), trimmed: $.trim(el.text())},
70 elParent = el.parent(),
71 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
72 hasSpanBefore = el.prev().length > 0 && getNode($(el.prev()[0])).attr('wlxml-tag') === 'span',
73 hasSpanAfter = el.next().length > 0 && getNode($(el.next()[0])).attr('wlxml-tag') === 'span';
75 if(el.parent().hasClass('canvas-widget') || elParent.attr('document-text-element') !== undefined)
76 return true; // continue
78 var addInfo = function(toAdd, where) {
79 var parentContents = elParent.contents(),
80 idx = parentContents.index(el[0]),
81 prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
82 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
85 if(where === 'above') {
86 target = prev ? $(prev) : elParent.parent();
87 key = prev ? 'orig-after' : 'orig-begin';
88 } else if(where === 'below') {
89 target = next ? $(next) : elParent.parent();
90 key = next ? 'orig-before' : 'orig-end';
91 } else { throw new Object;}
93 target.data(key, toAdd);
96 text.transformed = text.trimmed;
98 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
99 var startSpace = /\s/g.test(text.original.substr(0,1)),
100 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
101 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
103 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
105 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
106 text.transformed = ' ';
109 if(!text.transformed) {
110 addInfo(text.original, 'below');
112 return true; // continue
115 if(text.transformed !== text.original) {
117 addInfo(text.original, 'below');
119 var startingMatch = text.original.match(/^\s+/g),
120 endingMatch = text.original.match(/\s+$/g),
121 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
122 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
124 if(endingWhiteSpace) {
125 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
126 endingWhiteSpace = endingWhiteSpace.substr(1);
127 addInfo(endingWhiteSpace, 'below');
130 if(startingWhiteSpace) {
131 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
132 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
133 addInfo(startingWhiteSpace, 'above');
138 var element = documentElement.DocumentTextElement.create({text: text.transformed});
139 el.replaceWith(element.dom());
142 this.d = this.wrapper.children(0);
155 this.wrapper.on('keyup', function(e) {
156 if(e.which >= 37 && e.which <= 40) {
157 var element = canvas.getCursor().getPosition().element,
162 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
169 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
171 canvas.setCurrentElement(element, {caretTo: caretTo});
175 this.wrapper.on('keydown', function(e) {
176 var cursor = canvas.getCursor(),
177 position = canvas.getCursor().getPosition(),
178 element = position.element;
179 if(e.which >= 37 && e.which <= 40) {
181 if(element && (element instanceof documentElement.DocumentTextElement)) {
182 if(element.isEmpty()) {
183 var direction, caretTo;
184 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
191 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
192 canvas.setCurrentElement(element, {caretTo: caretTo});
194 var txt = element.dom().contents()[0].data;
195 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
197 canvas._moveCaretToTextElement(element, position.offset-2);
199 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
201 canvas._moveCaretToTextElement(element, position.offset+2);
209 var selectsWholeTextElement = function() {
210 if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd)
215 if(e.which === KEYS.X && e.ctrlKey && selectsWholeTextElement()) {
219 if(e.which === KEYS.BACKSPACE || e.which === KEYS.DELETE) {
220 if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
225 var cursorAtOperationEdge = position.offsetAtBeginning;
226 if(e.which === KEYS.DELETE) {
227 cursorAtOperationEdge = position.offsetAtEnd;
230 if(element.getText().length === 1 || selectsWholeTextElement()) {
234 else if(element.isEmpty()) {
236 var direction = 'above',
239 if(e.which === KEYS.DELETE) {
246 var parent = element.parent(),
247 grandParent = parent ? parent.parent() : null,
249 if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
250 if(grandParent && grandParent.children().length === 1) {
251 goto = grandParent.append({text: ''});
253 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
257 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
260 canvas.setCurrentElement(goto, {caretTo: caretTo});
261 canvas.publisher('contentChanged');
263 else if(cursorAtOperationEdge) {
269 if(e.which === KEYS.ENTER) {
271 var cursor = canvas.getCursor(),
272 position = cursor.getPosition(),
273 element = position.element;
275 if(!cursor.isSelecting()) {
277 var added = element.after({tag: 'block'});
278 added.append({text:''});
279 canvas.setCurrentElement(added, {caretTo: 'start'});
283 if(!(element.parent().parent())) {
284 return false; // top level element is unsplittable
287 var elements = position.element.split({offset: position.offset}),
292 if(position.offsetAtBeginning)
293 newEmpty = elements.first;
294 else if(position.offsetAtEnd)
295 newEmpty = elements.second;
298 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
301 goto = elements.second;
302 gotoOptions = {caretTo: 'start'};
305 canvas.setCurrentElement(goto, gotoOptions);
311 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
313 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
316 var observer = new MutationObserver(function(mutations) {
317 mutations.forEach(function(mutation) {
318 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
319 if(mutation.target.data === '')
320 mutation.target.data = utils.unicode.ZWS;
321 canvas.publisher('contentChanged');
325 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
326 observer.observe(this.d[0], config);
329 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
330 var el = canvas.getDocumentElement(e.currentTarget);
334 if(el instanceof documentElement.DocumentTextElement)
336 el.toggleLabel(true);
338 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
339 var el = canvas.getDocumentElement(e.currentTarget);
343 if(el instanceof documentElement.DocumentTextElement)
345 el.toggleLabel(false);
348 this.eventBus.on('elementToggled', function(toggle, element) {
350 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
351 canvas.setCurrentElement(element);
367 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
370 wrapText: function(params) {
371 params = _.extend({textNodeIdx: 0}, params);
372 if(typeof params.textNodeIdx === 'number')
373 params.textNodeIdx = [params.textNodeIdx];
375 var childrenInside = params.inside.children(),
376 idx1 = Math.min.apply(Math, params.textNodeIdx),
377 idx2 = Math.max.apply(Math, params.textNodeIdx),
378 textNode1 = childrenInside[idx1],
379 textNode2 = childrenInside[idx2],
380 sameNode = textNode1.sameNode(textNode2),
381 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
382 prefixInside = textNode1.getText().substr(params.offsetStart),
383 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
384 suffixOutside = textNode2.getText().substr(params.offsetEnd)
387 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
388 textNode1.after(wrapperElement);
391 if(prefixOutside.length > 0)
392 wrapperElement.before({text:prefixOutside});
394 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
395 wrapperElement.append({text: core});
398 if(prefixInside.length > 0)
399 wrapperElement.append({text: prefixInside});
400 for(var i = idx1 + 1; i < idx2; i++) {
401 wrapperElement.append(childrenInside[i]);
403 if(suffixInside.length > 0)
404 wrapperElement.append({text: suffixInside});
406 if(suffixOutside.length > 0)
407 wrapperElement.after({text: suffixOutside});
408 return wrapperElement;
411 wrapElements: function(params) {
412 if(!(params.element1.parent().sameNode(params.element2.parent())))
415 var parent = params.element1.parent(),
416 parentChildren = parent.children(),
417 wrapper = documentElement.DocumentNodeElement.create({
418 tag: params._with.tag,
419 klass: params._with.klass}),
420 idx1 = parent.childIndex(params.element1),
421 idx2 = parent.childIndex(params.element2);
429 var insertingMethod, insertingTarget;
431 insertingMethod = 'prepend';
432 insertingTarget = parent;
434 insertingMethod = 'after';
435 insertingTarget = parentChildren[idx1-1];
438 for(var i = idx1; i <= idx2; i++) {
439 wrapper.append(parentChildren[i].detach());
442 insertingTarget[insertingMethod](wrapper);
446 getSiblingParents: function(params) {
447 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
448 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
449 noSiblingParents = null;
451 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
452 return noSiblingParents;
455 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
456 if(parents1[i].sameNode(parents2[i]))
460 return {element1: parents1[i], element2: parents2[i]};
463 getDocumentElement: function(from) {
464 if(from instanceof HTMLElement || from instanceof Text) {
465 return documentElement.DocumentElement.fromHTMLElement(from, this);
468 getCursor: function() {
469 return new Cursor(this);
475 getCurrentNodeElement: function() {
476 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
479 getCurrentTextElement: function() {
480 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
485 setCurrentElement: function(element, params) {
486 params = _.extend({caretTo: 'end'}, params);
487 var findFirstDirectTextChild = function(e, nodeToLand) {
488 var byBrowser = this.getCursor().getPosition().element;
489 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
491 var children = e.children();
492 for(var i = 0; i < children.length; i++) {
493 if(children[i] instanceof documentElement.DocumentTextElement)
498 var _markAsCurrent = function(element) {
499 if(element instanceof documentElement.DocumentTextElement) {
500 this.wrapper.find('.current-text-element').removeClass('current-text-element');
501 element.dom().addClass('current-text-element');
503 this.wrapper.find('.current-node-element').removeClass('current-node-element')
504 element._container().addClass('current-node-element');
505 this.publisher('currentElementChanged', element);
510 var isTextElement = element instanceof documentElement.DocumentTextElement,
511 nodeElementToLand = isTextElement ? element.parent() : element,
512 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
513 currentTextElement = this.getCurrentTextElement(),
514 currentNodeElement = this.getCurrentNodeElement();
516 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
517 this.wrapper.find('.current-text-element').removeClass('current-text-element');
519 if(textElementToLand) {
520 _markAsCurrent(textElementToLand);
521 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
522 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
523 if(!(textElementToLand.sameNode(currentTextElement)))
524 this.publisher('currentTextElementSet', textElementToLand);
526 document.getSelection().removeAllRanges();
529 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
530 _markAsCurrent(nodeElementToLand);
532 this.publisher('currentNodeElementSet', nodeElementToLand);
536 _moveCaretToTextElement: function(element, where) {
537 var range = document.createRange(),
538 node = element.dom().contents()[0];
540 if(typeof where !== 'number') {
541 range.selectNodeContents(node);
543 range.setStart(node, where);
546 var collapseArg = true;
549 range.collapse(collapseArg);
551 var selection = document.getSelection();
553 selection.removeAllRanges();
554 selection.addRange(range);
555 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
558 setCursorPosition: function(position) {
560 this._moveCaretToTextElement(position.element, position.offset);
564 var parent = $('<div>'),
565 parts = this.doc().toXML(0);
566 parent.append(parts);
567 return parent.html();
571 $.extend(Canvas.prototype.list, {
572 create: function(params) {
573 if(!(params.element1.parent().sameNode(params.element2.parent())))
576 var parent = params.element1.parent();
578 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
579 var tmp = params.element1;
580 params.element1 = params.element2;
581 params.element2 = tmp;
584 var elementsToWrap = [];
586 var place = 'before';
588 parent.children().some(function(element) {
590 if(element.sameNode(params.element1))
592 if(place === 'inside') {
593 if(element instanceof documentElement.DocumentTextElement) {
594 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
595 if(element.children()[0].sameNode(params.element1))
596 params.element1 = element;
598 element.setWlxmlClass('item');
599 elementsToWrap.push(element);
601 if(_e.sameNode(params.element2))
605 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
608 if(parent.is('list')) {
609 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
610 item.exec('toggleBullet', false);
611 toret = listElement.parent();
616 params.element1.before(toret);
618 elementsToWrap.forEach(function(element) {
620 listElement.append(element);
623 extractItems: function(params) {
624 params = _.extend({merge: true}, params);
625 var list = params.element1.parent();
626 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
629 var idx1 = list.childIndex(params.element1),
630 idx2 = list.childIndex(params.element2),
633 succeedingItems = [],
634 items = list.children(),
635 listIsNested = list.parent().getWlxmlClass() === 'item',
639 var tmp = idx1; idx1 = idx2; idx2 = tmp;
642 items.forEach(function(item, idx) {
644 precedingItems.push(item);
645 else if(idx >= idx1 && idx <= idx2) {
646 extractedItems.push(item);
649 succeedingItems.push(item);
653 var reference = listIsNested ? list.parent() : list;
654 if(succeedingItems.length === 0) {
655 var reference_orig = reference;
656 extractedItems.forEach(function(item) {
657 reference.after(item);
660 item.setWlxmlClass(null);
662 if(precedingItems.length === 0)
663 reference_orig.detach();
664 } else if(precedingItems.length === 0) {
665 extractedItems.forEach(function(item) {
666 reference.before(item);
668 item.setWlxmlClass(null);
671 extractedItems.forEach(function(item) {
672 reference.after(item);
674 item.setWlxmlClass(null);
677 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
681 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
683 succeedingItems.forEach(function(item) {
684 secondList.append(item);
687 reference.after(toAdd);
689 if(!params.merge && listIsNested) {
690 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
694 areItemsOfTheSameList: function(params) {
695 var e1 = params.element1,
696 e2 = params.element2;
697 return e1.parent().sameNode(e2.parent())
698 && e1.parent().is('list');
703 var Cursor = function(canvas) {
704 this.canvas = canvas;
707 $.extend(Cursor.prototype, {
708 isSelecting: function() {
709 var selection = window.getSelection();
710 return !selection.isCollapsed;
712 isSelectingWithinElement: function() {
713 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
715 isSelectingSiblings: function() {
716 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
718 getPosition: function() {
719 return this.getSelectionAnchor();
721 getSelectionStart: function() {
722 return this.getSelectionBoundry('start');
724 getSelectionEnd: function() {
725 return this.getSelectionBoundry('end');
727 getSelectionAnchor: function() {
728 return this.getSelectionBoundry('anchor');
730 getSelectionFocus: function() {
731 return this.getSelectionBoundry('focus');
733 getSelectionBoundry: function(which) {
734 var selection = window.getSelection(),
735 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
736 focusElement = this.canvas.getDocumentElement(selection.focusNode);
738 var getOffset = function(where) {
740 if(where === 'anchor') {
741 node = selection.anchorNode;
742 toret = selection.anchorOffset;
744 node = selection.focusNode;
745 toret = selection.focusOffset;
748 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
750 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
755 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
758 if(which === 'anchor') {
760 element: anchorElement,
761 offset: getOffset('anchor'),
762 offsetAtBeginning: getOffset('anchor') === 0,
763 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
766 if(which === 'focus') {
768 element: focusElement,
769 offset: getOffset('focus'),
770 offsetAtBeginning: getOffset('focus') === 0,
771 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
778 if(anchorElement.parent().sameNode(focusElement.parent())) {
779 var parent = anchorElement.parent(),
780 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
782 if(which === 'start') {
783 element = anchorElement;
784 offset = getOffset('anchor')
786 else if(which === 'end') {
787 element = focusElement,
788 offset = getOffset('focus')
791 if(which === 'start') {
792 element = focusElement,
793 offset = getOffset('focus')
795 else if(which === 'end') {
796 element = anchorElement;
797 offset = getOffset('anchor')
801 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
802 if(which === 'start') {
803 element = anchorElement;
804 offset = getOffset('anchor')
806 element = focusElement;
807 offset = getOffset('focus')
811 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
815 offsetAtBeginning: offset === 0,
816 offsetAtEnd: nodeLen === offset
822 fromXML: function(xml, publisher) {
823 return new Canvas(xml, publisher);