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