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'),
44 element.dom().append(currentTag.contents());
45 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
46 element.data(attr, '');
51 var FIRST_CONTENT_INDEX = 1;
53 this.wrapper.find(':not(iframe)').addBack().contents()
54 .filter(function() {return this.nodeType === Node.TEXT_NODE})
57 // TODO: use DocumentElement API
60 text = {original: el.text(), trimmed: $.trim(el.text())},
61 elParent = el.parent(),
62 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
63 hasSpanBefore = el.prev().length > 0 && $(el.prev()[0]).attr('wlxml-tag') === 'span',
64 hasSpanAfter = el.next().length > 0 && $(el.next()[0]).attr('wlxml-tag') === 'span';
66 if(el.parent().hasClass('canvas-widget'))
67 return true; // continue
69 var addInfo = function(toAdd, where) {
70 var parentContents = elParent.contents(),
71 idx = parentContents.index(el[0]),
72 prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
73 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
76 if(where === 'above') {
77 target = prev ? $(prev) : elParent;
78 key = prev ? 'orig-after' : 'orig-begin';
79 } else if(where === 'below') {
80 target = next ? $(next) : elParent;
81 key = next ? 'orig-before' : 'orig-end';
82 } else { throw new Object;}
84 target.data(key, toAdd);
87 text.transformed = text.trimmed;
89 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
90 var startSpace = /\s/g.test(text.original.substr(0,1)),
91 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
92 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
94 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
96 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 2)
97 text.transformed = ' ';
100 if(!text.transformed) {
101 addInfo(text.original, 'below');
103 return true; // continue
106 if(text.transformed !== text.original) {
108 addInfo(text.original, 'below');
110 var startingMatch = text.original.match(/^\s+/g),
111 endingMatch = text.original.match(/\s+$/g),
112 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
113 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
115 if(endingWhiteSpace) {
116 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
117 endingWhiteSpace = endingWhiteSpace.substr(1);
118 addInfo(endingWhiteSpace, 'below');
121 if(startingWhiteSpace) {
122 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
123 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
124 addInfo(startingWhiteSpace, 'above');
129 var element = documentElement.DocumentTextElement.create({text: text.transformed});
130 el.replaceWith(element.dom());
133 this.d = this.wrapper.children(0);
136 this.wrapper.on('keydown', function(e) {
139 var cursor = canvas.getCursor();
140 if(!cursor.isSelecting()) {
141 var position = cursor.getPosition(),
142 elements = position.element.split({offset: position.offset}),
146 if(position.offsetAtBeginning)
147 newEmpty = elements.first;
148 else if(position.offsetAtEnd)
149 newEmpty = elements.second;
151 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: ''}, this));
152 canvas.setCurrentElement(goto);
166 this.wrapper.on('keyup', function(e) {
167 if(e.which >= 37 && e.which <= 40)
168 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
171 this.wrapper.on('keydown', function(e) {
172 if(e.which >= 37 && e.which <= 40) {
173 var position = canvas.getCursor().getPosition(),
174 element = position.element;
175 if(element && (element instanceof documentElement.DocumentTextElement)) {
176 if(element.isEmpty()) {
177 var direction, caretTo;
178 if(e.which === KEYS.ARROW_LEFT || e.which === KEYS.ARROW_UP) {
185 var el = canvas.getDocumentElement(utils.nearestInDocumentOrder('[document-text-element]', direction, window.getSelection().focusNode))
186 canvas.setCurrentElement(element, {caretTo: caretTo});
188 var txt = element.dom().contents()[0].data;
189 if(e.which === KEYS.ARROW_LEFT && position.offset > 1 && txt.charAt(position.offset-2) === utils.unicode.ZWS) {
191 canvas._moveCaretToTextElement(element, position.offset-2);
193 if(e.which === KEYS.ARROW_RIGHT && position.offset < txt.length - 1 && txt.charAt(position.offset+1) === utils.unicode.ZWS) {
195 canvas._moveCaretToTextElement(element, position.offset+2);
204 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
206 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
209 var observer = new MutationObserver(function(mutations) {
210 mutations.forEach(function(mutation) {
211 if(documentElement.DocumentTextElement.isContentContainer(mutation.target) && mutation.target.data === '')
212 mutation.target.data = utils.unicode.ZWS;
215 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
216 observer.observe(this.d[0], config);
218 this.wrapper.on('mouseover', '[wlxml-tag], [wlxml-text]', function(e) {
219 var el = canvas.getDocumentElement(e.target);
223 if(el instanceof documentElement.DocumentTextElement)
225 el.toggleLabel(true);
227 this.wrapper.on('mouseout', '[wlxml-tag], [wlxml-text]', function(e) {
228 var el = canvas.getDocumentElement(e.target);
232 if(el instanceof documentElement.DocumentTextElement)
234 el.toggleLabel(false);
249 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
252 wrapText: function(params) {
253 params = _.extend({textNodeIdx: 0}, params);
254 if(typeof params.textNodeIdx === 'number')
255 params.textNodeIdx = [params.textNodeIdx];
257 var childrenInside = params.inside.children(),
258 idx1 = Math.min.apply(Math, params.textNodeIdx),
259 idx2 = Math.max.apply(Math, params.textNodeIdx),
260 textNode1 = childrenInside[idx1],
261 textNode2 = childrenInside[idx2],
262 sameNode = textNode1.sameNode(textNode2),
263 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
264 prefixInside = textNode1.getText().substr(params.offsetStart),
265 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
266 suffixOutside = textNode2.getText().substr(params.offsetEnd)
269 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
270 textNode1.after(wrapperElement);
273 if(prefixOutside.length > 0)
274 wrapperElement.before({text:prefixOutside});
276 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
277 wrapperElement.append({text: core});
280 if(prefixInside.length > 0)
281 wrapperElement.append({text: prefixInside});
282 for(var i = idx1 + 1; i < idx2; i++) {
283 wrapperElement.append(childrenInside[i]);
285 if(suffixInside.length > 0)
286 wrapperElement.append({text: suffixInside});
288 if(suffixOutside.length > 0)
289 wrapperElement.after({text: suffixOutside});
290 return wrapperElement;
292 getDocumentElement: function(from) {
293 if(from instanceof HTMLElement || from instanceof Text) {
294 return documentElement.DocumentElement.fromHTMLElement(from, this);
297 getCursor: function() {
298 return new Cursor(this);
305 highlightElement: function(element) {
306 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
307 element.dom().addClass('highlighted-element');
310 dimElement: function(element) {
311 element.dom().removeClass('highlighted-element');
314 getCurrentNodeElement: function() {
315 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
318 getCurrentTextElement: function() {
319 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
324 setCurrentElement: function(element, params) {
325 params = _.extend({caretTo: 'end'}, params);
326 var findFirstDirectTextChild = function(e, nodeToLand) {
327 var byBrowser = this.getCursor().getPosition().element;
328 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
330 var children = e.children();
331 for(var i = 0; i < children.length; i++) {
332 if(children[i] instanceof documentElement.DocumentTextElement)
337 var _markAsCurrent = function(element) {
338 if(element instanceof documentElement.DocumentTextElement) {
339 this.wrapper.find('.current-text-element').removeClass('current-text-element');
340 element.dom().addClass('current-text-element');
342 this.wrapper.find('.current-node-element').removeClass('current-node-element')
343 element.dom().addClass('current-node-element');
344 this.publisher('currentElementChanged', element);
349 var isTextElement = element instanceof documentElement.DocumentTextElement,
350 nodeElementToLand = isTextElement ? element.parent() : element,
351 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
352 currentTextElement = this.getCurrentTextElement(),
353 currentNodeElement = this.getCurrentNodeElement();
355 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
356 this.wrapper.find('.current-text-element').removeClass('current-text-element');
358 if(textElementToLand) {
359 _markAsCurrent(textElementToLand);
360 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
361 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
362 if(!(textElementToLand.sameNode(currentTextElement)))
363 this.publisher('currentTextElementSet', textElementToLand);
365 document.getSelection().removeAllRanges();
368 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
369 _markAsCurrent(nodeElementToLand);
371 this.publisher('currentNodeElementSet', nodeElementToLand);
375 _moveCaretToTextElement: function(element, where) {
376 var range = document.createRange(),
377 node = element.dom().contents()[0];
379 if(typeof where !== 'number') {
380 range.selectNodeContents(node);
382 range.setStart(node, where);
385 var collapseArg = true;
388 range.collapse(collapseArg);
390 var selection = document.getSelection();
392 selection.removeAllRanges();
393 selection.addRange(range);
394 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
397 setCursorPosition: function(position) {
399 this._moveCaretToTextElement(position.element, position.offset);
403 var parent = $('<div>'),
404 parts = this.doc().toXML(0);
405 parent.append(parts);
406 return parent.html();
410 $.extend(Canvas.prototype.list, {
411 create: function(params) {
412 if(!(params.element1.parent().sameNode(params.element2.parent())))
415 var parent = params.element1.parent();
417 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
418 var tmp = params.element1;
419 params.element1 = params.element2;
420 params.element2 = tmp;
423 var elementsToWrap = [];
425 var place = 'before';
427 parent.children().some(function(element) {
429 if(element.sameNode(params.element1))
431 if(place === 'inside') {
432 if(element instanceof documentElement.DocumentTextElement) {
433 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
434 if(element.children()[0].sameNode(params.element1))
435 params.element1 = element;
437 element.setWlxmlClass('item');
438 elementsToWrap.push(element);
440 if(_e.sameNode(params.element2))
444 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
447 if(parent.is('list')) {
448 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
449 toret = listElement.parent();
454 params.element1.before(toret);
456 elementsToWrap.forEach(function(element) {
458 listElement.append(element);
461 extractItems: function(params) {
462 params = _.extend({merge: true}, params);
463 var list = params.element1.parent();
464 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
467 var idx1 = list.childIndex(params.element1),
468 idx2 = list.childIndex(params.element2),
471 succeedingItems = [],
472 items = list.children(),
473 listIsNested = list.parent().getWlxmlClass() === 'item',
477 var tmp = idx1; idx1 = idx2; idx2 = tmp;
480 items.forEach(function(item, idx) {
482 precedingItems.push(item);
483 else if(idx >= idx1 && idx <= idx2) {
484 extractedItems.push(item);
487 succeedingItems.push(item);
491 var reference = listIsNested ? list.parent() : list;
492 if(succeedingItems.length === 0) {
493 var reference_orig = reference;
494 extractedItems.forEach(function(item) {
495 reference.after(item);
498 item.setWlxmlClass(null);
500 if(precedingItems.length === 0)
501 reference_orig.detach();
502 } else if(precedingItems.length === 0) {
503 extractedItems.forEach(function(item) {
504 reference.before(item);
506 item.setWlxmlClass(null);
509 extractedItems.forEach(function(item) {
510 reference.after(item);
512 item.setWlxmlClass(null);
515 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
519 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
521 succeedingItems.forEach(function(item) {
522 secondList.append(item);
525 reference.after(toAdd);
527 if(!params.merge && listIsNested) {
528 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
532 areItemsOfTheSameList: function(params) {
533 var e1 = params.element1,
534 e2 = params.element2;
535 return e1.parent().sameNode(e2.parent())
536 && e1.parent().is('list');
541 var Cursor = function(canvas) {
542 this.canvas = canvas;
545 $.extend(Cursor.prototype, {
546 isSelecting: function() {
547 var selection = window.getSelection();
548 return !selection.isCollapsed;
550 isSelectingWithinElement: function() {
551 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
553 isSelectingSiblings: function() {
554 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
556 getPosition: function() {
557 return this.getSelectionAnchor();
559 getSelectionStart: function() {
560 return this.getSelectionBoundry('start');
562 getSelectionEnd: function() {
563 return this.getSelectionBoundry('end');
565 getSelectionAnchor: function() {
566 return this.getSelectionBoundry('anchor');
568 getSelectionFocus: function() {
569 return this.getSelectionBoundry('focus');
571 getSelectionBoundry: function(which) {
572 var selection = window.getSelection(),
573 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
574 focusElement = this.canvas.getDocumentElement(selection.focusNode);
576 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
579 if(which === 'anchor') {
581 element: anchorElement,
582 offset: selection.anchorOffset,
583 offsetAtBeginning: selection.anchorOffset === 0,
584 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
587 if(which === 'focus') {
589 element: focusElement,
590 offset: selection.focusOffset,
591 offsetAtBeginning: selection.focusOffset === 0,
592 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
599 if(anchorElement.parent().sameNode(focusElement.parent())) {
600 var parent = anchorElement.parent(),
601 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
603 if(which === 'start') {
604 element = anchorElement;
605 offset = selection.anchorOffset;
607 else if(which === 'end') {
608 element = focusElement,
609 offset = selection.focusOffset;
612 if(which === 'start') {
613 element = focusElement,
614 offset = selection.focusOffset
616 else if(which === 'end') {
617 element = anchorElement;
618 offset = selection.anchorOffset;
622 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
623 if(which === 'start') {
624 element = anchorElement;
625 offset = selection.anchorOffset
627 element = focusElement;
628 offset = selection.focusOffset
635 offsetAtBeginning: offset === 0,
636 offsetAtEnd: element.getText().length === offset
642 fromXML: function(xml, publisher) {
643 return new Canvas(xml, publisher);