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);
154 this.wrapper.on('keyup', function(e) {
155 if(e.which >= 37 && e.which <= 40) {
156 var element = canvas.getCursor().getPosition().element,
161 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
168 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
170 canvas.setCurrentElement(element, {caretTo: caretTo});
174 this.wrapper.on('keydown', function(e) {
175 var cursor = canvas.getCursor(),
176 position = canvas.getCursor().getPosition(),
177 element = position.element;
178 if(e.which >= 37 && e.which <= 40) {
180 if(element && (element instanceof documentElement.DocumentTextElement)) {
181 if(element.isEmpty()) {
182 var direction, caretTo;
183 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
190 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
191 canvas.setCurrentElement(element, {caretTo: caretTo});
193 var txt = element.dom().contents()[0].data;
194 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
196 canvas._moveCaretToTextElement(element, position.offset-2);
198 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
200 canvas._moveCaretToTextElement(element, position.offset+2);
208 var selectsWholeTextElement = function() {
209 if(cursor.isSelecting() && cursor.getSelectionStart().offsetAtBeginning && cursor.getSelectionEnd().offsetAtEnd)
214 if(e.which === KEYS.X && e.ctrlKey && selectsWholeTextElement()) {
218 if(e.which === KEYS.BACKSPACE || e.which === KEYS.DELETE) {
219 if(cursor.isSelecting() && !cursor.isSelectingWithinElement()) {
224 var cursorAtOperationEdge = position.offsetAtBeginning;
225 if(e.which === KEYS.DELETE) {
226 cursorAtOperationEdge = position.offsetAtEnd;
229 if(element.getText().length === 1 || selectsWholeTextElement()) {
233 else if(element.isEmpty()) {
235 var direction = 'above',
238 if(e.which === KEYS.DELETE) {
245 var parent = element.parent(),
246 grandParent = parent ? parent.parent() : null,
248 if(parent.children().length === 1 && parent.children()[0].sameNode(element)) {
249 if(grandParent && grandParent.children().length === 1) {
250 goto = grandParent.append({text: ''});
252 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
256 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, element.dom()[0]));
259 canvas.setCurrentElement(goto, {caretTo: caretTo});
260 canvas.publisher('contentChanged');
262 else if(cursorAtOperationEdge) {
268 if(e.which === KEYS.ENTER) {
270 var cursor = canvas.getCursor(),
271 position = cursor.getPosition(),
272 element = position.element;
274 if(!cursor.isSelecting()) {
276 var added = element.after({tag: 'block'});
277 added.append({text:''});
278 canvas.setCurrentElement(added, {caretTo: 'start'});
282 if(!(element.parent().parent())) {
283 return false; // top level element is unsplittable
286 var elements = position.element.split({offset: position.offset}),
291 if(position.offsetAtBeginning)
292 newEmpty = elements.first;
293 else if(position.offsetAtEnd)
294 newEmpty = elements.second;
297 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
300 goto = elements.second;
301 gotoOptions = {caretTo: 'start'};
304 canvas.setCurrentElement(goto, gotoOptions);
310 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
312 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
315 var observer = new MutationObserver(function(mutations) {
316 mutations.forEach(function(mutation) {
317 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
318 if(mutation.target.data === '')
319 mutation.target.data = utils.unicode.ZWS;
320 canvas.publisher('contentChanged');
324 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
325 observer.observe(this.d[0], config);
328 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
329 var el = canvas.getDocumentElement(e.currentTarget);
333 if(el instanceof documentElement.DocumentTextElement)
335 el.toggleLabel(true);
337 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
338 var el = canvas.getDocumentElement(e.currentTarget);
342 if(el instanceof documentElement.DocumentTextElement)
344 el.toggleLabel(false);
347 this.eventBus.on('elementToggled', function(toggle, element) {
349 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
350 canvas.setCurrentElement(element);
366 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
369 wrapText: function(params) {
370 params = _.extend({textNodeIdx: 0}, params);
371 if(typeof params.textNodeIdx === 'number')
372 params.textNodeIdx = [params.textNodeIdx];
374 var childrenInside = params.inside.children(),
375 idx1 = Math.min.apply(Math, params.textNodeIdx),
376 idx2 = Math.max.apply(Math, params.textNodeIdx),
377 textNode1 = childrenInside[idx1],
378 textNode2 = childrenInside[idx2],
379 sameNode = textNode1.sameNode(textNode2),
380 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
381 prefixInside = textNode1.getText().substr(params.offsetStart),
382 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
383 suffixOutside = textNode2.getText().substr(params.offsetEnd)
386 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
387 textNode1.after(wrapperElement);
390 if(prefixOutside.length > 0)
391 wrapperElement.before({text:prefixOutside});
393 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
394 wrapperElement.append({text: core});
397 if(prefixInside.length > 0)
398 wrapperElement.append({text: prefixInside});
399 for(var i = idx1 + 1; i < idx2; i++) {
400 wrapperElement.append(childrenInside[i]);
402 if(suffixInside.length > 0)
403 wrapperElement.append({text: suffixInside});
405 if(suffixOutside.length > 0)
406 wrapperElement.after({text: suffixOutside});
407 return wrapperElement;
410 wrapElements: function(params) {
411 if(!(params.element1.parent().sameNode(params.element2.parent())))
414 var parent = params.element1.parent(),
415 parentChildren = parent.children(),
416 wrapper = documentElement.DocumentNodeElement.create({
417 tag: params._with.tag,
418 klass: params._with.klass}),
419 idx1 = parent.childIndex(params.element1),
420 idx2 = parent.childIndex(params.element2);
428 var insertingMethod, insertingTarget;
430 insertingMethod = 'prepend';
431 insertingTarget = parent;
433 insertingMethod = 'after';
434 insertingTarget = parentChildren[idx1-1];
437 for(var i = idx1; i <= idx2; i++) {
438 wrapper.append(parentChildren[i].detach());
441 insertingTarget[insertingMethod](wrapper);
445 getSiblingParents: function(params) {
446 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
447 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
448 noSiblingParents = null;
450 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
451 return noSiblingParents;
454 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
455 if(parents1[i].sameNode(parents2[i]))
459 return {element1: parents1[i], element2: parents2[i]};
462 getDocumentElement: function(from) {
463 if(from instanceof HTMLElement || from instanceof Text) {
464 return documentElement.DocumentElement.fromHTMLElement(from, this);
467 getCursor: function() {
468 return new Cursor(this);
474 getCurrentNodeElement: function() {
475 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
478 getCurrentTextElement: function() {
479 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
484 setCurrentElement: function(element, params) {
485 params = _.extend({caretTo: 'end'}, params);
486 var findFirstDirectTextChild = function(e, nodeToLand) {
487 var byBrowser = this.getCursor().getPosition().element;
488 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
490 var children = e.children();
491 for(var i = 0; i < children.length; i++) {
492 if(children[i] instanceof documentElement.DocumentTextElement)
497 var _markAsCurrent = function(element) {
498 if(element instanceof documentElement.DocumentTextElement) {
499 this.wrapper.find('.current-text-element').removeClass('current-text-element');
500 element.dom().addClass('current-text-element');
502 this.wrapper.find('.current-node-element').removeClass('current-node-element')
503 element._container().addClass('current-node-element');
504 this.publisher('currentElementChanged', element);
509 var isTextElement = element instanceof documentElement.DocumentTextElement,
510 nodeElementToLand = isTextElement ? element.parent() : element,
511 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
512 currentTextElement = this.getCurrentTextElement(),
513 currentNodeElement = this.getCurrentNodeElement();
515 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
516 this.wrapper.find('.current-text-element').removeClass('current-text-element');
518 if(textElementToLand) {
519 _markAsCurrent(textElementToLand);
520 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
521 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
522 if(!(textElementToLand.sameNode(currentTextElement)))
523 this.publisher('currentTextElementSet', textElementToLand);
525 document.getSelection().removeAllRanges();
528 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
529 _markAsCurrent(nodeElementToLand);
531 this.publisher('currentNodeElementSet', nodeElementToLand);
535 _moveCaretToTextElement: function(element, where) {
536 var range = document.createRange(),
537 node = element.dom().contents()[0];
539 if(typeof where !== 'number') {
540 range.selectNodeContents(node);
542 range.setStart(node, where);
545 var collapseArg = true;
548 range.collapse(collapseArg);
550 var selection = document.getSelection();
552 selection.removeAllRanges();
553 selection.addRange(range);
554 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
557 setCursorPosition: function(position) {
559 this._moveCaretToTextElement(position.element, position.offset);
563 var parent = $('<div>'),
564 parts = this.doc().toXML(0);
565 parent.append(parts);
566 return parent.html();
570 $.extend(Canvas.prototype.list, {
571 create: function(params) {
572 if(!(params.element1.parent().sameNode(params.element2.parent())))
575 var parent = params.element1.parent();
577 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
578 var tmp = params.element1;
579 params.element1 = params.element2;
580 params.element2 = tmp;
583 var elementsToWrap = [];
585 var place = 'before';
587 parent.children().some(function(element) {
589 if(element.sameNode(params.element1))
591 if(place === 'inside') {
592 if(element instanceof documentElement.DocumentTextElement) {
593 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
594 if(element.children()[0].sameNode(params.element1))
595 params.element1 = element;
597 element.setWlxmlClass('item');
598 elementsToWrap.push(element);
600 if(_e.sameNode(params.element2))
604 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
607 if(parent.is('list')) {
608 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
609 item.exec('toggleBullet', false);
610 toret = listElement.parent();
615 params.element1.before(toret);
617 elementsToWrap.forEach(function(element) {
619 listElement.append(element);
622 extractItems: function(params) {
623 params = _.extend({merge: true}, params);
624 var list = params.element1.parent();
625 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
628 var idx1 = list.childIndex(params.element1),
629 idx2 = list.childIndex(params.element2),
632 succeedingItems = [],
633 items = list.children(),
634 listIsNested = list.parent().getWlxmlClass() === 'item',
638 var tmp = idx1; idx1 = idx2; idx2 = tmp;
641 items.forEach(function(item, idx) {
643 precedingItems.push(item);
644 else if(idx >= idx1 && idx <= idx2) {
645 extractedItems.push(item);
648 succeedingItems.push(item);
652 var reference = listIsNested ? list.parent() : list;
653 if(succeedingItems.length === 0) {
654 var reference_orig = reference;
655 extractedItems.forEach(function(item) {
656 reference.after(item);
659 item.setWlxmlClass(null);
661 if(precedingItems.length === 0)
662 reference_orig.detach();
663 } else if(precedingItems.length === 0) {
664 extractedItems.forEach(function(item) {
665 reference.before(item);
667 item.setWlxmlClass(null);
670 extractedItems.forEach(function(item) {
671 reference.after(item);
673 item.setWlxmlClass(null);
676 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
680 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
682 succeedingItems.forEach(function(item) {
683 secondList.append(item);
686 reference.after(toAdd);
688 if(!params.merge && listIsNested) {
689 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
693 areItemsOfTheSameList: function(params) {
694 var e1 = params.element1,
695 e2 = params.element2;
696 return e1.parent().sameNode(e2.parent())
697 && e1.parent().is('list');
702 var Cursor = function(canvas) {
703 this.canvas = canvas;
706 $.extend(Cursor.prototype, {
707 isSelecting: function() {
708 var selection = window.getSelection();
709 return !selection.isCollapsed;
711 isSelectingWithinElement: function() {
712 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
714 isSelectingSiblings: function() {
715 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
717 getPosition: function() {
718 return this.getSelectionAnchor();
720 getSelectionStart: function() {
721 return this.getSelectionBoundry('start');
723 getSelectionEnd: function() {
724 return this.getSelectionBoundry('end');
726 getSelectionAnchor: function() {
727 return this.getSelectionBoundry('anchor');
729 getSelectionFocus: function() {
730 return this.getSelectionBoundry('focus');
732 getSelectionBoundry: function(which) {
733 var selection = window.getSelection(),
734 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
735 focusElement = this.canvas.getDocumentElement(selection.focusNode);
737 var getOffset = function(where) {
739 if(where === 'anchor') {
740 node = selection.anchorNode;
741 toret = selection.anchorOffset;
743 node = selection.focusNode;
744 toret = selection.focusOffset;
747 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
749 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
754 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
757 if(which === 'anchor') {
759 element: anchorElement,
760 offset: getOffset('anchor'),
761 offsetAtBeginning: getOffset('anchor') === 0,
762 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
765 if(which === 'focus') {
767 element: focusElement,
768 offset: getOffset('focus'),
769 offsetAtBeginning: getOffset('focus') === 0,
770 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
777 if(anchorElement.parent().sameNode(focusElement.parent())) {
778 var parent = anchorElement.parent(),
779 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
781 if(which === 'start') {
782 element = anchorElement;
783 offset = getOffset('anchor')
785 else if(which === 'end') {
786 element = focusElement,
787 offset = getOffset('focus')
790 if(which === 'start') {
791 element = focusElement,
792 offset = getOffset('focus')
794 else if(which === 'end') {
795 element = anchorElement;
796 offset = getOffset('anchor')
800 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
801 if(which === 'start') {
802 element = anchorElement;
803 offset = getOffset('anchor')
805 element = focusElement;
806 offset = getOffset('focus')
810 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
814 offsetAtBeginning: offset === 0,
815 offsetAtEnd: nodeLen === offset
821 fromXML: function(xml, publisher) {
822 return new Canvas(xml, publisher);