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-append'].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) {
64 var parentContents = elParent.contents(),
65 idx = parentContents.index(el[0]),
66 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null;
68 $(next).data('orig-before', toAdd);
70 elParent.data('orig-append', toAdd);
74 text.transformed = text.trimmed;
76 if(hasSpanParent || hasSpanBefore || hasSpanAfter) {
77 var startSpace = /\s/g.test(text.original.substr(0,1)),
78 endSpace = /\s/g.test(text.original.substr(-1)) && text.original.length > 1;
79 text.transformed = (startSpace && (hasSpanParent || hasSpanBefore) ? ' ' : '')
81 + (endSpace && (hasSpanParent || hasSpanAfter) ? ' ' : '');
83 if(text.trimmed.length === 0 && text.original.length > 0 && elParent.contents().length === 1)
84 text.transformed = ' ';
87 if(!text.transformed) {
88 addInfo([text.original]);
90 return true; // continue
93 if(text.transformed !== text.original) {
96 toAdd.push(text.original);
98 var startingMatch = text.original.match(/^\s+/g),
99 endingMatch = text.original.match(/\s+$/g),
100 startingWhiteSpace = startingMatch ? startingMatch[0] : null,
101 endingWhiteSpace = endingMatch ? endingMatch[0] : null;
103 if(endingWhiteSpace) {
104 if(text.transformed[text.transformed.length - 1] === ' ' && endingWhiteSpace[0] === ' ')
105 endingWhiteSpace = endingWhiteSpace.substr(1);
106 toAdd.push(endingWhiteSpace);
109 if(startingWhiteSpace) {
110 if(text.transformed[0] === ' ' && startingWhiteSpace[startingWhiteSpace.length-1] === ' ')
111 startingWhiteSpace = startingWhiteSpace.substr(0, startingWhiteSpace.length -1);
112 toAdd.push(startingWhiteSpace);
118 var element = documentElement.DocumentTextElement.create({text: text.transformed});
119 el.replaceWith(element.dom());
122 this.d = this.wrapper.children(0);
125 this.wrapper.on('keydown', function(e) {
128 var cursor = canvas.getCursor();
129 if(!cursor.isSelecting()) {
130 var position = cursor.getPosition(),
131 elements = position.element.split({offset: position.offset}),
135 if(position.offsetAtBeginning)
136 newEmpty = elements.first;
137 else if(position.offsetAtEnd)
138 newEmpty = elements.second;
140 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: '\u200B'}, this));
141 canvas.setCurrentElement(goto);
147 this.wrapper.on('keyup', function(e) {
148 if(e.which >= 37 && e.which <= 40)
149 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
152 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
154 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
169 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
172 wrapText: function(params) {
173 params = _.extend({textNodeIdx: 0}, params);
174 if(typeof params.textNodeIdx === 'number')
175 params.textNodeIdx = [params.textNodeIdx];
177 var childrenInside = params.inside.children(),
178 idx1 = Math.min.apply(Math, params.textNodeIdx),
179 idx2 = Math.max.apply(Math, params.textNodeIdx),
180 textNode1 = childrenInside[idx1],
181 textNode2 = childrenInside[idx2],
182 sameNode = textNode1.sameNode(textNode2),
183 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
184 prefixInside = textNode1.getText().substr(params.offsetStart),
185 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
186 suffixOutside = textNode2.getText().substr(params.offsetEnd)
189 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
190 textNode1.after(wrapperElement);
193 if(prefixOutside.length > 0)
194 wrapperElement.before({text:prefixOutside});
196 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
197 wrapperElement.append({text: core});
200 if(prefixInside.length > 0)
201 wrapperElement.append({text: prefixInside});
202 for(var i = idx1 + 1; i < idx2; i++) {
203 wrapperElement.append(childrenInside[i]);
205 if(suffixInside.length > 0)
206 wrapperElement.append({text: suffixInside});
208 if(suffixOutside.length > 0)
209 wrapperElement.after({text: suffixOutside});
210 return wrapperElement;
212 getDocumentElement: function(from) {
213 if(from instanceof HTMLElement || from instanceof Text) {
214 return documentElement.DocumentElement.fromHTMLElement(from, this);
217 getCursor: function() {
218 return new Cursor(this);
225 highlightElement: function(element) {
226 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
227 element.dom().addClass('highlighted-element');
230 dimElement: function(element) {
231 element.dom().removeClass('highlighted-element');
234 getCurrentNodeElement: function() {
235 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
238 getCurrentTextElement: function() {
239 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
244 setCurrentElement: function(element, params) {
245 params = _.extend({caretTo: 'end'}, params);
246 var findFirstDirectTextChild = function(e, nodeToLand) {
247 var byBrowser = this.getCursor().getPosition().element;
248 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
250 var children = e.children();
251 for(var i = 0; i < children.length; i++) {
252 if(children[i] instanceof documentElement.DocumentTextElement)
257 var _markAsCurrent = function(element) {
258 if(element instanceof documentElement.DocumentTextElement) {
259 this.wrapper.find('.current-text-element').removeClass('current-text-element');
260 element.dom().addClass('current-text-element');
262 this.wrapper.find('.current-node-element').removeClass('current-node-element')
263 element.dom().addClass('current-node-element');
264 this.publisher('currentElementChanged', element);
269 var isTextElement = element instanceof documentElement.DocumentTextElement,
270 nodeElementToLand = isTextElement ? element.parent() : element,
271 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
272 currentTextElement = this.getCurrentTextElement(),
273 currentNodeElement = this.getCurrentNodeElement();
275 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
276 this.wrapper.find('.current-text-element').removeClass('current-text-element');
278 if(textElementToLand) {
279 _markAsCurrent(textElementToLand);
280 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
281 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
282 if(!(textElementToLand.sameNode(currentTextElement)))
283 this.publisher('currentTextElementSet', textElementToLand);
285 document.getSelection().removeAllRanges();
288 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
289 _markAsCurrent(nodeElementToLand);
291 this.publisher('currentNodeElementSet', nodeElementToLand);
295 _moveCaretToTextElement: function(element, where) {
296 var range = document.createRange(),
297 node = element.dom().contents()[0];
299 if(typeof where !== 'number') {
300 range.selectNodeContents(node);
302 range.setStart(node, where);
305 var collapseArg = true;
308 range.collapse(collapseArg);
310 var selection = document.getSelection();
312 selection.removeAllRanges();
313 selection.addRange(range);
314 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
317 setCursorPosition: function(position) {
319 this._moveCaretToTextElement(position.element, position.offset);
323 var parent = $('<div>'),
324 parts = this.doc().toXML(0);
325 parent.append(parts);
326 return parent.html();
330 $.extend(Canvas.prototype.list, {
331 create: function(params) {
332 if(!(params.element1.parent().sameNode(params.element2.parent())))
335 var parent = params.element1.parent();
337 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
338 var tmp = params.element1;
339 params.element1 = params.element2;
340 params.element2 = tmp;
343 var elementsToWrap = [];
345 var place = 'before';
347 parent.children().some(function(element) {
349 if(element.sameNode(params.element1))
351 if(place === 'inside') {
352 if(element instanceof documentElement.DocumentTextElement) {
353 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
354 if(element.children()[0].sameNode(params.element1))
355 params.element1 = element;
357 element.setWlxmlClass('item');
358 elementsToWrap.push(element);
360 if(_e.sameNode(params.element2))
364 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
367 if(parent.is('list')) {
368 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
369 toret = listElement.parent();
374 params.element1.before(toret);
376 elementsToWrap.forEach(function(element) {
378 listElement.append(element);
381 extractItems: function(params) {
382 params = _.extend({merge: true}, params);
383 var list = params.element1.parent();
384 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
387 var idx1 = list.childIndex(params.element1),
388 idx2 = list.childIndex(params.element2),
391 succeedingItems = [],
392 items = list.children(),
393 listIsNested = list.parent().getWlxmlClass() === 'item',
397 var tmp = idx1; idx1 = idx2; idx2 = tmp;
400 items.forEach(function(item, idx) {
402 precedingItems.push(item);
403 else if(idx >= idx1 && idx <= idx2) {
404 extractedItems.push(item);
407 succeedingItems.push(item);
411 var reference = listIsNested ? list.parent() : list;
412 if(succeedingItems.length === 0) {
413 var reference_orig = reference;
414 extractedItems.forEach(function(item) {
415 reference.after(item);
418 item.setWlxmlClass(null);
420 if(precedingItems.length === 0)
421 reference_orig.detach();
422 } else if(precedingItems.length === 0) {
423 extractedItems.forEach(function(item) {
424 reference.before(item);
426 item.setWlxmlClass(null);
429 extractedItems.forEach(function(item) {
430 reference.after(item);
432 item.setWlxmlClass(null);
435 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
439 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
441 succeedingItems.forEach(function(item) {
442 secondList.append(item);
445 reference.after(toAdd);
447 if(!params.merge && listIsNested) {
448 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
452 areItemsOfTheSameList: function(params) {
453 var e1 = params.element1,
454 e2 = params.element2;
455 return e1.parent().sameNode(e2.parent())
456 && e1.parent().is('list');
461 var Cursor = function(canvas) {
462 this.canvas = canvas;
465 $.extend(Cursor.prototype, {
466 isSelecting: function() {
467 var selection = window.getSelection();
468 return !selection.isCollapsed;
470 isSelectingWithinElement: function() {
471 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
473 isSelectingSiblings: function() {
474 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
476 getPosition: function() {
477 return this.getSelectionAnchor();
479 getSelectionStart: function() {
480 return this.getSelectionBoundry('start');
482 getSelectionEnd: function() {
483 return this.getSelectionBoundry('end');
485 getSelectionAnchor: function() {
486 return this.getSelectionBoundry('anchor');
488 getSelectionFocus: function() {
489 return this.getSelectionBoundry('focus');
491 getSelectionBoundry: function(which) {
492 var selection = window.getSelection(),
493 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
494 focusElement = this.canvas.getDocumentElement(selection.focusNode);
496 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
499 if(which === 'anchor') {
501 element: anchorElement,
502 offset: selection.anchorOffset,
503 offsetAtBeginning: selection.anchorOffset === 0,
504 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
507 if(which === 'focus') {
509 element: focusElement,
510 offset: selection.focusOffset,
511 offsetAtBeginning: selection.focusOffset === 0,
512 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
519 if(anchorElement.parent().sameNode(focusElement.parent())) {
520 var parent = anchorElement.parent(),
521 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
523 if(which === 'start') {
524 element = anchorElement;
525 offset = selection.anchorOffset;
527 else if(which === 'end') {
528 element = focusElement,
529 offset = selection.focusOffset;
532 if(which === 'start') {
533 element = focusElement,
534 offset = selection.focusOffset
536 else if(which === 'end') {
537 element = anchorElement;
538 offset = selection.anchorOffset;
542 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
543 if(which === 'start') {
544 element = anchorElement;
545 offset = selection.anchorOffset
547 element = focusElement;
548 offset = selection.focusOffset
555 offsetAtBeginning: offset === 0,
556 offsetAtEnd: element.getText().length === offset
562 fromXML: function(xml, publisher) {
563 return new Canvas(xml, publisher);