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, ver) {
13 this.eventBus = _.extend({}, Backbone.Events);
15 this.loadWlxmlDocument(wlxml);
17 this.loadWlxml(wlxml);
19 this.publisher = publisher ? publisher : function() {};
22 $.extend(Canvas.prototype, {
24 loadWlxmlDocument: function(wlxmlDocument) {
25 var canvasDOM = this.generateCanvasDOM(wlxmlDocument.root);
27 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
28 this.wrapper.append(canvasDOM);
29 this.d = this.wrapper.children(0);
30 this.setupEventHandling();
33 generateCanvasDOM: function(wlxmlNode) {
34 // var element = this.createNodeElement2({
35 // tag: wlxmlNode.getTagName(),
36 // klass: wlxmlNode.getClass(), //currentTag.attr('class'),
37 // meta: wlxmlNode.getMetaAttributes(), //meta,
38 // others: wlxmlNode.getOtherAttributes(), // ~ //others,
39 // rawChildren: wlxmlNode.contents(),
40 // prepopulateOnEmpty: true
43 var element = documentElement.DocumentNodeElement.create2(wlxmlNode, this);
46 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
47 element.data(attr, '');
52 loadWlxml: function(wlxml) {
53 var d = wlxml ? $($.trim(wlxml)) : null;
55 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
56 this.wrapper.append(d);
59 this.wrapper.find('*').replaceWith(function() {
60 var currentTag = $(this);
61 if(currentTag.attr('wlxml-tag'))
64 var meta = {}, others = {};
65 for(var i = 0; i < this.attributes.length; i++) {
66 var attr = this.attributes[i];
67 if(attr.name.substr(0, 5) === 'meta-')
68 meta[attr.name.substr(5)] = attr.value;
69 else if(attr.name !== 'class')
70 others[attr.name] = attr.value;
73 var element = canvas.createNodeElement({
74 tag: currentTag.prop('tagName').toLowerCase(),
75 klass: currentTag.attr('class'),
78 rawChildren: currentTag.contents(),
79 prepopulateOnEmpty: true
82 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
83 element.data(attr, '');
88 var FIRST_CONTENT_INDEX = 0;
90 // @@ TODO - refactor!
91 var getNode = function(element) {
92 return element.children('[document-element-content]');
95 this.wrapper.find(':not(iframe)').addBack().contents()
96 .filter(function() {return this.nodeType === Node.TEXT_NODE})
99 // TODO: use DocumentElement API
102 text = {original: el.text(), trimmed: $.trim(el.text())},
103 elParent = el.parent(),
104 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
105 hasSpanBefore = el.prev().length > 0 && getNode($(el.prev()[0])).attr('wlxml-tag') === 'span',
106 hasSpanAfter = el.next().length > 0 && getNode($(el.next()[0])).attr('wlxml-tag') === 'span';
108 if(el.parent().hasClass('canvas-widget') || elParent.attr('document-text-element') !== undefined)
109 return true; // continue
111 var addInfo = function(toAdd, where) {
112 var parentContents = elParent.contents(),
113 idx = parentContents.index(el[0]),
114 prev = idx > FIRST_CONTENT_INDEX ? parentContents[idx-1] : null,
115 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
118 if(where === 'above') {
119 target = prev ? $(prev) : elParent.parent();
120 key = prev ? 'orig-after' : 'orig-begin';
121 } else if(where === 'below') {
122 target = next ? $(next) : elParent.parent();
123 key = next ? 'orig-before' : 'orig-end';
124 } else { throw new Object;}
126 target.data(key, toAdd);
129 text.transformed = text.trimmed;
131 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
132 var startSpace = /\s/g.test(text.original.substr(0,1)),
133 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
134 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
136 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
138 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
139 text.transformed = ' ';
142 if(!text.transformed) {
143 addInfo(text.original, 'below');
145 return true; // continue
148 if(text.transformed !== text.original) {
150 addInfo(text.original, 'below');
152 var startingMatch = text.original.match(/^\s+/g),
153 endingMatch = text.original.match(/\s+$/g),
154 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
155 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
157 if(endingWhiteSpace) {
158 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
159 endingWhiteSpace = endingWhiteSpace.substr(1);
160 addInfo(endingWhiteSpace, 'below');
163 if(startingWhiteSpace) {
164 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
165 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
166 addInfo(startingWhiteSpace, 'above');
171 var element = documentElement.DocumentTextElement.create({text: text.transformed});
172 el.replaceWith(element.dom());
175 this.d = this.wrapper.children(0);
177 this.setupEventHandling();
184 setupEventHandling: function() {
186 this.wrapper.on('keyup keydown keypress', function(e) {
187 keyboard.handleKey(e, this);
190 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
192 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
195 var observer = new MutationObserver(function(mutations) {
196 mutations.forEach(function(mutation) {
197 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
198 observer.disconnect();
199 if(mutation.target.data === '')
200 mutation.target.data = utils.unicode.ZWS;
201 else if(mutation.oldValue === utils.unicode.ZWS) {
202 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
203 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
205 observer.observe(canvas.d[0], config);
206 canvas.publisher('contentChanged');
210 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
211 observer.observe(this.d[0], config);
214 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
215 var el = canvas.getDocumentElement(e.currentTarget);
219 if(el instanceof documentElement.DocumentTextElement)
221 el.toggleLabel(true);
223 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
224 var el = canvas.getDocumentElement(e.currentTarget);
228 if(el instanceof documentElement.DocumentTextElement)
230 el.toggleLabel(false);
233 this.eventBus.on('elementToggled', function(toggle, element) {
235 canvas.setCurrentElement(element.getPreviousTextElement());
247 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
250 createNodeElement: function(params) {
251 return documentElement.DocumentNodeElement.create(params, this);
254 wrapText: function(params) {
255 params = _.extend({textNodeIdx: 0}, params);
256 if(typeof params.textNodeIdx === 'number')
257 params.textNodeIdx = [params.textNodeIdx];
259 var childrenInside = params.inside.children(),
260 idx1 = Math.min.apply(Math, params.textNodeIdx),
261 idx2 = Math.max.apply(Math, params.textNodeIdx),
262 textNode1 = childrenInside[idx1],
263 textNode2 = childrenInside[idx2],
264 sameNode = textNode1.sameNode(textNode2),
265 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
266 prefixInside = textNode1.getText().substr(params.offsetStart),
267 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
268 suffixOutside = textNode2.getText().substr(params.offsetEnd)
271 var wrapperElement = this.createNodeElement({tag: params._with.tag, klass: params._with.klass});
272 textNode1.after(wrapperElement);
275 if(prefixOutside.length > 0)
276 wrapperElement.before({text:prefixOutside});
278 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
279 wrapperElement.append({text: core});
282 if(prefixInside.length > 0)
283 wrapperElement.append({text: prefixInside});
284 for(var i = idx1 + 1; i < idx2; i++) {
285 wrapperElement.append(childrenInside[i]);
287 if(suffixInside.length > 0)
288 wrapperElement.append({text: suffixInside});
290 if(suffixOutside.length > 0)
291 wrapperElement.after({text: suffixOutside});
292 return wrapperElement;
295 wrapElements: function(params) {
296 if(!(params.element1.parent().sameNode(params.element2.parent())))
299 var parent = params.element1.parent(),
300 parentChildren = parent.children(),
301 wrapper = this.createNodeElement({
302 tag: params._with.tag,
303 klass: params._with.klass}),
304 idx1 = parent.childIndex(params.element1),
305 idx2 = parent.childIndex(params.element2);
313 var insertingMethod, insertingTarget;
315 insertingMethod = 'prepend';
316 insertingTarget = parent;
318 insertingMethod = 'after';
319 insertingTarget = parentChildren[idx1-1];
322 for(var i = idx1; i <= idx2; i++) {
323 wrapper.append(parentChildren[i].detach());
326 insertingTarget[insertingMethod](wrapper);
330 getSiblingParents: function(params) {
331 var parents1 = [params.element1].concat(params.element1.parents()).reverse(),
332 parents2 = [params.element2].concat(params.element2.parents()).reverse(),
333 noSiblingParents = null;
335 if(parents1.length === 0 || parents2.length === 0 || !(parents1[0].sameNode(parents2[0])))
336 return noSiblingParents;
339 for(i = 0; i < Math.min(parents1.length, parents2.length); i++) {
340 if(parents1[i].sameNode(parents2[i]))
344 return {element1: parents1[i], element2: parents2[i]};
347 getDocumentElement: function(from) {
348 if(from instanceof HTMLElement || from instanceof Text) {
349 return documentElement.DocumentElement.fromHTMLElement(from, this);
352 getCursor: function() {
353 return new Cursor(this);
359 getCurrentNodeElement: function() {
360 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
363 getCurrentTextElement: function() {
364 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
369 setCurrentElement: function(element, params) {
370 params = _.extend({caretTo: 'end'}, params);
371 var findFirstDirectTextChild = function(e, nodeToLand) {
372 var byBrowser = this.getCursor().getPosition().element;
373 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
375 var children = e.children();
376 for(var i = 0; i < children.length; i++) {
377 if(children[i] instanceof documentElement.DocumentTextElement)
382 var _markAsCurrent = function(element) {
383 if(element instanceof documentElement.DocumentTextElement) {
384 this.wrapper.find('.current-text-element').removeClass('current-text-element');
385 element.dom().addClass('current-text-element');
387 this.wrapper.find('.current-node-element').removeClass('current-node-element')
388 element._container().addClass('current-node-element');
389 this.publisher('currentElementChanged', element);
394 var isTextElement = element instanceof documentElement.DocumentTextElement,
395 nodeElementToLand = isTextElement ? element.parent() : element,
396 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
397 currentTextElement = this.getCurrentTextElement(),
398 currentNodeElement = this.getCurrentNodeElement();
400 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
401 this.wrapper.find('.current-text-element').removeClass('current-text-element');
403 if(textElementToLand) {
404 _markAsCurrent(textElementToLand);
405 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
406 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
407 if(!(textElementToLand.sameNode(currentTextElement)))
408 this.publisher('currentTextElementSet', textElementToLand);
410 document.getSelection().removeAllRanges();
413 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
414 _markAsCurrent(nodeElementToLand);
416 this.publisher('currentNodeElementSet', nodeElementToLand);
420 _moveCaretToTextElement: function(element, where) {
421 var range = document.createRange(),
422 node = element.dom().contents()[0];
424 if(typeof where !== 'number') {
425 range.selectNodeContents(node);
427 range.setStart(node, where);
430 var collapseArg = true;
433 range.collapse(collapseArg);
435 var selection = document.getSelection();
437 selection.removeAllRanges();
438 selection.addRange(range);
439 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
442 setCursorPosition: function(position) {
444 this._moveCaretToTextElement(position.element, position.offset);
448 var parent = $('<div>'),
449 parts = this.doc().toXML(0);
450 parent.append(parts);
451 return parent.html();
455 $.extend(Canvas.prototype.list, {
456 create: function(params) {
457 if(!(params.element1.parent().sameNode(params.element2.parent())))
460 var parent = params.element1.parent(),
461 canvas = params.element1.canvas;
463 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
464 var tmp = params.element1;
465 params.element1 = params.element2;
466 params.element2 = tmp;
469 var elementsToWrap = [];
471 var place = 'before';
472 parent.children().some(function(element) {
474 if(element.sameNode(params.element1))
476 if(place === 'inside') {
477 if(element instanceof documentElement.DocumentTextElement) {
478 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
479 if(element.children()[0].sameNode(params.element1))
480 params.element1 = element;
482 element.setWlxmlClass('item');
483 elementsToWrap.push(element);
485 if(_e.sameNode(params.element2))
489 var listElement = canvas.createNodeElement({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
491 if(parent.is('list')) {
492 var item = listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
493 item.exec('toggleBullet', false);
494 toret = listElement.parent();
499 params.element1.before(toret);
501 elementsToWrap.forEach(function(element) {
503 listElement.append(element);
506 extractItems: function(params) {
507 params = _.extend({merge: true}, params);
508 var list = params.element1.parent();
509 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
512 var idx1 = list.childIndex(params.element1),
513 idx2 = list.childIndex(params.element2),
516 succeedingItems = [],
517 items = list.children(),
518 listIsNested = list.parent().getWlxmlClass() === 'item',
519 canvas = params.element1.canvas,
523 var tmp = idx1; idx1 = idx2; idx2 = tmp;
526 items.forEach(function(item, idx) {
528 precedingItems.push(item);
529 else if(idx >= idx1 && idx <= idx2) {
530 extractedItems.push(item);
533 succeedingItems.push(item);
537 var reference = listIsNested ? list.parent() : list;
538 if(succeedingItems.length === 0) {
539 var reference_orig = reference;
540 extractedItems.forEach(function(item) {
541 reference.after(item);
544 item.setWlxmlClass(null);
546 if(precedingItems.length === 0)
547 reference_orig.detach();
548 } else if(precedingItems.length === 0) {
549 extractedItems.forEach(function(item) {
550 reference.before(item);
552 item.setWlxmlClass(null);
555 extractedItems.forEach(function(item) {
556 reference.after(item);
558 item.setWlxmlClass(null);
561 var secondList = canvas.createNodeElement({tag: 'div', klass:'list-items'}),
565 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
567 succeedingItems.forEach(function(item) {
568 secondList.append(item);
571 reference.after(toAdd);
573 if(!params.merge && listIsNested) {
574 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
578 areItemsOfTheSameList: function(params) {
579 var e1 = params.element1,
580 e2 = params.element2;
581 return e1.parent().sameNode(e2.parent())
582 && e1.parent().is('list');
587 var Cursor = function(canvas) {
588 this.canvas = canvas;
591 $.extend(Cursor.prototype, {
592 isSelecting: function() {
593 var selection = window.getSelection();
594 return !selection.isCollapsed;
596 isSelectingWithinElement: function() {
597 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
599 isSelectingSiblings: function() {
600 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
602 getPosition: function() {
603 return this.getSelectionAnchor();
605 getSelectionStart: function() {
606 return this.getSelectionBoundry('start');
608 getSelectionEnd: function() {
609 return this.getSelectionBoundry('end');
611 getSelectionAnchor: function() {
612 return this.getSelectionBoundry('anchor');
614 getSelectionFocus: function() {
615 return this.getSelectionBoundry('focus');
617 getSelectionBoundry: function(which) {
618 var selection = window.getSelection(),
619 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
620 focusElement = this.canvas.getDocumentElement(selection.focusNode);
622 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement)
625 if(which === 'anchor') {
627 element: anchorElement,
628 offset: selection.anchorOffset,
629 offsetAtBeginning: selection.anchorOffset === 0,
630 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset
633 if(which === 'focus') {
635 element: focusElement,
636 offset: selection.focusOffset,
637 offsetAtBeginning: selection.focusOffset === 0,
638 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset
645 if(anchorElement.parent().sameNode(focusElement.parent())) {
646 var parent = anchorElement.parent(),
647 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
649 if(which === 'start') {
650 element = anchorElement;
651 offset = selection.anchorOffset
653 else if(which === 'end') {
654 element = focusElement,
655 offset = selection.focusOffset
658 if(which === 'start') {
659 element = focusElement,
660 offset = selection.focusOffset
662 else if(which === 'end') {
663 element = anchorElement;
664 offset = selection.anchorOffset
668 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
669 if(which === 'start') {
670 element = anchorElement;
671 offset = selection.anchorOffset
673 element = focusElement;
674 offset = selection.focusOffset
678 var nodeLen = (element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
682 offsetAtBeginning: offset === 0,
683 offsetAtEnd: nodeLen === offset
689 fromXML: function(xml, publisher) {
690 return new Canvas(xml, publisher);
692 fromXML2: function(wlxmlNode, publisher) {
693 return new Canvas(wlxmlNode, publisher, 2);