2 'libs/jquery-1.9.1.min',
5 'modules/documentCanvas/canvas/documentElement',
6 'modules/documentCanvas/canvas/keyboard',
7 'modules/documentCanvas/canvas/utils'
8 ], function($, _, Backbone, documentElement, keyboard, utils) {
12 var Canvas = function(wlxml, publisher) {
13 this.eventBus = _.extend({}, Backbone.Events);
14 this.loadWlxml(wlxml);
15 this.publisher = publisher ? publisher : function() {};
18 $.extend(Canvas.prototype, {
20 loadWlxml: function(wlxml) {
21 var d = wlxml ? $($.trim(wlxml)) : null;
23 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
24 this.wrapper.append(d);
27 this.wrapper.find('*').replaceWith(function() {
28 var currentTag = $(this);
29 if(currentTag.attr('wlxml-tag'))
32 var meta = {}, others = {};
33 for(var i = 0; i < this.attributes.length; i++) {
34 var attr = this.attributes[i];
35 if(attr.name.substr(0, 5) === 'meta-')
36 meta[attr.name.substr(5)] = attr.value;
37 else if(attr.name !== 'class')
38 others[attr.name] = attr.value;
41 var element = documentElement.DocumentNodeElement.create({
42 tag: currentTag.prop('tagName').toLowerCase(),
43 klass: currentTag.attr('class'),
46 rawChildren: currentTag.contents(),
47 prepopulateOnEmpty: true
50 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
51 element.data(attr, '');
56 var FIRST_CONTENT_INDEX = 0;
58 // @@ TODO - refactor!
59 var getNode = function(element) {
60 return element.children('[document-element-content]');
63 this.wrapper.find(':not(iframe)').addBack().contents()
64 .filter(function() {return this.nodeType === Node.TEXT_NODE})
67 // TODO: use DocumentElement API
70 text = {original: el.text(), trimmed: $.trim(el.text())},
71 elParent = el.parent(),
72 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
73 hasSpanBefore = el.prev().length > 0 && getNode($(el.prev()[0])).attr('wlxml-tag') === 'span',
74 hasSpanAfter = el.next().length > 0 && getNode($(el.next()[0])).attr('wlxml-tag') === 'span';
76 if(el.parent().hasClass('canvas-widget') || elParent.attr('document-text-element') !== undefined)
77 return true; // continue
79 var addInfo = function(toAdd, where) {
80 var parentContents = elParent.contents(),
81 idx = parentContents.index(el[0]),
82 prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
83 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
86 if(where === 'above') {
87 target = prev ? $(prev) : elParent.parent();
88 key = prev ? 'orig-after' : 'orig-begin';
89 } else if(where === 'below') {
90 target = next ? $(next) : elParent.parent();
91 key = next ? 'orig-before' : 'orig-end';
92 } else { throw new Object;}
94 target.data(key, toAdd);
97 text.transformed = text.trimmed;
99 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
100 var startSpace = /\s/g.test(text.original.substr(0,1)),
101 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
102 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
104 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
106 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
107 text.transformed = ' ';
110 if(!text.transformed) {
111 addInfo(text.original, 'below');
113 return true; // continue
116 if(text.transformed !== text.original) {
118 addInfo(text.original, 'below');
120 var startingMatch = text.original.match(/^\s+/g),
121 endingMatch = text.original.match(/\s+$/g),
122 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
123 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
125 if(endingWhiteSpace) {
126 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
127 endingWhiteSpace = endingWhiteSpace.substr(1);
128 addInfo(endingWhiteSpace, 'below');
131 if(startingWhiteSpace) {
132 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
133 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
134 addInfo(startingWhiteSpace, 'above');
139 var element = documentElement.DocumentTextElement.create({text: text.transformed});
140 el.replaceWith(element.dom());
143 this.d = this.wrapper.children(0);
145 this.wrapper.on('keyup keydown keypress', function(e) {
146 keyboard.handleKey(e, this);
149 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
151 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
154 var observer = new MutationObserver(function(mutations) {
155 mutations.forEach(function(mutation) {
156 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
157 observer.disconnect();
158 if(mutation.target.data === '')
159 mutation.target.data = utils.unicode.ZWS;
160 else if(mutation.oldValue === utils.unicode.ZWS) {
161 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
162 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
164 observer.observe(canvas.d[0], config);
165 canvas.publisher('contentChanged');
169 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
170 observer.observe(this.d[0], config);
173 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
174 var el = canvas.getDocumentElement(e.currentTarget);
178 if(el instanceof documentElement.DocumentTextElement)
180 el.toggleLabel(true);
182 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
183 var el = canvas.getDocumentElement(e.currentTarget);
187 if(el instanceof documentElement.DocumentTextElement)
189 el.toggleLabel(false);
192 this.eventBus.on('elementToggled', function(toggle, element) {
194 canvas.setCurrentElement(element.getPreviousTextElement());
210 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
213 wrapText: function(params) {
214 params = _.extend({textNodeIdx: 0}, params);
215 if(typeof params.textNodeIdx === 'number')
216 params.textNodeIdx = [params.textNodeIdx];
218 var childrenInside = params.inside.children(),
219 idx1 = Math.min.apply(Math, params.textNodeIdx),
220 idx2 = Math.max.apply(Math, params.textNodeIdx),
221 textNode1 = childrenInside[idx1],
222 textNode2 = childrenInside[idx2],
223 sameNode = textNode1.sameNode(textNode2),
224 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
225 prefixInside = textNode1.getText().substr(params.offsetStart),
226 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
227 suffixOutside = textNode2.getText().substr(params.offsetEnd)
230 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass}, this);
231 textNode1.after(wrapperElement);
234 if(prefixOutside.length > 0)
235 wrapperElement.before({text:prefixOutside});
237 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
238 wrapperElement.append({text: core});
241 if(prefixInside.length > 0)
242 wrapperElement.append({text: prefixInside});
243 for(var i = idx1 + 1; i < idx2; i++) {
244 wrapperElement.append(childrenInside[i]);
246 if(suffixInside.length > 0)
247 wrapperElement.append({text: suffixInside});
249 if(suffixOutside.length > 0)
250 wrapperElement.after({text: suffixOutside});
251 return wrapperElement;
254 wrapElements: function(params) {
255 if(!(params.element1.parent().sameNode(params.element2.parent())))
258 var parent = params.element1.parent(),
259 parentChildren = parent.children(),
260 wrapper = documentElement.DocumentNodeElement.create({
261 tag: params._with.tag,
262 klass: params._with.klass}),
263 idx1 = parent.childIndex(params.element1),
264 idx2 = parent.childIndex(params.element2);
272 var insertingMethod, insertingTarget;
274 insertingMethod = 'prepend';
275 insertingTarget = parent;
277 insertingMethod = 'after';
278 insertingTarget = parentChildren[idx1-1];
281 for(var i = idx1; i <= idx2; i++) {
282 wrapper.append(parentChildren[i].detach());
285 insertingTarget[insertingMethod](wrapper);
289 getSiblingParents: function(params) {
290 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
291 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
292 noSiblingParents = null;
294 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
295 return noSiblingParents;
298 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
299 if(parents1[i].sameNode(parents2[i]))
303 return {element1: parents1[i], element2: parents2[i]};
306 getDocumentElement: function(from) {
307 if(from instanceof HTMLElement || from instanceof Text) {
308 return documentElement.DocumentElement.fromHTMLElement(from, this);
311 getCursor: function() {
312 return new Cursor(this);
318 getCurrentNodeElement: function() {
319 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
322 getCurrentTextElement: function() {
323 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
328 setCurrentElement: function(element, params) {
329 params = _.extend({caretTo: 'end'}, params);
330 var findFirstDirectTextChild = function(e, nodeToLand) {
331 var byBrowser = this.getCursor().getPosition().element;
332 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
334 var children = e.children();
335 for(var i = 0; i < children.length; i++) {
336 if(children[i] instanceof documentElement.DocumentTextElement)
341 var _markAsCurrent = function(element) {
342 if(element instanceof documentElement.DocumentTextElement) {
343 this.wrapper.find('.current-text-element').removeClass('current-text-element');
344 element.dom().addClass('current-text-element');
346 this.wrapper.find('.current-node-element').removeClass('current-node-element')
347 element._container().addClass('current-node-element');
348 this.publisher('currentElementChanged', element);
353 var isTextElement = element instanceof documentElement.DocumentTextElement,
354 nodeElementToLand = isTextElement ? element.parent() : element,
355 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
356 currentTextElement = this.getCurrentTextElement(),
357 currentNodeElement = this.getCurrentNodeElement();
359 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
360 this.wrapper.find('.current-text-element').removeClass('current-text-element');
362 if(textElementToLand) {
363 _markAsCurrent(textElementToLand);
364 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
365 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
366 if(!(textElementToLand.sameNode(currentTextElement)))
367 this.publisher('currentTextElementSet', textElementToLand);
369 document.getSelection().removeAllRanges();
372 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
373 _markAsCurrent(nodeElementToLand);
375 this.publisher('currentNodeElementSet', nodeElementToLand);
379 _moveCaretToTextElement: function(element, where) {
380 var range = document.createRange(),
381 node = element.dom().contents()[0];
383 if(typeof where !== 'number') {
384 range.selectNodeContents(node);
386 range.setStart(node, where);
389 var collapseArg = true;
392 range.collapse(collapseArg);
394 var selection = document.getSelection();
396 selection.removeAllRanges();
397 selection.addRange(range);
398 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
401 setCursorPosition: function(position) {
403 this._moveCaretToTextElement(position.element, position.offset);
407 var parent = $('<div>'),
408 parts = this.doc().toXML(0);
409 parent.append(parts);
410 return parent.html();
414 $.extend(Canvas.prototype.list, {
415 create: function(params) {
416 if(!(params.element1.parent().sameNode(params.element2.parent())))
419 var parent = params.element1.parent();
421 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
422 var tmp = params.element1;
423 params.element1 = params.element2;
424 params.element2 = tmp;
427 var elementsToWrap = [];
429 var place = 'before';
431 parent.children().some(function(element) {
433 if(element.sameNode(params.element1))
435 if(place === 'inside') {
436 if(element instanceof documentElement.DocumentTextElement) {
437 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
438 if(element.children()[0].sameNode(params.element1))
439 params.element1 = element;
441 element.setWlxmlClass('item');
442 elementsToWrap.push(element);
444 if(_e.sameNode(params.element2))
448 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
451 if(parent.is('list')) {
452 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
453 item.exec('toggleBullet', false);
454 toret = listElement.parent();
459 params.element1.before(toret);
461 elementsToWrap.forEach(function(element) {
463 listElement.append(element);
466 extractItems: function(params) {
467 params = _.extend({merge: true}, params);
468 var list = params.element1.parent();
469 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
472 var idx1 = list.childIndex(params.element1),
473 idx2 = list.childIndex(params.element2),
476 succeedingItems = [],
477 items = list.children(),
478 listIsNested = list.parent().getWlxmlClass() === 'item',
482 var tmp = idx1; idx1 = idx2; idx2 = tmp;
485 items.forEach(function(item, idx) {
487 precedingItems.push(item);
488 else if(idx >= idx1 && idx <= idx2) {
489 extractedItems.push(item);
492 succeedingItems.push(item);
496 var reference = listIsNested ? list.parent() : list;
497 if(succeedingItems.length === 0) {
498 var reference_orig = reference;
499 extractedItems.forEach(function(item) {
500 reference.after(item);
503 item.setWlxmlClass(null);
505 if(precedingItems.length === 0)
506 reference_orig.detach();
507 } else if(precedingItems.length === 0) {
508 extractedItems.forEach(function(item) {
509 reference.before(item);
511 item.setWlxmlClass(null);
514 extractedItems.forEach(function(item) {
515 reference.after(item);
517 item.setWlxmlClass(null);
520 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
524 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
526 succeedingItems.forEach(function(item) {
527 secondList.append(item);
530 reference.after(toAdd);
532 if(!params.merge && listIsNested) {
533 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
537 areItemsOfTheSameList: function(params) {
538 var e1 = params.element1,
539 e2 = params.element2;
540 return e1.parent().sameNode(e2.parent())
541 && e1.parent().is('list');
546 var Cursor = function(canvas) {
547 this.canvas = canvas;
550 $.extend(Cursor.prototype, {
551 isSelecting: function() {
552 var selection = window.getSelection();
553 return !selection.isCollapsed;
555 isSelectingWithinElement: function() {
556 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
558 isSelectingSiblings: function() {
559 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
561 getPosition: function() {
562 return this.getSelectionAnchor();
564 getSelectionStart: function() {
565 return this.getSelectionBoundry('start');
567 getSelectionEnd: function() {
568 return this.getSelectionBoundry('end');
570 getSelectionAnchor: function() {
571 return this.getSelectionBoundry('anchor');
573 getSelectionFocus: function() {
574 return this.getSelectionBoundry('focus');
576 getSelectionBoundry: function(which) {
577 var selection = window.getSelection(),
578 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
579 focusElement = this.canvas.getDocumentElement(selection.focusNode);
581 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
584 if(which === 'anchor') {
586 element: anchorElement,
587 offset: selection.anchorOffset,
588 offsetAtBeginning: selection.anchorOffset === 0,
589 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
592 if(which === 'focus') {
594 element: focusElement,
595 offset: selection.focusOffset,
596 offsetAtBeginning: selection.focusOffset === 0,
597 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
604 if(anchorElement.parent().sameNode(focusElement.parent())) {
605 var parent = anchorElement.parent(),
606 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
608 if(which === 'start') {
609 element = anchorElement;
610 offset = selection.anchorOffset
612 else if(which === 'end') {
613 element = focusElement,
614 offset = selection.focusOffset
617 if(which === 'start') {
618 element = focusElement,
619 offset = selection.focusOffset
621 else if(which === 'end') {
622 element = anchorElement;
623 offset = selection.anchorOffset
627 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
628 if(which === 'start') {
629 element = anchorElement;
630 offset = selection.anchorOffset
632 element = focusElement;
633 offset = selection.focusOffset
637 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
641 offsetAtBeginning: offset === 0,
642 offsetAtEnd: nodeLen === offset
648 fromXML: function(xml, publisher) {
649 return new Canvas(xml, publisher);