2 'libs/jquery-1.9.1.min',
4 'modules/documentCanvas/canvas/documentElement'
5 ], function($, _, documentElement) {
9 var Canvas = function(wlxml, publisher) {
10 this.loadWlxml(wlxml);
11 this.publisher = publisher ? publisher : function() {};
14 $.extend(Canvas.prototype, {
16 loadWlxml: function(wlxml) {
17 var d = wlxml ? $($.trim(wlxml)) : null;
19 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
20 this.wrapper.append(d);
22 this.wrapper.find('*').replaceWith(function() {
23 var currentTag = $(this);
24 if(currentTag.attr('wlxml-tag'))
27 var meta = {}, others = {};
28 for(var i = 0; i < this.attributes.length; i++) {
29 var attr = this.attributes[i];
30 if(attr.name.substr(0, 5) === 'meta-')
31 meta[attr.name.substr(5)] = attr.value;
32 else if(attr.name !== 'class')
33 others[attr.name] = attr.value;
36 var element = documentElement.DocumentNodeElement.create({
37 tag: currentTag.prop('tagName').toLowerCase(),
38 klass: currentTag.attr('class'),
43 element.dom().append(currentTag.contents());
44 ['orig-before', 'orig-after', 'orig-begin', 'orig-end'].forEach(function(attr) {
45 element.data(attr, '');
50 this.wrapper.find(':not(iframe)').addBack().contents()
51 .filter(function() {return this.nodeType === Node.TEXT_NODE})
53 // TODO: use DocumentElement API
56 text = {original: el.text(), trimmed: $.trim(el.text())},
57 elParent = el.parent(),
58 hasSpanParent = elParent.attr('wlxml-tag') === 'span',
59 hasSpanBefore = el.prev().length > 0 && $(el.prev()[0]).attr('wlxml-tag') === 'span',
60 hasSpanAfter = el.next().length > 0 && $(el.next()[0]).attr('wlxml-tag') === 'span';
63 var addInfo = function(toAdd, where) {
64 var parentContents = elParent.contents(),
65 idx = parentContents.index(el[0]),
66 prev = idx > 0 ? parentContents[idx-1] : null,
67 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null,
70 if(where === 'above') {
71 target = prev ? $(prev) : elParent;
72 key = prev ? 'orig-after' : 'orig-begin';
73 } else if(where === 'below') {
74 target = next ? $(next) : elParent;
75 key = next ? 'orig-before' : 'orig-end';
76 } else { throw new Object;}
78 target.data(key, toAdd);
81 text.transformed = text.trimmed;
83 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
84 var startSpace = /\s/g.test(text.original.substr(0,1)),
85 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
86 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
88 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
90 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
91 text.transformed = ' ';
94 if(!text.transformed) {
95 addInfo(text.original, 'below');
97 return true; // continue
100 if(text.transformed !== text.original) {
102 addInfo(text.original, 'below');
104 var startingMatch = text.original.match(/^\s+/g),
105 endingMatch = text.original.match(/\s+$/g),
106 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
107 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
109 if(endingWhiteSpace) {
110 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
111 endingWhiteSpace = endingWhiteSpace.substr(1);
112 addInfo(endingWhiteSpace, 'below');
115 if(startingWhiteSpace) {
116 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
117 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
118 addInfo(startingWhiteSpace, 'above');
123 var element = documentElement.DocumentTextElement.create({text: text.transformed});
124 el.replaceWith(element.dom());
127 this.d = this.wrapper.children(0);
130 this.wrapper.on('keydown', function(e) {
133 var cursor = canvas.getCursor();
134 if(!cursor.isSelecting()) {
135 var position = cursor.getPosition(),
136 elements = position.element.split({offset: position.offset}),
140 if(position.offsetAtBeginning)
141 newEmpty = elements.first;
142 else if(position.offsetAtEnd)
143 newEmpty = elements.second;
145 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: '\u200B'}, this));
146 canvas.setCurrentElement(goto);
152 this.wrapper.on('keyup', function(e) {
153 if(e.which >= 37 && e.which <= 40)
154 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
157 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
159 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
174 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
177 wrapText: function(params) {
178 params = _.extend({textNodeIdx: 0}, params);
179 if(typeof params.textNodeIdx === 'number')
180 params.textNodeIdx = [params.textNodeIdx];
182 var childrenInside = params.inside.children(),
183 idx1 = Math.min.apply(Math, params.textNodeIdx),
184 idx2 = Math.max.apply(Math, params.textNodeIdx),
185 textNode1 = childrenInside[idx1],
186 textNode2 = childrenInside[idx2],
187 sameNode = textNode1.sameNode(textNode2),
188 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
189 prefixInside = textNode1.getText().substr(params.offsetStart),
190 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
191 suffixOutside = textNode2.getText().substr(params.offsetEnd)
194 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
195 textNode1.after(wrapperElement);
198 if(prefixOutside.length > 0)
199 wrapperElement.before({text:prefixOutside});
201 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
202 wrapperElement.append({text: core});
205 if(prefixInside.length > 0)
206 wrapperElement.append({text: prefixInside});
207 for(var i = idx1 + 1; i < idx2; i++) {
208 wrapperElement.append(childrenInside[i]);
210 if(suffixInside.length > 0)
211 wrapperElement.append({text: suffixInside});
213 if(suffixOutside.length > 0)
214 wrapperElement.after({text: suffixOutside});
215 return wrapperElement;
217 getDocumentElement: function(from) {
218 if(from instanceof HTMLElement || from instanceof Text) {
219 return documentElement.DocumentElement.fromHTMLElement(from, this);
222 getCursor: function() {
223 return new Cursor(this);
230 highlightElement: function(element) {
231 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
232 element.dom().addClass('highlighted-element');
235 dimElement: function(element) {
236 element.dom().removeClass('highlighted-element');
239 getCurrentNodeElement: function() {
240 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
243 getCurrentTextElement: function() {
244 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
249 setCurrentElement: function(element, params) {
250 params = _.extend({caretTo: 'end'}, params);
251 var findFirstDirectTextChild = function(e, nodeToLand) {
252 var byBrowser = this.getCursor().getPosition().element;
253 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
255 var children = e.children();
256 for(var i = 0; i < children.length; i++) {
257 if(children[i] instanceof documentElement.DocumentTextElement)
262 var _markAsCurrent = function(element) {
263 if(element instanceof documentElement.DocumentTextElement) {
264 this.wrapper.find('.current-text-element').removeClass('current-text-element');
265 element.dom().addClass('current-text-element');
267 this.wrapper.find('.current-node-element').removeClass('current-node-element')
268 element.dom().addClass('current-node-element');
269 this.publisher('currentElementChanged', element);
274 var isTextElement = element instanceof documentElement.DocumentTextElement,
275 nodeElementToLand = isTextElement ? element.parent() : element,
276 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
277 currentTextElement = this.getCurrentTextElement(),
278 currentNodeElement = this.getCurrentNodeElement();
280 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
281 this.wrapper.find('.current-text-element').removeClass('current-text-element');
283 if(textElementToLand) {
284 _markAsCurrent(textElementToLand);
285 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
286 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
287 if(!(textElementToLand.sameNode(currentTextElement)))
288 this.publisher('currentTextElementSet', textElementToLand);
290 document.getSelection().removeAllRanges();
293 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
294 _markAsCurrent(nodeElementToLand);
296 this.publisher('currentNodeElementSet', nodeElementToLand);
300 _moveCaretToTextElement: function(element, where) {
301 var range = document.createRange(),
302 node = element.dom().contents()[0];
304 if(typeof where !== 'number') {
305 range.selectNodeContents(node);
307 range.setStart(node, where);
310 var collapseArg = true;
313 range.collapse(collapseArg);
315 var selection = document.getSelection();
317 selection.removeAllRanges();
318 selection.addRange(range);
319 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
322 setCursorPosition: function(position) {
324 this._moveCaretToTextElement(position.element, position.offset);
328 var parent = $('<div>'),
329 parts = this.doc().toXML(0);
330 parent.append(parts);
331 return parent.html();
335 $.extend(Canvas.prototype.list, {
336 create: function(params) {
337 if(!(params.element1.parent().sameNode(params.element2.parent())))
340 var parent = params.element1.parent();
342 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
343 var tmp = params.element1;
344 params.element1 = params.element2;
345 params.element2 = tmp;
348 var elementsToWrap = [];
350 var place = 'before';
352 parent.children().some(function(element) {
354 if(element.sameNode(params.element1))
356 if(place === 'inside') {
357 if(element instanceof documentElement.DocumentTextElement) {
358 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
359 if(element.children()[0].sameNode(params.element1))
360 params.element1 = element;
362 element.setWlxmlClass('item');
363 elementsToWrap.push(element);
365 if(_e.sameNode(params.element2))
369 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
372 if(parent.is('list')) {
373 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
374 toret = listElement.parent();
379 params.element1.before(toret);
381 elementsToWrap.forEach(function(element) {
383 listElement.append(element);
386 extractItems: function(params) {
387 params = _.extend({merge: true}, params);
388 var list = params.element1.parent();
389 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
392 var idx1 = list.childIndex(params.element1),
393 idx2 = list.childIndex(params.element2),
396 succeedingItems = [],
397 items = list.children(),
398 listIsNested = list.parent().getWlxmlClass() === 'item',
402 var tmp = idx1; idx1 = idx2; idx2 = tmp;
405 items.forEach(function(item, idx) {
407 precedingItems.push(item);
408 else if(idx >= idx1 && idx <= idx2) {
409 extractedItems.push(item);
412 succeedingItems.push(item);
416 var reference = listIsNested ? list.parent() : list;
417 if(succeedingItems.length === 0) {
418 var reference_orig = reference;
419 extractedItems.forEach(function(item) {
420 reference.after(item);
423 item.setWlxmlClass(null);
425 if(precedingItems.length === 0)
426 reference_orig.detach();
427 } else if(precedingItems.length === 0) {
428 extractedItems.forEach(function(item) {
429 reference.before(item);
431 item.setWlxmlClass(null);
434 extractedItems.forEach(function(item) {
435 reference.after(item);
437 item.setWlxmlClass(null);
440 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
444 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
446 succeedingItems.forEach(function(item) {
447 secondList.append(item);
450 reference.after(toAdd);
452 if(!params.merge && listIsNested) {
453 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
457 areItemsOfTheSameList: function(params) {
458 var e1 = params.element1,
459 e2 = params.element2;
460 return e1.parent().sameNode(e2.parent())
461 && e1.parent().is('list');
466 var Cursor = function(canvas) {
467 this.canvas = canvas;
470 $.extend(Cursor.prototype, {
471 isSelecting: function() {
472 var selection = window.getSelection();
473 return !selection.isCollapsed;
475 isSelectingWithinElement: function() {
476 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
478 isSelectingSiblings: function() {
479 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
481 getPosition: function() {
482 return this.getSelectionAnchor();
484 getSelectionStart: function() {
485 return this.getSelectionBoundry('start');
487 getSelectionEnd: function() {
488 return this.getSelectionBoundry('end');
490 getSelectionAnchor: function() {
491 return this.getSelectionBoundry('anchor');
493 getSelectionFocus: function() {
494 return this.getSelectionBoundry('focus');
496 getSelectionBoundry: function(which) {
497 var selection = window.getSelection(),
498 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
499 focusElement = this.canvas.getDocumentElement(selection.focusNode);
501 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
504 if(which === 'anchor') {
506 element: anchorElement,
507 offset: selection.anchorOffset,
508 offsetAtBeginning: selection.anchorOffset === 0,
509 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
512 if(which === 'focus') {
514 element: focusElement,
515 offset: selection.focusOffset,
516 offsetAtBeginning: selection.focusOffset === 0,
517 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
524 if(anchorElement.parent().sameNode(focusElement.parent())) {
525 var parent = anchorElement.parent(),
526 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
528 if(which === 'start') {
529 element = anchorElement;
530 offset = selection.anchorOffset;
532 else if(which === 'end') {
533 element = focusElement,
534 offset = selection.focusOffset;
537 if(which === 'start') {
538 element = focusElement,
539 offset = selection.focusOffset
541 else if(which === 'end') {
542 element = anchorElement;
543 offset = selection.anchorOffset;
547 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
548 if(which === 'start') {
549 element = anchorElement;
550 offset = selection.anchorOffset
552 element = focusElement;
553 offset = selection.focusOffset
560 offsetAtBeginning: offset === 0,
561 offsetAtEnd: element.getText().length === offset
567 fromXML: function(xml, publisher) {
568 return new Canvas(xml, publisher);