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 var willDeleteWholeText = function() {
231 return element.getText().length === 1 || selectsWholeTextElement();
234 if(willDeleteWholeText()) {
238 else if(element.isEmpty()) {
240 var direction = 'above',
243 if(e.which === KEYS.DELETE) {
250 var parent = element.parent(),
251 grandParent = parent ? parent.parent() : null,
253 if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
254 if(grandParent && grandParent.children().length === 1) {
255 goto = grandParent.append({text: ''});
257 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
261 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
264 canvas.setCurrentElement(goto, {caretTo: caretTo});
265 canvas.publisher('contentChanged');
267 else if(cursorAtOperationEdge) {
273 if(e.which === KEYS.ENTER) {
275 var cursor = canvas.getCursor(),
276 position = cursor.getPosition(),
277 element = position.element;
279 if(!cursor.isSelecting()) {
281 var added = element.after({tag: 'block'});
282 added.append({text:''});
283 canvas.setCurrentElement(added, {caretTo: 'start'});
287 if(!(element.parent().parent())) {
288 return false; // top level element is unsplittable
291 var elements = position.element.split({offset: position.offset}),
296 if(position.offsetAtBeginning)
297 newEmpty = elements.first;
298 else if(position.offsetAtEnd)
299 newEmpty = elements.second;
302 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
305 goto = elements.second;
306 gotoOptions = {caretTo: 'start'};
309 canvas.setCurrentElement(goto, gotoOptions);
315 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
317 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
320 var observer = new MutationObserver(function(mutations) {
321 mutations.forEach(function(mutation) {
322 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
323 if(mutation.target.data === '')
324 mutation.target.data = utils.unicode.ZWS;
325 canvas.publisher('contentChanged');
329 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
330 observer.observe(this.d[0], config);
333 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
334 var el = canvas.getDocumentElement(e.currentTarget);
338 if(el instanceof documentElement.DocumentTextElement)
340 el.toggleLabel(true);
342 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
343 var el = canvas.getDocumentElement(e.currentTarget);
347 if(el instanceof documentElement.DocumentTextElement)
349 el.toggleLabel(false);
352 this.eventBus.on('elementToggled', function(toggle, element) {
354 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
355 canvas.setCurrentElement(element);
371 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
374 wrapText: function(params) {
375 params = _.extend({textNodeIdx: 0}, params);
376 if(typeof params.textNodeIdx === 'number')
377 params.textNodeIdx = [params.textNodeIdx];
379 var childrenInside = params.inside.children(),
380 idx1 = Math.min.apply(Math, params.textNodeIdx),
381 idx2 = Math.max.apply(Math, params.textNodeIdx),
382 textNode1 = childrenInside[idx1],
383 textNode2 = childrenInside[idx2],
384 sameNode = textNode1.sameNode(textNode2),
385 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
386 prefixInside = textNode1.getText().substr(params.offsetStart),
387 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
388 suffixOutside = textNode2.getText().substr(params.offsetEnd)
391 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
392 textNode1.after(wrapperElement);
395 if(prefixOutside.length > 0)
396 wrapperElement.before({text:prefixOutside});
398 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
399 wrapperElement.append({text: core});
402 if(prefixInside.length > 0)
403 wrapperElement.append({text: prefixInside});
404 for(var i = idx1 + 1; i < idx2; i++) {
405 wrapperElement.append(childrenInside[i]);
407 if(suffixInside.length > 0)
408 wrapperElement.append({text: suffixInside});
410 if(suffixOutside.length > 0)
411 wrapperElement.after({text: suffixOutside});
412 return wrapperElement;
415 wrapElements: function(params) {
416 if(!(params.element1.parent().sameNode(params.element2.parent())))
419 var parent = params.element1.parent(),
420 parentChildren = parent.children(),
421 wrapper = documentElement.DocumentNodeElement.create({
422 tag: params._with.tag,
423 klass: params._with.klass}),
424 idx1 = parent.childIndex(params.element1),
425 idx2 = parent.childIndex(params.element2);
433 var insertingMethod, insertingTarget;
435 insertingMethod = 'prepend';
436 insertingTarget = parent;
438 insertingMethod = 'after';
439 insertingTarget = parentChildren[idx1-1];
442 for(var i = idx1; i <= idx2; i++) {
443 wrapper.append(parentChildren[i].detach());
446 insertingTarget[insertingMethod](wrapper);
450 getSiblingParents: function(params) {
451 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
452 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
453 noSiblingParents = null;
455 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
456 return noSiblingParents;
459 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
460 if(parents1[i].sameNode(parents2[i]))
464 return {element1: parents1[i], element2: parents2[i]};
467 getDocumentElement: function(from) {
468 if(from instanceof HTMLElement || from instanceof Text) {
469 return documentElement.DocumentElement.fromHTMLElement(from, this);
472 getCursor: function() {
473 return new Cursor(this);
479 getCurrentNodeElement: function() {
480 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
483 getCurrentTextElement: function() {
484 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
489 setCurrentElement: function(element, params) {
490 params = _.extend({caretTo: 'end'}, params);
491 var findFirstDirectTextChild = function(e, nodeToLand) {
492 var byBrowser = this.getCursor().getPosition().element;
493 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
495 var children = e.children();
496 for(var i = 0; i < children.length; i++) {
497 if(children[i] instanceof documentElement.DocumentTextElement)
502 var _markAsCurrent = function(element) {
503 if(element instanceof documentElement.DocumentTextElement) {
504 this.wrapper.find('.current-text-element').removeClass('current-text-element');
505 element.dom().addClass('current-text-element');
507 this.wrapper.find('.current-node-element').removeClass('current-node-element')
508 element._container().addClass('current-node-element');
509 this.publisher('currentElementChanged', element);
514 var isTextElement = element instanceof documentElement.DocumentTextElement,
515 nodeElementToLand = isTextElement ? element.parent() : element,
516 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
517 currentTextElement = this.getCurrentTextElement(),
518 currentNodeElement = this.getCurrentNodeElement();
520 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
521 this.wrapper.find('.current-text-element').removeClass('current-text-element');
523 if(textElementToLand) {
524 _markAsCurrent(textElementToLand);
525 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
526 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
527 if(!(textElementToLand.sameNode(currentTextElement)))
528 this.publisher('currentTextElementSet', textElementToLand);
530 document.getSelection().removeAllRanges();
533 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
534 _markAsCurrent(nodeElementToLand);
536 this.publisher('currentNodeElementSet', nodeElementToLand);
540 _moveCaretToTextElement: function(element, where) {
541 var range = document.createRange(),
542 node = element.dom().contents()[0];
544 if(typeof where !== 'number') {
545 range.selectNodeContents(node);
547 range.setStart(node, where);
550 var collapseArg = true;
553 range.collapse(collapseArg);
555 var selection = document.getSelection();
557 selection.removeAllRanges();
558 selection.addRange(range);
559 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
562 setCursorPosition: function(position) {
564 this._moveCaretToTextElement(position.element, position.offset);
568 var parent = $('<div>'),
569 parts = this.doc().toXML(0);
570 parent.append(parts);
571 return parent.html();
575 $.extend(Canvas.prototype.list, {
576 create: function(params) {
577 if(!(params.element1.parent().sameNode(params.element2.parent())))
580 var parent = params.element1.parent();
582 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
583 var tmp = params.element1;
584 params.element1 = params.element2;
585 params.element2 = tmp;
588 var elementsToWrap = [];
590 var place = 'before';
592 parent.children().some(function(element) {
594 if(element.sameNode(params.element1))
596 if(place === 'inside') {
597 if(element instanceof documentElement.DocumentTextElement) {
598 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
599 if(element.children()[0].sameNode(params.element1))
600 params.element1 = element;
602 element.setWlxmlClass('item');
603 elementsToWrap.push(element);
605 if(_e.sameNode(params.element2))
609 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
612 if(parent.is('list')) {
613 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
614 item.exec('toggleBullet', false);
615 toret = listElement.parent();
620 params.element1.before(toret);
622 elementsToWrap.forEach(function(element) {
624 listElement.append(element);
627 extractItems: function(params) {
628 params = _.extend({merge: true}, params);
629 var list = params.element1.parent();
630 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
633 var idx1 = list.childIndex(params.element1),
634 idx2 = list.childIndex(params.element2),
637 succeedingItems = [],
638 items = list.children(),
639 listIsNested = list.parent().getWlxmlClass() === 'item',
643 var tmp = idx1; idx1 = idx2; idx2 = tmp;
646 items.forEach(function(item, idx) {
648 precedingItems.push(item);
649 else if(idx >= idx1 && idx <= idx2) {
650 extractedItems.push(item);
653 succeedingItems.push(item);
657 var reference = listIsNested ? list.parent() : list;
658 if(succeedingItems.length === 0) {
659 var reference_orig = reference;
660 extractedItems.forEach(function(item) {
661 reference.after(item);
664 item.setWlxmlClass(null);
666 if(precedingItems.length === 0)
667 reference_orig.detach();
668 } else if(precedingItems.length === 0) {
669 extractedItems.forEach(function(item) {
670 reference.before(item);
672 item.setWlxmlClass(null);
675 extractedItems.forEach(function(item) {
676 reference.after(item);
678 item.setWlxmlClass(null);
681 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
685 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
687 succeedingItems.forEach(function(item) {
688 secondList.append(item);
691 reference.after(toAdd);
693 if(!params.merge && listIsNested) {
694 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
698 areItemsOfTheSameList: function(params) {
699 var e1 = params.element1,
700 e2 = params.element2;
701 return e1.parent().sameNode(e2.parent())
702 && e1.parent().is('list');
707 var Cursor = function(canvas) {
708 this.canvas = canvas;
711 $.extend(Cursor.prototype, {
712 isSelecting: function() {
713 var selection = window.getSelection();
714 return !selection.isCollapsed;
716 isSelectingWithinElement: function() {
717 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
719 isSelectingSiblings: function() {
720 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
722 getPosition: function() {
723 return this.getSelectionAnchor();
725 getSelectionStart: function() {
726 return this.getSelectionBoundry('start');
728 getSelectionEnd: function() {
729 return this.getSelectionBoundry('end');
731 getSelectionAnchor: function() {
732 return this.getSelectionBoundry('anchor');
734 getSelectionFocus: function() {
735 return this.getSelectionBoundry('focus');
737 getSelectionBoundry: function(which) {
738 var selection = window.getSelection(),
739 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
740 focusElement = this.canvas.getDocumentElement(selection.focusNode);
742 var getOffset = function(where) {
744 if(where === 'anchor') {
745 node = selection.anchorNode;
746 toret = selection.anchorOffset;
748 node = selection.focusNode;
749 toret = selection.focusOffset;
752 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
754 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
759 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
762 if(which === 'anchor') {
764 element: anchorElement,
765 offset: getOffset('anchor'),
766 offsetAtBeginning: getOffset('anchor') === 0,
767 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
770 if(which === 'focus') {
772 element: focusElement,
773 offset: getOffset('focus'),
774 offsetAtBeginning: getOffset('focus') === 0,
775 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
782 if(anchorElement.parent().sameNode(focusElement.parent())) {
783 var parent = anchorElement.parent(),
784 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
786 if(which === 'start') {
787 element = anchorElement;
788 offset = getOffset('anchor')
790 else if(which === 'end') {
791 element = focusElement,
792 offset = getOffset('focus')
795 if(which === 'start') {
796 element = focusElement,
797 offset = getOffset('focus')
799 else if(which === 'end') {
800 element = anchorElement;
801 offset = getOffset('anchor')
805 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
806 if(which === 'start') {
807 element = anchorElement;
808 offset = getOffset('anchor')
810 element = focusElement;
811 offset = getOffset('focus')
815 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
819 offsetAtBeginning: offset === 0,
820 offsetAtEnd: nodeLen === offset
826 fromXML: function(xml, publisher) {
827 return new Canvas(xml, publisher);