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() {
70 $(next).data('orig-before', oldText);
72 parent.data('orig-append', oldText);
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) {
89 this.data = $.trim(this.data);
90 if(this.data.length === 0 && oldLength > 0 && el.parent().contents().length === 1)
92 if(this.data.length === 0) {
96 return true; // continue
100 var element = documentElement.DocumentTextElement.create({text: this.data});
101 $(this).replaceWith(element.dom());
104 this.d = this.wrapper.children(0);
107 this.wrapper.on('keydown', function(e) {
110 var cursor = canvas.getCursor();
111 if(!cursor.isSelecting()) {
112 var position = cursor.getPosition(),
113 elements = position.element.split({offset: position.offset}),
117 if(position.offsetAtBeginning)
118 newEmpty = elements.first;
119 else if(position.offsetAtEnd)
120 newEmpty = elements.second;
122 goto = newEmpty.append(documentElement.DocumentTextElement.create({text: '\u200B'}, this));
123 canvas.setCurrentElement(goto);
129 this.wrapper.on('keyup', function(e) {
130 if(e.which >= 37 && e.which <= 40)
131 canvas.setCurrentElement(canvas.getCursor().getPosition().element, {caretTo: false})
134 this.wrapper.on('click', '[wlxml-tag], [wlxml-text]', function(e) {
136 canvas.setCurrentElement(canvas.getDocumentElement(e.target), {caretTo: false});
151 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
154 wrapText: function(params) {
155 params = _.extend({textNodeIdx: 0}, params);
156 if(typeof params.textNodeIdx === 'number')
157 params.textNodeIdx = [params.textNodeIdx];
159 var childrenInside = params.inside.children(),
160 idx1 = Math.min.apply(Math, params.textNodeIdx),
161 idx2 = Math.max.apply(Math, params.textNodeIdx),
162 textNode1 = childrenInside[idx1],
163 textNode2 = childrenInside[idx2],
164 sameNode = textNode1.sameNode(textNode2),
165 prefixOutside = textNode1.getText().substr(0, params.offsetStart),
166 prefixInside = textNode1.getText().substr(params.offsetStart),
167 suffixInside = textNode2.getText().substr(0, params.offsetEnd),
168 suffixOutside = textNode2.getText().substr(params.offsetEnd)
171 var wrapperElement = documentElement.DocumentNodeElement.create({tag: params._with.tag, klass: params._with.klass});
172 textNode1.after(wrapperElement);
175 if(prefixOutside.length > 0)
176 wrapperElement.before({text:prefixOutside});
178 var core = textNode1.getText().substr(params.offsetStart, params.offsetEnd - params.offsetStart);
179 wrapperElement.append({text: core});
182 if(prefixInside.length > 0)
183 wrapperElement.append({text: prefixInside});
184 for(var i = idx1 + 1; i < idx2; i++) {
185 wrapperElement.append(childrenInside[i]);
187 if(suffixInside.length > 0)
188 wrapperElement.append({text: suffixInside});
190 if(suffixOutside.length > 0)
191 wrapperElement.after({text: suffixOutside});
192 return wrapperElement;
194 getDocumentElement: function(from) {
195 if(from instanceof HTMLElement || from instanceof Text) {
196 return documentElement.DocumentElement.fromHTMLElement(from, this);
199 getCursor: function() {
200 return new Cursor(this);
207 highlightElement: function(element) {
208 this.wrapper.find('.highlighted-element').removeClass('highlighted-element');
209 element.dom().addClass('highlighted-element');
212 dimElement: function(element) {
213 element.dom().removeClass('highlighted-element');
216 getCurrentNodeElement: function() {
217 return this.getDocumentElement(this.wrapper.find('.current-node-element')[0]);
220 getCurrentTextElement: function() {
221 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
226 setCurrentElement: function(element, params) {
227 params = _.extend({caretTo: 'end'}, params);
228 var findFirstDirectTextChild = function(e, nodeToLand) {
229 var byBrowser = this.getCursor().getPosition().element;
230 if(byBrowser && byBrowser.parent().sameNode(nodeToLand))
232 var children = e.children();
233 for(var i = 0; i < children.length; i++) {
234 if(children[i] instanceof documentElement.DocumentTextElement)
239 var _markAsCurrent = function(element) {
240 if(element instanceof documentElement.DocumentTextElement) {
241 this.wrapper.find('.current-text-element').removeClass('current-text-element');
242 element.dom().addClass('current-text-element');
244 this.wrapper.find('.current-node-element').removeClass('current-node-element')
245 element.dom().addClass('current-node-element');
246 this.publisher('currentElementChanged', element);
251 var isTextElement = element instanceof documentElement.DocumentTextElement,
252 nodeElementToLand = isTextElement ? element.parent() : element,
253 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
254 currentTextElement = this.getCurrentTextElement(),
255 currentNodeElement = this.getCurrentNodeElement();
257 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand)))
258 this.wrapper.find('.current-text-element').removeClass('current-text-element');
260 if(textElementToLand) {
261 _markAsCurrent(textElementToLand);
262 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element))
263 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
264 if(!(textElementToLand.sameNode(currentTextElement)))
265 this.publisher('currentTextElementSet', textElementToLand);
267 document.getSelection().removeAllRanges();
270 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
271 _markAsCurrent(nodeElementToLand);
273 this.publisher('currentNodeElementSet', nodeElementToLand);
277 _moveCaretToTextElement: function(element, where) {
278 var range = document.createRange(),
279 node = element.dom().contents()[0];
281 if(typeof where !== 'number') {
282 range.selectNodeContents(node);
284 range.setStart(node, where);
287 var collapseArg = true;
290 range.collapse(collapseArg);
292 var selection = document.getSelection();
294 selection.removeAllRanges();
295 selection.addRange(range);
296 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
299 setCursorPosition: function(position) {
301 this._moveCaretToTextElement(position.element, position.offset);
305 var d = function(element, parent, level) {
306 console.log(element.getText ? 'text: ' + element.getText() : 'node: ' + element.getWlxmlTag());
307 var isElementNode = element instanceof documentElement.DocumentNodeElement;
308 parent.prepend(element.toXML(level));
310 var dom = $(parent.children()[0]),
311 elementChildren = element.children();
312 for(var i = elementChildren.length - 1; i >= 0; i--) {
313 d(elementChildren[i], dom, level + 1);
317 var parent = $('<div>');
318 d(this.doc(), parent, 0);
319 return parent.html();
323 $.extend(Canvas.prototype.list, {
324 create: function(params) {
325 if(!(params.element1.parent().sameNode(params.element2.parent())))
328 var parent = params.element1.parent();
330 if(parent.childIndex(params.element1) > parent.childIndex(params.element2)) {
331 var tmp = params.element1;
332 params.element1 = params.element2;
333 params.element2 = tmp;
336 var elementsToWrap = [];
338 var place = 'before';
340 parent.children().some(function(element) {
342 if(element.sameNode(params.element1))
344 if(place === 'inside') {
345 if(element instanceof documentElement.DocumentTextElement) {
346 element = element.wrapWithNodeElement({tag: 'div', klass: 'list.item'});
347 if(element.children()[0].sameNode(params.element1))
348 params.element1 = element;
350 element.setWlxmlClass('item');
351 elementsToWrap.push(element);
353 if(_e.sameNode(params.element2))
357 var listElement = documentElement.DocumentNodeElement.create({tag: 'div', klass: 'list-items' + (params.type === 'enum' ? '-enum' : '')});
360 if(parent.is('list')) {
361 listElement.wrapWithNodeElement({tag: 'div', klass: 'item'});
362 toret = listElement.parent();
367 params.element1.before(toret);
369 elementsToWrap.forEach(function(element) {
371 listElement.append(element);
374 extractItems: function(params) {
375 params = _.extend({merge: true}, params);
376 var list = params.element1.parent();
377 if(!list.is('list') || !(list.sameNode(params.element2.parent())))
380 var idx1 = list.childIndex(params.element1),
381 idx2 = list.childIndex(params.element2),
384 succeedingItems = [],
385 items = list.children(),
386 listIsNested = list.parent().getWlxmlClass() === 'item',
390 var tmp = idx1; idx1 = idx2; idx2 = tmp;
393 items.forEach(function(item, idx) {
395 precedingItems.push(item);
396 else if(idx >= idx1 && idx <= idx2) {
397 extractedItems.push(item);
400 succeedingItems.push(item);
404 var reference = listIsNested ? list.parent() : list;
405 if(succeedingItems.length === 0) {
406 var reference_orig = reference;
407 extractedItems.forEach(function(item) {
408 reference.after(item);
411 item.setWlxmlClass(null);
413 if(precedingItems.length === 0)
414 reference_orig.detach();
415 } else if(precedingItems.length === 0) {
416 extractedItems.forEach(function(item) {
417 reference.before(item);
419 item.setWlxmlClass(null);
422 extractedItems.forEach(function(item) {
423 reference.after(item);
425 item.setWlxmlClass(null);
428 var secondList = documentElement.DocumentNodeElement.create({tag: 'div', klass:'list-items'}, this),
432 toAdd = secondList.wrapWithNodeElement({tag: 'div', klass:'item'});
434 succeedingItems.forEach(function(item) {
435 secondList.append(item);
438 reference.after(toAdd);
440 if(!params.merge && listIsNested) {
441 return this.extractItems({element1: extractedItems[0], element2: extractedItems[extractedItems.length-1]});
445 areItemsOfTheSameList: function(params) {
446 var e1 = params.element1,
447 e2 = params.element2;
448 return e1.parent().sameNode(e2.parent())
449 && e1.parent().is('list');
454 var Cursor = function(canvas) {
455 this.canvas = canvas;
458 $.extend(Cursor.prototype, {
459 isSelecting: function() {
460 var selection = window.getSelection();
461 return !selection.isCollapsed;
463 isSelectingWithinElement: function() {
464 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
466 isSelectingSiblings: function() {
467 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
469 getPosition: function() {
470 return this.getSelectionAnchor();
472 getSelectionStart: function() {
473 return this.getSelectionBoundry('start');
475 getSelectionEnd: function() {
476 return this.getSelectionBoundry('end');
478 getSelectionAnchor: function() {
479 return this.getSelectionBoundry('anchor');
481 getSelectionFocus: function() {
482 return this.getSelectionBoundry('focus');
484 getSelectionBoundry: function(which) {
485 var selection = window.getSelection(),
486 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
487 focusElement = this.canvas.getDocumentElement(selection.focusNode);
489 if(anchorElement instanceof documentElement.DocumentNodeElement || focusElement instanceof documentElement.DocumentNodeElement)
492 if(which === 'anchor') {
494 element: anchorElement,
495 offset: selection.anchorOffset,
496 offsetAtBeginning: selection.anchorOffset === 0,
497 offsetAtEnd: anchorElement && anchorElement.getText().length === selection.anchorOffset
500 if(which === 'focus') {
502 element: focusElement,
503 offset: selection.focusOffset,
504 offsetAtBeginning: selection.focusOffset === 0,
505 offsetAtEnd: focusElement && focusElement.getText().length === selection.focusOffset
512 if(anchorElement.parent().sameNode(focusElement.parent())) {
513 var parent = anchorElement.parent(),
514 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
516 if(which === 'start') {
517 element = anchorElement;
518 offset = selection.anchorOffset;
520 else if(which === 'end') {
521 element = focusElement,
522 offset = selection.focusOffset;
525 if(which === 'start') {
526 element = focusElement,
527 offset = selection.focusOffset
529 else if(which === 'end') {
530 element = anchorElement;
531 offset = selection.anchorOffset;
535 // TODO: Handle order via https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
536 if(which === 'start') {
537 element = anchorElement;
538 offset = selection.anchorOffset
540 element = focusElement;
541 offset = selection.focusOffset
548 offsetAtBeginning: offset === 0,
549 offsetAtEnd: element.getText().length === offset
555 fromXML: function(xml, publisher) {
556 return new Canvas(xml, publisher);