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);
179 this.wrapper.on('keyup', function(e) {
180 if(e.which >= 37 && e.which <= 40) {
181 var element = canvas.getCursor().getPosition().element,
186 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
193 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
195 canvas.setCurrentElement(element, {caretTo: caretTo});
199 this.wrapper.on('keydown', function(e) {
200 if(e.which >= 37 && e.which <= 40) {
201 var position = canvas.getCursor().getPosition(),
202 element = position.element;
203 if(element && (element instanceof documentElement.DocumentTextElement)) {
204 if(element.isEmpty()) {
205 var direction, caretTo;
206 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
213 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
214 canvas.setCurrentElement(element, {caretTo: caretTo});
216 var txt = element.dom().contents()[0].data;
217 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
219 canvas._moveCaretToTextElement(element, position.offset-2);
221 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
223 canvas._moveCaretToTextElement(element, position.offset+2);
232 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
234 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
237 var observer = new MutationObserver(function(mutations) {
238 mutations.forEach(function(mutation) {
239 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
240 mutation.target.data = utils.unicode.ZWS;
243 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
244 observer.observe(this.d[0], config);
247 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
248 var el = canvas.getDocumentElement(e.currentTarget);
252 if(el instanceof documentElement.DocumentTextElement)
254 el.toggleLabel(true);
256 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
257 var el = canvas.getDocumentElement(e.currentTarget);
261 if(el instanceof documentElement.DocumentTextElement)
263 el.toggleLabel(false);
266 this.eventBus.on('elementToggled', function(toggle, element) {
268 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
269 canvas.setCurrentElement(element);
285 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
288 wrapText: function(params) {
289 params = _.extend({textNodeIdx: 0}, params);
290 if(typeof params.textNodeIdx === 'number')
291 params.textNodeIdx = [params.textNodeIdx];
293 var childrenInside = params.inside.children(),
294 idx1 = Math.min.apply(Math, params.textNodeIdx),
295 idx2 = Math.max.apply(Math, params.textNodeIdx),
296 textNode1 = childrenInside[idx1],
297 textNode2 = childrenInside[idx2],
298 sameNode = textNode1.sameNode(textNode2),
299 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
300 prefixInside = textNode1.getText().substr(params.offsetStart),
301 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
302 suffixOutside = textNode2.getText().substr(params.offsetEnd)
305 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
306 textNode1.after(wrapperElement);
309 if(prefixOutside.length > 0)
310 wrapperElement.before({text:prefixOutside});
312 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
313 wrapperElement.append({text: core});
316 if(prefixInside.length > 0)
317 wrapperElement.append({text: prefixInside});
318 for(var i = idx1 + 1; i < idx2; i++) {
319 wrapperElement.append(childrenInside[i]);
321 if(suffixInside.length > 0)
322 wrapperElement.append({text: suffixInside});
324 if(suffixOutside.length > 0)
325 wrapperElement.after({text: suffixOutside});
326 return wrapperElement;
329 wrapElements: function(params) {
330 if(!(params.element1.parent().sameNode(params.element2.parent())))
333 var parent = params.element1.parent(),
334 parentChildren = parent.children(),
335 wrapper = documentElement.DocumentNodeElement.create({
336 tag: params._with.tag,
337 klass: params._with.klass}),
338 idx1 = parent.childIndex(params.element1),
339 idx2 = parent.childIndex(params.element2);
347 var insertingMethod, insertingTarget;
349 insertingMethod = 'prepend';
350 insertingTarget = parent;
352 insertingMethod = 'after';
353 insertingTarget = parentChildren[idx1-1];
356 for(var i = idx1; i <= idx2; i++) {
357 wrapper.append(parentChildren[i].detach());
360 insertingTarget[insertingMethod](wrapper);
364 getSiblingParents: function(params) {
365 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
366 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
367 noSiblingParents = null;
369 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
370 return noSiblingParents;
373 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
374 if(parents1[i].sameNode(parents2[i]))
378 return {element1: parents1[i], element2: parents2[i]};
381 getDocumentElement: function(from) {
382 if(from instanceof HTMLElement || from instanceof Text) {
383 return documentElement.DocumentElement.fromHTMLElement(from, this);
386 getCursor: function() {
387 return new Cursor(this);
393 getCurrentNodeElement: function() {
394 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
397 getCurrentTextElement: function() {
398 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
403 setCurrentElement: function(element, params) {
404 params = _.extend({caretTo: 'end'}, params);
405 var findFirstDirectTextChild = function(e, nodeToLand) {
406 var byBrowser = this.getCursor().getPosition().element;
407 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
409 var children = e.children();
410 for(var i = 0; i < children.length; i++) {
411 if(children[i] instanceof documentElement.DocumentTextElement)
416 var _markAsCurrent = function(element) {
417 if(element instanceof documentElement.DocumentTextElement) {
418 this.wrapper.find('.current-text-element').removeClass('current-text-element');
419 element.dom().addClass('current-text-element');
421 this.wrapper.find('.current-node-element').removeClass('current-node-element')
422 element._container().addClass('current-node-element');
423 this.publisher('currentElementChanged', element);
428 var isTextElement = element instanceof documentElement.DocumentTextElement,
429 nodeElementToLand = isTextElement ? element.parent() : element,
430 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
431 currentTextElement = this.getCurrentTextElement(),
432 currentNodeElement = this.getCurrentNodeElement();
434 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
435 this.wrapper.find('.current-text-element').removeClass('current-text-element');
437 if(textElementToLand) {
438 _markAsCurrent(textElementToLand);
439 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
440 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
441 if(!(textElementToLand.sameNode(currentTextElement)))
442 this.publisher('currentTextElementSet', textElementToLand);
444 document.getSelection().removeAllRanges();
447 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
448 _markAsCurrent(nodeElementToLand);
450 this.publisher('currentNodeElementSet', nodeElementToLand);
454 _moveCaretToTextElement: function(element, where) {
455 var range = document.createRange(),
456 node = element.dom().contents()[0];
458 if(typeof where !== 'number') {
459 range.selectNodeContents(node);
461 range.setStart(node, where);
464 var collapseArg = true;
467 range.collapse(collapseArg);
469 var selection = document.getSelection();
471 selection.removeAllRanges();
472 selection.addRange(range);
473 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
476 setCursorPosition: function(position) {
478 this._moveCaretToTextElement(position.element, position.offset);
482 var parent = $('<div>'),
483 parts = this.doc().toXML(0);
484 parent.append(parts);
485 return parent.html();
489 $.extend(Canvas.prototype.list, {
490 create: function(params) {
491 if(!(params.element1.parent().sameNode(params.element2.parent())))
494 var parent = params.element1.parent();
496 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
497 var tmp = params.element1;
498 params.element1 = params.element2;
499 params.element2 = tmp;
502 var elementsToWrap = [];
504 var place = 'before';
506 parent.children().some(function(element) {
508 if(element.sameNode(params.element1))
510 if(place === 'inside') {
511 if(element instanceof documentElement.DocumentTextElement) {
512 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
513 if(element.children()[0].sameNode(params.element1))
514 params.element1 = element;
516 element.setWlxmlClass('item');
517 elementsToWrap.push(element);
519 if(_e.sameNode(params.element2))
523 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
526 if(parent.is('list')) {
527 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
528 toret = listElement.parent();
533 params.element1.before(toret);
535 elementsToWrap.forEach(function(element) {
537 listElement.append(element);
540 extractItems: function(params) {
541 params = _.extend({merge: true}, params);
542 var list = params.element1.parent();
543 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
546 var idx1 = list.childIndex(params.element1),
547 idx2 = list.childIndex(params.element2),
550 succeedingItems = [],
551 items = list.children(),
552 listIsNested = list.parent().getWlxmlClass() === 'item',
556 var tmp = idx1; idx1 = idx2; idx2 = tmp;
559 items.forEach(function(item, idx) {
561 precedingItems.push(item);
562 else if(idx >= idx1 && idx <= idx2) {
563 extractedItems.push(item);
566 succeedingItems.push(item);
570 var reference = listIsNested ? list.parent() : list;
571 if(succeedingItems.length === 0) {
572 var reference_orig = reference;
573 extractedItems.forEach(function(item) {
574 reference.after(item);
577 item.setWlxmlClass(null);
579 if(precedingItems.length === 0)
580 reference_orig.detach();
581 } else if(precedingItems.length === 0) {
582 extractedItems.forEach(function(item) {
583 reference.before(item);
585 item.setWlxmlClass(null);
588 extractedItems.forEach(function(item) {
589 reference.after(item);
591 item.setWlxmlClass(null);
594 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
598 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
600 succeedingItems.forEach(function(item) {
601 secondList.append(item);
604 reference.after(toAdd);
606 if(!params.merge && listIsNested) {
607 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
611 areItemsOfTheSameList: function(params) {
612 var e1 = params.element1,
613 e2 = params.element2;
614 return e1.parent().sameNode(e2.parent())
615 && e1.parent().is('list');
620 var Cursor = function(canvas) {
621 this.canvas = canvas;
624 $.extend(Cursor.prototype, {
625 isSelecting: function() {
626 var selection = window.getSelection();
627 return !selection.isCollapsed;
629 isSelectingWithinElement: function() {
630 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
632 isSelectingSiblings: function() {
633 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
635 getPosition: function() {
636 return this.getSelectionAnchor();
638 getSelectionStart: function() {
639 return this.getSelectionBoundry('start');
641 getSelectionEnd: function() {
642 return this.getSelectionBoundry('end');
644 getSelectionAnchor: function() {
645 return this.getSelectionBoundry('anchor');
647 getSelectionFocus: function() {
648 return this.getSelectionBoundry('focus');
650 getSelectionBoundry: function(which) {
651 var selection = window.getSelection(),
652 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
653 focusElement = this.canvas.getDocumentElement(selection.focusNode);
655 var getOffset = function(where) {
657 if(where === 'anchor') {
658 node = selection.anchorNode;
659 toret = selection.anchorOffset;
661 node = selection.focusNode;
662 toret = selection.focusOffset;
665 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
667 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
672 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
675 if(which === 'anchor') {
677 element: anchorElement,
678 offset: getOffset('anchor'),
679 offsetAtBeginning: getOffset('anchor') === 0,
680 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
683 if(which === 'focus') {
685 element: focusElement,
686 offset: getOffset('focus'),
687 offsetAtBeginning: getOffset('focus') === 0,
688 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
695 if(anchorElement.parent().sameNode(focusElement.parent())) {
696 var parent = anchorElement.parent(),
697 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
699 if(which === 'start') {
700 element = anchorElement;
701 offset = getOffset('anchor')
703 else if(which === 'end') {
704 element = focusElement,
705 offset = getOffset('focus')
708 if(which === 'start') {
709 element = focusElement,
710 offset = getOffset('focus')
712 else if(which === 'end') {
713 element = anchorElement;
714 offset = getOffset('anchor')
718 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
719 if(which === 'start') {
720 element = anchorElement;
721 offset = getOffset('anchor')
723 element = focusElement;
724 offset = getOffset('focus')
728 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
732 offsetAtBeginning: offset === 0,
733 offsetAtEnd: nodeLen === offset
739 fromXML: function(xml, publisher) {
740 return new Canvas(xml, publisher);