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