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 = canvas.createNodeElement({
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 canvas.setCurrentElement(element.getPreviousTextElement());
210 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
213 createNodeElement: function(params) {
214 return documentElement.DocumentNodeElement.create(params, this);
217 wrapText: function(params) {
218 params = _.extend({textNodeIdx: 0}, params);
219 if(typeof params.textNodeIdx === 'number')
220 params.textNodeIdx = [params.textNodeIdx];
222 var childrenInside = params.inside.children(),
223 idx1 = Math.min.apply(Math, params.textNodeIdx),
224 idx2 = Math.max.apply(Math, params.textNodeIdx),
225 textNode1 = childrenInside[idx1],
226 textNode2 = childrenInside[idx2],
227 sameNode = textNode1.sameNode(textNode2),
228 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
229 prefixInside = textNode1.getText().substr(params.offsetStart),
230 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
231 suffixOutside = textNode2.getText().substr(params.offsetEnd)
234 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
235 textNode1.after(wrapperElement);
238 if(prefixOutside.length > 0)
239 wrapperElement.before({text:prefixOutside});
241 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
242 wrapperElement.append({text: core});
245 if(prefixInside.length > 0)
246 wrapperElement.append({text: prefixInside});
247 for(var i = idx1 + 1; i < idx2; i++) {
248 wrapperElement.append(childrenInside[i]);
250 if(suffixInside.length > 0)
251 wrapperElement.append({text: suffixInside});
253 if(suffixOutside.length > 0)
254 wrapperElement.after({text: suffixOutside});
255 return wrapperElement;
258 wrapElements: function(params) {
259 if(!(params.element1.parent().sameNode(params.element2.parent())))
262 var parent = params.element1.parent(),
263 parentChildren = parent.children(),
264 wrapper = this.createNodeElement({
265 tag: params._with.tag,
266 klass: params._with.klass}),
267 idx1 = parent.childIndex(params.element1),
268 idx2 = parent.childIndex(params.element2);
276 var insertingMethod, insertingTarget;
278 insertingMethod = 'prepend';
279 insertingTarget = parent;
281 insertingMethod = 'after';
282 insertingTarget = parentChildren[idx1-1];
285 for(var i = idx1; i <= idx2; i++) {
286 wrapper.append(parentChildren[i].detach());
289 insertingTarget[insertingMethod](wrapper);
293 getSiblingParents: function(params) {
294 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
295 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
296 noSiblingParents = null;
298 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
299 return noSiblingParents;
302 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
303 if(parents1[i].sameNode(parents2[i]))
307 return {element1: parents1[i], element2: parents2[i]};
310 getDocumentElement: function(from) {
311 if(from instanceof HTMLElement || from instanceof Text) {
312 return documentElement.DocumentElement.fromHTMLElement(from, this);
315 getCursor: function() {
316 return new Cursor(this);
322 getCurrentNodeElement: function() {
323 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
326 getCurrentTextElement: function() {
327 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
332 setCurrentElement: function(element, params) {
333 params = _.extend({caretTo: 'end'}, params);
334 var findFirstDirectTextChild = function(e, nodeToLand) {
335 var byBrowser = this.getCursor().getPosition().element;
336 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
338 var children = e.children();
339 for(var i = 0; i < children.length; i++) {
340 if(children[i] instanceof documentElement.DocumentTextElement)
345 var _markAsCurrent = function(element) {
346 if(element instanceof documentElement.DocumentTextElement) {
347 this.wrapper.find('.current-text-element').removeClass('current-text-element');
348 element.dom().addClass('current-text-element');
350 this.wrapper.find('.current-node-element').removeClass('current-node-element')
351 element._container().addClass('current-node-element');
352 this.publisher('currentElementChanged', element);
357 var isTextElement = element instanceof documentElement.DocumentTextElement,
358 nodeElementToLand = isTextElement ? element.parent() : element,
359 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
360 currentTextElement = this.getCurrentTextElement(),
361 currentNodeElement = this.getCurrentNodeElement();
363 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
364 this.wrapper.find('.current-text-element').removeClass('current-text-element');
366 if(textElementToLand) {
367 _markAsCurrent(textElementToLand);
368 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
369 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
370 if(!(textElementToLand.sameNode(currentTextElement)))
371 this.publisher('currentTextElementSet', textElementToLand);
373 document.getSelection().removeAllRanges();
376 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
377 _markAsCurrent(nodeElementToLand);
379 this.publisher('currentNodeElementSet', nodeElementToLand);
383 _moveCaretToTextElement: function(element, where) {
384 var range = document.createRange(),
385 node = element.dom().contents()[0];
387 if(typeof where !== 'number') {
388 range.selectNodeContents(node);
390 range.setStart(node, where);
393 var collapseArg = true;
396 range.collapse(collapseArg);
398 var selection = document.getSelection();
400 selection.removeAllRanges();
401 selection.addRange(range);
402 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
405 setCursorPosition: function(position) {
407 this._moveCaretToTextElement(position.element, position.offset);
411 var parent = $('<div>'),
412 parts = this.doc().toXML(0);
413 parent.append(parts);
414 return parent.html();
418 $.extend(Canvas.prototype.list, {
419 create: function(params) {
420 if(!(params.element1.parent().sameNode(params.element2.parent())))
423 var parent = params.element1.parent(),
424 canvas = params.element1.canvas;
426 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
427 var tmp = params.element1;
428 params.element1 = params.element2;
429 params.element2 = tmp;
432 var elementsToWrap = [];
434 var place = 'before';
435 parent.children().some(function(element) {
437 if(element.sameNode(params.element1))
439 if(place === 'inside') {
440 if(element instanceof documentElement.DocumentTextElement) {
441 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
442 if(element.children()[0].sameNode(params.element1))
443 params.element1 = element;
445 element.setWlxmlClass('item');
446 elementsToWrap.push(element);
448 if(_e.sameNode(params.element2))
452 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
454 if(parent.is('list')) {
455 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
456 item.exec('toggleBullet', false);
457 toret = listElement.parent();
462 params.element1.before(toret);
464 elementsToWrap.forEach(function(element) {
466 listElement.append(element);
469 extractItems: function(params) {
470 params = _.extend({merge: true}, params);
471 var list = params.element1.parent();
472 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
475 var idx1 = list.childIndex(params.element1),
476 idx2 = list.childIndex(params.element2),
479 succeedingItems = [],
480 items = list.children(),
481 listIsNested = list.parent().getWlxmlClass() === 'item',
482 canvas = params.element1.canvas,
486 var tmp = idx1; idx1 = idx2; idx2 = tmp;
489 items.forEach(function(item, idx) {
491 precedingItems.push(item);
492 else if(idx >= idx1 && idx <= idx2) {
493 extractedItems.push(item);
496 succeedingItems.push(item);
500 var reference = listIsNested ? list.parent() : list;
501 if(succeedingItems.length === 0) {
502 var reference_orig = reference;
503 extractedItems.forEach(function(item) {
504 reference.after(item);
507 item.setWlxmlClass(null);
509 if(precedingItems.length === 0)
510 reference_orig.detach();
511 } else if(precedingItems.length === 0) {
512 extractedItems.forEach(function(item) {
513 reference.before(item);
515 item.setWlxmlClass(null);
518 extractedItems.forEach(function(item) {
519 reference.after(item);
521 item.setWlxmlClass(null);
524 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
528 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
530 succeedingItems.forEach(function(item) {
531 secondList.append(item);
534 reference.after(toAdd);
536 if(!params.merge && listIsNested) {
537 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
541 areItemsOfTheSameList: function(params) {
542 var e1 = params.element1,
543 e2 = params.element2;
544 return e1.parent().sameNode(e2.parent())
545 && e1.parent().is('list');
550 var Cursor = function(canvas) {
551 this.canvas = canvas;
554 $.extend(Cursor.prototype, {
555 isSelecting: function() {
556 var selection = window.getSelection();
557 return !selection.isCollapsed;
559 isSelectingWithinElement: function() {
560 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
562 isSelectingSiblings: function() {
563 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
565 getPosition: function() {
566 return this.getSelectionAnchor();
568 getSelectionStart: function() {
569 return this.getSelectionBoundry('start');
571 getSelectionEnd: function() {
572 return this.getSelectionBoundry('end');
574 getSelectionAnchor: function() {
575 return this.getSelectionBoundry('anchor');
577 getSelectionFocus: function() {
578 return this.getSelectionBoundry('focus');
580 getSelectionBoundry: function(which) {
581 var selection = window.getSelection(),
582 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
583 focusElement = this.canvas.getDocumentElement(selection.focusNode);
585 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
588 if(which === 'anchor') {
590 element: anchorElement,
591 offset: selection.anchorOffset,
592 offsetAtBeginning: selection.anchorOffset === 0,
593 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
596 if(which === 'focus') {
598 element: focusElement,
599 offset: selection.focusOffset,
600 offsetAtBeginning: selection.focusOffset === 0,
601 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
608 if(anchorElement.parent().sameNode(focusElement.parent())) {
609 var parent = anchorElement.parent(),
610 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
612 if(which === 'start') {
613 element = anchorElement;
614 offset = selection.anchorOffset
616 else if(which === 'end') {
617 element = focusElement,
618 offset = selection.focusOffset
621 if(which === 'start') {
622 element = focusElement,
623 offset = selection.focusOffset
625 else if(which === 'end') {
626 element = anchorElement;
627 offset = selection.anchorOffset
631 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
632 if(which === 'start') {
633 element = anchorElement;
634 offset = selection.anchorOffset
636 element = focusElement;
637 offset = selection.focusOffset
641 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
645 offsetAtBeginning: offset === 0,
646 offsetAtEnd: nodeLen === offset
652 fromXML: function(xml, publisher) {
653 return new Canvas(xml, publisher);