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);
180 this.wrapper.on('keyup', function(e) {
181 if(e.which >= 37 && e.which <= 40) {
182 var element = canvas.getCursor().getPosition().element,
187 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
194 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
196 canvas.setCurrentElement(element, {caretTo: caretTo});
200 this.wrapper.on('keydown', function(e) {
201 var position = canvas.getCursor().getPosition(),
202 element = position.element;
203 if(e.which >= 37 && e.which <= 40) {
205 if(element && (element instanceof documentElement.DocumentTextElement)) {
206 if(element.isEmpty()) {
207 var direction, caretTo;
208 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
215 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
216 canvas.setCurrentElement(element, {caretTo: caretTo});
218 var txt = element.dom().contents()[0].data;
219 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
221 canvas._moveCaretToTextElement(element, position.offset-2);
223 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
225 canvas._moveCaretToTextElement(element, position.offset+2);
232 if(e.which === KEYS.BACKSPACE) {
233 if(element.getText().length === 1) {
237 else if(element.isEmpty()) {
240 var parent = element.parent(),
241 grandParent = parent ? parent.parent() : null,
243 if(parent.children().length === 1) {
244 if(grandParent && grandParent.children().length === 1) {
245 goto = grandParent.append({text: ''});
247 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', 'above', element.dom()[0]));
251 goto = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', 'above', element.dom()[0]));
254 canvas.setCurrentElement(goto, {caretTo: 'end'});
256 else if(position.offset === 0) {
262 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
264 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
267 var observer = new MutationObserver(function(mutations) {
268 mutations.forEach(function(mutation) {
269 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
270 mutation.target.data = utils.unicode.ZWS;
273 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
274 observer.observe(this.d[0], config);
277 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
278 var el = canvas.getDocumentElement(e.currentTarget);
282 if(el instanceof documentElement.DocumentTextElement)
284 el.toggleLabel(true);
286 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
287 var el = canvas.getDocumentElement(e.currentTarget);
291 if(el instanceof documentElement.DocumentTextElement)
293 el.toggleLabel(false);
296 this.eventBus.on('elementToggled', function(toggle, element) {
298 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
299 canvas.setCurrentElement(element);
315 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
318 wrapText: function(params) {
319 params = _.extend({textNodeIdx: 0}, params);
320 if(typeof params.textNodeIdx === 'number')
321 params.textNodeIdx = [params.textNodeIdx];
323 var childrenInside = params.inside.children(),
324 idx1 = Math.min.apply(Math, params.textNodeIdx),
325 idx2 = Math.max.apply(Math, params.textNodeIdx),
326 textNode1 = childrenInside[idx1],
327 textNode2 = childrenInside[idx2],
328 sameNode = textNode1.sameNode(textNode2),
329 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
330 prefixInside = textNode1.getText().substr(params.offsetStart),
331 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
332 suffixOutside = textNode2.getText().substr(params.offsetEnd)
335 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
336 textNode1.after(wrapperElement);
339 if(prefixOutside.length > 0)
340 wrapperElement.before({text:prefixOutside});
342 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
343 wrapperElement.append({text: core});
346 if(prefixInside.length > 0)
347 wrapperElement.append({text: prefixInside});
348 for(var i = idx1 + 1; i < idx2; i++) {
349 wrapperElement.append(childrenInside[i]);
351 if(suffixInside.length > 0)
352 wrapperElement.append({text: suffixInside});
354 if(suffixOutside.length > 0)
355 wrapperElement.after({text: suffixOutside});
356 return wrapperElement;
359 wrapElements: function(params) {
360 if(!(params.element1.parent().sameNode(params.element2.parent())))
363 var parent = params.element1.parent(),
364 parentChildren = parent.children(),
365 wrapper = documentElement.DocumentNodeElement.create({
366 tag: params._with.tag,
367 klass: params._with.klass}),
368 idx1 = parent.childIndex(params.element1),
369 idx2 = parent.childIndex(params.element2);
377 var insertingMethod, insertingTarget;
379 insertingMethod = 'prepend';
380 insertingTarget = parent;
382 insertingMethod = 'after';
383 insertingTarget = parentChildren[idx1-1];
386 for(var i = idx1; i <= idx2; i++) {
387 wrapper.append(parentChildren[i].detach());
390 insertingTarget[insertingMethod](wrapper);
394 getSiblingParents: function(params) {
395 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
396 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
397 noSiblingParents = null;
399 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
400 return noSiblingParents;
403 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
404 if(parents1[i].sameNode(parents2[i]))
408 return {element1: parents1[i], element2: parents2[i]};
411 getDocumentElement: function(from) {
412 if(from instanceof HTMLElement || from instanceof Text) {
413 return documentElement.DocumentElement.fromHTMLElement(from, this);
416 getCursor: function() {
417 return new Cursor(this);
423 getCurrentNodeElement: function() {
424 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
427 getCurrentTextElement: function() {
428 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
433 setCurrentElement: function(element, params) {
434 params = _.extend({caretTo: 'end'}, params);
435 var findFirstDirectTextChild = function(e, nodeToLand) {
436 var byBrowser = this.getCursor().getPosition().element;
437 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
439 var children = e.children();
440 for(var i = 0; i < children.length; i++) {
441 if(children[i] instanceof documentElement.DocumentTextElement)
446 var _markAsCurrent = function(element) {
447 if(element instanceof documentElement.DocumentTextElement) {
448 this.wrapper.find('.current-text-element').removeClass('current-text-element');
449 element.dom().addClass('current-text-element');
451 this.wrapper.find('.current-node-element').removeClass('current-node-element')
452 element._container().addClass('current-node-element');
453 this.publisher('currentElementChanged', element);
458 var isTextElement = element instanceof documentElement.DocumentTextElement,
459 nodeElementToLand = isTextElement ? element.parent() : element,
460 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
461 currentTextElement = this.getCurrentTextElement(),
462 currentNodeElement = this.getCurrentNodeElement();
464 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
465 this.wrapper.find('.current-text-element').removeClass('current-text-element');
467 if(textElementToLand) {
468 _markAsCurrent(textElementToLand);
469 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
470 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
471 if(!(textElementToLand.sameNode(currentTextElement)))
472 this.publisher('currentTextElementSet', textElementToLand);
474 document.getSelection().removeAllRanges();
477 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
478 _markAsCurrent(nodeElementToLand);
480 this.publisher('currentNodeElementSet', nodeElementToLand);
484 _moveCaretToTextElement: function(element, where) {
485 var range = document.createRange(),
486 node = element.dom().contents()[0];
488 if(typeof where !== 'number') {
489 range.selectNodeContents(node);
491 range.setStart(node, where);
494 var collapseArg = true;
497 range.collapse(collapseArg);
499 var selection = document.getSelection();
501 selection.removeAllRanges();
502 selection.addRange(range);
503 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
506 setCursorPosition: function(position) {
508 this._moveCaretToTextElement(position.element, position.offset);
512 var parent = $('<div>'),
513 parts = this.doc().toXML(0);
514 parent.append(parts);
515 return parent.html();
519 $.extend(Canvas.prototype.list, {
520 create: function(params) {
521 if(!(params.element1.parent().sameNode(params.element2.parent())))
524 var parent = params.element1.parent();
526 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
527 var tmp = params.element1;
528 params.element1 = params.element2;
529 params.element2 = tmp;
532 var elementsToWrap = [];
534 var place = 'before';
536 parent.children().some(function(element) {
538 if(element.sameNode(params.element1))
540 if(place === 'inside') {
541 if(element instanceof documentElement.DocumentTextElement) {
542 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
543 if(element.children()[0].sameNode(params.element1))
544 params.element1 = element;
546 element.setWlxmlClass('item');
547 elementsToWrap.push(element);
549 if(_e.sameNode(params.element2))
553 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
556 if(parent.is('list')) {
557 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
558 toret = listElement.parent();
563 params.element1.before(toret);
565 elementsToWrap.forEach(function(element) {
567 listElement.append(element);
570 extractItems: function(params) {
571 params = _.extend({merge: true}, params);
572 var list = params.element1.parent();
573 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
576 var idx1 = list.childIndex(params.element1),
577 idx2 = list.childIndex(params.element2),
580 succeedingItems = [],
581 items = list.children(),
582 listIsNested = list.parent().getWlxmlClass() === 'item',
586 var tmp = idx1; idx1 = idx2; idx2 = tmp;
589 items.forEach(function(item, idx) {
591 precedingItems.push(item);
592 else if(idx >= idx1 && idx <= idx2) {
593 extractedItems.push(item);
596 succeedingItems.push(item);
600 var reference = listIsNested ? list.parent() : list;
601 if(succeedingItems.length === 0) {
602 var reference_orig = reference;
603 extractedItems.forEach(function(item) {
604 reference.after(item);
607 item.setWlxmlClass(null);
609 if(precedingItems.length === 0)
610 reference_orig.detach();
611 } else if(precedingItems.length === 0) {
612 extractedItems.forEach(function(item) {
613 reference.before(item);
615 item.setWlxmlClass(null);
618 extractedItems.forEach(function(item) {
619 reference.after(item);
621 item.setWlxmlClass(null);
624 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
628 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
630 succeedingItems.forEach(function(item) {
631 secondList.append(item);
634 reference.after(toAdd);
636 if(!params.merge && listIsNested) {
637 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
641 areItemsOfTheSameList: function(params) {
642 var e1 = params.element1,
643 e2 = params.element2;
644 return e1.parent().sameNode(e2.parent())
645 && e1.parent().is('list');
650 var Cursor = function(canvas) {
651 this.canvas = canvas;
654 $.extend(Cursor.prototype, {
655 isSelecting: function() {
656 var selection = window.getSelection();
657 return !selection.isCollapsed;
659 isSelectingWithinElement: function() {
660 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
662 isSelectingSiblings: function() {
663 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
665 getPosition: function() {
666 return this.getSelectionAnchor();
668 getSelectionStart: function() {
669 return this.getSelectionBoundry('start');
671 getSelectionEnd: function() {
672 return this.getSelectionBoundry('end');
674 getSelectionAnchor: function() {
675 return this.getSelectionBoundry('anchor');
677 getSelectionFocus: function() {
678 return this.getSelectionBoundry('focus');
680 getSelectionBoundry: function(which) {
681 var selection = window.getSelection(),
682 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
683 focusElement = this.canvas.getDocumentElement(selection.focusNode);
685 var getOffset = function(where) {
687 if(where === 'anchor') {
688 node = selection.anchorNode;
689 toret = selection.anchorOffset;
691 node = selection.focusNode;
692 toret = selection.focusOffset;
695 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
697 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
702 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
705 if(which === 'anchor') {
707 element: anchorElement,
708 offset: getOffset('anchor'),
709 offsetAtBeginning: getOffset('anchor') === 0,
710 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
713 if(which === 'focus') {
715 element: focusElement,
716 offset: getOffset('focus'),
717 offsetAtBeginning: getOffset('focus') === 0,
718 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
725 if(anchorElement.parent().sameNode(focusElement.parent())) {
726 var parent = anchorElement.parent(),
727 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
729 if(which === 'start') {
730 element = anchorElement;
731 offset = getOffset('anchor')
733 else if(which === 'end') {
734 element = focusElement,
735 offset = getOffset('focus')
738 if(which === 'start') {
739 element = focusElement,
740 offset = getOffset('focus')
742 else if(which === 'end') {
743 element = anchorElement;
744 offset = getOffset('anchor')
748 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
749 if(which === 'start') {
750 element = anchorElement;
751 offset = getOffset('anchor')
753 element = focusElement;
754 offset = getOffset('focus')
758 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
762 offsetAtBeginning: offset === 0,
763 offsetAtEnd: nodeLen === offset
769 fromXML: function(xml, publisher) {
770 return new Canvas(xml, publisher);