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