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