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 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', 'above', element.dom()[0]));
195 canvas.setCurrentElement(element);
211 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
214 wrapText: function(params) {
215 params = _.extend({textNodeIdx: 0}, params);
216 if(typeof params.textNodeIdx === 'number')
217 params.textNodeIdx = [params.textNodeIdx];
219 var childrenInside = params.inside.children(),
220 idx1 = Math.min.apply(Math, params.textNodeIdx),
221 idx2 = Math.max.apply(Math, params.textNodeIdx),
222 textNode1 = childrenInside[idx1],
223 textNode2 = childrenInside[idx2],
224 sameNode = textNode1.sameNode(textNode2),
225 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
226 prefixInside = textNode1.getText().substr(params.offsetStart),
227 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
228 suffixOutside = textNode2.getText().substr(params.offsetEnd)
231 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
232 textNode1.after(wrapperElement);
235 if(prefixOutside.length > 0)
236 wrapperElement.before({text:prefixOutside});
238 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
239 wrapperElement.append({text: core});
242 if(prefixInside.length > 0)
243 wrapperElement.append({text: prefixInside});
244 for(var i = idx1 + 1; i < idx2; i++) {
245 wrapperElement.append(childrenInside[i]);
247 if(suffixInside.length > 0)
248 wrapperElement.append({text: suffixInside});
250 if(suffixOutside.length > 0)
251 wrapperElement.after({text: suffixOutside});
252 return wrapperElement;
255 wrapElements: function(params) {
256 if(!(params.element1.parent().sameNode(params.element2.parent())))
259 var parent = params.element1.parent(),
260 parentChildren = parent.children(),
261 wrapper = documentElement.DocumentNodeElement.create({
262 tag: params._with.tag,
263 klass: params._with.klass}),
264 idx1 = parent.childIndex(params.element1),
265 idx2 = parent.childIndex(params.element2);
273 var insertingMethod, insertingTarget;
275 insertingMethod = 'prepend';
276 insertingTarget = parent;
278 insertingMethod = 'after';
279 insertingTarget = parentChildren[idx1-1];
282 for(var i = idx1; i <= idx2; i++) {
283 wrapper.append(parentChildren[i].detach());
286 insertingTarget[insertingMethod](wrapper);
290 getSiblingParents: function(params) {
291 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
292 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
293 noSiblingParents = null;
295 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
296 return noSiblingParents;
299 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
300 if(parents1[i].sameNode(parents2[i]))
304 return {element1: parents1[i], element2: parents2[i]};
307 getDocumentElement: function(from) {
308 if(from instanceof HTMLElement || from instanceof Text) {
309 return documentElement.DocumentElement.fromHTMLElement(from, this);
312 getCursor: function() {
313 return new Cursor(this);
319 getCurrentNodeElement: function() {
320 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
323 getCurrentTextElement: function() {
324 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
329 setCurrentElement: function(element, params) {
330 params = _.extend({caretTo: 'end'}, params);
331 var findFirstDirectTextChild = function(e, nodeToLand) {
332 var byBrowser = this.getCursor().getPosition().element;
333 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
335 var children = e.children();
336 for(var i = 0; i < children.length; i++) {
337 if(children[i] instanceof documentElement.DocumentTextElement)
342 var _markAsCurrent = function(element) {
343 if(element instanceof documentElement.DocumentTextElement) {
344 this.wrapper.find('.current-text-element').removeClass('current-text-element');
345 element.dom().addClass('current-text-element');
347 this.wrapper.find('.current-node-element').removeClass('current-node-element')
348 element._container().addClass('current-node-element');
349 this.publisher('currentElementChanged', element);
354 var isTextElement = element instanceof documentElement.DocumentTextElement,
355 nodeElementToLand = isTextElement ? element.parent() : element,
356 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
357 currentTextElement = this.getCurrentTextElement(),
358 currentNodeElement = this.getCurrentNodeElement();
360 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
361 this.wrapper.find('.current-text-element').removeClass('current-text-element');
363 if(textElementToLand) {
364 _markAsCurrent(textElementToLand);
365 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
366 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
367 if(!(textElementToLand.sameNode(currentTextElement)))
368 this.publisher('currentTextElementSet', textElementToLand);
370 document.getSelection().removeAllRanges();
373 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
374 _markAsCurrent(nodeElementToLand);
376 this.publisher('currentNodeElementSet', nodeElementToLand);
380 _moveCaretToTextElement: function(element, where) {
381 var range = document.createRange(),
382 node = element.dom().contents()[0];
384 if(typeof where !== 'number') {
385 range.selectNodeContents(node);
387 range.setStart(node, where);
390 var collapseArg = true;
393 range.collapse(collapseArg);
395 var selection = document.getSelection();
397 selection.removeAllRanges();
398 selection.addRange(range);
399 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
402 setCursorPosition: function(position) {
404 this._moveCaretToTextElement(position.element, position.offset);
408 var parent = $('<div>'),
409 parts = this.doc().toXML(0);
410 parent.append(parts);
411 return parent.html();
415 $.extend(Canvas.prototype.list, {
416 create: function(params) {
417 if(!(params.element1.parent().sameNode(params.element2.parent())))
420 var parent = params.element1.parent();
422 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
423 var tmp = params.element1;
424 params.element1 = params.element2;
425 params.element2 = tmp;
428 var elementsToWrap = [];
430 var place = 'before';
432 parent.children().some(function(element) {
434 if(element.sameNode(params.element1))
436 if(place === 'inside') {
437 if(element instanceof documentElement.DocumentTextElement) {
438 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
439 if(element.children()[0].sameNode(params.element1))
440 params.element1 = element;
442 element.setWlxmlClass('item');
443 elementsToWrap.push(element);
445 if(_e.sameNode(params.element2))
449 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
452 if(parent.is('list')) {
453 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
454 item.exec('toggleBullet', false);
455 toret = listElement.parent();
460 params.element1.before(toret);
462 elementsToWrap.forEach(function(element) {
464 listElement.append(element);
467 extractItems: function(params) {
468 params = _.extend({merge: true}, params);
469 var list = params.element1.parent();
470 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
473 var idx1 = list.childIndex(params.element1),
474 idx2 = list.childIndex(params.element2),
477 succeedingItems = [],
478 items = list.children(),
479 listIsNested = list.parent().getWlxmlClass() === 'item',
483 var tmp = idx1; idx1 = idx2; idx2 = tmp;
486 items.forEach(function(item, idx) {
488 precedingItems.push(item);
489 else if(idx >= idx1 && idx <= idx2) {
490 extractedItems.push(item);
493 succeedingItems.push(item);
497 var reference = listIsNested ? list.parent() : list;
498 if(succeedingItems.length === 0) {
499 var reference_orig = reference;
500 extractedItems.forEach(function(item) {
501 reference.after(item);
504 item.setWlxmlClass(null);
506 if(precedingItems.length === 0)
507 reference_orig.detach();
508 } else if(precedingItems.length === 0) {
509 extractedItems.forEach(function(item) {
510 reference.before(item);
512 item.setWlxmlClass(null);
515 extractedItems.forEach(function(item) {
516 reference.after(item);
518 item.setWlxmlClass(null);
521 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
525 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
527 succeedingItems.forEach(function(item) {
528 secondList.append(item);
531 reference.after(toAdd);
533 if(!params.merge && listIsNested) {
534 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
538 areItemsOfTheSameList: function(params) {
539 var e1 = params.element1,
540 e2 = params.element2;
541 return e1.parent().sameNode(e2.parent())
542 && e1.parent().is('list');
547 var Cursor = function(canvas) {
548 this.canvas = canvas;
551 $.extend(Cursor.prototype, {
552 isSelecting: function() {
553 var selection = window.getSelection();
554 return !selection.isCollapsed;
556 isSelectingWithinElement: function() {
557 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
559 isSelectingSiblings: function() {
560 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
562 getPosition: function() {
563 return this.getSelectionAnchor();
565 getSelectionStart: function() {
566 return this.getSelectionBoundry('start');
568 getSelectionEnd: function() {
569 return this.getSelectionBoundry('end');
571 getSelectionAnchor: function() {
572 return this.getSelectionBoundry('anchor');
574 getSelectionFocus: function() {
575 return this.getSelectionBoundry('focus');
577 getSelectionBoundry: function(which) {
578 var selection = window.getSelection(),
579 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
580 focusElement = this.canvas.getDocumentElement(selection.focusNode);
582 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
585 if(which === 'anchor') {
587 element: anchorElement,
588 offset: selection.anchorOffset,
589 offsetAtBeginning: selection.anchorOffset === 0,
590 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
593 if(which === 'focus') {
595 element: focusElement,
596 offset: selection.focusOffset,
597 offsetAtBeginning: selection.focusOffset === 0,
598 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
605 if(anchorElement.parent().sameNode(focusElement.parent())) {
606 var parent = anchorElement.parent(),
607 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
609 if(which === 'start') {
610 element = anchorElement;
611 offset = selection.anchorOffset
613 else if(which === 'end') {
614 element = focusElement,
615 offset = selection.focusOffset
618 if(which === 'start') {
619 element = focusElement,
620 offset = selection.focusOffset
622 else if(which === 'end') {
623 element = anchorElement;
624 offset = selection.anchorOffset
628 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
629 if(which === 'start') {
630 element = anchorElement;
631 offset = selection.anchorOffset
633 element = focusElement;
634 offset = selection.focusOffset
638 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
642 offsetAtBeginning: offset === 0,
643 offsetAtEnd: nodeLen === offset
649 fromXML: function(xml, publisher) {
650 return new Canvas(xml, publisher);