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], [document-text-element]', 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);
224 this.wrapper.on('mouseover', '[wlxml-tag], [document-text-element]', function(e) {
225 var el = canvas.getDocumentElement(e.target);
229 if(el instanceof documentElement.DocumentTextElement)
231 el.toggleLabel(true);
233 this.wrapper.on('mouseout', '[wlxml-tag], [document-text-element]', function(e) {
234 var el = canvas.getDocumentElement(e.target);
238 if(el instanceof documentElement.DocumentTextElement)
240 el.toggleLabel(false);
255 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
258 wrapText: function(params) {
259 params = _.extend({textNodeIdx: 0}, params);
260 if(typeof params.textNodeIdx === 'number')
261 params.textNodeIdx = [params.textNodeIdx];
263 var childrenInside = params.inside.children(),
264 idx1 = Math.min.apply(Math, params.textNodeIdx),
265 idx2 = Math.max.apply(Math, params.textNodeIdx),
266 textNode1 = childrenInside[idx1],
267 textNode2 = childrenInside[idx2],
268 sameNode = textNode1.sameNode(textNode2),
269 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
270 prefixInside = textNode1.getText().substr(params.offsetStart),
271 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
272 suffixOutside = textNode2.getText().substr(params.offsetEnd)
275 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
276 textNode1.after(wrapperElement);
279 if(prefixOutside.length > 0)
280 wrapperElement.before({text:prefixOutside});
282 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
283 wrapperElement.append({text: core});
286 if(prefixInside.length > 0)
287 wrapperElement.append({text: prefixInside});
288 for(var i = idx1 + 1; i < idx2; i++) {
289 wrapperElement.append(childrenInside[i]);
291 if(suffixInside.length > 0)
292 wrapperElement.append({text: suffixInside});
294 if(suffixOutside.length > 0)
295 wrapperElement.after({text: suffixOutside});
296 return wrapperElement;
298 getDocumentElement: function(from) {
299 if(from instanceof HTMLElement || from instanceof Text) {
300 return documentElement.DocumentElement.fromHTMLElement(from, this);
303 getCursor: function() {
304 return new Cursor(this);
311 highlightElement: function(element) {
312 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
313 element.dom().addClass('highlighted-element');
316 dimElement: function(element) {
317 element.dom().removeClass('highlighted-element');
320 getCurrentNodeElement: function() {
321 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
324 getCurrentTextElement: function() {
325 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
330 setCurrentElement: function(element, params) {
331 params = _.extend({caretTo: 'end'}, params);
332 var findFirstDirectTextChild = function(e, nodeToLand) {
333 var byBrowser = this.getCursor().getPosition().element;
334 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
336 var children = e.children();
337 for(var i = 0; i < children.length; i++) {
338 if(children[i] instanceof documentElement.DocumentTextElement)
343 var _markAsCurrent = function(element) {
344 if(element instanceof documentElement.DocumentTextElement) {
345 this.wrapper.find('.current-text-element').removeClass('current-text-element');
346 element.dom().addClass('current-text-element');
348 this.wrapper.find('.current-node-element').removeClass('current-node-element')
349 element.dom().addClass('current-node-element');
350 this.publisher('currentElementChanged', element);
355 var isTextElement = element instanceof documentElement.DocumentTextElement,
356 nodeElementToLand = isTextElement ? element.parent() : element,
357 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
358 currentTextElement = this.getCurrentTextElement(),
359 currentNodeElement = this.getCurrentNodeElement();
361 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
362 this.wrapper.find('.current-text-element').removeClass('current-text-element');
364 if(textElementToLand) {
365 _markAsCurrent(textElementToLand);
366 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
367 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
368 if(!(textElementToLand.sameNode(currentTextElement)))
369 this.publisher('currentTextElementSet', textElementToLand);
371 document.getSelection().removeAllRanges();
374 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
375 _markAsCurrent(nodeElementToLand);
377 this.publisher('currentNodeElementSet', nodeElementToLand);
381 _moveCaretToTextElement: function(element, where) {
382 var range = document.createRange(),
383 node = element.dom().contents()[0];
385 if(typeof where !== 'number') {
386 range.selectNodeContents(node);
388 range.setStart(node, where);
391 var collapseArg = true;
394 range.collapse(collapseArg);
396 var selection = document.getSelection();
398 selection.removeAllRanges();
399 selection.addRange(range);
400 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
403 setCursorPosition: function(position) {
405 this._moveCaretToTextElement(position.element, position.offset);
409 var parent = $('<div>'),
410 parts = this.doc().toXML(0);
411 parent.append(parts);
412 return parent.html();
416 $.extend(Canvas.prototype.list, {
417 create: function(params) {
418 if(!(params.element1.parent().sameNode(params.element2.parent())))
421 var parent = params.element1.parent();
423 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
424 var tmp = params.element1;
425 params.element1 = params.element2;
426 params.element2 = tmp;
429 var elementsToWrap = [];
431 var place = 'before';
433 parent.children().some(function(element) {
435 if(element.sameNode(params.element1))
437 if(place === 'inside') {
438 if(element instanceof documentElement.DocumentTextElement) {
439 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
440 if(element.children()[0].sameNode(params.element1))
441 params.element1 = element;
443 element.setWlxmlClass('item');
444 elementsToWrap.push(element);
446 if(_e.sameNode(params.element2))
450 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
453 if(parent.is('list')) {
454 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
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 instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
585 if(which === 'anchor') {
587 element: anchorElement,
588 offset: selection.anchorOffset,
589 offsetAtBeginning: selection.anchorOffset === 0,
590 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
593 if(which === 'focus') {
595 element: focusElement,
596 offset: selection.focusOffset,
597 offsetAtBeginning: selection.focusOffset === 0,
598 offsetAtEnd: focusElement && focusElement.getText().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
641 offsetAtBeginning: offset === 0,
642 offsetAtEnd: element.getText().length === offset
648 fromXML: function(xml, publisher) {
649 return new Canvas(xml, publisher);