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 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
176 this.wrapper.on('keydown', function(e) {
177 if(e.which >= 37 && e.which <= 40) {
178 var position = canvas.getCursor().getPosition(),
179 element = position.element;
180 if(element && (element instanceof documentElement.DocumentTextElement)) {
181 if(element.isEmpty()) {
182 var direction, caretTo;
183 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
190 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
191 canvas.setCurrentElement(element, {caretTo: caretTo});
193 var txt = element.dom().contents()[0].data;
194 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
196 canvas._moveCaretToTextElement(element, position.offset-2);
198 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
200 canvas._moveCaretToTextElement(element, position.offset+2);
209 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
211 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
214 var observer = new MutationObserver(function(mutations) {
215 mutations.forEach(function(mutation) {
216 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
217 mutation.target.data = utils.unicode.ZWS;
220 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
221 observer.observe(this.d[0], config);
223 this.wrapper.on('mouseover', '[wlxml-tag], [wlxml-text]', function(e) {
224 var el = canvas.getDocumentElement(e.target);
228 if(el instanceof documentElement.DocumentTextElement)
230 el.toggleLabel(true);
232 this.wrapper.on('mouseout', '[wlxml-tag], [wlxml-text]', function(e) {
233 var el = canvas.getDocumentElement(e.target);
237 if(el instanceof documentElement.DocumentTextElement)
239 el.toggleLabel(false);
254 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
257 wrapText: function(params) {
258 params = _.extend({textNodeIdx: 0}, params);
259 if(typeof params.textNodeIdx === 'number')
260 params.textNodeIdx = [params.textNodeIdx];
262 var childrenInside = params.inside.children(),
263 idx1 = Math.min.apply(Math, params.textNodeIdx),
264 idx2 = Math.max.apply(Math, params.textNodeIdx),
265 textNode1 = childrenInside[idx1],
266 textNode2 = childrenInside[idx2],
267 sameNode = textNode1.sameNode(textNode2),
268 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
269 prefixInside = textNode1.getText().substr(params.offsetStart),
270 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
271 suffixOutside = textNode2.getText().substr(params.offsetEnd)
274 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
275 textNode1.after(wrapperElement);
278 if(prefixOutside.length > 0)
279 wrapperElement.before({text:prefixOutside});
281 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
282 wrapperElement.append({text: core});
285 if(prefixInside.length > 0)
286 wrapperElement.append({text: prefixInside});
287 for(var i = idx1 + 1; i < idx2; i++) {
288 wrapperElement.append(childrenInside[i]);
290 if(suffixInside.length > 0)
291 wrapperElement.append({text: suffixInside});
293 if(suffixOutside.length > 0)
294 wrapperElement.after({text: suffixOutside});
295 return wrapperElement;
297 getDocumentElement: function(from) {
298 if(from instanceof HTMLElement || from instanceof Text) {
299 return documentElement.DocumentElement.fromHTMLElement(from, this);
302 getCursor: function() {
303 return new Cursor(this);
310 highlightElement: function(element) {
311 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
312 element.dom().addClass('highlighted-element');
315 dimElement: function(element) {
316 element.dom().removeClass('highlighted-element');
319 getCurrentNodeElement: function() {
320 return this.getDocumentElement(this.wrapper.find('.current-node-element')[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.dom().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 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
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 instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
584 if(which === 'anchor') {
586 element: anchorElement,
587 offset: selection.anchorOffset,
588 offsetAtBeginning: selection.anchorOffset === 0,
589 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
592 if(which === 'focus') {
594 element: focusElement,
595 offset: selection.focusOffset,
596 offsetAtBeginning: selection.focusOffset === 0,
597 offsetAtEnd: focusElement && focusElement.getText().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
640 offsetAtBeginning: offset === 0,
641 offsetAtEnd: element.getText().length === offset
647 fromXML: function(xml, publisher) {
648 return new Canvas(xml, publisher);