2 'libs/jquery-1.9.1.min',
4 'modules/documentCanvas/canvas/documentElement',
5 'modules/documentCanvas/canvas/utils'
6 ], function($, _, documentElement, utils) {
10 var Canvas = function(wlxml, publisher) {
11 this.loadWlxml(wlxml);
12 this.publisher = publisher ? publisher : function() {};
15 $.extend(Canvas.prototype, {
17 loadWlxml: function(wlxml) {
18 var d = wlxml ? $($.trim(wlxml)) : null;
20 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
21 this.wrapper.append(d);
23 this.wrapper.find('*').replaceWith(function() {
24 var currentTag = $(this);
25 if(currentTag.attr('wlxml-tag'))
28 var meta = {}, others = {};
29 for(var i = 0; i < this.attributes.length; i++) {
30 var attr = this.attributes[i];
31 if(attr.name.substr(0, 5) === 'meta-')
32 meta[attr.name.substr(5)] = attr.value;
33 else if(attr.name !== 'class')
34 others[attr.name] = attr.value;
37 var element = documentElement.DocumentNodeElement.create({
38 tag: currentTag.prop('tagName').toLowerCase(),
39 klass: currentTag.attr('class'),
42 rawChildren: currentTag.contents()
45 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
46 element.data(attr, '');
51 var FIRST_CONTENT_INDEX = 0;
53 // @@ TODO - refactor!
54 var getNode = function(element) {
55 return element.children('[document-element-content]');
58 this.wrapper.find(':not(iframe)').addBack().contents()
59 .filter(function() {return this.nodeType === Node.TEXT_NODE})
62 // TODO: use DocumentElement API
65 text = {original: el.text(), trimmed: $.trim(el.text())},
66 elParent = el.parent(),
67 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
68 hasSpanBefore = el.prev().length > 0 && getNode($(el.prev()[0])).attr('wlxml-tag') === 'span',
69 hasSpanAfter = el.next().length > 0 && getNode($(el.next()[0])).attr('wlxml-tag') === 'span';
71 if(el.parent().hasClass('canvas-widget'))
72 return true; // continue
74 var addInfo = function(toAdd, where) {
75 var parentContents = elParent.contents(),
76 idx = parentContents.index(el[0]),
77 prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
78 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
81 if(where === 'above') {
82 target = prev ? $(prev) : elParent.parent();
83 key = prev ? 'orig-after' : 'orig-begin';
84 } else if(where === 'below') {
85 target = next ? $(next) : elParent.parent();
86 key = next ? 'orig-before' : 'orig-end';
87 } else { throw new Object;}
89 target.data(key, toAdd);
92 text.transformed = text.trimmed;
94 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
95 var startSpace = /\s/g.test(text.original.substr(0,1)),
96 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
97 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
99 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
101 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
102 text.transformed = ' ';
105 if(!text.transformed) {
106 addInfo(text.original, 'below');
108 return true; // continue
111 if(text.transformed !== text.original) {
113 addInfo(text.original, 'below');
115 var startingMatch = text.original.match(/^\s+/g),
116 endingMatch = text.original.match(/\s+$/g),
117 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
118 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
120 if(endingWhiteSpace) {
121 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
122 endingWhiteSpace = endingWhiteSpace.substr(1);
123 addInfo(endingWhiteSpace, 'below');
126 if(startingWhiteSpace) {
127 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
128 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
129 addInfo(startingWhiteSpace, 'above');
134 var element = documentElement.DocumentTextElement.create({text: text.transformed});
135 el.replaceWith(element.dom());
138 this.d = this.wrapper.children(0);
141 this.wrapper.on('keydown', function(e) {
144 var cursor = canvas.getCursor();
145 if(!cursor.isSelecting()) {
146 var position = cursor.getPosition(),
147 elements = position.element.split({offset: position.offset}),
151 if(position.offsetAtBeginning)
152 newEmpty = elements.first;
153 else if(position.offsetAtEnd)
154 newEmpty = elements.second;
156 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
157 canvas.setCurrentElement(goto);
171 this.wrapper.on('keyup', function(e) {
172 if(e.which >= 37 && e.which <= 40) {
173 var element = canvas.getCursor().getPosition().element,
178 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
185 element = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]:visible', direction, window.getSelection().focusNode));
187 canvas.setCurrentElement(element, {caretTo: caretTo});
191 this.wrapper.on('keydown', function(e) {
192 if(e.which >= 37 && e.which <= 40) {
193 var position = canvas.getCursor().getPosition(),
194 element = position.element;
195 if(element && (element instanceof documentElement.DocumentTextElement)) {
196 if(element.isEmpty()) {
197 var direction, caretTo;
198 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
205 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
206 canvas.setCurrentElement(element, {caretTo: caretTo});
208 var txt = element.dom().contents()[0].data;
209 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
211 canvas._moveCaretToTextElement(element, position.offset-2);
213 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
215 canvas._moveCaretToTextElement(element, position.offset+2);
224 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
226 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
229 var observer = new MutationObserver(function(mutations) {
230 mutations.forEach(function(mutation) {
231 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
232 mutation.target.data = utils.unicode.ZWS;
235 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
236 observer.observe(this.d[0], config);
239 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
240 var el = canvas.getDocumentElement(e.currentTarget);
244 if(el instanceof documentElement.DocumentTextElement)
246 el.toggleLabel(true);
248 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
249 var el = canvas.getDocumentElement(e.currentTarget);
253 if(el instanceof documentElement.DocumentTextElement)
255 el.toggleLabel(false);
270 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
273 wrapText: function(params) {
274 params = _.extend({textNodeIdx: 0}, params);
275 if(typeof params.textNodeIdx === 'number')
276 params.textNodeIdx = [params.textNodeIdx];
278 var childrenInside = params.inside.children(),
279 idx1 = Math.min.apply(Math, params.textNodeIdx),
280 idx2 = Math.max.apply(Math, params.textNodeIdx),
281 textNode1 = childrenInside[idx1],
282 textNode2 = childrenInside[idx2],
283 sameNode = textNode1.sameNode(textNode2),
284 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
285 prefixInside = textNode1.getText().substr(params.offsetStart),
286 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
287 suffixOutside = textNode2.getText().substr(params.offsetEnd)
290 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
291 textNode1.after(wrapperElement);
294 if(prefixOutside.length > 0)
295 wrapperElement.before({text:prefixOutside});
297 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
298 wrapperElement.append({text: core});
301 if(prefixInside.length > 0)
302 wrapperElement.append({text: prefixInside});
303 for(var i = idx1 + 1; i < idx2; i++) {
304 wrapperElement.append(childrenInside[i]);
306 if(suffixInside.length > 0)
307 wrapperElement.append({text: suffixInside});
309 if(suffixOutside.length > 0)
310 wrapperElement.after({text: suffixOutside});
311 return wrapperElement;
313 getDocumentElement: function(from) {
314 if(from instanceof HTMLElement || from instanceof Text) {
315 return documentElement.DocumentElement.fromHTMLElement(from, this);
318 getCursor: function() {
319 return new Cursor(this);
325 getCurrentNodeElement: function() {
326 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
329 getCurrentTextElement: function() {
330 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
335 setCurrentElement: function(element, params) {
336 params = _.extend({caretTo: 'end'}, params);
337 var findFirstDirectTextChild = function(e, nodeToLand) {
338 var byBrowser = this.getCursor().getPosition().element;
339 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
341 var children = e.children();
342 for(var i = 0; i < children.length; i++) {
343 if(children[i] instanceof documentElement.DocumentTextElement)
348 var _markAsCurrent = function(element) {
349 if(element instanceof documentElement.DocumentTextElement) {
350 this.wrapper.find('.current-text-element').removeClass('current-text-element');
351 element.dom().addClass('current-text-element');
353 this.wrapper.find('.current-node-element').removeClass('current-node-element')
354 element._container().addClass('current-node-element');
355 this.publisher('currentElementChanged', element);
360 var isTextElement = element instanceof documentElement.DocumentTextElement,
361 nodeElementToLand = isTextElement ? element.parent() : element,
362 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
363 currentTextElement = this.getCurrentTextElement(),
364 currentNodeElement = this.getCurrentNodeElement();
366 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
367 this.wrapper.find('.current-text-element').removeClass('current-text-element');
369 if(textElementToLand) {
370 _markAsCurrent(textElementToLand);
371 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
372 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
373 if(!(textElementToLand.sameNode(currentTextElement)))
374 this.publisher('currentTextElementSet', textElementToLand);
376 document.getSelection().removeAllRanges();
379 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
380 _markAsCurrent(nodeElementToLand);
382 this.publisher('currentNodeElementSet', nodeElementToLand);
386 _moveCaretToTextElement: function(element, where) {
387 var range = document.createRange(),
388 node = element.dom().contents()[0];
390 if(typeof where !== 'number') {
391 range.selectNodeContents(node);
393 range.setStart(node, where);
396 var collapseArg = true;
399 range.collapse(collapseArg);
401 var selection = document.getSelection();
403 selection.removeAllRanges();
404 selection.addRange(range);
405 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
408 setCursorPosition: function(position) {
410 this._moveCaretToTextElement(position.element, position.offset);
414 var parent = $('<div>'),
415 parts = this.doc().toXML(0);
416 parent.append(parts);
417 return parent.html();
421 $.extend(Canvas.prototype.list, {
422 create: function(params) {
423 if(!(params.element1.parent().sameNode(params.element2.parent())))
426 var parent = params.element1.parent();
428 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
429 var tmp = params.element1;
430 params.element1 = params.element2;
431 params.element2 = tmp;
434 var elementsToWrap = [];
436 var place = 'before';
438 parent.children().some(function(element) {
440 if(element.sameNode(params.element1))
442 if(place === 'inside') {
443 if(element instanceof documentElement.DocumentTextElement) {
444 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
445 if(element.children()[0].sameNode(params.element1))
446 params.element1 = element;
448 element.setWlxmlClass('item');
449 elementsToWrap.push(element);
451 if(_e.sameNode(params.element2))
455 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
458 if(parent.is('list')) {
459 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
460 toret = listElement.parent();
465 params.element1.before(toret);
467 elementsToWrap.forEach(function(element) {
469 listElement.append(element);
472 extractItems: function(params) {
473 params = _.extend({merge: true}, params);
474 var list = params.element1.parent();
475 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
478 var idx1 = list.childIndex(params.element1),
479 idx2 = list.childIndex(params.element2),
482 succeedingItems = [],
483 items = list.children(),
484 listIsNested = list.parent().getWlxmlClass() === 'item',
488 var tmp = idx1; idx1 = idx2; idx2 = tmp;
491 items.forEach(function(item, idx) {
493 precedingItems.push(item);
494 else if(idx >= idx1 && idx <= idx2) {
495 extractedItems.push(item);
498 succeedingItems.push(item);
502 var reference = listIsNested ? list.parent() : list;
503 if(succeedingItems.length === 0) {
504 var reference_orig = reference;
505 extractedItems.forEach(function(item) {
506 reference.after(item);
509 item.setWlxmlClass(null);
511 if(precedingItems.length === 0)
512 reference_orig.detach();
513 } else if(precedingItems.length === 0) {
514 extractedItems.forEach(function(item) {
515 reference.before(item);
517 item.setWlxmlClass(null);
520 extractedItems.forEach(function(item) {
521 reference.after(item);
523 item.setWlxmlClass(null);
526 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
530 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
532 succeedingItems.forEach(function(item) {
533 secondList.append(item);
536 reference.after(toAdd);
538 if(!params.merge && listIsNested) {
539 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
543 areItemsOfTheSameList: function(params) {
544 var e1 = params.element1,
545 e2 = params.element2;
546 return e1.parent().sameNode(e2.parent())
547 && e1.parent().is('list');
552 var Cursor = function(canvas) {
553 this.canvas = canvas;
556 $.extend(Cursor.prototype, {
557 isSelecting: function() {
558 var selection = window.getSelection();
559 return !selection.isCollapsed;
561 isSelectingWithinElement: function() {
562 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
564 isSelectingSiblings: function() {
565 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
567 getPosition: function() {
568 return this.getSelectionAnchor();
570 getSelectionStart: function() {
571 return this.getSelectionBoundry('start');
573 getSelectionEnd: function() {
574 return this.getSelectionBoundry('end');
576 getSelectionAnchor: function() {
577 return this.getSelectionBoundry('anchor');
579 getSelectionFocus: function() {
580 return this.getSelectionBoundry('focus');
582 getSelectionBoundry: function(which) {
583 var selection = window.getSelection(),
584 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
585 focusElement = this.canvas.getDocumentElement(selection.focusNode);
587 var getOffset = function(where) {
589 if(where === 'anchor') {
590 node = selection.anchorNode;
591 toret = selection.anchorOffset;
593 node = selection.focusNode;
594 toret = selection.focusOffset;
597 if(toret === 1 && node.data.charAt(0) === utils.unicode.ZWS)
599 else if((toret === node.data.length - 1) && (node.data.charAt(node.data.length - 1) === utils.unicode.ZWS))
604 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
607 if(which === 'anchor') {
609 element: anchorElement,
610 offset: getOffset('anchor'),
611 offsetAtBeginning: getOffset('anchor') === 0,
612 offsetAtEnd: selection.anchorNode.data.length === getOffset('anchor')
615 if(which === 'focus') {
617 element: focusElement,
618 offset: getOffset('focus'),
619 offsetAtBeginning: getOffset('focus') === 0,
620 offsetAtEnd: selection.focusElement.data.length === getOffset('focus')
627 if(anchorElement.parent().sameNode(focusElement.parent())) {
628 var parent = anchorElement.parent(),
629 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
631 if(which === 'start') {
632 element = anchorElement;
633 offset = getOffset('anchor')
635 else if(which === 'end') {
636 element = focusElement,
637 offset = getOffset('focus')
640 if(which === 'start') {
641 element = focusElement,
642 offset = getOffset('focus')
644 else if(which === 'end') {
645 element = anchorElement;
646 offset = getOffset('anchor')
650 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
651 if(which === 'start') {
652 element = anchorElement;
653 offset = getOffset('anchor')
655 element = focusElement;
656 offset = getOffset('focus')
660 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
664 offsetAtBeginning: offset === 0,
665 offsetAtEnd: nodeLen === offset
671 fromXML: function(xml, publisher) {
672 return new Canvas(xml, publisher);