editor: cleanup - removing unnecessary wlxml class handling code in canvas generic...
[fnpeditor.git] / src / smartxml / smartxml.test.js
1 define([
2     'libs/chai',
3     'libs/sinon',
4     'libs/underscore',
5     './smartxml.js'
6 ], function(chai, sinon, _, smartxml) {
7     
8 'use strict';
9 /*jshint expr:true */
10 /* global describe, it, beforeEach, Node, DOMParser */
11
12 var expect = chai.expect;
13
14
15 var getDocumentFromXML = function(xml) {
16     return smartxml.documentFromXML(xml);
17 };
18
19 var elementNodeFromParams = function(params) {
20     return smartxml.elementNodeFromXML('<' + params.tag + '></' + params.tag + '>');
21 };
22
23 var elementNodeFromXML = function(xml) {
24     return smartxml.elementNodeFromXML(xml);
25 };
26
27
28 describe('smartxml', function() {
29
30     describe('Basic Document properties', function() {
31         it('exposes its root element', function() {
32             var doc = getDocumentFromXML('<div></div>');
33             expect(doc.root.getTagName()).to.equal('div');
34         });
35
36         it('can resets its content entirely', function() {
37             var doc = getDocumentFromXML('<div></div>');
38
39             expect(doc.root.getTagName()).to.equal('div');
40
41             doc.loadXML('<header></header>');
42             expect(doc.root.getTagName()).to.equal('header');
43         });
44
45         it('knows if it contains an ElementNode in its tree', function() {
46             var doc = getDocumentFromXML('<root><a></a>text</root>'),
47                 root = doc.root,
48                 a = root.contents()[0],
49                 text = root.contents()[1];
50
51             expect(doc.containsNode(root)).to.equal(true, 'contains its root');
52             expect(doc.containsNode(a)).to.equal(true, 'contains Element Node');
53             expect(doc.containsNode(text)).to.equal(true, 'contains Text Node');
54         });
55
56         it('creates text nodes', function() {
57             var doc = getDocumentFromXML('<div></div>'),
58                 emptyTextNode = doc.createDocumentNode({text:''}),
59                 nonEmptyTextNode = doc.createDocumentNode({text: 'alice'});
60             expect(emptyTextNode.getText()).to.equal('', 'empty ok');
61             expect(nonEmptyTextNode.getText()).to.equal('alice', 'non empty ok');
62         });
63
64         it('creates nodes from xml strings', function() {
65             var doc = getDocumentFromXML('<div></div>'),
66                 node = doc.createDocumentNode('<a>Alice<b></b></a>');
67             expect(node.getTagName()).to.equal('a');
68             expect(node.contents().length).to.equal(2);
69             expect(node.contents()[0].getText()).to.equal('Alice');
70             expect(node.contents()[1].getTagName()).to.equal('b');
71         });
72
73         describe('Retrieving node by path', function() {
74             it('passes smoke tests', function() {
75                 var doc = getDocumentFromXML('<root><a><b>c</b></a>');
76                 expect(doc.getNodeByPath([0]).sameNode(doc.root.contents()[0])).to.be.true;
77                 expect(doc.getNodeByPath([0,0]).sameNode(doc.root.contents()[0].contents()[0])).to.be.true;
78             });
79             it('treats empty path as a root path', function() {
80                 var doc = getDocumentFromXML('<root></root>');
81                 expect(doc.getNodeByPath([]).sameNode(doc.root)).to.be.true;
82             });
83             it('returns undefined for non existing paths', function() {
84                 var doc = getDocumentFromXML('<root><a></a></root>');
85                 expect(doc.getNodeByPath([1])).to.be.undefined;
86                 expect(doc.getNodeByPath([0,1])).to.be.undefined;
87                 expect(doc.getNodeByPath([10,1])).to.be.undefined;
88             });
89         });
90     });
91
92     describe('DocumentNode', function() {
93         it('can be cloned', function() {
94             var doc = getDocumentFromXML('<div>Alice</div>'),
95                 text = doc.root.contents()[0],
96                 clone, suffix;
97
98             [doc.root, text].forEach(function(node) {
99                 suffix = ' (' + (node.nodeType === Node.TEXT_NODE ? 'text' : 'element')  + ')';
100                 clone = node.clone();
101                 expect(doc.containsNode(clone)).to.equal(false, 'clone is not contained in a document' + suffix);
102                 expect(node.sameNode(clone)).to.equal(false, 'clone is not same node as its originator' + suffix);
103                 expect(node.nativeNode.isEqualNode(clone.nativeNode)).to.equal(true, 'clone is identical as its originator' + suffix);
104             });
105         });
106
107         it('can be cloned with its contents and its contents data', function() {
108             var doc = getDocumentFromXML('<root><div></div></root>'),
109                 root = doc.root,
110                 div = root.contents()[0];
111
112             var ClonableObject = function(arg) {
113                 this.arg = arg;
114             };
115             ClonableObject.prototype.clone = function() {
116                 return new ClonableObject(this.arg);
117             };
118
119             div.setData('key', 'value');
120             div.setData('clonableObject', new ClonableObject('test'));
121
122             var rootClone = root.clone(),
123                 divClone = rootClone.contents()[0],
124                 stringClone = divClone.getData('key'),
125                 objClone = divClone.getData('clonableObject');
126
127             expect(stringClone).to.equal('value');
128             expect(objClone.arg).to.equal('test', 'clonable object got copied');
129             expect(objClone !== div.getData('clonableObject')).to.be.equal(true, 'copy of the clonable object is a new object');
130         });
131
132         it('knows its path in the document tree', function() {
133             var doc = getDocumentFromXML('<root><a><b><c></c>text</b></a></root>'),
134                 root = doc.root,
135                 a = root.contents()[0],
136                 b = a.contents()[0],
137                 text = b.contents()[1];
138
139             expect(root.getPath()).to.eql([], 'path of the root element is empty');
140             expect(a.getPath()).to.eql([0]);
141             expect(b.getPath()).to.eql([0, 0]);
142             expect(text.getPath()).to.eql([0,0,1]);
143
144             /* Paths relative to a given ancestor */
145             expect(text.getPath(root)).to.eql([0,0,1]);
146             expect(text.getPath(a)).to.eql([0,1]);
147             expect(text.getPath(b)).to.eql([1]);
148         });
149     });
150
151     describe('Basic ElementNode properties', function() {
152         it('exposes node contents', function() {
153             var node = elementNodeFromXML('<node>Some<node>text</node>is here</node>'),
154                 contents = node.contents();
155
156             expect(contents).to.have.length(3);
157             expect(contents[0].nodeType).to.equal(Node.TEXT_NODE, 'text node 1');
158             expect(contents[1].nodeType).to.equal(Node.ELEMENT_NODE, 'element node 1');
159             expect(contents[2].nodeType).to.equal(Node.TEXT_NODE, 'text node 2');
160         });
161
162         describe('Storing custom data', function() {
163             var node;
164
165             beforeEach(function() {
166                 node = elementNodeFromXML('<div></div>');
167             });
168
169             it('can append single value', function() {
170                 node.setData('key', 'value');
171                 expect(node.getData('key')).to.equal('value');
172             });
173
174             it('can overwrite the whole data', function() {
175                 node.setData('key1', 'value1');
176                 node.setData({key2: 'value2'});
177                 expect(node.getData('key2')).to.equal('value2');
178             });
179
180             it('can fetch the whole data at once', function() {
181                 node.setData({key1: 'value1', key2: 'value2'});
182                 expect(node.getData()).to.eql({key1: 'value1', key2: 'value2'});
183             });
184
185             it('can remove specific data', function() {
186                 node.setData('key', 'value');
187                 node.setData('key', undefined);
188                 expect(node.getData('key')).to.be.undefined;
189             });
190         });
191
192         describe('Changing node tag', function() {
193
194             it('can change tag name', function() {
195                 var node = elementNodeFromXML('<div></div>');
196                 node = node.setTag('span');
197                 expect(node.getTagName()).to.equal('span');
198             });
199
200             describe('Implementation specific expectations', function() {
201                 it('keeps custom data', function() {
202                     var node = elementNodeFromXML('<div></div>');
203
204                     node.setData('key', 'value');
205                     node = node.setTag('header');
206                     
207                     expect(node.getTagName()).to.equal('header');
208                     expect(node.getData()).to.eql({key: 'value'});
209                 });
210
211                 it('can change document root tag name', function() {
212                     var doc = getDocumentFromXML('<div></div>');
213                     doc.root.setTag('span');
214                     expect(doc.root.getTagName()).to.equal('span');
215                 });
216
217                 it('keeps node contents', function() {
218                     var node = elementNodeFromXML('<div><div></div></div>');
219                     node = node.setTag('header');
220                     expect(node.contents()).to.have.length(1);
221                 });
222             });
223         });
224
225         describe('Setting node attributes', function() {
226             it('can set node attribute', function() {
227                 var node = elementNodeFromXML('<div></div>');
228
229                 node.setAttr('key', 'value');
230                 expect(node.getAttr('key')).to.equal('value');
231             });
232             it('emits nodeAttrChange event', function() {
233                 var node = elementNodeFromXML('<div key="value1"></div>'),
234                     spy = sinon.spy();
235
236                 node.document.on('change', spy);
237                 node.setAttr('key', 'value2');
238                 var event = spy.args[0][0];
239
240                 expect(event.type).to.equal('nodeAttrChange');
241                 expect(event.meta.node.sameNode(node)).to.be.true;
242                 expect(event.meta.attr).to.equal('key');
243                 expect(event.meta.oldVal).to.equal('value1');
244             });
245         });
246
247         describe('Searching for the last child text node', function() {
248             [
249                 '<div>xxx<div></div>last</div>',
250                 '<div><div>last</div></div>',
251                 '<div>xxx<div>last</div><div></div></div>'
252             ].forEach(function(xml, i) {
253                 var example = 'example ' + i;
254                 it('returns last child text node ' + example + ')', function() {
255                     var doc = getDocumentFromXML(xml),
256                         lastTextNode = doc.root.getLastTextNode();
257                     expect(lastTextNode.getText()).to.equal('last', example);
258                 });
259             });
260         });
261
262         describe('Putting nodes around', function() {
263             it('will not allow to put node before or after root node', function() {
264                 var doc = getDocumentFromXML('<root></root>'),
265                     spy = sinon.spy(),
266                     root = doc.root,
267                     result;
268
269                 doc.on('change', spy);
270
271                 result = doc.root.before({tagName: 'test'});
272
273                 expect(spy.callCount).to.equal(0);
274                 expect(result).to.undefined;
275
276                 result = doc.root.after({tagName: 'test'});
277                 
278                 expect(spy.callCount).to.equal(0);
279                 expect(result).to.undefined;
280
281                 expect(doc.root.sameNode(root));
282             });
283         });
284     });
285
286     describe('Basic TextNode properties', function() {
287         it('can have its text set', function() {
288             var node = elementNodeFromXML('<div>Alice</div>'),
289                 textNode = node.contents()[0];
290
291             textNode.setText('Cat');
292             expect(textNode.getText()).to.equal('Cat');
293         });
294
295         it('emits nodeTextChange', function() {
296             var node = elementNodeFromXML('<div>Alice</div>'),
297                 textNode = node.contents()[0],
298                 spy = sinon.spy();
299
300             textNode.document.on('change', spy);
301             textNode.setText('Cat');
302
303             var event = spy.args[0][0];
304             expect(event.type).to.equal('nodeTextChange');
305         });
306
307         it('puts NodeElement after itself', function() {
308             var node = elementNodeFromXML('<div>Alice</div>'),
309                 textNode = node.contents()[0],
310                 returned = textNode.after({tagName:'div'});
311             expect(returned.sameNode(node.contents()[1])).to.be.true;
312         });
313
314         it('puts NodeElement before itself', function() {
315             var node = elementNodeFromXML('<div>Alice</div>'),
316                 textNode = node.contents()[0],
317                 returned = textNode.before({tagName:'div'});
318             expect(returned.sameNode(node.contents()[0])).to.be.true;
319         });
320
321         describe('Wrapping TextNode contents', function() {
322
323             it('wraps DocumentTextElement', function() {
324                 var node = elementNodeFromXML('<section>Alice</section>'),
325                     textNode = node.contents()[0];
326                 
327                 var returned = textNode.wrapWith({tagName: 'header'}),
328                     parent = textNode.parent(),
329                     parent2 = node.contents()[0];
330
331                 expect(returned.sameNode(parent)).to.be.equal(true, 'wrapper is a parent');
332                 expect(returned.sameNode(parent2)).to.be.equal(true, 'wrapper has a correct parent');
333                 expect(returned.getTagName()).to.equal('header');
334             });
335
336             describe('wrapping part of DocumentTextElement', function() {
337                 [{start: 5, end: 12}, {start: 12, end: 5}].forEach(function(offsets) {
338                     it('wraps in the middle ' + offsets.start + '/' + offsets.end, function() {
339                         var node = elementNodeFromXML('<section>Alice has a cat</section>'),
340                             textNode = node.contents()[0];
341                         
342                         var returned = textNode.wrapWith({tagName: 'header', attrs: {'attr1': 'value1'}, start: offsets.start, end: offsets.end}),
343                             contents = node.contents();
344
345                         expect(contents.length).to.equal(3);
346                         
347                         expect(contents[0].nodeType).to.be.equal(Node.TEXT_NODE, 'first node is text node');
348                         expect(contents[0].getText()).to.equal('Alice');
349
350                         expect(contents[1].sameNode(returned)).to.be.true;
351                         expect(returned.getTagName()).to.equal('header');
352                         expect(returned.getAttr('attr1')).to.equal('value1');
353                         expect(contents[1].contents().length).to.equal(1, 'wrapper has one node inside');
354                         expect(contents[1].contents()[0].getText()).to.equal(' has a ');
355
356                         expect(contents[2].nodeType).to.be.equal(Node.TEXT_NODE, 'third node is text node');
357                         expect(contents[2].getText()).to.equal('cat');
358                     });
359                 });
360
361                 it('wraps whole text inside DocumentTextElement if offsets span entire content', function() {
362                     var node = elementNodeFromXML('<section>Alice has a cat</section>'),
363                          textNode = node.contents()[0];
364                      
365                     textNode.wrapWith({tagName: 'header', start: 0, end: 15});
366                     
367                     var contents = node.contents();
368                     expect(contents.length).to.equal(1);
369                     expect(contents[0].getTagName()).to.equal('header');
370                     expect(contents[0].contents()[0].getText()).to.equal('Alice has a cat');
371                 });
372             });
373         });
374
375         describe('Dividing text node into two with element node', function() {
376                 it('can divide text node with element node, splitting text node into two', function() {
377                     var doc = getDocumentFromXML('<div>Alice has a cat</div>'),
378                         text = doc.root.contents()[0];
379
380                     var returned = text.divideWithElementNode({tagName: 'aside'}, {offset: 5}),
381                         contents = doc.root.contents(),
382                         lhsText = contents[0],
383                         rhsText = contents[2];
384
385                     expect(lhsText.getText()).to.equal('Alice');
386                     expect(returned.sameNode(contents[1]));
387                     expect(rhsText.getText()).to.equal(' has a cat');
388                 });
389
390                 it('treats dividing at the very end as appending after it', function() {
391                     var doc = getDocumentFromXML('<div>Alice has a cat</div>'),
392                         text = doc.root.contents()[0];
393
394
395                     var returned = text.divideWithElementNode({tagName: 'aside'}, {offset: 15}),
396                         contents = doc.root.contents(),
397                         textNode = contents[0],
398                         elementNode = contents[1];
399
400                     expect(contents.length).to.equal(2);
401                     expect(textNode.getText()).to.equal('Alice has a cat');
402                     expect(returned.sameNode(elementNode)).to.be.true;
403                     expect(elementNode.getTagName()).to.equal('aside');
404                 });
405
406                 it('treats dividing at the very beginning as prepending before it', function() {
407                     var doc = getDocumentFromXML('<div>Alice has a cat</div>'),
408                         text = doc.root.contents()[0];
409
410                     var returned = text.divideWithElementNode({tagName: 'aside'}, {offset: 0}),
411                         contents = doc.root.contents(),
412                         textNode = contents[1],
413                         elementNode = contents[0];
414
415                     expect(contents.length).to.equal(2);
416                     expect(textNode.getText()).to.equal('Alice has a cat');
417                     expect(returned.sameNode(elementNode)).to.be.true;
418                     expect(elementNode.getTagName()).to.equal('aside');
419                 });
420         });
421     });
422
423     describe('Manipulations', function() {
424
425         describe('detaching nodes', function() {
426             it('can detach document root node', function() {
427                 var doc = getDocumentFromXML('<div></div>');
428
429                 doc.root.detach();
430                 expect(doc.root).to.equal(null);
431             });
432         });
433
434         describe('replacing node with another one', function() {
435             it('replaces node with another one', function() {
436                 var doc = getDocumentFromXML('<div><a></a></div>'),
437                     a = doc.root.contents()[0];
438
439                 var c = a.replaceWith({tagName: 'b', attrs: {b:'1'}});
440
441                 expect(doc.root.contents()[0].sameNode(c));
442                 expect(c.getTagName()).to.equal('b');
443                 expect(c.getAttr('b')).to.equal('1');
444             });
445             it('can replace document root', function() {
446                 var doc = getDocumentFromXML('<div></div>');
447
448                 var header = doc.root.replaceWith({tagName: 'header'});
449
450                 expect(doc.root.sameNode(header)).to.be.true;
451                 expect(doc.containsNode(header)).to.be.true;
452             });
453         });
454
455         it('merges adjacent text nodes resulting from detaching an element node in between', function() {
456             var doc = getDocumentFromXML('<div>Alice <span>has</span>a cat</div>'),
457                 span = doc.root.contents()[1];
458
459             span.detach();
460
461             var rootContents = doc.root.contents();
462             expect(rootContents).to.have.length(1, 'one child left');
463             expect(rootContents[0].getText()).to.equal('Alice a cat');
464         });
465
466         it('merges adjacent text nodes resulting from moving an element node in between', function() {
467             var doc = getDocumentFromXML('<div><a></a>Alice <span>has</span>a cat</div>'),
468                 span = doc.root.contents()[2],
469                 a = doc.root.contents()[0];
470
471             a.append(span);
472
473             var rootContents = doc.root.contents();
474             expect(rootContents).to.have.length(2, 'one child left');
475             expect(rootContents[1].getText()).to.equal('Alice a cat');
476         });
477
478         it('inserts node at index', function() {
479             var doc = getDocumentFromXML('<div><a></a><b></b><c></c></div>'),
480                 b = doc.root.contents()[1];
481
482             var inserted = doc.root.insertAtIndex({tagName: 'test'}, 1);
483
484             expect(doc.root.contents()[1].sameNode(inserted)).to.equal(true, 'inserted node returned');
485             expect(b.getIndex()).to.equal(2, 'b node shifted right');
486         });
487
488         it('appends node when inserting node at index out of range', function() {
489             var doc = getDocumentFromXML('<div></div>');
490
491             var test1 = doc.root.insertAtIndex({tagName: 'test1'}, 0),
492                 test2 = doc.root.insertAtIndex({tagName: 'test1'}, 10);
493
494             expect(doc.root.contents()[0].sameNode(test1)).to.equal(true, 'inserting at index 0 of empty nodes appends node');
495             expect(doc.root.contents().length).to.equal(1, 'inserting at index out of range does nothing');
496             expect(test2).to.equal(undefined, 'inserting at index out of range returns undefined');
497         });
498
499         it('appends element node to another element node', function() {
500             var node1 = elementNodeFromParams({tag: 'div'}),
501                 node2 = elementNodeFromParams({tag: 'a'}),
502                 node3 = elementNodeFromParams({tag: 'p'});
503             node1.append(node2);
504             node1.append(node3);
505             expect(node1.contents()[0].sameNode(node2)).to.be.true;
506             expect(node1.contents()[1].sameNode(node3)).to.be.true;
507         });
508
509         it('prepends element node to another element node', function() {
510             var node1 = elementNodeFromParams({tag: 'div'}),
511                 node2 = elementNodeFromParams({tag: 'a'}),
512                 node3 = elementNodeFromParams({tag: 'p'});
513             node1.prepend(node2);
514             node1.prepend(node3);
515             expect(node1.contents()[0].sameNode(node3)).to.be.true;
516             expect(node1.contents()[1].sameNode(node2)).to.be.true;
517         });
518
519         describe('adding text nodes', function() {
520             it('merges text nodes on append', function() {
521                 var doc = getDocumentFromXML('<root>text1</root>'),
522                     returned;
523                 returned = doc.root.append({text: 'text2'});
524                 expect(doc.root.contents().length).to.equal(1);
525                 expect(returned.sameNode(doc.root.contents()[0])).to.equal(true, 'modified node returned');
526                 expect(doc.root.contents()[0].getText()).to.equal('text1text2');
527             });
528
529             it('merges text nodes on prepend', function() {
530                 var doc = getDocumentFromXML('<root>text1</root>'),
531                     returned;
532                 returned = doc.root.prepend({text: 'text2'});
533                 expect(doc.root.contents().length).to.equal(1);
534                 expect(returned.sameNode(doc.root.contents()[0])).to.equal(true, 'modified node returned');
535                 expect(doc.root.contents()[0].getText()).to.equal('text2text1');
536             });
537
538             it('merges text nodes on before text node', function() {
539                 var doc = getDocumentFromXML('<root>text1</root>'),
540                     textNode = doc.root.contents()[0],
541                     returned;
542                 returned = textNode.before({text: 'text2'});
543                 expect(doc.root.contents().length).to.equal(1);
544                 expect(returned.sameNode(doc.root.contents()[0])).to.equal(true, 'modified node returned');
545                 expect(doc.root.contents()[0].getText()).to.equal('text2text1');
546             });
547
548             it('merges text nodes on after text node', function() {
549                 var doc = getDocumentFromXML('<root>text1</root>'),
550                     textNode = doc.root.contents()[0],
551                     returned;
552                 returned = textNode.after({text: 'text2'});
553                 expect(doc.root.contents().length).to.equal(1);
554                 expect(returned.sameNode(doc.root.contents()[0])).to.equal(true, 'modified node returned');
555                 expect(doc.root.contents()[0].getText()).to.equal('text1text2');
556             });
557
558             it('merges text nodes on before element node', function() {
559                 var doc = getDocumentFromXML('<root>text1<div></div></root>'),
560                     textNode = doc.root.contents()[0],
561                     div = doc.root.contents()[1],
562                     returned;
563                 returned = div.before({text: 'text2'});
564                 expect(doc.root.contents().length).to.equal(2);
565                 expect(returned.sameNode(doc.root.contents()[0])).to.equal(true, 'modified node returned');
566                 expect(textNode.getText()).to.equal('text1text2');
567             });
568
569             it('merges text nodes on after element node', function() {
570                 var doc = getDocumentFromXML('<root><div></div>text1</root>'),
571                     textNode = doc.root.contents()[1],
572                     div = doc.root.contents()[0],
573                     returned;
574                 returned = div.after({text: 'text2'});
575                 expect(doc.root.contents().length).to.equal(2);
576                 expect(returned.sameNode(doc.root.contents()[1])).to.equal(true, 'modified node returned');
577                 expect(textNode.getText()).to.equal('text2text1');
578             });
579         });
580
581         it('wraps root element node with another element node', function() {
582             var node = elementNodeFromXML('<div></div>'),
583                 wrapper = elementNodeFromXML('<wrapper></wrapper>');
584
585             node.wrapWith(wrapper);
586             expect(node.parent().sameNode(wrapper)).to.be.true;
587             expect(node.document.root.sameNode(wrapper)).to.be.true;
588         });
589
590         it('wraps element node with another element node', function() {
591             var doc = getDocumentFromXML('<section><div></div></section>'),
592                 div = doc.root.contents()[0];
593
594             var wrapper = div.wrapWith({tagName: 'wrapper'});
595             expect(wrapper.sameNode(doc.root.contents()[0])).to.equal(true, '1');
596             expect(div.parent().sameNode(wrapper)).to.equal(true, '2');
597             expect(wrapper.contents()[0].sameNode(div)).to.equal(true, '3');
598         });
599
600         it('wraps element outside of document tree', function() {
601             var doc = getDocumentFromXML('<section><div></div></section>'),
602                 node = doc.createDocumentNode({tagName: 'node'});
603
604             node.wrapWith({tagName: 'wrapper'});
605             expect(node.parent().getTagName()).to.equal('wrapper');
606             expect(node.parent().contents()[0].sameNode(node)).to.be.true;
607             expect(doc.root.getTagName()).to.equal('section');
608         });
609
610         it('unwraps element node contents', function() {
611             var node = elementNodeFromXML('<div>Alice <div>has <span>propably</span> a cat</div>!</div>'),
612                 outerDiv = node.contents()[1];
613             
614             outerDiv.unwrapContent();
615
616             expect(node.contents().length).to.equal(3);
617             expect(node.contents()[0].getText()).to.equal('Alice has ');
618             expect(node.contents()[1].getTagName()).to.equal('span');
619             expect(node.contents()[2].getText()).to.equal(' a cat!');
620         });
621
622         it('removes parent-describing sibling nodes of unwrapped node', function() {
623             var doc = getDocumentFromXML('<root><div><a></a><x></x><a></a></div></root>'),
624                 div = doc.root.contents()[0],
625                 x = div.contents()[1];
626
627             doc.registerExtension({documentNode: {methods: {
628                 object: {
629                     describesParent: function() {
630                         return this.getTagName() === 'x';
631                     }
632                 }
633             }}});
634
635             div.unwrapContent();
636             expect(doc.root.contents().length).to.equal(2);
637             expect(x.isInDocument()).to.be.false;
638         });
639
640         it('unwrap single element node from its parent', function() {
641             var doc = getDocumentFromXML('<div><a><b></b></a></div>'),
642                 div = doc.root,
643                 a = div.contents()[0],
644                 b = a.contents()[0];
645
646             var parent = b.unwrap();
647
648             expect(parent.sameNode(div)).to.equal(true, 'returns new parent');
649             expect(div.contents()).to.have.length(1, 'root contains only one node');
650             expect(div.contents()[0].sameNode(b)).to.equal(true, 'node got unwrapped');
651         });
652
653         it('unwrap single text node from its parent', function() {
654             var doc = getDocumentFromXML('<div>Some <span>text</span>!</div>'),
655                 div = doc.root,
656                 span = div.contents()[1],
657                 text = span.contents()[0];
658
659             var parent = text.unwrap();
660
661             expect(parent.sameNode(div)).to.equal(true, 'returns new parent');
662             expect(div.contents()).to.have.length(1, 'root contains only one node');
663             expect(div.contents()[0].getText()).to.equal('Some text!');
664         });
665
666         describe('Wrapping text', function() {
667             it('wraps text spanning multiple sibling TextNodes', function() {
668                 var section = elementNodeFromXML('<section>Alice has a <span>small</span> cat</section>'),
669                     wrapper = section.wrapText({
670                         _with: {tagName: 'span', attrs: {'attr1': 'value1'}},
671                         offsetStart: 6,
672                         offsetEnd: 4,
673                         textNodeIdx: [0,2]
674                     });
675
676                 expect(section.contents().length).to.equal(2);
677                 expect(section.contents()[0].nodeType).to.equal(Node.TEXT_NODE);
678                 expect(section.contents()[0].getText()).to.equal('Alice ');
679
680                 var wrapper2 = section.contents()[1];
681                 expect(wrapper2.sameNode(wrapper)).to.be.true;
682                 expect(wrapper.getTagName()).to.equal('span');
683
684                 var wrapperContents = wrapper.contents();
685                 expect(wrapperContents.length).to.equal(3);
686                 expect(wrapperContents[0].getText()).to.equal('has a ');
687
688                 expect(wrapperContents[1].nodeType).to.equal(Node.ELEMENT_NODE);
689                 expect(wrapperContents[1].contents().length).to.equal(1);
690                 expect(wrapperContents[1].contents()[0].getText()).to.equal('small');
691             });
692
693             it('keeps parent-describing nodes in place', function() {
694                 var doc = getDocumentFromXML('<root>Alice <x></x> probably <y></y> has a cat</root>'),
695                     root = doc.root,
696                     x = root.contents()[1],
697                     y = root.contents()[3];
698
699                 doc.registerExtension({documentNode: {methods: {
700                     object: {
701                         describesParent: function() {
702                             /* globals Node */
703                             return this.nodeType === Node.ELEMENT_NODE && this.getTagName() === 'x';
704                         }
705                     }
706                 }}});
707
708                 root.wrapText({
709                     _with: {tagName: 'span', attrs: {'attr1': 'value1'}},
710                     offsetStart: 1,
711                     offsetEnd: 4,
712                     textNodeIdx: [0,4]
713                 });
714
715                 expect(x.parent().sameNode(root)).to.be.true;
716                 expect(y.parent().getTagName()).to.equal('span');
717             });
718         });
719
720         describe('Wrapping Nodes', function() {
721             it('wraps multiple sibling nodes', function() {
722                 var section = elementNodeFromXML('<section>Alice<div>has</div><div>a cat</div></section>'),
723                     aliceText = section.contents()[0],
724                     firstDiv = section.contents()[1],
725                     lastDiv = section.contents()[section.contents().length -1];
726
727                 var returned = section.document.wrapNodes({
728                         node1: aliceText,
729                         node2: lastDiv,
730                         _with: {tagName: 'header'}
731                     });
732
733                 var sectionContentss = section.contents(),
734                     header = sectionContentss[0],
735                     headerContents = header.contents();
736
737                 expect(sectionContentss).to.have.length(1);
738                 expect(header.sameNode(returned)).to.equal(true, 'wrapper returned');
739                 expect(header.parent().sameNode(section)).to.be.true;
740                 expect(headerContents).to.have.length(3);
741                 expect(headerContents[0].sameNode(aliceText)).to.equal(true, 'first node wrapped');
742                 expect(headerContents[1].sameNode(firstDiv)).to.equal(true, 'second node wrapped');
743                 expect(headerContents[2].sameNode(lastDiv)).to.equal(true, 'third node wrapped');
744             });
745
746             it('wraps multiple sibling Elements - middle case', function() {
747                 var section = elementNodeFromXML('<section><div></div><div></div><div></div><div></div></section>'),
748                     div2 = section.contents()[1],
749                     div3 = section.contents()[2];
750
751                 section.document.wrapNodes({
752                         node1: div2,
753                         node2: div3,
754                         _with: {tagName: 'header'}
755                     });
756
757                 var sectionContentss = section.contents(),
758                     header = sectionContentss[1],
759                     headerChildren = header.contents();
760
761                 expect(sectionContentss).to.have.length(3);
762                 expect(headerChildren).to.have.length(2);
763                 expect(headerChildren[0].sameNode(div2)).to.equal(true, 'first node wrapped');
764                 expect(headerChildren[1].sameNode(div3)).to.equal(true, 'second node wrapped');
765             });
766
767             it('keeps parent-describing nodes in place', function() {
768                 var section = elementNodeFromXML('<section>Alice<x></x><div>a cat</div></section>'),
769                     aliceText = section.contents()[0],
770                     x = section.contents()[1],
771                     lastDiv = section.contents()[2];
772
773                 section.document.registerExtension({documentNode: {methods: {
774                     object: {
775                         describesParent: function() {
776                             return this.nodeType === Node.ELEMENT_NODE && this.getTagName() === 'x';
777                         }
778                     }
779                 }}});
780
781                 section.document.wrapNodes({
782                         node1: aliceText,
783                         node2: lastDiv,
784                         _with: {tagName: 'header'}
785                     });
786
787                 expect(x.parent().sameNode(section)).to.be.true;
788                 expect(aliceText.parent().getTagName()).to.equal('header');
789                 expect(lastDiv.parent().getTagName()).to.equal('header');
790             });
791         });
792
793     });
794
795     var getTextNodes = function(text, doc) {
796         /* globals Node */
797         var toret = [];
798         var search = function(node) {
799             node.contents().forEach(function(node) {
800                 if(node.nodeType === Node.TEXT_NODE) {
801                     if(node.getText() === text) {
802                         toret.push(node);
803                     }
804                 } else {
805                     search(node);
806                 }
807             });
808         };
809         search(doc.root);
810         return toret;
811     };
812
813     var getTextNode = function(text, doc) {
814         var nodes = getTextNodes(text, doc),
815             error;
816         if(nodes.length === 0) {
817             error = 'Text not found';
818         } else if(nodes.length > 1) {
819             error = 'Text not unique';
820         } else if(nodes[0].getText() !== text) {
821             error = 'I was trying to cheat your test :(';
822         }
823         if(error) {
824             throw new Error(error);
825         }
826         return nodes[0];
827     };
828
829     describe('Removing arbitrary text', function() {
830         it('removes within single text element', function() {
831             var doc = getDocumentFromXML('<div>Alice</div>'),
832                 text = getTextNode('Alice', doc);
833             doc.deleteText({
834                 from: {
835                     node: text,
836                     offset: 1
837                 },
838                 to: {
839                     node: text,
840                     offset: 4
841                 }
842             });
843             expect(doc.root.contents().length).to.equal(1);
844             expect(doc.root.contents()[0].getText()).to.equal('Ae');
845         });
846         it('removes across elements - 1', function() {
847             var doc = getDocumentFromXML('<div><a>aaa</a><b>bbb</b></div>');
848
849             doc.deleteText({
850                 from: {
851                     node: getTextNode('aaa', doc),
852                     offset: 2
853                 },
854                 to: {
855                     node: getTextNode('bbb', doc),
856                     offset: 2
857                 }
858             });
859
860             var contents = doc.root.contents();
861             expect(contents.length).to.equal(2);
862             expect(contents[0].contents()[0].getText()).to.equal('aa');
863             expect(contents[1].contents()[0].getText()).to.equal('b');
864         });
865         it('removes across elements - 2', function() {
866             var doc = getDocumentFromXML('<a><b><c>ccc</c></b>xxx</a>');
867             doc.deleteText({
868                 from: {
869                     node: getTextNode('ccc', doc),
870                     offset: 2
871                 },
872                 to: {
873                     node: getTextNode('xxx', doc),
874                     offset: 2
875                 }
876             });
877
878             var contents = doc.root.contents();
879             expect(contents.length).to.equal(2);
880             expect(contents[0].getTagName()).to.equal('b');
881             expect(contents[1].getText()).to.equal('x');
882             
883             var bContents = contents[0].contents();
884             expect(bContents.length).to.equal(1);
885             expect(bContents[0].getTagName()).to.equal('c');
886             expect(bContents[0].contents().length).to.equal(1);
887             expect(bContents[0].contents()[0].getText()).to.equal('cc');
888         });
889         it('remove across elements - 3 (merged text nodes)', function() {
890             var doc = getDocumentFromXML('<div>Alice <span>has</span> a cat</div>');
891             doc.deleteText({
892                 from: {
893                     node: getTextNode('Alice ', doc),
894                     offset: 1
895                 },
896                 to: {
897                     node: getTextNode(' a cat', doc),
898                     offset: 3
899                 }
900             });
901             var contents = doc.root.contents();
902             expect(contents.length).to.equal(1);
903             expect(contents[0].getText()).to.equal('Acat');
904         });
905         it('remove across elements - 4', function() {
906             var doc = getDocumentFromXML('<div>Alice <div>has <span>a</span> cat</div></div>');
907             doc.deleteText({
908                 from: {
909                     node: getTextNode('Alice ', doc),
910                     offset: 1
911                 },
912                 to: {
913                     node: getTextNode(' cat', doc),
914                     offset: 1
915                 }
916             });
917             var contents = doc.root.contents();
918             expect(contents.length).to.equal(2);
919             expect(contents[0].getText()).to.equal('A');
920             expect(contents[1].getTagName()).to.equal('div');
921             expect(contents[1].contents().length).to.equal(1);
922             expect(contents[1].contents()[0].getText()).to.equal('cat');
923         });
924         it('removes across elements - 5 (whole document)', function() {
925             var doc = getDocumentFromXML('<div>Alice <div>has <span>a</span> cat</div>!!!</div>');
926             doc.deleteText({
927                 from: {
928                     node: getTextNode('Alice ', doc),
929                     offset: 0
930                 },
931                 to: {
932                     node: getTextNode('!!!', doc),
933                     offset: 3
934                 }
935             });
936
937             expect(doc.root.getTagName()).to.equal('div');
938             expect(doc.root.contents().length).to.equal(1);
939             expect(doc.root.contents()[0].getText()).to.equal('');
940         });
941         it('removes nodes in between', function() {
942             var doc = getDocumentFromXML('<div><a>aaa<x>!</x></a>xxx<x></x><b><x>!</x>bbb</b></div>');
943             doc.deleteText({
944                 from: {
945                     node: getTextNode('aaa', doc),
946                     offset: 2
947                 },
948                 to: {
949                     node: getTextNode('bbb', doc),
950                     offset: 2
951                 }
952             });
953
954             var contents = doc.root.contents();
955             expect(contents.length).to.equal(2, 'two nodes survived');
956             expect(contents[0].getTagName()).to.equal('a');
957             expect(contents[1].getTagName()).to.equal('b');
958             expect(contents[0].contents().length).to.equal(1);
959             expect(contents[0].contents()[0].getText()).to.equal('aa');
960             expect(contents[1].contents().length).to.equal(1);
961             expect(contents[1].contents()[0].getText()).to.equal('b');
962         });
963         it('removes across elements - 6', function() {
964             var doc = getDocumentFromXML('<root><div>aaa<span>bbb</span>ccc</div><div>ddd</div></root>');
965             doc.deleteText({
966                 from: {
967                     node: getTextNode('aaa', doc),
968                     offset: 1
969                 },
970                 to: {
971                     node: getTextNode('ddd', doc),
972                     offset: 1
973                 }
974             }, {
975                 error: function(e) {throw e;}
976             });
977
978             var contents = doc.root.contents();
979             expect(contents.length).to.equal(2);
980             expect(contents[0].contents().length).to.equal(1);
981             expect(contents[0].contents()[0].getText()).to.equal('a');
982             expect(contents[1].contents().length).to.equal(1);
983             expect(contents[1].contents()[0].getText()).to.equal('dd');
984         });
985     });
986
987     describe('Splitting text', function() {
988     
989         it('splits TextNode\'s parent into two ElementNodes', function() {
990             var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
991                 section = doc.root,
992                 text = section.contents()[0].contents()[0];
993
994             var returnedValue = text.split({offset: 5});
995             expect(section.contents().length).to.equal(2, 'section has two children');
996             
997             var header1 = section.contents()[0];
998             var header2 = section.contents()[1];
999
1000             expect(header1.getTagName()).to.equal('header', 'first section child ok');
1001             expect(header1.contents().length).to.equal(1, 'first header has one child');
1002             expect(header1.contents()[0].getText()).to.equal('Some ', 'first header has correct content');
1003             expect(header2.getTagName()).to.equal('header', 'second section child ok');
1004             expect(header2.contents().length).to.equal(1, 'second header has one child');
1005             expect(header2.contents()[0].getText()).to.equal('header', 'second header has correct content');
1006
1007             expect(returnedValue.first.sameNode(header1)).to.equal(true, 'first node returned');
1008             expect(returnedValue.second.sameNode(header2)).to.equal(true, 'second node returned');
1009         });
1010
1011         it('leaves empty copy of ElementNode if splitting at the very beginning', function() {
1012                 var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
1013                 section = doc.root,
1014                 text = section.contents()[0].contents()[0];
1015
1016                 text.split({offset: 0});
1017                 
1018                 var header1 = section.contents()[0];
1019                 var header2 = section.contents()[1];
1020
1021                 expect(header1.contents().length).to.equal(0);
1022                 expect(header2.contents()[0].getText()).to.equal('Some header');
1023         });
1024
1025         it('leaves empty copy of ElementNode if splitting at the very end', function() {
1026                 var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
1027                 section = doc.root,
1028                 text = section.contents()[0].contents()[0];
1029
1030                 text.split({offset: 11});
1031                 
1032                 var header1 = section.contents()[0];
1033                 var header2 = section.contents()[1];
1034
1035                 expect(header1.contents()[0].getText()).to.equal('Some header');
1036                 expect(header2.contents().length).to.equal(0);
1037         });
1038
1039         it('keeps TextNodes\'s parent\'s children elements intact', function() {
1040             var doc = getDocumentFromXML('<section><header>A <span>fancy</span> and <span>nice</span> header</header></section>'),
1041                 section = doc.root,
1042                 header = section.contents()[0],
1043                 textAnd = header.contents()[2];
1044
1045             textAnd.split({offset: 2});
1046             
1047             var sectionContents = section.contents();
1048             expect(sectionContents.length).to.equal(2, 'Section has two children');
1049             expect(sectionContents[0].getTagName()).to.equal('header', 'First section node is a header');
1050             expect(sectionContents[1].getTagName()).to.equal('header', 'Second section node is a header');
1051
1052             var firstHeaderContents = sectionContents[0].contents();
1053             expect(firstHeaderContents.length).to.equal(3, 'First header has three children');
1054             expect(firstHeaderContents[0].getText()).to.equal('A ', 'First header starts with a text');
1055             expect(firstHeaderContents[1].getTagName()).to.equal('span', 'First header has span in the middle');
1056             expect(firstHeaderContents[2].getText()).to.equal(' a', 'First header ends with text');
1057
1058             var secondHeaderContents = sectionContents[1].contents();
1059             expect(secondHeaderContents.length).to.equal(3, 'Second header has three children');
1060             expect(secondHeaderContents[0].getText()).to.equal('nd ', 'Second header starts with text');
1061             expect(secondHeaderContents[1].getTagName()).to.equal('span', 'Second header has span in the middle');
1062             expect(secondHeaderContents[2].getText()).to.equal(' header', 'Second header ends with text');
1063         });
1064     });
1065
1066     describe('Events', function() {
1067         it('emits nodeDetached event on node detach', function() {
1068             var node = elementNodeFromXML('<div><div></div></div>'),
1069                 innerNode = node.contents()[0],
1070                 spy = sinon.spy();
1071             node.document.on('change', spy);
1072             
1073             var detached = innerNode.detach(),
1074                 event = spy.args[0][0];
1075
1076             expect(event.type).to.equal('nodeDetached');
1077             expect(event.meta.node.sameNode(detached, 'detached node in event meta'));
1078             expect(event.meta.parent.sameNode(node), 'original parent node in event meta');
1079         }),
1080
1081         it('emits nodeAdded event when appending new node', function() {
1082             var node = elementNodeFromXML('<div></div>'),
1083                 spy = sinon.spy();
1084             node.document.on('change', spy);
1085             
1086             var appended = node.append({tagName:'div'}),
1087                 event = spy.args[0][0];
1088             expect(event.type).to.equal('nodeAdded');
1089             expect(event.meta.node.sameNode(appended)).to.be.true;
1090         });
1091         
1092         it('emits nodeDetached/nodeAdded events with `move` flag when appending aready existing node', function() {
1093             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
1094                 a = node.contents()[0],
1095                 b = node.contents()[1],
1096                 spy = sinon.spy();
1097             node.document.on('change', spy);
1098             
1099             var appended = a.append(b),
1100                 detachedEvent = spy.args[0][0],
1101                 addedEvent = spy.args[1][0];
1102
1103             expect(spy.callCount).to.equal(2);
1104             expect(detachedEvent.type).to.equal('nodeDetached');
1105             expect(detachedEvent.meta.node.sameNode(appended)).to.be.true;
1106             expect(detachedEvent.meta.move).to.equal(true, 'move flag set to true for nodeDetachedEvent');
1107             expect(addedEvent.type).to.equal('nodeAdded');
1108             expect(addedEvent.meta.node.sameNode(appended)).to.be.true;
1109             expect(addedEvent.meta.move).to.equal(true, 'move flag set to true for nodeAddedEvent');
1110
1111         });
1112         
1113         it('emits nodeAdded event when prepending new node', function() {
1114             var node = elementNodeFromXML('<div></div>'),
1115                 spy = sinon.spy();
1116             node.document.on('change', spy);
1117             
1118             var prepended = node.prepend({tagName:'div'}),
1119                 event = spy.args[0][0];
1120             expect(event.type).to.equal('nodeAdded');
1121             expect(event.meta.node.sameNode(prepended)).to.be.true;
1122         });
1123         
1124         it('emits nodeDetached/nodeAdded events with `move` flag when prepending aready existing node', function() {
1125             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
1126                 a = node.contents()[0],
1127                 b = node.contents()[1],
1128                 spy = sinon.spy();
1129             node.document.on('change', spy);
1130
1131             var prepended = a.prepend(b),
1132                 detachedEvent = spy.args[0][0],
1133                 addedEvent = spy.args[1][0];
1134
1135             expect(spy.callCount).to.equal(2);
1136             expect(detachedEvent.type).to.equal('nodeDetached');
1137             expect(detachedEvent.meta.node.sameNode(prepended)).to.be.true;
1138             expect(detachedEvent.meta.move).to.equal(true, 'move flag set to true for nodeDetachedEvent');
1139             expect(addedEvent.type).to.equal('nodeAdded');
1140             expect(addedEvent.meta.node.sameNode(prepended)).to.be.true;
1141             expect(addedEvent.meta.move).to.equal(true, 'move flag set to true for nodeAddedEvent');
1142         });
1143         
1144         it('emits nodeAdded event when inserting node after another', function() {
1145             var node = elementNodeFromXML('<div><a></a></div>').contents()[0],
1146                 spy = sinon.spy();
1147             node.document.on('change', spy);
1148             
1149             var inserted = node.after({tagName:'div'}),
1150                 event = spy.args[0][0];
1151             expect(event.type).to.equal('nodeAdded');
1152             expect(event.meta.node.sameNode(inserted)).to.be.true;
1153         });
1154         
1155         it('emits nodeDetached/nodeAdded events with `move` flag when inserting aready existing node after another', function() {
1156             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
1157                 a = node.contents()[0],
1158                 b = node.contents()[1],
1159                 spy = sinon.spy();
1160             node.document.on('change', spy);
1161             var inserted = b.after(a),
1162                 detachedEvent = spy.args[0][0],
1163                 addedEvent = spy.args[1][0];
1164
1165             expect(spy.callCount).to.equal(2);
1166             expect(detachedEvent.type).to.equal('nodeDetached');
1167             expect(detachedEvent.meta.node.sameNode(inserted)).to.be.true;
1168             expect(detachedEvent.meta.move).to.equal(true, 'move flag set to true for nodeDetachedEvent');
1169             expect(addedEvent.type).to.equal('nodeAdded');
1170             expect(addedEvent.meta.node.sameNode(inserted)).to.be.true;
1171             expect(addedEvent.meta.move).to.equal(true, 'move flag set to true for nodeAddedEvent');
1172         });
1173
1174         it('emits nodeAdded event when inserting node before another', function() {
1175             var node = elementNodeFromXML('<div><a></a></div>').contents()[0],
1176                 spy = sinon.spy();
1177             node.document.on('change', spy);
1178             
1179             var inserted = node.before({tagName:'div'}),
1180                 event = spy.args[0][0];
1181             expect(event.type).to.equal('nodeAdded');
1182             expect(event.meta.node.sameNode(inserted)).to.be.true;
1183         });
1184         
1185         it('emits nodeDetached/nodeAdded events with `move` flag when inserting aready existing node before another', function() {
1186             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
1187                 a = node.contents()[0],
1188                 b = node.contents()[1],
1189                 spy = sinon.spy();
1190             node.document.on('change', spy);
1191             var inserted = a.before(b),
1192                 detachedEvent = spy.args[0][0],
1193                 addedEvent = spy.args[1][0];
1194
1195             expect(spy.callCount).to.equal(2);
1196             expect(detachedEvent.type).to.equal('nodeDetached');
1197             expect(detachedEvent.meta.node.sameNode(inserted)).to.be.true;
1198             expect(detachedEvent.meta.move).to.equal(true, 'move flag set to true for nodeDetachedEvent');
1199             expect(addedEvent.type).to.equal('nodeAdded');
1200             expect(addedEvent.meta.node.sameNode(inserted)).to.be.true;
1201             expect(addedEvent.meta.move).to.equal(true, 'move flag set to true for nodeAddedEvent');
1202         });
1203
1204         it('emits nodeDetached and nodeAdded when replacing root node with another', function() {
1205             var doc = getDocumentFromXML('<a></a>'),
1206                 oldRoot = doc.root,
1207                 spy = sinon.spy();
1208
1209             doc.on('change', spy);
1210
1211             doc.root.replaceWith({tagName: 'b'});
1212
1213             expect(spy.callCount).to.equal(2);
1214
1215             var event1 = spy.args[0][0],
1216                 event2 = spy.args[1][0];
1217
1218             expect(event1.type).to.equal('nodeDetached');
1219             expect(event1.meta.node.sameNode(oldRoot)).to.equal(true, 'root node in nodeDetached event metadata');
1220             expect(event2.type).to.equal('nodeAdded');
1221             expect(event2.meta.node.sameNode(doc.root)).to.equal(true, 'new root node in nodelAdded event meta');
1222         });
1223
1224
1225         ['append', 'prepend', 'before', 'after'].forEach(function(insertionMethod) {
1226             it('emits nodeDetached for node moved from a document tree to out of document node ' + insertionMethod, function() {
1227                 var doc = getDocumentFromXML('<div><a></a></div>'),
1228                     a = doc.root.contents()[0],
1229                     spy = sinon.spy();
1230
1231                 doc.on('change', spy);
1232
1233                 var newNode = doc.createDocumentNode({tagName: 'b'}),
1234                     newNodeInner = newNode.append({tagName:'c'});
1235
1236                 newNodeInner[insertionMethod](a);
1237
1238                 var event = spy.args[0][0];
1239                 expect(event.type).to.equal('nodeDetached');
1240                 expect(event.meta.node.sameNode(a));
1241             });
1242
1243             it('doesn\'t emit nodeDetached event for already out of document node moved to out of document node' + insertionMethod, function() {
1244                 var doc = getDocumentFromXML('<div><a></a></div>'),
1245                     spy = sinon.spy();
1246
1247                 doc.on('change', spy);
1248
1249                 var newNode = doc.createDocumentNode({tagName: 'b'});
1250                 newNode.append({tagName:'c'});
1251
1252                 expect(spy.callCount).to.equal(0);
1253             });
1254         });
1255
1256
1257     });
1258
1259     describe('Traversing', function() {
1260         describe('Basic', function() {
1261             it('can access node parent', function() {
1262                 var doc = getDocumentFromXML('<a><b></b></a>'),
1263                     a = doc.root,
1264                     b = a.contents()[0];
1265
1266                 expect(a.parent()).to.equal(null, 'parent of a root is null');
1267                 expect(b.parent().sameNode(a)).to.be.true;
1268             });
1269             it('can access node parents', function() {
1270                 var doc = getDocumentFromXML('<a><b><c></c></b></a>'),
1271                     a = doc.root,
1272                     b = a.contents()[0],
1273                     c = b.contents()[0];
1274
1275                 var parents = c.parents();
1276                 // @@
1277                 expect(parents[0].sameNode(b)).to.be.true;
1278                 expect(parents[1].sameNode(a)).to.be.true;
1279             });
1280         });
1281
1282         describe('finding sibling parents of two elements', function() {
1283             it('returns elements themself if they have direct common parent', function() {
1284                 var doc = getDocumentFromXML('<section><div><div>A</div><div>B</div></div></section>'),
1285                     wrappingDiv = doc.root.contents()[0],
1286                     divA = wrappingDiv.contents()[0],
1287                     divB = wrappingDiv.contents()[1];
1288
1289                 var siblingParents = doc.getSiblingParents({node1: divA, node2: divB});
1290
1291                 expect(siblingParents.node1.sameNode(divA)).to.equal(true, 'divA');
1292                 expect(siblingParents.node2.sameNode(divB)).to.equal(true, 'divB');
1293             });
1294
1295             it('returns sibling parents - example 1', function() {
1296                 var doc = getDocumentFromXML('<section>Alice <span>has a cat</span></section>'),
1297                     aliceText = doc.root.contents()[0],
1298                     span = doc.root.contents()[1],
1299                     spanText = span.contents()[0];
1300
1301                 var siblingParents = doc.getSiblingParents({node1: aliceText, node2: spanText});
1302
1303                 expect(siblingParents.node1.sameNode(aliceText)).to.equal(true, 'aliceText');
1304                 expect(siblingParents.node2.sameNode(span)).to.equal(true, 'span');
1305             });
1306
1307             it('returns node itself for two same nodes', function() {
1308                 var doc = getDocumentFromXML('<section><div></div></section>'),
1309                     div = doc.root.contents()[0];
1310
1311                 var siblingParents = doc.getSiblingParents({node1: div, node2: div});
1312                 expect(!!siblingParents.node1 && !!siblingParents.node2).to.equal(true, 'nodes defined');
1313                 expect(siblingParents.node1.sameNode(div)).to.be.equal(true, 'node1');
1314                 expect(siblingParents.node2.sameNode(div)).to.be.equal(true, 'node2');
1315             });
1316         });
1317     });
1318
1319     describe('Serializing document to WLXML', function() {
1320         it('keeps document intact when no changes have been made', function() {
1321             var xmlIn = '<section>Alice<div>has</div>a <span class="uri" meta-uri="http://cat.com">cat</span>!</section>',
1322                 doc = getDocumentFromXML(xmlIn),
1323                 xmlOut = doc.toXML();
1324
1325             var parser = new DOMParser(),
1326                 input = parser.parseFromString(xmlIn, 'application/xml').childNodes[0],
1327                 output = parser.parseFromString(xmlOut, 'application/xml').childNodes[0];
1328             
1329             expect(input.isEqualNode(output)).to.be.true;
1330         });
1331
1332         it('keeps entities intact', function() {
1333             var xmlIn = '<section>&lt; &gt;</section>',
1334                 doc = getDocumentFromXML(xmlIn),
1335                 xmlOut = doc.toXML();
1336             expect(xmlOut).to.equal(xmlIn);
1337         });
1338         it('keeps entities intact when they form html/xml', function() {
1339             var xmlIn = '<section>&lt;abc&gt;</section>',
1340                 doc = getDocumentFromXML(xmlIn),
1341                 xmlOut = doc.toXML();
1342             expect(xmlOut).to.equal(xmlIn);
1343         });
1344     });
1345
1346     describe('Extension API', function() {
1347         var doc, extension, elementNode, textNode;
1348
1349         beforeEach(function() {
1350             doc = getDocumentFromXML('<section>Alice<div class="test_class"></div></section>');
1351             elementNode = doc.root;
1352             textNode = doc.root.contents()[0];
1353             extension = {};
1354             
1355             expect(elementNode.testTransformation).to.be.undefined;
1356             expect(textNode.testTransformation).to.be.undefined;
1357             expect(doc.testTransformation).to.be.undefined;
1358             
1359             expect(doc.testMethod).to.be.undefined;
1360             expect(elementNode.testMethod).to.be.undefined;
1361             expect(textNode.testMethod).to.be.undefined;
1362             expect(elementNode.elementTestMethod).to.be.undefined;
1363             expect(textNode.textTestMethod).to.be.undefined;
1364         });
1365
1366         it('allows adding method to a document', function() {
1367             extension = {document: {methods: {
1368                 testMethod: function() { return this; }
1369             }}};
1370
1371             doc.registerExtension(extension);
1372             expect(doc.testMethod()).to.equal(doc, 'context is set to a document instance');
1373         });
1374
1375         it('allows adding transformation to a document', function() {
1376             extension = {document: {transformations: {
1377                 testTransformation: function() { return this; },
1378                 testTransformation2: {impl: function() { return this;}}
1379             }}};
1380
1381             doc.registerExtension(extension);
1382             expect(doc.testTransformation()).to.equal(doc, 'context is set to a document instance');
1383             expect(doc.testTransformation2()).to.equal(doc, 'context is set to a document instance');
1384         });
1385
1386         it('allows adding method to a DocumentNode instance', function() {
1387             extension = {
1388                 documentNode: {
1389                     methods: {
1390                         testMethod: function() { return this; }
1391                     }
1392                 },
1393                 textNode: {
1394                     methods: {
1395                         textTestMethod: function() { return this; }
1396                     }
1397                 },
1398                 elementNode: {
1399                     methods: {
1400                         elementTestMethod: function() { return this; }
1401                     }
1402                 }
1403             };
1404
1405             doc.registerExtension(extension);
1406
1407             /* refresh */
1408             elementNode = doc.root;
1409             textNode = doc.root.contents()[0];
1410
1411             expect(elementNode.testMethod().sameNode(elementNode)).to.equal(true, 'context is set to a node instance');
1412             expect(textNode.testMethod().sameNode(textNode)).to.equal(true, 'context is set to a node instance');
1413
1414             expect(elementNode.elementTestMethod().sameNode(elementNode)).to.be.true;
1415             expect(elementNode.textTestMethod).to.be.undefined;
1416         
1417             expect(textNode.textTestMethod().sameNode(textNode)).to.be.true;
1418             expect(textNode.elementTestMethod).to.be.undefined;
1419         });
1420
1421         it('allows adding transformation to a DocumentNode', function() {
1422             extension = {
1423                 documentNode: {
1424                     transformations: {
1425                         testTransformation: function() { return this; },
1426                         testTransformation2: {impl: function() { return this;}}
1427                     }
1428                 },
1429                 textNode: {
1430                     transformations: {
1431                         textTestTransformation: function() { return this; }
1432                     }
1433                 },
1434                 elementNode: {
1435                     transformations: {
1436                         elementTestTransformation: function() { return this; }
1437                     }
1438                 }
1439             };
1440             
1441             doc.registerExtension(extension);
1442
1443             /* refresh */
1444             elementNode = doc.root;
1445             textNode = doc.root.contents()[0];
1446             
1447             expect(elementNode.testTransformation().sameNode(elementNode)).to.equal(true, '1');
1448             expect(elementNode.testTransformation2().sameNode(elementNode)).to.equal(true, '2');
1449             expect(textNode.testTransformation().sameNode(textNode)).to.equal(true, '3');
1450             expect(textNode.testTransformation2().sameNode(textNode)).to.equal(true, '4');
1451
1452             expect(elementNode.elementTestTransformation().sameNode(elementNode)).to.be.true;
1453             expect(elementNode.textTestTransformation).to.be.undefined;
1454         
1455             expect(textNode.textTestTransformation().sameNode(textNode)).to.be.true;
1456             expect(textNode.elementTestTransfomation).to.be.undefined;
1457         });
1458
1459         it('allows text/element node methods and transformations to access node and transormations on document node', function() {
1460
1461             var doc = getDocumentFromXML('<div>text</div>');
1462
1463             doc.registerExtension({
1464                 documentNode: {
1465                     methods: {
1466                         test: function() {
1467                             return 'super';
1468                         }
1469                     },
1470                     transformations: {
1471                         testT: function() {
1472                             return 'super_trans';
1473                         }
1474                     }
1475                 },
1476                 elementNode: {
1477                     methods: {
1478                         test: function() {
1479                             return 'element_sub_' + this.__super__.test();
1480                         }
1481                     },
1482                     transformations: {
1483                         testT: function() {
1484                             return 'element_trans_sub_' + this.__super__.testT();
1485                         }
1486                     }
1487                 },
1488                 textNode: {
1489                     methods: {
1490                         test: function() {
1491                             return 'text_sub_' + this.__super__.test();
1492                         }
1493                     },
1494                     transformations: {
1495                         testT: function() {
1496                             return 'text_trans_sub_' + this.__super__.testT();
1497                         }
1498                     }
1499                 }
1500             });
1501
1502             var textNode = doc.root.contents()[0];
1503
1504             expect(doc.root.test()).to.equal('element_sub_super');
1505             expect(textNode.test()).to.equal('text_sub_super');
1506             expect(doc.root.testT()).to.equal('element_trans_sub_super_trans');
1507             expect(textNode.testT()).to.equal('text_trans_sub_super_trans');
1508         });
1509     });
1510
1511     describe('Undo/redo', function() {
1512
1513         it('smoke tests', function() {
1514             var doc = getDocumentFromXML('<div>Alice</div>'),
1515                 textNode = doc.root.contents()[0];
1516
1517             expect(doc.undoStack).to.have.length(0);
1518             
1519             textNode.wrapWith({tagName: 'span', start:1, end:2});
1520             expect(doc.undoStack).to.have.length(1, '1');
1521             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1522
1523             doc.undo();
1524             expect(doc.undoStack).to.have.length(0, '2');
1525             expect(doc.toXML()).to.equal('<div>Alice</div>');
1526
1527             doc.redo();
1528             expect(doc.undoStack).to.have.length(1, '3');
1529             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1530
1531             doc.undo();
1532             expect(doc.undoStack).to.have.length(0, '4');
1533             expect(doc.toXML()).to.equal('<div>Alice</div>');
1534
1535             doc.undo();
1536             expect(doc.undoStack).to.have.length(0, '5');
1537             expect(doc.toXML()).to.equal('<div>Alice</div>');
1538         });
1539
1540         it('smoke tests 2', function() {
1541             var doc = getDocumentFromXML('<div>Alice</div>'),
1542                 textNode = doc.root.contents()[0],
1543                 path = textNode.getPath();
1544
1545             textNode.setText('Alice ');
1546             textNode.setText('Alice h');
1547             textNode.setText('Alice ha');
1548             textNode.setText('Alice has');
1549
1550             expect(textNode.getText()).to.equal('Alice has');
1551
1552             doc.undo();
1553             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '1');
1554
1555             doc.undo();
1556             expect(doc.root.contents()[0].getText()).to.equal('Alice h', '2');
1557
1558             doc.redo();
1559             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '3');
1560
1561             doc.redo();
1562             expect(doc.root.contents()[0].getText()).to.equal('Alice has', '4');
1563
1564             doc.undo();
1565             doc.undo();
1566             textNode = doc.getNodeByPath(path);
1567             textNode.setText('Cat');
1568             doc.undo();
1569             textNode = doc.getNodeByPath(path);
1570             expect(textNode.getText()).to.equal('Alice h');
1571         });
1572
1573         
1574         var sampleMethod = function(val) {
1575             this._$.attr('x', val);
1576             this.triggerChangeEvent();
1577         };
1578
1579         var transformations = {
1580             'unaware': sampleMethod,
1581             'returning change root': {
1582                 impl: sampleMethod,
1583                 getChangeRoot: function() {
1584                     return this.context;
1585                 }
1586             },
1587             'implementing undo operation': {
1588                 impl: function(t, val) {
1589                     t.oldVal = this.getAttr('x');
1590                     sampleMethod.call(this, val);
1591                 },
1592                 undo: function(t) {
1593                     this.setAttr('x', t.oldVal);
1594                 }
1595             }
1596         };
1597
1598         _.pairs(transformations).forEach(function(pair) {
1599             var name = pair[0],
1600                 transformaton = pair[1];
1601
1602             describe(name + ' transformation: ', function() {
1603                 var doc, node, nodePath;
1604
1605                 beforeEach(function() {
1606                     doc = getDocumentFromXML('<div><test x="old"></test></div>');
1607
1608                     doc.registerExtension({elementNode: {transformations: {
1609                         test: transformaton
1610                     }}});
1611
1612                     node = doc.root.contents()[0];
1613                     nodePath = node.getPath();
1614                 });
1615
1616                 it('transforms as expected', function() {
1617                     node.test('new');
1618                     expect(node.getAttr('x')).to.equal('new');
1619                 });
1620
1621                 it('can be undone', function() {
1622                     node.test('new');
1623                     doc.undo();
1624                     node = doc.getNodeByPath(nodePath);
1625                     expect(node.getAttr('x')).to.equal('old');
1626                 });
1627
1628                 it('can be undone and then redone', function() {
1629                     node.test('new');
1630                     doc.undo();
1631                     doc.redo();
1632                     node = doc.getNodeByPath(nodePath);
1633                     expect(node.getAttr('x')).to.equal('new');
1634                 });
1635
1636                 it('handles a sample scenario', function() {
1637                     doc.root.contents()[0].test('1');
1638                     doc.root.contents()[0].test('2');
1639                     doc.root.contents()[0].test('3');
1640                     doc.root.contents()[0].test('4');
1641                     doc.root.contents()[0].test('5');
1642
1643                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'after initial transformations');
1644                     doc.undo();
1645                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 1.1');
1646                     doc.undo();
1647                     expect(doc.root.contents()[0].getAttr('x')).to.equal('3', 'undo 1.2');
1648                     doc.redo();
1649                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'redo 1.1');
1650                     doc.redo();
1651                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'redo 1.2');
1652                     doc.undo();
1653                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 2.1');
1654                     doc.root.contents()[0].test('10');
1655                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'additional transformation');
1656                     expect(doc.redoStack.length).to.equal(0, 'transformation cleared redo stack');
1657                     doc.redo();
1658                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'empty redoStack so redo was noop');
1659                     doc.undo();
1660                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undoing additional transformation');
1661                     doc.redo();
1662                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'redoing additional transformation');
1663                 });
1664             });
1665         });
1666
1667         it('smoke tests nested transformations', function() {
1668             var doc = getDocumentFromXML('<div></div>');
1669
1670             doc.registerExtension({elementNode: {transformations: {
1671                 nested: function(v) {
1672                     this._$.attr('innerAttr', v);
1673                     this.triggerChangeEvent();
1674                 },
1675                 outer: function(v) {
1676                     this.nested(v);
1677                     this._$.attr('outerAttr', v);
1678                     this.triggerChangeEvent();
1679                 }
1680             }}});
1681
1682             doc.root.outer('test1');
1683             doc.root.outer('test2');
1684
1685             expect(doc.root.getAttr('innerAttr')).to.equal('test2');
1686             expect(doc.root.getAttr('outerAttr')).to.equal('test2');
1687
1688             doc.undo();
1689
1690             expect(doc.root.getAttr('innerAttr')).to.equal('test1');
1691             expect(doc.root.getAttr('outerAttr')).to.equal('test1');
1692
1693             doc.undo();
1694
1695             expect(doc.root.getAttr('innerAttr')).to.equal(undefined);
1696             expect(doc.root.getAttr('outerAttr')).to.equal(undefined);
1697
1698             doc.redo();
1699
1700             expect(doc.root.getAttr('innerAttr')).to.equal('test1');
1701             expect(doc.root.getAttr('outerAttr')).to.equal('test1');
1702
1703             doc.redo();
1704
1705             expect(doc.root.getAttr('innerAttr')).to.equal('test2');
1706             expect(doc.root.getAttr('outerAttr')).to.equal('test2');
1707
1708         });
1709
1710         it('ignores transformation if document didn\'t emit change event', function() {
1711             var doc = getDocumentFromXML('<div></div>');
1712
1713             doc.registerExtension({elementNode: {transformations: {
1714                 test: function() {
1715                     // empty
1716                 }
1717             }}});
1718
1719             doc.root.test();
1720             expect(doc.undoStack.length).to.equal(0);
1721
1722         });
1723
1724         describe('Transactions', function() {
1725             it('allows to undo/redo series of transformations at once', function() {
1726                 var doc = getDocumentFromXML('<div></div>');
1727
1728                 doc.registerExtension({
1729                     elementNode: {transformations: {
1730                         test: function(v) {
1731                             this.setAttr('test', v);
1732                         }
1733                     }}
1734                 });
1735
1736                 doc.startTransaction();
1737                 doc.root.test('1');
1738                 doc.root.test('2');
1739                 doc.root.test('3');
1740                 doc.endTransaction();
1741
1742                 doc.undo();
1743                 expect(doc.root.getAttr('test'), '1');
1744                 doc.redo();
1745                 expect(doc.root.getAttr('test'), '3');
1746                 doc.undo();
1747                 expect(doc.root.getAttr('test'), '1');
1748                 doc.redo();
1749                 expect(doc.root.getAttr('test'), '3');
1750             });
1751
1752             it('ignores empty transactions', function() {
1753                 var doc = getDocumentFromXML('<div></div>');
1754                 doc.startTransaction();
1755                 doc.endTransaction();
1756                 expect(doc.undoStack).to.have.length(0, 'empty transaction doesn\'t get pushed into undo stack');
1757             });
1758
1759             it('doesn\'t break on optimizations', function() {
1760                 // This is a smoke test checking if optimizations made to transaction undoing
1761                 // doesnt't break anything.
1762                 var doc = getDocumentFromXML('<div smart="1" unaware="1"></div>');
1763
1764                 doc.registerExtension({
1765                     elementNode: {transformations: {
1766                         unaware: function(v) {
1767                             this.setAttr('unware', v);
1768                             this.triggerChangeEvent();
1769                         },
1770                         smart: {
1771                             impl: function(t, v) {
1772                                 t.oldVal = this.getAttr('smart');
1773                                 this.setAttr('smart', v);
1774                                 this.triggerChangeEvent();
1775                             },
1776                             undo: function(t) {
1777                                 this.setAttr('smart', t.oldVal);
1778                                 this.triggerChangeEvent();
1779                             }
1780                         }
1781                     }}
1782                 });
1783
1784                 doc.startTransaction();
1785                 doc.root.smart('2');
1786                 doc.root.unaware('2');
1787                 doc.root.smart('3');
1788                 doc.root.unaware('3');
1789                 doc.endTransaction();
1790
1791                 doc.undo();
1792
1793                 expect(doc.root.getAttr('smart')).to.equal('1');
1794                 expect(doc.root.getAttr('unaware')).to.equal('1');
1795             });
1796
1797             it('can have associated metadata', function() {
1798                 var doc = getDocumentFromXML('<div></div>'),
1799                     metadata = Object.create({});
1800
1801                 doc.registerExtension({document: {transformations: {
1802                     test: function() {
1803                         this.trigger('change');
1804                     }
1805                 }}});
1806
1807                 doc.startTransaction(metadata);
1808                 doc.test();
1809                 doc.endTransaction();
1810
1811                 var transaction = doc.undoStack[0];
1812                 expect(transaction.metadata).to.equal(metadata);
1813             });
1814
1815             it('can be rolled back', function() {
1816                 var doc = getDocumentFromXML('<root></root>');
1817
1818                 doc.startTransaction();
1819                 doc.root.append({tagName: 'div'});
1820                 doc.rollbackTransaction();
1821
1822                 expect(doc.undoStack.length).to.equal(0, 'nothing to undo');
1823                 expect(doc.root.contents().length).to.equal(0);
1824             });
1825
1826             it('rollbacks and calls error handleor if error gets thrown', function() {
1827                 var doc = getDocumentFromXML('<root></root>'),
1828                     err = new Error(),
1829                     spy = sinon.spy();
1830                 
1831                 doc.transaction(function() {
1832                     doc.root.append({tagName: 'div'});
1833                     throw err;
1834                 }, {error: spy});
1835
1836                 expect(spy.args[0][0]).to.equal(err);
1837                 expect(doc.root.contents().length).to.equal(0);
1838                 expect(doc.undoStack.length).to.equal(0);
1839             });
1840         });
1841
1842         describe('Regression tests', function() {
1843             it('redos correctly after running its own undo followed by unaware transformation undo', function() {
1844                 var doc = getDocumentFromXML('<section t="0"></section>');
1845                 
1846                 doc.registerExtension({elementNode: {transformations: {
1847                     unaware: function() {
1848                         this.triggerChangeEvent();
1849                     },
1850                     test: {
1851                         impl: function() {
1852                             this._$.attr('t', 1);
1853                             this.triggerChangeEvent();
1854                         },
1855                         undo: function() {
1856                             this._$.attr('t', 0);
1857                         }
1858                     }
1859                 }}});
1860                 doc.root.unaware();
1861                 doc.root.test();
1862                 doc.undo();
1863                 doc.undo();
1864                 doc.redo();
1865                 doc.redo();
1866                 expect(doc.root.getAttr('t')).to.equal('1');
1867             });
1868             it('can perform undo of an operation performed after automatic transaction rollback', function() {
1869                 var doc = getDocumentFromXML('<section></section>'),
1870                     extension = {document: {transformations: {
1871                         throwingTransformation: function() { throw new Error(); }
1872                     }}};
1873
1874                 doc.registerExtension(extension);
1875
1876                 doc.throwingTransformation();
1877
1878                 doc.transaction(function() {
1879                     doc.root.setAttr('x', '2');
1880                 });
1881
1882                 expect(doc.undoStack.length).to.equal(1);
1883                 expect(doc.root.getAttr('x')).to.equal('2');
1884
1885                 doc.undo();
1886
1887                 expect(doc.undoStack.length).to.equal(0);
1888                 expect(doc.root.getAttr('x')).to.be.undefined;
1889
1890             });
1891         });
1892     });
1893
1894 });
1895
1896 });