Linting, minor test description fix
[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
65     describe('DocumentNode', function() {
66         it('can be cloned', function() {
67             var doc = getDocumentFromXML('<div>Alice</div>'),
68                 text = doc.root.contents()[0],
69                 clone, suffix;
70
71             [doc.root, text].forEach(function(node) {
72                 suffix = ' (' + (node.nodeType === Node.TEXT_NODE ? 'text' : 'element')  + ')';
73                 clone = node.clone();
74                 expect(doc.containsNode(clone)).to.equal(false, 'clone is not contained in a document' + suffix);
75                 expect(node.sameNode(clone)).to.equal(false, 'clone is not same node as its originator' + suffix);
76                 expect(node.nativeNode.isEqualNode(clone.nativeNode)).to.equal(true, 'clone is identical as its originator' + suffix);
77             });
78         });
79
80         it('knows its path in the document tree', function() {
81             var doc = getDocumentFromXML('<root><a><b><c></c>text</b></a></root>'),
82                 root = doc.root,
83                 a = root.contents()[0],
84                 b = a.contents()[0],
85                 text = b.contents()[1];
86
87             expect(root.getPath()).to.eql([], 'path of the root element is empty');
88             expect(a.getPath()).to.eql([0]);
89             expect(b.getPath()).to.eql([0, 0]);
90             expect(text.getPath()).to.eql([0,0,1]);
91
92             /* Paths relative to a given ancestor */
93             expect(text.getPath(root)).to.eql([0,0,1]);
94             expect(text.getPath(a)).to.eql([0,1]);
95             expect(text.getPath(b)).to.eql([1]);
96         });
97     });
98
99     describe('Basic ElementNode properties', function() {
100         it('exposes node contents', function() {
101             var node = elementNodeFromXML('<node>Some<node>text</node>is here</node>'),
102                 contents = node.contents();
103
104             expect(contents).to.have.length(3);
105             expect(contents[0].nodeType).to.equal(Node.TEXT_NODE, 'text node 1');
106             expect(contents[1].nodeType).to.equal(Node.ELEMENT_NODE, 'element node 1');
107             expect(contents[2].nodeType).to.equal(Node.TEXT_NODE, 'text node 2');
108         });
109
110         describe('Storing custom data', function() {
111             var node;
112
113             beforeEach(function() {
114                 node = elementNodeFromXML('<div></div>');
115             });
116
117             it('can append single value', function() {
118                 node.setData('key', 'value');
119                 expect(node.getData('key')).to.equal('value');
120             });
121
122             it('can overwrite the whole data', function() {
123                 node.setData('key1', 'value1');
124                 node.setData({key2: 'value2'});
125                 expect(node.getData('key2')).to.equal('value2');
126             });
127
128             it('can fetch the whole data at once', function() {
129                 node.setData({key1: 'value1', key2: 'value2'});
130                 expect(node.getData()).to.eql({key1: 'value1', key2: 'value2'});
131             });
132         });
133
134         describe('Changing node tag', function() {
135
136             it('can change tag name', function() {
137                 var node = elementNodeFromXML('<div></div>');
138                 node.setTag('span');
139                 expect(node.getTagName()).to.equal('span');
140             });
141
142             it('emits nodeTagChange event', function() {
143                 var node = elementNodeFromXML('<div></div>'),
144                     spy = sinon.spy();
145
146                 node.document.on('change', spy);
147                 node.setTag('span');
148                 var event = spy.args[0][0];
149
150                 expect(event.type).to.equal('nodeTagChange');
151                 expect(event.meta.node.sameNode(node)).to.be.true;
152                 expect(event.meta.oldTagName).to.equal('div');
153             });
154
155             describe('Implementation specific expectations', function() {
156                 // DOM specifies ElementNode tag as a read-only property, so
157                 // changing it in a seamless way is a little bit tricky. For this reason
158                 // the folowing expectations are required, despite the fact that they actually are
159                 // motivated by implemetation details.
160
161                 it('keeps node in the document', function() {
162                     var doc = getDocumentFromXML('<div><header></header></div>'),
163                         header = doc.root.contents()[0];
164                     header.setTag('span');
165                     expect(header.parent().sameNode(doc.root)).to.be.true;
166                 });
167                 it('keeps custom data', function() {
168                     var node = elementNodeFromXML('<div></div>');
169
170                     node.setData('key', 'value');
171                     node.setTag('header');
172                     
173                     expect(node.getTagName()).to.equal('header');
174                     expect(node.getData()).to.eql({key: 'value'});
175                 });
176
177                 it('can change document root tag name', function() {
178                     var doc = getDocumentFromXML('<div></div>');
179                     doc.root.setTag('span');
180                     expect(doc.root.getTagName()).to.equal('span');
181                 });
182
183                 it('keeps contents', function() {
184                     var node = elementNodeFromXML('<div><div></div></div>');
185                     node.setTag('header');
186                     expect(node.contents()).to.have.length(1);
187                 });
188             });
189
190         describe('Setting node attributes', function() {
191             it('can set node attribute', function() {
192                 var node = elementNodeFromXML('<div></div>');
193
194                 node.setAttr('key', 'value');
195                 expect(node.getAttr('key')).to.equal('value');
196             });
197             it('emits nodeAttrChange event', function() {
198                 var node = elementNodeFromXML('<div key="value1"></div>'),
199                     spy = sinon.spy();
200
201                 node.document.on('change', spy);
202                 node.setAttr('key', 'value2');
203                 var event = spy.args[0][0];
204
205                 expect(event.type).to.equal('nodeAttrChange');
206                 expect(event.meta.node.sameNode(node)).to.be.true;
207                 expect(event.meta.attr).to.equal('key');
208                 expect(event.meta.oldVal).to.equal('value1');
209             });
210         });
211
212         });
213     });
214
215     describe('Basic TextNode properties', function() {
216         it('can have its text set', function() {
217             var node = elementNodeFromXML('<div>Alice</div>'),
218                 textNode = node.contents()[0];
219
220             textNode.setText('Cat');
221             expect(textNode.getText()).to.equal('Cat');
222         });
223
224         it('emits nodeTextChange', function() {
225             var node = elementNodeFromXML('<div>Alice</div>'),
226                 textNode = node.contents()[0],
227                 spy = sinon.spy();
228
229             textNode.document.on('change', spy);
230             textNode.setText('Cat');
231
232             var event = spy.args[0][0];
233             expect(event.type).to.equal('nodeTextChange');
234         });
235
236         it('puts NodeElement after itself', function() {
237             var node = elementNodeFromXML('<div>Alice</div>'),
238                 textNode = node.contents()[0],
239                 returned = textNode.after({tagName:'div'});
240             expect(returned.sameNode(node.contents()[1])).to.be.true;
241         });
242
243         it('puts NodeElement before itself', function() {
244             var node = elementNodeFromXML('<div>Alice</div>'),
245                 textNode = node.contents()[0],
246                 returned = textNode.before({tagName:'div'});
247             expect(returned.sameNode(node.contents()[0])).to.be.true;
248         });
249
250         describe('Wrapping TextNode contents', function() {
251
252             it('wraps DocumentTextElement', function() {
253                 var node = elementNodeFromXML('<section>Alice</section>'),
254                     textNode = node.contents()[0];
255                 
256                 var returned = textNode.wrapWith({tagName: 'header'}),
257                     parent = textNode.parent(),
258                     parent2 = node.contents()[0];
259
260                 expect(returned.sameNode(parent)).to.be.equal(true, 'wrapper is a parent');
261                 expect(returned.sameNode(parent2)).to.be.equal(true, 'wrapper has a correct parent');
262                 expect(returned.getTagName()).to.equal('header');
263             });
264
265             describe('wrapping part of DocumentTextElement', function() {
266                 [{start: 5, end: 12}, {start: 12, end: 5}].forEach(function(offsets) {
267                     it('wraps in the middle ' + offsets.start + '/' + offsets.end, function() {
268                         var node = elementNodeFromXML('<section>Alice has a cat</section>'),
269                             textNode = node.contents()[0];
270                         
271                         var returned = textNode.wrapWith({tagName: 'header', attrs: {'attr1': 'value1'}, start: offsets.start, end: offsets.end}),
272                             contents = node.contents();
273
274                         expect(contents.length).to.equal(3);
275                         
276                         expect(contents[0].nodeType).to.be.equal(Node.TEXT_NODE, 'first node is text node');
277                         expect(contents[0].getText()).to.equal('Alice');
278
279                         expect(contents[1].sameNode(returned)).to.be.true;
280                         expect(returned.getTagName()).to.equal('header');
281                         expect(returned.getAttr('attr1')).to.equal('value1');
282                         expect(contents[1].contents().length).to.equal(1, 'wrapper has one node inside');
283                         expect(contents[1].contents()[0].getText()).to.equal(' has a ');
284
285                         expect(contents[2].nodeType).to.be.equal(Node.TEXT_NODE, 'third node is text node');
286                         expect(contents[2].getText()).to.equal('cat');
287                     });
288                 });
289
290                 it('wraps whole text inside DocumentTextElement if offsets span entire content', function() {
291                     var node = elementNodeFromXML('<section>Alice has a cat</section>'),
292                          textNode = node.contents()[0];
293                      
294                     textNode.wrapWith({tagName: 'header', start: 0, end: 15});
295                     
296                     var contents = node.contents();
297                     expect(contents.length).to.equal(1);
298                     expect(contents[0].getTagName()).to.equal('header');
299                     expect(contents[0].contents()[0].getText()).to.equal('Alice has a cat');
300                 });
301             });
302         });
303
304     });
305
306     describe('Manipulations', function() {
307
308         describe('replacing node with another one', function() {
309             it('replaces node with another one', function() {
310                 var doc = getDocumentFromXML('<div><a></a></div>'),
311                     a = doc.root.contents()[0];
312
313                 var c = a.replaceWith({tagName: 'b', attrs: {b:'1'}});
314
315                 expect(doc.root.contents()[0].sameNode(c));
316                 expect(c.getTagName()).to.equal('b');
317                 expect(c.getAttr('b')).to.equal('1');
318             });
319             it('can replace document root', function() {
320                 var doc = getDocumentFromXML('<div></div>');
321
322                 var header = doc.root.replaceWith({tagName: 'header'});
323
324                 expect(doc.root.sameNode(header)).to.be.true;
325                 expect(doc.containsNode(header)).to.be.true;
326             });
327         });
328
329         it('merges adjacent text nodes resulting from detaching an element node in between', function() {
330             var doc = getDocumentFromXML('<div>Alice <span>has</span>a cat</div>'),
331                 span = doc.root.contents()[1];
332
333             span.detach();
334
335             var rootContents = doc.root.contents();
336             expect(rootContents).to.have.length(1, 'one child left');
337             expect(rootContents[0].getText()).to.equal('Alice a cat');
338         });
339
340         it('inserts node at index', function() {
341             var doc = getDocumentFromXML('<div><a></a><b></b><c></c></div>'),
342                 b = doc.root.contents()[1];
343
344             var inserted = doc.root.insertAtIndex({tagName: 'test'}, 1);
345
346             expect(doc.root.contents()[1].sameNode(inserted)).to.equal(true, 'inserted node returned');
347             expect(b.getIndex()).to.equal(2, 'b node shifted right');
348         });
349
350         it('appends node when inserting node at index out of range', function() {
351             var doc = getDocumentFromXML('<div></div>');
352
353             var test1 = doc.root.insertAtIndex({tagName: 'test1'}, 0),
354                 test2 = doc.root.insertAtIndex({tagName: 'test1'}, 10);
355
356             expect(doc.root.contents()[0].sameNode(test1)).to.equal(true, 'inserting at index 0 of empty nodes appends node');
357             expect(doc.root.contents().length).to.equal(1, 'inserting at index out of range does nothing');
358             expect(test2).to.equal(undefined, 'inserting at index out of range returns undefined');
359         });
360
361         it('appends element node to another element node', function() {
362             var node1 = elementNodeFromParams({tag: 'div'}),
363                 node2 = elementNodeFromParams({tag: 'a'}),
364                 node3 = elementNodeFromParams({tag: 'p'});
365             node1.append(node2);
366             node1.append(node3);
367             expect(node1.contents()[0].sameNode(node2)).to.be.true;
368             expect(node1.contents()[1].sameNode(node3)).to.be.true;
369         });
370
371         it('prepends element node to another element node', function() {
372             var node1 = elementNodeFromParams({tag: 'div'}),
373                 node2 = elementNodeFromParams({tag: 'a'}),
374                 node3 = elementNodeFromParams({tag: 'p'});
375             node1.prepend(node2);
376             node1.prepend(node3);
377             expect(node1.contents()[0].sameNode(node3)).to.be.true;
378             expect(node1.contents()[1].sameNode(node2)).to.be.true;
379         });
380
381         it('wraps element node with another element node', function() {
382             var node = elementNodeFromXML('<div></div>'),
383                 wrapper = elementNodeFromXML('<wrapper></wrapper>');
384
385             node.wrapWith(wrapper);
386             expect(node.parent().sameNode(wrapper)).to.be.true;
387         });
388
389         it('unwraps element node contents', function() {
390             var node = elementNodeFromXML('<div>Alice <div>has <span>propably</span> a cat</div>!</div>'),
391                 outerDiv = node.contents()[1];
392             
393             outerDiv.unwrapContent();
394
395             expect(node.contents().length).to.equal(3);
396             expect(node.contents()[0].getText()).to.equal('Alice has ');
397             expect(node.contents()[1].getTagName()).to.equal('span');
398             expect(node.contents()[2].getText()).to.equal(' a cat!');
399         });
400
401         it('unwrap single element node from its parent', function() {
402             var doc = getDocumentFromXML('<div><a><b></b></a></div>'),
403                 div = doc.root,
404                 a = div.contents()[0],
405                 b = a.contents()[0];
406
407             var parent = b.unwrap();
408
409             expect(parent.sameNode(div)).to.equal(true, 'returns new parent');
410             expect(div.contents()).to.have.length(1, 'root contains only one node');
411             expect(div.contents()[0].sameNode(b)).to.equal(true, 'node got unwrapped');
412         });
413
414         it('unwrap single text node from its parent', function() {
415             var doc = getDocumentFromXML('<div>Some <span>text</span>!</div>'),
416                 div = doc.root,
417                 span = div.contents()[1],
418                 text = span.contents()[0];
419
420             var parent = text.unwrap();
421
422             expect(parent.sameNode(div)).to.equal(true, 'returns new parent');
423             expect(div.contents()).to.have.length(1, 'root contains only one node');
424             expect(div.contents()[0].getText()).to.equal('Some text!');
425         });
426
427         describe('Wrapping text', function() {
428             it('wraps text spanning multiple sibling TextNodes', function() {
429                 var section = elementNodeFromXML('<section>Alice has a <span>small</span> cat</section>'),
430                     wrapper = section.wrapText({
431                         _with: {tagName: 'span', attrs: {'attr1': 'value1'}},
432                         offsetStart: 6,
433                         offsetEnd: 4,
434                         textNodeIdx: [0,2]
435                     });
436
437                 expect(section.contents().length).to.equal(2);
438                 expect(section.contents()[0].nodeType).to.equal(Node.TEXT_NODE);
439                 expect(section.contents()[0].getText()).to.equal('Alice ');
440
441                 var wrapper2 = section.contents()[1];
442                 expect(wrapper2.sameNode(wrapper)).to.be.true;
443                 expect(wrapper.getTagName()).to.equal('span');
444
445                 var wrapperContents = wrapper.contents();
446                 expect(wrapperContents.length).to.equal(3);
447                 expect(wrapperContents[0].getText()).to.equal('has a ');
448
449                 expect(wrapperContents[1].nodeType).to.equal(Node.ELEMENT_NODE);
450                 expect(wrapperContents[1].contents().length).to.equal(1);
451                 expect(wrapperContents[1].contents()[0].getText()).to.equal('small');
452             });
453         });
454
455         describe('Wrapping Nodes', function() {
456             it('wraps multiple sibling nodes', function() {
457                 var section = elementNodeFromXML('<section>Alice<div>has</div><div>a cat</div></section>'),
458                     aliceText = section.contents()[0],
459                     firstDiv = section.contents()[1],
460                     lastDiv = section.contents()[section.contents().length -1];
461
462                 var returned = section.document.wrapNodes({
463                         node1: aliceText,
464                         node2: lastDiv,
465                         _with: {tagName: 'header'}
466                     });
467
468                 var sectionContentss = section.contents(),
469                     header = sectionContentss[0],
470                     headerContents = header.contents();
471
472                 expect(sectionContentss).to.have.length(1);
473                 expect(header.sameNode(returned)).to.equal(true, 'wrapper returned');
474                 expect(header.parent().sameNode(section)).to.be.true;
475                 expect(headerContents).to.have.length(3);
476                 expect(headerContents[0].sameNode(aliceText)).to.equal(true, 'first node wrapped');
477                 expect(headerContents[1].sameNode(firstDiv)).to.equal(true, 'second node wrapped');
478                 expect(headerContents[2].sameNode(lastDiv)).to.equal(true, 'third node wrapped');
479             });
480
481             it('wraps multiple sibling Elements - middle case', function() {
482                 var section = elementNodeFromXML('<section><div></div><div></div><div></div><div></div></section>'),
483                     div2 = section.contents()[1],
484                     div3 = section.contents()[2];
485
486                 section.document.wrapNodes({
487                         node1: div2,
488                         node2: div3,
489                         _with: {tagName: 'header'}
490                     });
491
492                 var sectionContentss = section.contents(),
493                     header = sectionContentss[1],
494                     headerChildren = header.contents();
495
496                 expect(sectionContentss).to.have.length(3);
497                 expect(headerChildren).to.have.length(2);
498                 expect(headerChildren[0].sameNode(div2)).to.equal(true, 'first node wrapped');
499                 expect(headerChildren[1].sameNode(div3)).to.equal(true, 'second node wrapped');
500             });
501         });
502
503     });
504
505     describe('Splitting text', function() {
506     
507         it('splits TextNode\'s parent into two ElementNodes', function() {
508             var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
509                 section = doc.root,
510                 text = section.contents()[0].contents()[0];
511
512             var returnedValue = text.split({offset: 5});
513             expect(section.contents().length).to.equal(2, 'section has two children');
514             
515             var header1 = section.contents()[0];
516             var header2 = section.contents()[1];
517
518             expect(header1.getTagName()).to.equal('header', 'first section child ok');
519             expect(header1.contents().length).to.equal(1, 'first header has one child');
520             expect(header1.contents()[0].getText()).to.equal('Some ', 'first header has correct content');
521             expect(header2.getTagName()).to.equal('header', 'second section child ok');
522             expect(header2.contents().length).to.equal(1, 'second header has one child');
523             expect(header2.contents()[0].getText()).to.equal('header', 'second header has correct content');
524
525             expect(returnedValue.first.sameNode(header1)).to.equal(true, 'first node returned');
526             expect(returnedValue.second.sameNode(header2)).to.equal(true, 'second node returned');
527         });
528
529         it('leaves empty copy of ElementNode if splitting at the very beginning', function() {
530                 var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
531                 section = doc.root,
532                 text = section.contents()[0].contents()[0];
533
534                 text.split({offset: 0});
535                 
536                 var header1 = section.contents()[0];
537                 var header2 = section.contents()[1];
538
539                 expect(header1.contents().length).to.equal(0);
540                 expect(header2.contents()[0].getText()).to.equal('Some header');
541         });
542
543         it('leaves empty copy of ElementNode if splitting at the very end', function() {
544                 var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
545                 section = doc.root,
546                 text = section.contents()[0].contents()[0];
547
548                 text.split({offset: 11});
549                 
550                 var header1 = section.contents()[0];
551                 var header2 = section.contents()[1];
552
553                 expect(header1.contents()[0].getText()).to.equal('Some header');
554                 expect(header2.contents().length).to.equal(0);
555         });
556
557         it('keeps TextNodes\'s parent\'s children elements intact', function() {
558             var doc = getDocumentFromXML('<section><header>A <span>fancy</span> and <span>nice</span> header</header></section>'),
559                 section = doc.root,
560                 header = section.contents()[0],
561                 textAnd = header.contents()[2];
562
563             textAnd.split({offset: 2});
564             
565             var sectionContents = section.contents();
566             expect(sectionContents.length).to.equal(2, 'Section has two children');
567             expect(sectionContents[0].getTagName()).to.equal('header', 'First section node is a header');
568             expect(sectionContents[1].getTagName()).to.equal('header', 'Second section node is a header');
569
570             var firstHeaderContents = sectionContents[0].contents();
571             expect(firstHeaderContents.length).to.equal(3, 'First header has three children');
572             expect(firstHeaderContents[0].getText()).to.equal('A ', 'First header starts with a text');
573             expect(firstHeaderContents[1].getTagName()).to.equal('span', 'First header has span in the middle');
574             expect(firstHeaderContents[2].getText()).to.equal(' a', 'First header ends with text');
575
576             var secondHeaderContents = sectionContents[1].contents();
577             expect(secondHeaderContents.length).to.equal(3, 'Second header has three children');
578             expect(secondHeaderContents[0].getText()).to.equal('nd ', 'Second header starts with text');
579             expect(secondHeaderContents[1].getTagName()).to.equal('span', 'Second header has span in the middle');
580             expect(secondHeaderContents[2].getText()).to.equal(' header', 'Second header ends with text');
581         });
582     });
583
584     describe('Events', function() {
585         it('emits nodeDetached event on node detach', function() {
586             var node = elementNodeFromXML('<div><div></div></div>'),
587                 innerNode = node.contents()[0],
588                 spy = sinon.spy();
589             node.document.on('change', spy);
590             
591             var detached = innerNode.detach(),
592                 event = spy.args[0][0];
593
594             expect(event.type).to.equal('nodeDetached');
595             expect(event.meta.node.sameNode(detached, 'detached node in event meta'));
596             expect(event.meta.parent.sameNode(node), 'original parent node in event meta');
597         }),
598
599         it('emits nodeAdded event when appending new node', function() {
600             var node = elementNodeFromXML('<div></div>'),
601                 spy = sinon.spy();
602             node.document.on('change', spy);
603             
604             var appended = node.append({tagName:'div'}),
605                 event = spy.args[0][0];
606             expect(event.type).to.equal('nodeAdded');
607             expect(event.meta.node.sameNode(appended)).to.be.true;
608         });
609         
610         it('emits nodeMoved when appending aready existing node', function() {
611             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
612                 a = node.contents()[0],
613                 b = node.contents()[1],
614                 spy = sinon.spy();
615             node.document.on('change', spy);
616             
617             var appended = a.append(b),
618                 event = spy.args[0][0];
619
620             expect(spy.callCount).to.equal(1);
621             expect(event.type).to.equal('nodeMoved');
622             expect(event.meta.node.sameNode(appended)).to.be.true;
623         });
624         
625         it('emits nodeAdded event when prepending new node', function() {
626             var node = elementNodeFromXML('<div></div>'),
627                 spy = sinon.spy();
628             node.document.on('change', spy);
629             
630             var prepended = node.prepend({tagName:'div'}),
631                 event = spy.args[0][0];
632             expect(event.type).to.equal('nodeAdded');
633             expect(event.meta.node.sameNode(prepended)).to.be.true;
634         });
635         
636         it('emits nodeMoved when prepending aready existing node', function() {
637             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
638                 a = node.contents()[0],
639                 b = node.contents()[1],
640                 spy = sinon.spy();
641             node.document.on('change', spy);
642             
643             var prepended = a.prepend(b),
644                 event = spy.args[0][0];
645             expect(spy.callCount).to.equal(1);
646             expect(event.type).to.equal('nodeMoved');
647             expect(event.meta.node.sameNode(prepended)).to.be.true;
648         });
649         
650         it('emits nodeAdded event when inserting node after another', function() {
651             var node = elementNodeFromXML('<div><a></a></div>').contents()[0],
652                 spy = sinon.spy();
653             node.document.on('change', spy);
654             
655             var inserted = node.after({tagName:'div'}),
656                 event = spy.args[0][0];
657             expect(event.type).to.equal('nodeAdded');
658             expect(event.meta.node.sameNode(inserted)).to.be.true;
659         });
660         
661         it('emits nodeMoved when inserting aready existing node after another', function() {
662             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
663                 a = node.contents()[0],
664                 b = node.contents()[1],
665                 spy = sinon.spy();
666             node.document.on('change', spy);
667             var inserted = b.after(a),
668                 event = spy.args[0][0];
669
670             expect(spy.callCount).to.equal(1);
671             expect(event.type).to.equal('nodeMoved');
672             expect(event.meta.node.sameNode(inserted)).to.be.true;
673         });
674
675         it('emits nodeAdded event when inserting node before another', function() {
676             var node = elementNodeFromXML('<div><a></a></div>').contents()[0],
677                 spy = sinon.spy();
678             node.document.on('change', spy);
679             
680             var inserted = node.before({tagName:'div'}),
681                 event = spy.args[0][0];
682             expect(event.type).to.equal('nodeAdded');
683             expect(event.meta.node.sameNode(inserted)).to.be.true;
684         });
685         
686         it('emits nodeAdded when inserting aready existing node before another', function() {
687             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
688                 a = node.contents()[0],
689                 b = node.contents()[1],
690                 spy = sinon.spy();
691             node.document.on('change', spy);
692             var inserted = a.before(b),
693                 event = spy.args[0][0];
694
695             expect(spy.callCount).to.equal(1);
696             expect(event.type).to.equal('nodeMoved');
697             expect(event.meta.node.sameNode(inserted)).to.be.true;
698         });
699
700         it('emits nodeDetached and nodeAdded when replacing root node with another', function() {
701             var doc = getDocumentFromXML('<a></a>'),
702                 oldRoot = doc.root,
703                 spy = sinon.spy();
704
705             doc.on('change', spy);
706
707             doc.root.replaceWith({tagName: 'b'});
708
709             expect(spy.callCount).to.equal(2);
710
711             var event1 = spy.args[0][0],
712                 event2 = spy.args[1][0];
713
714             expect(event1.type).to.equal('nodeDetached');
715             expect(event1.meta.node.sameNode(oldRoot)).to.equal(true, 'root node in nodeDetached event metadata');
716             expect(event2.type).to.equal('nodeAdded');
717             expect(event2.meta.node.sameNode(doc.root)).to.equal(true, 'new root node in nodelAdded event meta');
718         });
719
720
721         ['append', 'prepend', 'before', 'after'].forEach(function(insertionMethod) {
722             it('emits nodeDetached for node moved from a document tree to out of document node ' + insertionMethod, function() {
723                 var doc = getDocumentFromXML('<div><a></a></div>'),
724                     a = doc.root.contents()[0],
725                     spy = sinon.spy();
726
727                 doc.on('change', spy);
728
729                 var newNode = doc.createDocumentNode({tagName: 'b'}),
730                     newNodeInner = newNode.append({tagName:'c'});
731
732                 newNodeInner[insertionMethod](a);
733
734                 var event = spy.args[0][0];
735                 expect(event.type).to.equal('nodeDetached');
736                 expect(event.meta.node.sameNode(a));
737             });
738
739             it('doesn\'t emit nodeDetached event for already out of document node moved to out of document node' + insertionMethod, function() {
740                 var doc = getDocumentFromXML('<div><a></a></div>'),
741                     spy = sinon.spy();
742
743                 doc.on('change', spy);
744
745                 var newNode = doc.createDocumentNode({tagName: 'b'});
746                 newNode.append({tagName:'c'});
747
748                 expect(spy.callCount).to.equal(0);
749             });
750         });
751
752
753     });
754
755     describe('Traversing', function() {
756         describe('Basic', function() {
757             it('can access node parent', function() {
758                 var doc = getDocumentFromXML('<a><b></b></a>'),
759                     a = doc.root,
760                     b = a.contents()[0];
761
762                 expect(a.parent()).to.equal(null, 'parent of a root is null');
763                 expect(b.parent().sameNode(a)).to.be.true;
764             });
765             it('can access node parents', function() {
766                 var doc = getDocumentFromXML('<a><b><c></c></b></a>'),
767                     a = doc.root,
768                     b = a.contents()[0],
769                     c = b.contents()[0];
770
771                 var parents = c.parents();
772                 // @@
773                 expect(parents[0].sameNode(b)).to.be.true;
774                 expect(parents[1].sameNode(a)).to.be.true;
775             });
776         });
777
778         describe('finding sibling parents of two elements', function() {
779             it('returns elements themself if they have direct common parent', function() {
780                 var doc = getDocumentFromXML('<section><div><div>A</div><div>B</div></div></section>'),
781                     wrappingDiv = doc.root.contents()[0],
782                     divA = wrappingDiv.contents()[0],
783                     divB = wrappingDiv.contents()[1];
784
785                 var siblingParents = doc.getSiblingParents({node1: divA, node2: divB});
786
787                 expect(siblingParents.node1.sameNode(divA)).to.equal(true, 'divA');
788                 expect(siblingParents.node2.sameNode(divB)).to.equal(true, 'divB');
789             });
790
791             it('returns sibling parents - example 1', function() {
792                 var doc = getDocumentFromXML('<section>Alice <span>has a cat</span></section>'),
793                     aliceText = doc.root.contents()[0],
794                     span = doc.root.contents()[1],
795                     spanText = span.contents()[0];
796
797                 var siblingParents = doc.getSiblingParents({node1: aliceText, node2: spanText});
798
799                 expect(siblingParents.node1.sameNode(aliceText)).to.equal(true, 'aliceText');
800                 expect(siblingParents.node2.sameNode(span)).to.equal(true, 'span');
801             });
802         });
803     });
804
805     describe('Serializing document to WLXML', function() {
806         it('keeps document intact when no changes have been made', function() {
807             var xmlIn = '<section>Alice<div>has</div>a <span class="uri" meta-uri="http://cat.com">cat</span>!</section>',
808                 doc = getDocumentFromXML(xmlIn),
809                 xmlOut = doc.toXML();
810
811             var parser = new DOMParser(),
812                 input = parser.parseFromString(xmlIn, 'application/xml').childNodes[0],
813                 output = parser.parseFromString(xmlOut, 'application/xml').childNodes[0];
814             
815             expect(input.isEqualNode(output)).to.be.true;
816         });
817
818         it('keeps entities intact', function() {
819             var xmlIn = '<section>&lt; &gt;</section>',
820                 doc = getDocumentFromXML(xmlIn),
821                 xmlOut = doc.toXML();
822             expect(xmlOut).to.equal(xmlIn);
823         });
824         it('keeps entities intact when they form html/xml', function() {
825             var xmlIn = '<section>&lt;abc&gt;</section>',
826                 doc = getDocumentFromXML(xmlIn),
827                 xmlOut = doc.toXML();
828             expect(xmlOut).to.equal(xmlIn);
829         });
830     });
831
832     describe('Extension API', function() {
833         var doc, extension, elementNode, textNode;
834
835         beforeEach(function() {
836             doc = getDocumentFromXML('<section>Alice<div class="test_class"></div></section>');
837             elementNode = doc.root;
838             textNode = doc.root.contents()[0];
839             extension = {};
840             
841             expect(elementNode.testTransformation).to.be.undefined;
842             expect(textNode.testTransformation).to.be.undefined;
843             expect(doc.testTransformation).to.be.undefined;
844             
845             expect(doc.testMethod).to.be.undefined;
846             expect(elementNode.testMethod).to.be.undefined;
847             expect(textNode.testMethod).to.be.undefined;
848             expect(elementNode.elementTestMethod).to.be.undefined;
849             expect(textNode.textTestMethod).to.be.undefined;
850         });
851
852         it('allows adding method to a document', function() {
853             extension = {document: {methods: {
854                 testMethod: function() { return this; }
855             }}};
856
857             doc.registerExtension(extension);
858             expect(doc.testMethod()).to.equal(doc, 'context is set to a document instance');
859         });
860
861         it('allows adding transformation to a document', function() {
862             extension = {document: {transformations: {
863                 testTransformation: function() { return this; },
864                 testTransformation2: {impl: function() { return this;}}
865             }}};
866
867             doc.registerExtension(extension);
868             expect(doc.testTransformation()).to.equal(doc, 'context is set to a document instance');
869             expect(doc.testTransformation2()).to.equal(doc, 'context is set to a document instance');
870         });
871
872         it('allows adding method to a DocumentNode instance', function() {
873             extension = {
874                 documentNode: {
875                     methods: {
876                         testMethod: function() { return this; }
877                     }
878                 },
879                 textNode: {
880                     methods: {
881                         textTestMethod: function() { return this; }
882                     }
883                 },
884                 elementNode: {
885                     methods: {
886                         elementTestMethod: function() { return this; }
887                     }
888                 }
889             };
890
891             doc.registerExtension(extension);
892
893             /* refresh */
894             elementNode = doc.root;
895             textNode = doc.root.contents()[0];
896
897             expect(elementNode.testMethod().sameNode(elementNode)).to.equal(true, 'context is set to a node instance');
898             expect(textNode.testMethod().sameNode(textNode)).to.equal(true, 'context is set to a node instance');
899
900             expect(elementNode.elementTestMethod().sameNode(elementNode)).to.be.true;
901             expect(elementNode.textTestMethod).to.be.undefined;
902         
903             expect(textNode.textTestMethod().sameNode(textNode)).to.be.true;
904             expect(textNode.elementTestMethod).to.be.undefined;
905         });
906
907         it('allows adding transformation to a DocumentNode', function() {
908             extension = {
909                 documentNode: {
910                     transformations: {
911                         testTransformation: function() { return this; },
912                         testTransformation2: {impl: function() { return this;}}
913                     }
914                 },
915                 textNode: {
916                     transformations: {
917                         textTestTransformation: function() { return this; }
918                     }
919                 },
920                 elementNode: {
921                     transformations: {
922                         elementTestTransformation: function() { return this; }
923                     }
924                 }
925             };
926             
927             doc.registerExtension(extension);
928
929             /* refresh */
930             elementNode = doc.root;
931             textNode = doc.root.contents()[0];
932             
933             expect(elementNode.testTransformation().sameNode(elementNode)).to.equal(true, '1');
934             expect(elementNode.testTransformation2().sameNode(elementNode)).to.equal(true, '2');
935             expect(textNode.testTransformation().sameNode(textNode)).to.equal(true, '3');
936             expect(textNode.testTransformation2().sameNode(textNode)).to.equal(true, '4');
937
938             expect(elementNode.elementTestTransformation().sameNode(elementNode)).to.be.true;
939             expect(elementNode.textTestTransformation).to.be.undefined;
940         
941             expect(textNode.textTestTransformation().sameNode(textNode)).to.be.true;
942             expect(textNode.elementTestTransfomation).to.be.undefined;
943         });
944
945         it('allows text/element node methods and transformations to access node and transormations on document node', function() {
946
947             var doc = getDocumentFromXML('<div>text</div>');
948
949             doc.registerExtension({
950                 documentNode: {
951                     methods: {
952                         test: function() {
953                             return 'super';
954                         }
955                     },
956                     transformations: {
957                         testT: function() {
958                             return 'super_trans';
959                         }
960                     }
961                 },
962                 elementNode: {
963                     methods: {
964                         test: function() {
965                             return 'element_sub_' + this.__super__.test();
966                         }
967                     },
968                     transformations: {
969                         testT: function() {
970                             return 'element_trans_sub_' + this.__super__.testT();
971                         }
972                     }
973                 },
974                 textNode: {
975                     methods: {
976                         test: function() {
977                             return 'text_sub_' + this.__super__.test();
978                         }
979                     },
980                     transformations: {
981                         testT: function() {
982                             return 'text_trans_sub_' + this.__super__.testT();
983                         }
984                     }
985                 }
986             });
987
988             var textNode = doc.root.contents()[0];
989
990             expect(doc.root.test()).to.equal('element_sub_super');
991             expect(textNode.test()).to.equal('text_sub_super');
992             expect(doc.root.testT()).to.equal('element_trans_sub_super_trans');
993             expect(textNode.testT()).to.equal('text_trans_sub_super_trans');
994         });
995     });
996
997     describe('Undo/redo', function() {
998
999         it('smoke tests', function() {
1000             var doc = getDocumentFromXML('<div>Alice</div>'),
1001                 textNode = doc.root.contents()[0];
1002
1003             expect(doc.undoStack).to.have.length(0);
1004             
1005             textNode.wrapWith({tagName: 'span', start:1, end:2});
1006             expect(doc.undoStack).to.have.length(1, '1');
1007             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1008
1009             doc.undo();
1010             expect(doc.undoStack).to.have.length(0, '2');
1011             expect(doc.toXML()).to.equal('<div>Alice</div>');
1012
1013             doc.redo();
1014             expect(doc.undoStack).to.have.length(1, '3');
1015             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1016
1017             doc.undo();
1018             expect(doc.undoStack).to.have.length(0, '4');
1019             expect(doc.toXML()).to.equal('<div>Alice</div>');
1020
1021             doc.undo();
1022             expect(doc.undoStack).to.have.length(0, '5');
1023             expect(doc.toXML()).to.equal('<div>Alice</div>');
1024         });
1025
1026         it('smoke tests 2', function() {
1027             var doc = getDocumentFromXML('<div>Alice</div>'),
1028                 textNode = doc.root.contents()[0],
1029                 path = textNode.getPath();
1030
1031             textNode.setText('Alice ');
1032             textNode.setText('Alice h');
1033             textNode.setText('Alice ha');
1034             textNode.setText('Alice has');
1035
1036             expect(textNode.getText()).to.equal('Alice has');
1037
1038             doc.undo();
1039             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '1');
1040
1041             doc.undo();
1042             expect(doc.root.contents()[0].getText()).to.equal('Alice h', '2');
1043
1044             doc.redo();
1045             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '3');
1046
1047             doc.redo();
1048             expect(doc.root.contents()[0].getText()).to.equal('Alice has', '4');
1049
1050             doc.undo();
1051             doc.undo();
1052             textNode = doc.getNodeByPath(path);
1053             textNode.setText('Cat');
1054             doc.undo();
1055             textNode = doc.getNodeByPath(path);
1056             expect(textNode.getText()).to.equal('Alice h');
1057         });
1058
1059         
1060         var sampleMethod = function(val) {
1061             this._$.attr('x', val);
1062         };
1063
1064         var transformations = {
1065             'unaware': sampleMethod,
1066             'returning change root': {
1067                 impl: sampleMethod,
1068                 getChangeRoot: function() {
1069                     return this.context;
1070                 }
1071             },
1072             'implementing undo operation': {
1073                 impl: function(t, val) {
1074                     t.oldVal = this.getAttr('x');
1075                     sampleMethod.call(this, val);
1076                 },
1077                 undo: function(t) {
1078                     this.setAttr('x', t.oldVal);
1079                 }
1080             }
1081         };
1082
1083         _.pairs(transformations).forEach(function(pair) {
1084             var name = pair[0],
1085                 transformaton = pair[1];
1086
1087             describe(name + ' transformation: ', function() {
1088                 var doc, node, nodePath;
1089
1090                 beforeEach(function() {
1091                     doc = getDocumentFromXML('<div><test x="old"></test></div>');
1092
1093                     doc.registerExtension({elementNode: {transformations: {
1094                         test: transformaton
1095                     }}});
1096
1097                     node = doc.root.contents()[0];
1098                     nodePath = node.getPath();
1099                 });
1100
1101                 it('transforms as expected', function() {
1102                     node.test('new');
1103                     expect(node.getAttr('x')).to.equal('new');
1104                 });
1105
1106                 it('can be undone', function() {
1107                     node.test('new');
1108                     doc.undo();
1109                     node = doc.getNodeByPath(nodePath);
1110                     expect(node.getAttr('x')).to.equal('old');
1111                 });
1112
1113                 it('can be undone and then redone', function() {
1114                     node.test('new');
1115                     doc.undo();
1116                     doc.redo();
1117                     node = doc.getNodeByPath(nodePath);
1118                     expect(node.getAttr('x')).to.equal('new');
1119                 });
1120
1121                 it('handles a sample scenario', function() {
1122                     doc.root.contents()[0].test('1');
1123                     doc.root.contents()[0].test('2');
1124                     doc.root.contents()[0].test('3');
1125                     doc.root.contents()[0].test('4');
1126                     doc.root.contents()[0].test('5');
1127
1128                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'after initial transformations');
1129                     doc.undo();
1130                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 1.1');
1131                     doc.undo();
1132                     expect(doc.root.contents()[0].getAttr('x')).to.equal('3', 'undo 1.2');
1133                     doc.redo();
1134                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'redo 1.1');
1135                     doc.redo();
1136                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'redo 1.2');
1137                     doc.undo();
1138                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 2.1');
1139                     doc.root.contents()[0].test('10');
1140                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'additional transformation');
1141                     expect(doc.redoStack.length).to.equal(0, 'transformation cleared redo stack');
1142                     doc.redo();
1143                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'empty redoStack so redo was noop');
1144                     doc.undo();
1145                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undoing additional transformation');
1146                     doc.redo();
1147                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'redoing additional transformation');
1148                 });
1149             });
1150         });
1151
1152         it('smoke tests nested transformations', function() {
1153             var doc = getDocumentFromXML('<div></div>');
1154
1155             doc.registerExtension({elementNode: {transformations: {
1156                 nested: function(v) {
1157                     this._$.attr('innerAttr', v);
1158                 },
1159                 outer: function(v) {
1160                     this.nested(v);
1161                     this._$.attr('outerAttr', v);
1162                 }
1163             }}});
1164
1165             doc.root.outer('test1');
1166             doc.root.outer('test2');
1167
1168             expect(doc.root.getAttr('innerAttr')).to.equal('test2');
1169             expect(doc.root.getAttr('outerAttr')).to.equal('test2');
1170
1171             doc.undo();
1172
1173             expect(doc.root.getAttr('innerAttr')).to.equal('test1');
1174             expect(doc.root.getAttr('outerAttr')).to.equal('test1');
1175
1176             doc.undo();
1177
1178             expect(doc.root.getAttr('innerAttr')).to.equal(undefined);
1179             expect(doc.root.getAttr('outerAttr')).to.equal(undefined);
1180
1181             doc.redo();
1182
1183             expect(doc.root.getAttr('innerAttr')).to.equal('test1');
1184             expect(doc.root.getAttr('outerAttr')).to.equal('test1');
1185
1186             doc.redo();
1187
1188             expect(doc.root.getAttr('innerAttr')).to.equal('test2');
1189             expect(doc.root.getAttr('outerAttr')).to.equal('test2');
1190
1191         });
1192     });
1193
1194 });
1195
1196 });