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