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