linting, cleanup, removing unused code
[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 moved to out of document node: ' + insertionMethod, function() {
740                 var doc = getDocumentFromXML('<div><a></a></div>'),
741                     a = doc.root.contents()[0],
742                     spy = sinon.spy();
743
744                 doc.on('change', spy);
745
746                 var newNode = doc.createDocumentNode({tagName: 'b'});
747                     var newNodeInner = newNode.append({tagName:'c'});
748
749                 expect(spy.callCount).to.equal(0);
750             });
751         });
752
753
754     });
755
756     describe('Traversing', function() {
757         describe('Basic', function() {
758             it('can access node parent', function() {
759                 var doc = getDocumentFromXML('<a><b></b></a>'),
760                     a = doc.root,
761                     b = a.contents()[0];
762
763                 expect(a.parent()).to.equal(null, 'parent of a root is null');
764                 expect(b.parent().sameNode(a)).to.be.true;
765             });
766             it('can access node parents', function() {
767                 var doc = getDocumentFromXML('<a><b><c></c></b></a>'),
768                     a = doc.root,
769                     b = a.contents()[0],
770                     c = b.contents()[0];
771
772                 var parents = c.parents();
773                 // @@
774                 expect(parents[0].sameNode(b)).to.be.true;
775                 expect(parents[1].sameNode(a)).to.be.true;
776             });
777         });
778
779         describe('finding sibling parents of two elements', function() {
780             it('returns elements themself if they have direct common parent', function() {
781                 var doc = getDocumentFromXML('<section><div><div>A</div><div>B</div></div></section>'),
782                     wrappingDiv = doc.root.contents()[0],
783                     divA = wrappingDiv.contents()[0],
784                     divB = wrappingDiv.contents()[1];
785
786                 var siblingParents = doc.getSiblingParents({node1: divA, node2: divB});
787
788                 expect(siblingParents.node1.sameNode(divA)).to.equal(true, 'divA');
789                 expect(siblingParents.node2.sameNode(divB)).to.equal(true, 'divB');
790             });
791
792             it('returns sibling parents - example 1', function() {
793                 var doc = getDocumentFromXML('<section>Alice <span>has a cat</span></section>'),
794                     aliceText = doc.root.contents()[0],
795                     span = doc.root.contents()[1],
796                     spanText = span.contents()[0];
797
798                 var siblingParents = doc.getSiblingParents({node1: aliceText, node2: spanText});
799
800                 expect(siblingParents.node1.sameNode(aliceText)).to.equal(true, 'aliceText');
801                 expect(siblingParents.node2.sameNode(span)).to.equal(true, 'span');
802             });
803         });
804     });
805
806     describe('Serializing document to WLXML', function() {
807         it('keeps document intact when no changes have been made', function() {
808             var xmlIn = '<section>Alice<div>has</div>a <span class="uri" meta-uri="http://cat.com">cat</span>!</section>',
809                 doc = getDocumentFromXML(xmlIn),
810                 xmlOut = doc.toXML();
811
812             var parser = new DOMParser(),
813                 input = parser.parseFromString(xmlIn, 'application/xml').childNodes[0],
814                 output = parser.parseFromString(xmlOut, 'application/xml').childNodes[0];
815             
816             expect(input.isEqualNode(output)).to.be.true;
817         });
818
819         it('keeps entities intact', function() {
820             var xmlIn = '<section>&lt; &gt;</section>',
821                 doc = getDocumentFromXML(xmlIn),
822                 xmlOut = doc.toXML();
823             expect(xmlOut).to.equal(xmlIn);
824         });
825         it('keeps entities intact when they form html/xml', function() {
826             var xmlIn = '<section>&lt;abc&gt;</section>',
827                 doc = getDocumentFromXML(xmlIn),
828                 xmlOut = doc.toXML();
829             expect(xmlOut).to.equal(xmlIn);
830         });
831     });
832
833     describe('Extension API', function() {
834         var doc, extension, elementNode, textNode, testClassNode;
835
836         beforeEach(function() {
837             doc = getDocumentFromXML('<section>Alice<div class="test_class"></div></section>');
838             elementNode = doc.root;
839             textNode = doc.root.contents()[0];
840             extension = {};
841             
842             expect(elementNode.testTransformation).to.be.undefined;
843             expect(textNode.testTransformation).to.be.undefined;
844             expect(doc.testTransformation).to.be.undefined;
845             
846             expect(doc.testMethod).to.be.undefined;
847             expect(elementNode.testMethod).to.be.undefined;
848             expect(textNode.testMethod).to.be.undefined;
849             expect(elementNode.elementTestMethod).to.be.undefined;
850             expect(textNode.textTestMethod).to.be.undefined;
851         });
852
853         it('allows adding method to a document', function() {
854             extension = {document: {methods: {
855                 testMethod: function() { return this; }
856             }}};
857
858             doc.registerExtension(extension);
859             expect(doc.testMethod()).to.equal(doc, 'context is set to a document instance');
860         });
861
862         it('allows adding transformation to a document', function() {
863             extension = {document: {transformations: {
864                 testTransformation: function() { return this; },
865                 testTransformation2: {impl: function() { return this;}}
866             }}};
867
868             doc.registerExtension(extension);
869             expect(doc.testTransformation()).to.equal(doc, 'context is set to a document instance');
870             expect(doc.testTransformation2()).to.equal(doc, 'context is set to a document instance');
871         });
872
873         it('allows adding method to a DocumentNode instance', function() {
874             extension = {
875                 documentNode: {
876                     methods: {
877                         testMethod: function() { return this; }
878                     }
879                 },
880                 textNode: {
881                     methods: {
882                         textTestMethod: function() { return this; }
883                     }
884                 },
885                 elementNode: {
886                     methods: {
887                         elementTestMethod: function() { return this; }
888                     }
889                 }
890             };
891
892             doc.registerExtension(extension);
893
894             /* refresh */
895             elementNode = doc.root;
896             textNode = doc.root.contents()[0];
897
898             expect(elementNode.testMethod().sameNode(elementNode)).to.equal(true, 'context is set to a node instance');
899             expect(textNode.testMethod().sameNode(textNode)).to.equal(true, 'context is set to a node instance');
900
901             expect(elementNode.elementTestMethod().sameNode(elementNode)).to.be.true;
902             expect(elementNode.textTestMethod).to.be.undefined;
903         
904             expect(textNode.textTestMethod().sameNode(textNode)).to.be.true;
905             expect(textNode.elementTestMethod).to.be.undefined;
906         });
907
908         it('allows adding transformation to a DocumentNode', function() {
909             extension = {
910                 documentNode: {
911                     transformations: {
912                         testTransformation: function() { return this; },
913                         testTransformation2: {impl: function() { return this;}}
914                     }
915                 },
916                 textNode: {
917                     transformations: {
918                         textTestTransformation: function() { return this; }
919                     }
920                 },
921                 elementNode: {
922                     transformations: {
923                         elementTestTransformation: function() { return this; }
924                     }
925                 }
926             };
927             
928             doc.registerExtension(extension);
929
930             /* refresh */
931             elementNode = doc.root;
932             textNode = doc.root.contents()[0];
933             
934             expect(elementNode.testTransformation().sameNode(elementNode)).to.equal(true, '1');
935             expect(elementNode.testTransformation2().sameNode(elementNode)).to.equal(true, '2');
936             expect(textNode.testTransformation().sameNode(textNode)).to.equal(true, '3');
937             expect(textNode.testTransformation2().sameNode(textNode)).to.equal(true, '4');
938
939             expect(elementNode.elementTestTransformation().sameNode(elementNode)).to.be.true;
940             expect(elementNode.textTestTransformation).to.be.undefined;
941         
942             expect(textNode.textTestTransformation().sameNode(textNode)).to.be.true;
943             expect(textNode.elementTestTransfomation).to.be.undefined;
944         });
945
946         it('allows text/element node methods and transformations to access node and transormations on document node', function() {
947
948             var doc = getDocumentFromXML('<div>text</div>');
949
950             doc.registerExtension({
951                 documentNode: {
952                     methods: {
953                         test: function() {
954                             return 'super';
955                         }
956                     },
957                     transformations: {
958                         testT: function() {
959                             return 'super_trans';
960                         }
961                     }
962                 },
963                 elementNode: {
964                     methods: {
965                         test: function() {
966                             return 'element_sub_' + this.__super__.test();
967                         }
968                     },
969                     transformations: {
970                         testT: function() {
971                             return 'element_trans_sub_' + this.__super__.testT();
972                         }
973                     }
974                 },
975                 textNode: {
976                     methods: {
977                         test: function() {
978                             return 'text_sub_' + this.__super__.test();
979                         }
980                     },
981                     transformations: {
982                         testT: function() {
983                             return 'text_trans_sub_' + this.__super__.testT();
984                         }
985                     }
986                 }
987             });
988
989             var textNode = doc.root.contents()[0];
990
991             expect(doc.root.test()).to.equal('element_sub_super');
992             expect(textNode.test()).to.equal('text_sub_super');
993             expect(doc.root.testT()).to.equal('element_trans_sub_super_trans');
994             expect(textNode.testT()).to.equal('text_trans_sub_super_trans');
995         });
996     });
997
998     describe('Undo/redo', function() {
999
1000         it('smoke tests', function() {
1001             var doc = getDocumentFromXML('<div>Alice</div>'),
1002                 textNode = doc.root.contents()[0];
1003
1004             expect(doc.undoStack).to.have.length(0);
1005             
1006             textNode.wrapWith({tagName: 'span', start:1, end:2});
1007             expect(doc.undoStack).to.have.length(1, '1');
1008             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1009
1010             doc.undo();
1011             expect(doc.undoStack).to.have.length(0, '2');
1012             expect(doc.toXML()).to.equal('<div>Alice</div>');
1013
1014             doc.redo();
1015             expect(doc.undoStack).to.have.length(1, '3');
1016             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1017
1018             doc.undo();
1019             expect(doc.undoStack).to.have.length(0, '4');
1020             expect(doc.toXML()).to.equal('<div>Alice</div>');
1021
1022             doc.undo();
1023             expect(doc.undoStack).to.have.length(0, '5');
1024             expect(doc.toXML()).to.equal('<div>Alice</div>');
1025         });
1026
1027         it('smoke tests 2', function() {
1028             var doc = getDocumentFromXML('<div>Alice</div>'),
1029                 textNode = doc.root.contents()[0],
1030                 path = textNode.getPath();
1031
1032             textNode.setText('Alice ');
1033             textNode.setText('Alice h');
1034             textNode.setText('Alice ha');
1035             textNode.setText('Alice has');
1036
1037             expect(textNode.getText()).to.equal('Alice has');
1038
1039             doc.undo();
1040             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '1');
1041
1042             doc.undo();
1043             expect(doc.root.contents()[0].getText()).to.equal('Alice h', '2');
1044
1045             doc.redo();
1046             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '3');
1047
1048             doc.redo();
1049             expect(doc.root.contents()[0].getText()).to.equal('Alice has', '4');
1050
1051             doc.undo();
1052             doc.undo();
1053             textNode = doc.getNodeByPath(path);
1054             textNode.setText('Cat');
1055             doc.undo();
1056             textNode = doc.getNodeByPath(path);
1057             expect(textNode.getText()).to.equal('Alice h');
1058         });
1059
1060         
1061         var sampleMethod = function(val) {
1062             this._$.attr('x', val);
1063         };
1064
1065         var transformations = {
1066             'unaware': sampleMethod,
1067             'returning change root': {
1068                 impl: sampleMethod,
1069                 getChangeRoot: function() {
1070                     return this.context;
1071                 }
1072             },
1073             'implementing undo operation': {
1074                 impl: function(t, val) {
1075                     t.oldVal = this.getAttr('x');
1076                     sampleMethod.call(this, val);
1077                 },
1078                 undo: function(t) {
1079                     this.setAttr('x', t.oldVal);
1080                 }
1081             }
1082         };
1083
1084         _.pairs(transformations).forEach(function(pair) {
1085             var name = pair[0],
1086                 transformaton = pair[1];
1087
1088             describe(name + ' transformation: ', function() {
1089                 var doc, node, nodePath;
1090
1091                 beforeEach(function() {
1092                     doc = getDocumentFromXML('<div><test x="old"></test></div>');
1093
1094                     doc.registerExtension({elementNode: {transformations: {
1095                         test: transformaton
1096                     }}});
1097
1098                     node = doc.root.contents()[0];
1099                     nodePath = node.getPath();
1100                 });
1101
1102                 it('transforms as expected', function() {
1103                     node.test('new');
1104                     expect(node.getAttr('x')).to.equal('new');
1105                 });
1106
1107                 it('can be undone', function() {
1108                     node.test('new');
1109                     doc.undo();
1110                     node = doc.getNodeByPath(nodePath);
1111                     expect(node.getAttr('x')).to.equal('old');
1112                 });
1113
1114                 it('can be undone and then redone', function() {
1115                     node.test('new');
1116                     doc.undo();
1117                     doc.redo();
1118                     node = doc.getNodeByPath(nodePath);
1119                     expect(node.getAttr('x')).to.equal('new');
1120                 });
1121
1122                 it('handles a sample scenario', function() {
1123                     doc.root.contents()[0].test('1');
1124                     doc.root.contents()[0].test('2');
1125                     doc.root.contents()[0].test('3');
1126                     doc.root.contents()[0].test('4');
1127                     doc.root.contents()[0].test('5');
1128
1129                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'after initial transformations');
1130                     doc.undo();
1131                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 1.1');
1132                     doc.undo();
1133                     expect(doc.root.contents()[0].getAttr('x')).to.equal('3', 'undo 1.2');
1134                     doc.redo();
1135                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'redo 1.1');
1136                     doc.redo();
1137                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'redo 1.2');
1138                     doc.undo();
1139                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 2.1');
1140                     doc.root.contents()[0].test('10');
1141                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'additional transformation');
1142                     expect(doc.redoStack.length).to.equal(0, 'transformation cleared redo stack');
1143                     doc.redo();
1144                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'empty redoStack so redo was noop');
1145                     doc.undo();
1146                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undoing additional transformation');
1147                     doc.redo();
1148                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'redoing additional transformation');
1149                 });
1150             });
1151         });
1152
1153         // it('does work', function() {
1154         //     var doc = getDocumentFromXML('<section><span>Alice</span></section>'),
1155         //         span = doc.root.contents()[0];
1156
1157         //     span.transform('smartxml.detach');
1158
1159
1160         //     doc.undo();
1161
1162         //     expect(doc.root.contents()).to.have.length(1);
1163         //     expect(doc.root.contents()[0].getTagName()).to.equal('span');
1164         //     expect(doc.root.contents()[0].contents()[0].getText()).to.equal('Alice');
1165
1166         //     doc.redo();
1167         //     expect(doc.root.contents()).to.have.length(0);
1168
1169         //     doc.undo();
1170         //     expect(doc.root.contents()).to.have.length(1);
1171         //     expect(doc.root.contents()[0].getTagName()).to.equal('span');
1172         //     expect(doc.root.contents()[0].contents()[0].getText()).to.equal('Alice');
1173
1174         // });
1175         // it('does work - merged text nodes case', function() {
1176         //     var doc = getDocumentFromXML('<section>Alice <span>has</span> a cat.</section>'),
1177         //         span = doc.root.contents()[1];
1178
1179         //     span.transform('smartxml.detach');
1180
1181
1182         //     doc.undo();
1183
1184         //     expect(doc.root.contents().length).to.equal(3);
1185         //     //console.log(doc.toXML());
1186         //     expect(doc.root.contents()[1].contents()[0].getText()).to.equal('has');
1187
1188         // });
1189         // it('dbg - don not store nodes in tranformation state!', function() {
1190         //     var doc = getDocumentFromXML('<section><a></a><b></b></section>'),
1191         //         a = doc.root.contents()[0],
1192         //         b = doc.root.contents()[1];
1193
1194         //     a.transform('smartxml.detach');
1195         //     b.transform('smartxml.detach');
1196         //     doc.undo();
1197         //     doc.undo();
1198         //     expect(doc.root.contents().length).to.equal(2);
1199         //     expect(doc.root.contents()[0].getTagName()).to.equal('a');
1200         //     expect(doc.root.contents()[1].getTagName()).to.equal('b');
1201
1202         //     doc.redo();
1203         //     doc.redo();
1204         //     expect(doc.root.contents().length).to.equal(0);
1205
1206         // });
1207     });
1208
1209 });
1210
1211 });