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})
56 // TODO: use DocumentElement API
57 var spanParent = el.parent().attr('wlxml-tag') === 'span',
58 spanBefore = el.prev().length > 0 && $(el.prev()[0]).attr('wlxml-tag') === 'span',
59 spanAfter = el.next().length > 0 && $(el.next()[0]).attr('wlxml-tag') === 'span';
61 var oldText = this.data,
62 oldLength = this.data.length;
63 var parent = el.parent(),
64 parentContents = parent.contents(),
65 idx = parentContents.index(this),
66 next = idx < parentContents.length - 1 ? parentContents[idx+1] : null;
68 var addInfo = function(toAdd) {
70 $(next).data('orig-before', toAdd);
72 parent.data('orig-append', toAdd);
76 if(spanParent || spanBefore || spanAfter) {
77 var startSpace = /\s/g.test(this.data.substr(0,1));
78 var endSpace = /\s/g.test(this.data.substr(-1)) && this.data.length > 1;
79 var trimmed = $.trim(this.data);
80 var newText = (startSpace && (spanParent || spanBefore) ? ' ' : '')
82 + (endSpace && (spanParent || spanAfter) ? ' ' : '');
83 if(newText !== oldText) {
86 var toAdd = oldText.match(/\s+$/g)[0];
87 if(newText[newText.length - 1] === ' ' && toAdd[0] === ' ')
88 toAdd = toAdd.substr(1);
94 this.data = $.trim(this.data);
95 if(this.data.length === 0 && oldLength > 0 && el.parent().contents().length === 1)
97 if(this.data.length === 0) {
101 return true; // continue
105 var element = documentElement.DocumentTextElement.create({text: this.data});
106 $(this).replaceWith(element.dom());
109 this.d = this.wrapper.children(0);
112 this.wrapper.on('keydown', function(e) {
115 var cursor = canvas.getCursor();
116 if(!cursor.isSelecting()) {
117 var position = cursor.getPosition(),
118 elements = position.element.split({offset: position.offset}),
122 if(position.offsetAtBeginning)
123 newEmpty = elements.first;
124 else if(position.offsetAtEnd)
125 newEmpty = elements.second;
127 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: '\u200B'}, this));
128 canvas.setCurrentElement(goto);
134 this.wrapper.on('keyup', function(e) {
135 if(e.which >= 37 && e.which <= 40)
136 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
139 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
141 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
156 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
159 wrapText: function(params) {
160 params = _.extend({textNodeIdx: 0}, params);
161 if(typeof params.textNodeIdx === 'number')
162 params.textNodeIdx = [params.textNodeIdx];
164 var childrenInside = params.inside.children(),
165 idx1 = Math.min.apply(Math, params.textNodeIdx),
166 idx2 = Math.max.apply(Math, params.textNodeIdx),
167 textNode1 = childrenInside[idx1],
168 textNode2 = childrenInside[idx2],
169 sameNode = textNode1.sameNode(textNode2),
170 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
171 prefixInside = textNode1.getText().substr(params.offsetStart),
172 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
173 suffixOutside = textNode2.getText().substr(params.offsetEnd)
176 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
177 textNode1.after(wrapperElement);
180 if(prefixOutside.length > 0)
181 wrapperElement.before({text:prefixOutside});
183 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
184 wrapperElement.append({text: core});
187 if(prefixInside.length > 0)
188 wrapperElement.append({text: prefixInside});
189 for(var i = idx1 + 1; i < idx2; i++) {
190 wrapperElement.append(childrenInside[i]);
192 if(suffixInside.length > 0)
193 wrapperElement.append({text: suffixInside});
195 if(suffixOutside.length > 0)
196 wrapperElement.after({text: suffixOutside});
197 return wrapperElement;
199 getDocumentElement: function(from) {
200 if(from instanceof HTMLElement || from instanceof Text) {
201 return documentElement.DocumentElement.fromHTMLElement(from, this);
204 getCursor: function() {
205 return new Cursor(this);
212 highlightElement: function(element) {
213 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
214 element.dom().addClass('highlighted-element');
217 dimElement: function(element) {
218 element.dom().removeClass('highlighted-element');
221 getCurrentNodeElement: function() {
222 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
225 getCurrentTextElement: function() {
226 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
231 setCurrentElement: function(element, params) {
232 params = _.extend({caretTo: 'end'}, params);
233 var findFirstDirectTextChild = function(e, nodeToLand) {
234 var byBrowser = this.getCursor().getPosition().element;
235 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
237 var children = e.children();
238 for(var i = 0; i < children.length; i++) {
239 if(children[i] instanceof documentElement.DocumentTextElement)
244 var _markAsCurrent = function(element) {
245 if(element instanceof documentElement.DocumentTextElement) {
246 this.wrapper.find('.current-text-element').removeClass('current-text-element');
247 element.dom().addClass('current-text-element');
249 this.wrapper.find('.current-node-element').removeClass('current-node-element')
250 element.dom().addClass('current-node-element');
251 this.publisher('currentElementChanged', element);
256 var isTextElement = element instanceof documentElement.DocumentTextElement,
257 nodeElementToLand = isTextElement ? element.parent() : element,
258 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
259 currentTextElement = this.getCurrentTextElement(),
260 currentNodeElement = this.getCurrentNodeElement();
262 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
263 this.wrapper.find('.current-text-element').removeClass('current-text-element');
265 if(textElementToLand) {
266 _markAsCurrent(textElementToLand);
267 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
268 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
269 if(!(textElementToLand.sameNode(currentTextElement)))
270 this.publisher('currentTextElementSet', textElementToLand);
272 document.getSelection().removeAllRanges();
275 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
276 _markAsCurrent(nodeElementToLand);
278 this.publisher('currentNodeElementSet', nodeElementToLand);
282 _moveCaretToTextElement: function(element, where) {
283 var range = document.createRange(),
284 node = element.dom().contents()[0];
286 if(typeof where !== 'number') {
287 range.selectNodeContents(node);
289 range.setStart(node, where);
292 var collapseArg = true;
295 range.collapse(collapseArg);
297 var selection = document.getSelection();
299 selection.removeAllRanges();
300 selection.addRange(range);
301 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
304 setCursorPosition: function(position) {
306 this._moveCaretToTextElement(position.element, position.offset);
310 var d = function(element, parent, level) {
311 console.log(element.getText ? 'text: ' + element.getText() : 'node: ' + element.getWlxmlTag());
312 var isElementNode = element instanceof documentElement.DocumentNodeElement;
313 parent.prepend(element.toXML(level));
315 var dom = $(parent.children()[0]),
316 elementChildren = element.children();
317 for(var i = elementChildren.length - 1; i >= 0; i--) {
318 d(elementChildren[i], dom, level + 1);
322 var parent = $('<div>');
323 d(this.doc(), parent, 0);
324 return parent.html();
328 $.extend(Canvas.prototype.list, {
329 create: function(params) {
330 if(!(params.element1.parent().sameNode(params.element2.parent())))
333 var parent = params.element1.parent();
335 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
336 var tmp = params.element1;
337 params.element1 = params.element2;
338 params.element2 = tmp;
341 var elementsToWrap = [];
343 var place = 'before';
345 parent.children().some(function(element) {
347 if(element.sameNode(params.element1))
349 if(place === 'inside') {
350 if(element instanceof documentElement.DocumentTextElement) {
351 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
352 if(element.children()[0].sameNode(params.element1))
353 params.element1 = element;
355 element.setWlxmlClass('item');
356 elementsToWrap.push(element);
358 if(_e.sameNode(params.element2))
362 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
365 if(parent.is('list')) {
366 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
367 toret = listElement.parent();
372 params.element1.before(toret);
374 elementsToWrap.forEach(function(element) {
376 listElement.append(element);
379 extractItems: function(params) {
380 params = _.extend({merge: true}, params);
381 var list = params.element1.parent();
382 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
385 var idx1 = list.childIndex(params.element1),
386 idx2 = list.childIndex(params.element2),
389 succeedingItems = [],
390 items = list.children(),
391 listIsNested = list.parent().getWlxmlClass() === 'item',
395 var tmp = idx1; idx1 = idx2; idx2 = tmp;
398 items.forEach(function(item, idx) {
400 precedingItems.push(item);
401 else if(idx >= idx1 && idx <= idx2) {
402 extractedItems.push(item);
405 succeedingItems.push(item);
409 var reference = listIsNested ? list.parent() : list;
410 if(succeedingItems.length === 0) {
411 var reference_orig = reference;
412 extractedItems.forEach(function(item) {
413 reference.after(item);
416 item.setWlxmlClass(null);
418 if(precedingItems.length === 0)
419 reference_orig.detach();
420 } else if(precedingItems.length === 0) {
421 extractedItems.forEach(function(item) {
422 reference.before(item);
424 item.setWlxmlClass(null);
427 extractedItems.forEach(function(item) {
428 reference.after(item);
430 item.setWlxmlClass(null);
433 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
437 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
439 succeedingItems.forEach(function(item) {
440 secondList.append(item);
443 reference.after(toAdd);
445 if(!params.merge && listIsNested) {
446 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
450 areItemsOfTheSameList: function(params) {
451 var e1 = params.element1,
452 e2 = params.element2;
453 return e1.parent().sameNode(e2.parent())
454 && e1.parent().is('list');
459 var Cursor = function(canvas) {
460 this.canvas = canvas;
463 $.extend(Cursor.prototype, {
464 isSelecting: function() {
465 var selection = window.getSelection();
466 return !selection.isCollapsed;
468 isSelectingWithinElement: function() {
469 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
471 isSelectingSiblings: function() {
472 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
474 getPosition: function() {
475 return this.getSelectionAnchor();
477 getSelectionStart: function() {
478 return this.getSelectionBoundry('start');
480 getSelectionEnd: function() {
481 return this.getSelectionBoundry('end');
483 getSelectionAnchor: function() {
484 return this.getSelectionBoundry('anchor');
486 getSelectionFocus: function() {
487 return this.getSelectionBoundry('focus');
489 getSelectionBoundry: function(which) {
490 var selection = window.getSelection(),
491 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
492 focusElement = this.canvas.getDocumentElement(selection.focusNode);
494 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
497 if(which === 'anchor') {
499 element: anchorElement,
500 offset: selection.anchorOffset,
501 offsetAtBeginning: selection.anchorOffset === 0,
502 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
505 if(which === 'focus') {
507 element: focusElement,
508 offset: selection.focusOffset,
509 offsetAtBeginning: selection.focusOffset === 0,
510 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
517 if(anchorElement.parent().sameNode(focusElement.parent())) {
518 var parent = anchorElement.parent(),
519 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
521 if(which === 'start') {
522 element = anchorElement;
523 offset = selection.anchorOffset;
525 else if(which === 'end') {
526 element = focusElement,
527 offset = selection.focusOffset;
530 if(which === 'start') {
531 element = focusElement,
532 offset = selection.focusOffset
534 else if(which === 'end') {
535 element = anchorElement;
536 offset = selection.anchorOffset;
540 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
541 if(which === 'start') {
542 element = anchorElement;
543 offset = selection.anchorOffset
545 element = focusElement;
546 offset = selection.focusOffset
553 offsetAtBeginning: offset === 0,
554 offsetAtEnd: element.getText().length === offset
560 fromXML: function(xml, publisher) {
561 return new Canvas(xml, publisher);