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 elements = position.element.split({offset: position.offset}),
153 if(position.offsetAtBeginning)
154 newEmpty = elements.first;
155 else if(position.offsetAtEnd)
156 newEmpty = elements.second;
158 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
159 canvas.setCurrentElement(goto);
173 this.wrapper.on('keyup', function(e) {
174 if(e.which >= 37 && e.which <= 40) {
175 var element = canvas.getCursor().getPosition().element,
180 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
187 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
189 canvas.setCurrentElement(element, {caretTo: caretTo});
193 this.wrapper.on('keydown', function(e) {
194 if(e.which >= 37 && e.which <= 40) {
195 var position = canvas.getCursor().getPosition(),
196 element = position.element;
197 if(element && (element instanceof documentElement.DocumentTextElement)) {
198 if(element.isEmpty()) {
199 var direction, caretTo;
200 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
207 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
208 canvas.setCurrentElement(element, {caretTo: caretTo});
210 var txt = element.dom().contents()[0].data;
211 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
213 canvas._moveCaretToTextElement(element, position.offset-2);
215 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
217 canvas._moveCaretToTextElement(element, position.offset+2);
226 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
228 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
231 var observer = new MutationObserver(function(mutations) {
232 mutations.forEach(function(mutation) {
233 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
234 mutation.target.data = utils.unicode.ZWS;
237 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
238 observer.observe(this.d[0], config);
241 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
242 var el = canvas.getDocumentElement(e.currentTarget);
246 if(el instanceof documentElement.DocumentTextElement)
248 el.toggleLabel(true);
250 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
251 var el = canvas.getDocumentElement(e.currentTarget);
255 if(el instanceof documentElement.DocumentTextElement)
257 el.toggleLabel(false);
260 this.eventBus.on('elementToggled', function(toggle, element) {
262 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
263 canvas.setCurrentElement(element);
279 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
282 wrapText: function(params) {
283 params = _.extend({textNodeIdx: 0}, params);
284 if(typeof params.textNodeIdx === 'number')
285 params.textNodeIdx = [params.textNodeIdx];
287 var childrenInside = params.inside.children(),
288 idx1 = Math.min.apply(Math, params.textNodeIdx),
289 idx2 = Math.max.apply(Math, params.textNodeIdx),
290 textNode1 = childrenInside[idx1],
291 textNode2 = childrenInside[idx2],
292 sameNode = textNode1.sameNode(textNode2),
293 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
294 prefixInside = textNode1.getText().substr(params.offsetStart),
295 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
296 suffixOutside = textNode2.getText().substr(params.offsetEnd)
299 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
300 textNode1.after(wrapperElement);
303 if(prefixOutside.length > 0)
304 wrapperElement.before({text:prefixOutside});
306 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
307 wrapperElement.append({text: core});
310 if(prefixInside.length > 0)
311 wrapperElement.append({text: prefixInside});
312 for(var i = idx1 + 1; i < idx2; i++) {
313 wrapperElement.append(childrenInside[i]);
315 if(suffixInside.length > 0)
316 wrapperElement.append({text: suffixInside});
318 if(suffixOutside.length > 0)
319 wrapperElement.after({text: suffixOutside});
320 return wrapperElement;
322 getSiblingParents: function(params) {
323 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
324 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
325 noSiblingParents = null;
327 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
328 return noSiblingParents;
331 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
332 if(parents1[i].sameNode(parents2[i]))
336 return {element1: parents1[i], element2: parents2[i]};
339 getDocumentElement: function(from) {
340 if(from instanceof HTMLElement || from instanceof Text) {
341 return documentElement.DocumentElement.fromHTMLElement(from, this);
344 getCursor: function() {
345 return new Cursor(this);
351 getCurrentNodeElement: function() {
352 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
355 getCurrentTextElement: function() {
356 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
361 setCurrentElement: function(element, params) {
362 params = _.extend({caretTo: 'end'}, params);
363 var findFirstDirectTextChild = function(e, nodeToLand) {
364 var byBrowser = this.getCursor().getPosition().element;
365 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
367 var children = e.children();
368 for(var i = 0; i < children.length; i++) {
369 if(children[i] instanceof documentElement.DocumentTextElement)
374 var _markAsCurrent = function(element) {
375 if(element instanceof documentElement.DocumentTextElement) {
376 this.wrapper.find('.current-text-element').removeClass('current-text-element');
377 element.dom().addClass('current-text-element');
379 this.wrapper.find('.current-node-element').removeClass('current-node-element')
380 element._container().addClass('current-node-element');
381 this.publisher('currentElementChanged', element);
386 var isTextElement = element instanceof documentElement.DocumentTextElement,
387 nodeElementToLand = isTextElement ? element.parent() : element,
388 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
389 currentTextElement = this.getCurrentTextElement(),
390 currentNodeElement = this.getCurrentNodeElement();
392 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
393 this.wrapper.find('.current-text-element').removeClass('current-text-element');
395 if(textElementToLand) {
396 _markAsCurrent(textElementToLand);
397 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
398 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
399 if(!(textElementToLand.sameNode(currentTextElement)))
400 this.publisher('currentTextElementSet', textElementToLand);
402 document.getSelection().removeAllRanges();
405 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
406 _markAsCurrent(nodeElementToLand);
408 this.publisher('currentNodeElementSet', nodeElementToLand);
412 _moveCaretToTextElement: function(element, where) {
413 var range = document.createRange(),
414 node = element.dom().contents()[0];
416 if(typeof where !== 'number') {
417 range.selectNodeContents(node);
419 range.setStart(node, where);
422 var collapseArg = true;
425 range.collapse(collapseArg);
427 var selection = document.getSelection();
429 selection.removeAllRanges();
430 selection.addRange(range);
431 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
434 setCursorPosition: function(position) {
436 this._moveCaretToTextElement(position.element, position.offset);
440 var parent = $('<div>'),
441 parts = this.doc().toXML(0);
442 parent.append(parts);
443 return parent.html();
447 $.extend(Canvas.prototype.list, {
448 create: function(params) {
449 if(!(params.element1.parent().sameNode(params.element2.parent())))
452 var parent = params.element1.parent();
454 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
455 var tmp = params.element1;
456 params.element1 = params.element2;
457 params.element2 = tmp;
460 var elementsToWrap = [];
462 var place = 'before';
464 parent.children().some(function(element) {
466 if(element.sameNode(params.element1))
468 if(place === 'inside') {
469 if(element instanceof documentElement.DocumentTextElement) {
470 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
471 if(element.children()[0].sameNode(params.element1))
472 params.element1 = element;
474 element.setWlxmlClass('item');
475 elementsToWrap.push(element);
477 if(_e.sameNode(params.element2))
481 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
484 if(parent.is('list')) {
485 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
486 toret = listElement.parent();
491 params.element1.before(toret);
493 elementsToWrap.forEach(function(element) {
495 listElement.append(element);
498 extractItems: function(params) {
499 params = _.extend({merge: true}, params);
500 var list = params.element1.parent();
501 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
504 var idx1 = list.childIndex(params.element1),
505 idx2 = list.childIndex(params.element2),
508 succeedingItems = [],
509 items = list.children(),
510 listIsNested = list.parent().getWlxmlClass() === 'item',
514 var tmp = idx1; idx1 = idx2; idx2 = tmp;
517 items.forEach(function(item, idx) {
519 precedingItems.push(item);
520 else if(idx >= idx1 && idx <= idx2) {
521 extractedItems.push(item);
524 succeedingItems.push(item);
528 var reference = listIsNested ? list.parent() : list;
529 if(succeedingItems.length === 0) {
530 var reference_orig = reference;
531 extractedItems.forEach(function(item) {
532 reference.after(item);
535 item.setWlxmlClass(null);
537 if(precedingItems.length === 0)
538 reference_orig.detach();
539 } else if(precedingItems.length === 0) {
540 extractedItems.forEach(function(item) {
541 reference.before(item);
543 item.setWlxmlClass(null);
546 extractedItems.forEach(function(item) {
547 reference.after(item);
549 item.setWlxmlClass(null);
552 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
556 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
558 succeedingItems.forEach(function(item) {
559 secondList.append(item);
562 reference.after(toAdd);
564 if(!params.merge && listIsNested) {
565 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
569 areItemsOfTheSameList: function(params) {
570 var e1 = params.element1,
571 e2 = params.element2;
572 return e1.parent().sameNode(e2.parent())
573 && e1.parent().is('list');
578 var Cursor = function(canvas) {
579 this.canvas = canvas;
582 $.extend(Cursor.prototype, {
583 isSelecting: function() {
584 var selection = window.getSelection();
585 return !selection.isCollapsed;
587 isSelectingWithinElement: function() {
588 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
590 isSelectingSiblings: function() {
591 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
593 getPosition: function() {
594 return this.getSelectionAnchor();
596 getSelectionStart: function() {
597 return this.getSelectionBoundry('start');
599 getSelectionEnd: function() {
600 return this.getSelectionBoundry('end');
602 getSelectionAnchor: function() {
603 return this.getSelectionBoundry('anchor');
605 getSelectionFocus: function() {
606 return this.getSelectionBoundry('focus');
608 getSelectionBoundry: function(which) {
609 var selection = window.getSelection(),
610 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
611 focusElement = this.canvas.getDocumentElement(selection.focusNode);
613 var getOffset = function(where) {
615 if(where === 'anchor') {
616 node = selection.anchorNode;
617 toret = selection.anchorOffset;
619 node = selection.focusNode;
620 toret = selection.focusOffset;
623 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
625 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
630 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
633 if(which === 'anchor') {
635 element: anchorElement,
636 offset: getOffset('anchor'),
637 offsetAtBeginning: getOffset('anchor') === 0,
638 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
641 if(which === 'focus') {
643 element: focusElement,
644 offset: getOffset('focus'),
645 offsetAtBeginning: getOffset('focus') === 0,
646 offsetAtEnd: selection.focusNode.data.length === getOffset('focus')
653 if(anchorElement.parent().sameNode(focusElement.parent())) {
654 var parent = anchorElement.parent(),
655 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
657 if(which === 'start') {
658 element = anchorElement;
659 offset = getOffset('anchor')
661 else if(which === 'end') {
662 element = focusElement,
663 offset = getOffset('focus')
666 if(which === 'start') {
667 element = focusElement,
668 offset = getOffset('focus')
670 else if(which === 'end') {
671 element = anchorElement;
672 offset = getOffset('anchor')
676 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
677 if(which === 'start') {
678 element = anchorElement;
679 offset = getOffset('anchor')
681 element = focusElement;
682 offset = getOffset('focus')
686 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
690 offsetAtBeginning: offset === 0,
691 offsetAtEnd: nodeLen === offset
697 fromXML: function(xml, publisher) {
698 return new Canvas(xml, publisher);