smartxml: dividing text node into two with element node
[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         describe('Dividing text node into two with element node', function() {
305                 it('can divide text node with element node, splitting text node into two', function() {
306                     var doc = getDocumentFromXML('<div>Alice has a cat</div>'),
307                         text = doc.root.contents()[0];
308
309                     var returned = text.divideWithElementNode({tagName: 'aside'}, {offset: 5}),
310                         contents = doc.root.contents(),
311                         lhsText = contents[0],
312                         rhsText = contents[2];
313
314                     expect(lhsText.getText()).to.equal('Alice');
315                     expect(returned.sameNode(contents[1]));
316                     expect(rhsText.getText()).to.equal(' has a cat');
317                 });
318
319                 it('treats dividing at the very end as appending after it', function() {
320                     var doc = getDocumentFromXML('<div>Alice has a cat</div>'),
321                         text = doc.root.contents()[0];
322
323
324                     var returned = text.divideWithElementNode({tagName: 'aside'}, {offset: 15}),
325                         contents = doc.root.contents(),
326                         textNode = contents[0],
327                         elementNode = contents[1];
328
329                     expect(contents.length).to.equal(2);
330                     expect(textNode.getText()).to.equal('Alice has a cat');
331                     expect(returned.sameNode(elementNode)).to.be.true;
332                     expect(elementNode.getTagName()).to.equal('aside');
333                 });
334
335                 it('treats dividing at the very beginning as prepending before it', function() {
336                     var doc = getDocumentFromXML('<div>Alice has a cat</div>'),
337                         text = doc.root.contents()[0];
338
339                     var returned = text.divideWithElementNode({tagName: 'aside'}, {offset: 0}),
340                         contents = doc.root.contents(),
341                         textNode = contents[1],
342                         elementNode = contents[0];
343
344                     expect(contents.length).to.equal(2);
345                     expect(textNode.getText()).to.equal('Alice has a cat');
346                     expect(returned.sameNode(elementNode)).to.be.true;
347                     expect(elementNode.getTagName()).to.equal('aside');
348                 });
349         });
350     });
351
352     describe('Manipulations', function() {
353
354         describe('replacing node with another one', function() {
355             it('replaces node with another one', function() {
356                 var doc = getDocumentFromXML('<div><a></a></div>'),
357                     a = doc.root.contents()[0];
358
359                 var c = a.replaceWith({tagName: 'b', attrs: {b:'1'}});
360
361                 expect(doc.root.contents()[0].sameNode(c));
362                 expect(c.getTagName()).to.equal('b');
363                 expect(c.getAttr('b')).to.equal('1');
364             });
365             it('can replace document root', function() {
366                 var doc = getDocumentFromXML('<div></div>');
367
368                 var header = doc.root.replaceWith({tagName: 'header'});
369
370                 expect(doc.root.sameNode(header)).to.be.true;
371                 expect(doc.containsNode(header)).to.be.true;
372             });
373         });
374
375         it('merges adjacent text nodes resulting from detaching an element node in between', function() {
376             var doc = getDocumentFromXML('<div>Alice <span>has</span>a cat</div>'),
377                 span = doc.root.contents()[1];
378
379             span.detach();
380
381             var rootContents = doc.root.contents();
382             expect(rootContents).to.have.length(1, 'one child left');
383             expect(rootContents[0].getText()).to.equal('Alice a cat');
384         });
385
386         it('inserts node at index', function() {
387             var doc = getDocumentFromXML('<div><a></a><b></b><c></c></div>'),
388                 b = doc.root.contents()[1];
389
390             var inserted = doc.root.insertAtIndex({tagName: 'test'}, 1);
391
392             expect(doc.root.contents()[1].sameNode(inserted)).to.equal(true, 'inserted node returned');
393             expect(b.getIndex()).to.equal(2, 'b node shifted right');
394         });
395
396         it('appends node when inserting node at index out of range', function() {
397             var doc = getDocumentFromXML('<div></div>');
398
399             var test1 = doc.root.insertAtIndex({tagName: 'test1'}, 0),
400                 test2 = doc.root.insertAtIndex({tagName: 'test1'}, 10);
401
402             expect(doc.root.contents()[0].sameNode(test1)).to.equal(true, 'inserting at index 0 of empty nodes appends node');
403             expect(doc.root.contents().length).to.equal(1, 'inserting at index out of range does nothing');
404             expect(test2).to.equal(undefined, 'inserting at index out of range returns undefined');
405         });
406
407         it('appends element node to another element node', function() {
408             var node1 = elementNodeFromParams({tag: 'div'}),
409                 node2 = elementNodeFromParams({tag: 'a'}),
410                 node3 = elementNodeFromParams({tag: 'p'});
411             node1.append(node2);
412             node1.append(node3);
413             expect(node1.contents()[0].sameNode(node2)).to.be.true;
414             expect(node1.contents()[1].sameNode(node3)).to.be.true;
415         });
416
417         it('prepends element node to another element node', function() {
418             var node1 = elementNodeFromParams({tag: 'div'}),
419                 node2 = elementNodeFromParams({tag: 'a'}),
420                 node3 = elementNodeFromParams({tag: 'p'});
421             node1.prepend(node2);
422             node1.prepend(node3);
423             expect(node1.contents()[0].sameNode(node3)).to.be.true;
424             expect(node1.contents()[1].sameNode(node2)).to.be.true;
425         });
426
427         it('wraps element node with another element node', function() {
428             var node = elementNodeFromXML('<div></div>'),
429                 wrapper = elementNodeFromXML('<wrapper></wrapper>');
430
431             node.wrapWith(wrapper);
432             expect(node.parent().sameNode(wrapper)).to.be.true;
433         });
434
435         it('unwraps element node contents', function() {
436             var node = elementNodeFromXML('<div>Alice <div>has <span>propably</span> a cat</div>!</div>'),
437                 outerDiv = node.contents()[1];
438             
439             outerDiv.unwrapContent();
440
441             expect(node.contents().length).to.equal(3);
442             expect(node.contents()[0].getText()).to.equal('Alice has ');
443             expect(node.contents()[1].getTagName()).to.equal('span');
444             expect(node.contents()[2].getText()).to.equal(' a cat!');
445         });
446
447         it('unwrap single element node from its parent', function() {
448             var doc = getDocumentFromXML('<div><a><b></b></a></div>'),
449                 div = doc.root,
450                 a = div.contents()[0],
451                 b = a.contents()[0];
452
453             var parent = b.unwrap();
454
455             expect(parent.sameNode(div)).to.equal(true, 'returns new parent');
456             expect(div.contents()).to.have.length(1, 'root contains only one node');
457             expect(div.contents()[0].sameNode(b)).to.equal(true, 'node got unwrapped');
458         });
459
460         it('unwrap single text node from its parent', function() {
461             var doc = getDocumentFromXML('<div>Some <span>text</span>!</div>'),
462                 div = doc.root,
463                 span = div.contents()[1],
464                 text = span.contents()[0];
465
466             var parent = text.unwrap();
467
468             expect(parent.sameNode(div)).to.equal(true, 'returns new parent');
469             expect(div.contents()).to.have.length(1, 'root contains only one node');
470             expect(div.contents()[0].getText()).to.equal('Some text!');
471         });
472
473         describe('Wrapping text', function() {
474             it('wraps text spanning multiple sibling TextNodes', function() {
475                 var section = elementNodeFromXML('<section>Alice has a <span>small</span> cat</section>'),
476                     wrapper = section.wrapText({
477                         _with: {tagName: 'span', attrs: {'attr1': 'value1'}},
478                         offsetStart: 6,
479                         offsetEnd: 4,
480                         textNodeIdx: [0,2]
481                     });
482
483                 expect(section.contents().length).to.equal(2);
484                 expect(section.contents()[0].nodeType).to.equal(Node.TEXT_NODE);
485                 expect(section.contents()[0].getText()).to.equal('Alice ');
486
487                 var wrapper2 = section.contents()[1];
488                 expect(wrapper2.sameNode(wrapper)).to.be.true;
489                 expect(wrapper.getTagName()).to.equal('span');
490
491                 var wrapperContents = wrapper.contents();
492                 expect(wrapperContents.length).to.equal(3);
493                 expect(wrapperContents[0].getText()).to.equal('has a ');
494
495                 expect(wrapperContents[1].nodeType).to.equal(Node.ELEMENT_NODE);
496                 expect(wrapperContents[1].contents().length).to.equal(1);
497                 expect(wrapperContents[1].contents()[0].getText()).to.equal('small');
498             });
499         });
500
501         describe('Wrapping Nodes', function() {
502             it('wraps multiple sibling nodes', function() {
503                 var section = elementNodeFromXML('<section>Alice<div>has</div><div>a cat</div></section>'),
504                     aliceText = section.contents()[0],
505                     firstDiv = section.contents()[1],
506                     lastDiv = section.contents()[section.contents().length -1];
507
508                 var returned = section.document.wrapNodes({
509                         node1: aliceText,
510                         node2: lastDiv,
511                         _with: {tagName: 'header'}
512                     });
513
514                 var sectionContentss = section.contents(),
515                     header = sectionContentss[0],
516                     headerContents = header.contents();
517
518                 expect(sectionContentss).to.have.length(1);
519                 expect(header.sameNode(returned)).to.equal(true, 'wrapper returned');
520                 expect(header.parent().sameNode(section)).to.be.true;
521                 expect(headerContents).to.have.length(3);
522                 expect(headerContents[0].sameNode(aliceText)).to.equal(true, 'first node wrapped');
523                 expect(headerContents[1].sameNode(firstDiv)).to.equal(true, 'second node wrapped');
524                 expect(headerContents[2].sameNode(lastDiv)).to.equal(true, 'third node wrapped');
525             });
526
527             it('wraps multiple sibling Elements - middle case', function() {
528                 var section = elementNodeFromXML('<section><div></div><div></div><div></div><div></div></section>'),
529                     div2 = section.contents()[1],
530                     div3 = section.contents()[2];
531
532                 section.document.wrapNodes({
533                         node1: div2,
534                         node2: div3,
535                         _with: {tagName: 'header'}
536                     });
537
538                 var sectionContentss = section.contents(),
539                     header = sectionContentss[1],
540                     headerChildren = header.contents();
541
542                 expect(sectionContentss).to.have.length(3);
543                 expect(headerChildren).to.have.length(2);
544                 expect(headerChildren[0].sameNode(div2)).to.equal(true, 'first node wrapped');
545                 expect(headerChildren[1].sameNode(div3)).to.equal(true, 'second node wrapped');
546             });
547         });
548
549     });
550
551     describe('Splitting text', function() {
552     
553         it('splits TextNode\'s parent into two ElementNodes', function() {
554             var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
555                 section = doc.root,
556                 text = section.contents()[0].contents()[0];
557
558             var returnedValue = text.split({offset: 5});
559             expect(section.contents().length).to.equal(2, 'section has two children');
560             
561             var header1 = section.contents()[0];
562             var header2 = section.contents()[1];
563
564             expect(header1.getTagName()).to.equal('header', 'first section child ok');
565             expect(header1.contents().length).to.equal(1, 'first header has one child');
566             expect(header1.contents()[0].getText()).to.equal('Some ', 'first header has correct content');
567             expect(header2.getTagName()).to.equal('header', 'second section child ok');
568             expect(header2.contents().length).to.equal(1, 'second header has one child');
569             expect(header2.contents()[0].getText()).to.equal('header', 'second header has correct content');
570
571             expect(returnedValue.first.sameNode(header1)).to.equal(true, 'first node returned');
572             expect(returnedValue.second.sameNode(header2)).to.equal(true, 'second node returned');
573         });
574
575         it('leaves empty copy of ElementNode if splitting at the very beginning', function() {
576                 var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
577                 section = doc.root,
578                 text = section.contents()[0].contents()[0];
579
580                 text.split({offset: 0});
581                 
582                 var header1 = section.contents()[0];
583                 var header2 = section.contents()[1];
584
585                 expect(header1.contents().length).to.equal(0);
586                 expect(header2.contents()[0].getText()).to.equal('Some header');
587         });
588
589         it('leaves empty copy of ElementNode if splitting at the very end', function() {
590                 var doc = getDocumentFromXML('<section><header>Some header</header></section>'),
591                 section = doc.root,
592                 text = section.contents()[0].contents()[0];
593
594                 text.split({offset: 11});
595                 
596                 var header1 = section.contents()[0];
597                 var header2 = section.contents()[1];
598
599                 expect(header1.contents()[0].getText()).to.equal('Some header');
600                 expect(header2.contents().length).to.equal(0);
601         });
602
603         it('keeps TextNodes\'s parent\'s children elements intact', function() {
604             var doc = getDocumentFromXML('<section><header>A <span>fancy</span> and <span>nice</span> header</header></section>'),
605                 section = doc.root,
606                 header = section.contents()[0],
607                 textAnd = header.contents()[2];
608
609             textAnd.split({offset: 2});
610             
611             var sectionContents = section.contents();
612             expect(sectionContents.length).to.equal(2, 'Section has two children');
613             expect(sectionContents[0].getTagName()).to.equal('header', 'First section node is a header');
614             expect(sectionContents[1].getTagName()).to.equal('header', 'Second section node is a header');
615
616             var firstHeaderContents = sectionContents[0].contents();
617             expect(firstHeaderContents.length).to.equal(3, 'First header has three children');
618             expect(firstHeaderContents[0].getText()).to.equal('A ', 'First header starts with a text');
619             expect(firstHeaderContents[1].getTagName()).to.equal('span', 'First header has span in the middle');
620             expect(firstHeaderContents[2].getText()).to.equal(' a', 'First header ends with text');
621
622             var secondHeaderContents = sectionContents[1].contents();
623             expect(secondHeaderContents.length).to.equal(3, 'Second header has three children');
624             expect(secondHeaderContents[0].getText()).to.equal('nd ', 'Second header starts with text');
625             expect(secondHeaderContents[1].getTagName()).to.equal('span', 'Second header has span in the middle');
626             expect(secondHeaderContents[2].getText()).to.equal(' header', 'Second header ends with text');
627         });
628     });
629
630     describe('Events', function() {
631         it('emits nodeDetached event on node detach', function() {
632             var node = elementNodeFromXML('<div><div></div></div>'),
633                 innerNode = node.contents()[0],
634                 spy = sinon.spy();
635             node.document.on('change', spy);
636             
637             var detached = innerNode.detach(),
638                 event = spy.args[0][0];
639
640             expect(event.type).to.equal('nodeDetached');
641             expect(event.meta.node.sameNode(detached, 'detached node in event meta'));
642             expect(event.meta.parent.sameNode(node), 'original parent node in event meta');
643         }),
644
645         it('emits nodeAdded event when appending new node', function() {
646             var node = elementNodeFromXML('<div></div>'),
647                 spy = sinon.spy();
648             node.document.on('change', spy);
649             
650             var appended = node.append({tagName:'div'}),
651                 event = spy.args[0][0];
652             expect(event.type).to.equal('nodeAdded');
653             expect(event.meta.node.sameNode(appended)).to.be.true;
654         });
655         
656         it('emits nodeMoved when appending aready existing node', function() {
657             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
658                 a = node.contents()[0],
659                 b = node.contents()[1],
660                 spy = sinon.spy();
661             node.document.on('change', spy);
662             
663             var appended = a.append(b),
664                 event = spy.args[0][0];
665
666             expect(spy.callCount).to.equal(1);
667             expect(event.type).to.equal('nodeMoved');
668             expect(event.meta.node.sameNode(appended)).to.be.true;
669         });
670         
671         it('emits nodeAdded event when prepending new node', function() {
672             var node = elementNodeFromXML('<div></div>'),
673                 spy = sinon.spy();
674             node.document.on('change', spy);
675             
676             var prepended = node.prepend({tagName:'div'}),
677                 event = spy.args[0][0];
678             expect(event.type).to.equal('nodeAdded');
679             expect(event.meta.node.sameNode(prepended)).to.be.true;
680         });
681         
682         it('emits nodeMoved when prepending aready existing node', function() {
683             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
684                 a = node.contents()[0],
685                 b = node.contents()[1],
686                 spy = sinon.spy();
687             node.document.on('change', spy);
688             
689             var prepended = a.prepend(b),
690                 event = spy.args[0][0];
691             expect(spy.callCount).to.equal(1);
692             expect(event.type).to.equal('nodeMoved');
693             expect(event.meta.node.sameNode(prepended)).to.be.true;
694         });
695         
696         it('emits nodeAdded event when inserting node after another', function() {
697             var node = elementNodeFromXML('<div><a></a></div>').contents()[0],
698                 spy = sinon.spy();
699             node.document.on('change', spy);
700             
701             var inserted = node.after({tagName:'div'}),
702                 event = spy.args[0][0];
703             expect(event.type).to.equal('nodeAdded');
704             expect(event.meta.node.sameNode(inserted)).to.be.true;
705         });
706         
707         it('emits nodeMoved when inserting aready existing node after another', function() {
708             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
709                 a = node.contents()[0],
710                 b = node.contents()[1],
711                 spy = sinon.spy();
712             node.document.on('change', spy);
713             var inserted = b.after(a),
714                 event = spy.args[0][0];
715
716             expect(spy.callCount).to.equal(1);
717             expect(event.type).to.equal('nodeMoved');
718             expect(event.meta.node.sameNode(inserted)).to.be.true;
719         });
720
721         it('emits nodeAdded event when inserting node before another', function() {
722             var node = elementNodeFromXML('<div><a></a></div>').contents()[0],
723                 spy = sinon.spy();
724             node.document.on('change', spy);
725             
726             var inserted = node.before({tagName:'div'}),
727                 event = spy.args[0][0];
728             expect(event.type).to.equal('nodeAdded');
729             expect(event.meta.node.sameNode(inserted)).to.be.true;
730         });
731         
732         it('emits nodeAdded when inserting aready existing node before another', function() {
733             var node = elementNodeFromXML('<div><a></a><b></b></div>'),
734                 a = node.contents()[0],
735                 b = node.contents()[1],
736                 spy = sinon.spy();
737             node.document.on('change', spy);
738             var inserted = a.before(b),
739                 event = spy.args[0][0];
740
741             expect(spy.callCount).to.equal(1);
742             expect(event.type).to.equal('nodeMoved');
743             expect(event.meta.node.sameNode(inserted)).to.be.true;
744         });
745
746         it('emits nodeDetached and nodeAdded when replacing root node with another', function() {
747             var doc = getDocumentFromXML('<a></a>'),
748                 oldRoot = doc.root,
749                 spy = sinon.spy();
750
751             doc.on('change', spy);
752
753             doc.root.replaceWith({tagName: 'b'});
754
755             expect(spy.callCount).to.equal(2);
756
757             var event1 = spy.args[0][0],
758                 event2 = spy.args[1][0];
759
760             expect(event1.type).to.equal('nodeDetached');
761             expect(event1.meta.node.sameNode(oldRoot)).to.equal(true, 'root node in nodeDetached event metadata');
762             expect(event2.type).to.equal('nodeAdded');
763             expect(event2.meta.node.sameNode(doc.root)).to.equal(true, 'new root node in nodelAdded event meta');
764         });
765
766
767         ['append', 'prepend', 'before', 'after'].forEach(function(insertionMethod) {
768             it('emits nodeDetached for node moved from a document tree to out of document node ' + insertionMethod, function() {
769                 var doc = getDocumentFromXML('<div><a></a></div>'),
770                     a = doc.root.contents()[0],
771                     spy = sinon.spy();
772
773                 doc.on('change', spy);
774
775                 var newNode = doc.createDocumentNode({tagName: 'b'}),
776                     newNodeInner = newNode.append({tagName:'c'});
777
778                 newNodeInner[insertionMethod](a);
779
780                 var event = spy.args[0][0];
781                 expect(event.type).to.equal('nodeDetached');
782                 expect(event.meta.node.sameNode(a));
783             });
784
785             it('doesn\'t emit nodeDetached event for already out of document node moved to out of document node' + insertionMethod, function() {
786                 var doc = getDocumentFromXML('<div><a></a></div>'),
787                     spy = sinon.spy();
788
789                 doc.on('change', spy);
790
791                 var newNode = doc.createDocumentNode({tagName: 'b'});
792                 newNode.append({tagName:'c'});
793
794                 expect(spy.callCount).to.equal(0);
795             });
796         });
797
798
799     });
800
801     describe('Traversing', function() {
802         describe('Basic', function() {
803             it('can access node parent', function() {
804                 var doc = getDocumentFromXML('<a><b></b></a>'),
805                     a = doc.root,
806                     b = a.contents()[0];
807
808                 expect(a.parent()).to.equal(null, 'parent of a root is null');
809                 expect(b.parent().sameNode(a)).to.be.true;
810             });
811             it('can access node parents', function() {
812                 var doc = getDocumentFromXML('<a><b><c></c></b></a>'),
813                     a = doc.root,
814                     b = a.contents()[0],
815                     c = b.contents()[0];
816
817                 var parents = c.parents();
818                 // @@
819                 expect(parents[0].sameNode(b)).to.be.true;
820                 expect(parents[1].sameNode(a)).to.be.true;
821             });
822         });
823
824         describe('finding sibling parents of two elements', function() {
825             it('returns elements themself if they have direct common parent', function() {
826                 var doc = getDocumentFromXML('<section><div><div>A</div><div>B</div></div></section>'),
827                     wrappingDiv = doc.root.contents()[0],
828                     divA = wrappingDiv.contents()[0],
829                     divB = wrappingDiv.contents()[1];
830
831                 var siblingParents = doc.getSiblingParents({node1: divA, node2: divB});
832
833                 expect(siblingParents.node1.sameNode(divA)).to.equal(true, 'divA');
834                 expect(siblingParents.node2.sameNode(divB)).to.equal(true, 'divB');
835             });
836
837             it('returns sibling parents - example 1', function() {
838                 var doc = getDocumentFromXML('<section>Alice <span>has a cat</span></section>'),
839                     aliceText = doc.root.contents()[0],
840                     span = doc.root.contents()[1],
841                     spanText = span.contents()[0];
842
843                 var siblingParents = doc.getSiblingParents({node1: aliceText, node2: spanText});
844
845                 expect(siblingParents.node1.sameNode(aliceText)).to.equal(true, 'aliceText');
846                 expect(siblingParents.node2.sameNode(span)).to.equal(true, 'span');
847             });
848         });
849     });
850
851     describe('Serializing document to WLXML', function() {
852         it('keeps document intact when no changes have been made', function() {
853             var xmlIn = '<section>Alice<div>has</div>a <span class="uri" meta-uri="http://cat.com">cat</span>!</section>',
854                 doc = getDocumentFromXML(xmlIn),
855                 xmlOut = doc.toXML();
856
857             var parser = new DOMParser(),
858                 input = parser.parseFromString(xmlIn, 'application/xml').childNodes[0],
859                 output = parser.parseFromString(xmlOut, 'application/xml').childNodes[0];
860             
861             expect(input.isEqualNode(output)).to.be.true;
862         });
863
864         it('keeps entities intact', function() {
865             var xmlIn = '<section>&lt; &gt;</section>',
866                 doc = getDocumentFromXML(xmlIn),
867                 xmlOut = doc.toXML();
868             expect(xmlOut).to.equal(xmlIn);
869         });
870         it('keeps entities intact when they form html/xml', function() {
871             var xmlIn = '<section>&lt;abc&gt;</section>',
872                 doc = getDocumentFromXML(xmlIn),
873                 xmlOut = doc.toXML();
874             expect(xmlOut).to.equal(xmlIn);
875         });
876     });
877
878     describe('Extension API', function() {
879         var doc, extension, elementNode, textNode;
880
881         beforeEach(function() {
882             doc = getDocumentFromXML('<section>Alice<div class="test_class"></div></section>');
883             elementNode = doc.root;
884             textNode = doc.root.contents()[0];
885             extension = {};
886             
887             expect(elementNode.testTransformation).to.be.undefined;
888             expect(textNode.testTransformation).to.be.undefined;
889             expect(doc.testTransformation).to.be.undefined;
890             
891             expect(doc.testMethod).to.be.undefined;
892             expect(elementNode.testMethod).to.be.undefined;
893             expect(textNode.testMethod).to.be.undefined;
894             expect(elementNode.elementTestMethod).to.be.undefined;
895             expect(textNode.textTestMethod).to.be.undefined;
896         });
897
898         it('allows adding method to a document', function() {
899             extension = {document: {methods: {
900                 testMethod: function() { return this; }
901             }}};
902
903             doc.registerExtension(extension);
904             expect(doc.testMethod()).to.equal(doc, 'context is set to a document instance');
905         });
906
907         it('allows adding transformation to a document', function() {
908             extension = {document: {transformations: {
909                 testTransformation: function() { return this; },
910                 testTransformation2: {impl: function() { return this;}}
911             }}};
912
913             doc.registerExtension(extension);
914             expect(doc.testTransformation()).to.equal(doc, 'context is set to a document instance');
915             expect(doc.testTransformation2()).to.equal(doc, 'context is set to a document instance');
916         });
917
918         it('allows adding method to a DocumentNode instance', function() {
919             extension = {
920                 documentNode: {
921                     methods: {
922                         testMethod: function() { return this; }
923                     }
924                 },
925                 textNode: {
926                     methods: {
927                         textTestMethod: function() { return this; }
928                     }
929                 },
930                 elementNode: {
931                     methods: {
932                         elementTestMethod: function() { return this; }
933                     }
934                 }
935             };
936
937             doc.registerExtension(extension);
938
939             /* refresh */
940             elementNode = doc.root;
941             textNode = doc.root.contents()[0];
942
943             expect(elementNode.testMethod().sameNode(elementNode)).to.equal(true, 'context is set to a node instance');
944             expect(textNode.testMethod().sameNode(textNode)).to.equal(true, 'context is set to a node instance');
945
946             expect(elementNode.elementTestMethod().sameNode(elementNode)).to.be.true;
947             expect(elementNode.textTestMethod).to.be.undefined;
948         
949             expect(textNode.textTestMethod().sameNode(textNode)).to.be.true;
950             expect(textNode.elementTestMethod).to.be.undefined;
951         });
952
953         it('allows adding transformation to a DocumentNode', function() {
954             extension = {
955                 documentNode: {
956                     transformations: {
957                         testTransformation: function() { return this; },
958                         testTransformation2: {impl: function() { return this;}}
959                     }
960                 },
961                 textNode: {
962                     transformations: {
963                         textTestTransformation: function() { return this; }
964                     }
965                 },
966                 elementNode: {
967                     transformations: {
968                         elementTestTransformation: function() { return this; }
969                     }
970                 }
971             };
972             
973             doc.registerExtension(extension);
974
975             /* refresh */
976             elementNode = doc.root;
977             textNode = doc.root.contents()[0];
978             
979             expect(elementNode.testTransformation().sameNode(elementNode)).to.equal(true, '1');
980             expect(elementNode.testTransformation2().sameNode(elementNode)).to.equal(true, '2');
981             expect(textNode.testTransformation().sameNode(textNode)).to.equal(true, '3');
982             expect(textNode.testTransformation2().sameNode(textNode)).to.equal(true, '4');
983
984             expect(elementNode.elementTestTransformation().sameNode(elementNode)).to.be.true;
985             expect(elementNode.textTestTransformation).to.be.undefined;
986         
987             expect(textNode.textTestTransformation().sameNode(textNode)).to.be.true;
988             expect(textNode.elementTestTransfomation).to.be.undefined;
989         });
990
991         it('allows text/element node methods and transformations to access node and transormations on document node', function() {
992
993             var doc = getDocumentFromXML('<div>text</div>');
994
995             doc.registerExtension({
996                 documentNode: {
997                     methods: {
998                         test: function() {
999                             return 'super';
1000                         }
1001                     },
1002                     transformations: {
1003                         testT: function() {
1004                             return 'super_trans';
1005                         }
1006                     }
1007                 },
1008                 elementNode: {
1009                     methods: {
1010                         test: function() {
1011                             return 'element_sub_' + this.__super__.test();
1012                         }
1013                     },
1014                     transformations: {
1015                         testT: function() {
1016                             return 'element_trans_sub_' + this.__super__.testT();
1017                         }
1018                     }
1019                 },
1020                 textNode: {
1021                     methods: {
1022                         test: function() {
1023                             return 'text_sub_' + this.__super__.test();
1024                         }
1025                     },
1026                     transformations: {
1027                         testT: function() {
1028                             return 'text_trans_sub_' + this.__super__.testT();
1029                         }
1030                     }
1031                 }
1032             });
1033
1034             var textNode = doc.root.contents()[0];
1035
1036             expect(doc.root.test()).to.equal('element_sub_super');
1037             expect(textNode.test()).to.equal('text_sub_super');
1038             expect(doc.root.testT()).to.equal('element_trans_sub_super_trans');
1039             expect(textNode.testT()).to.equal('text_trans_sub_super_trans');
1040         });
1041     });
1042
1043     describe('Undo/redo', function() {
1044
1045         it('smoke tests', function() {
1046             var doc = getDocumentFromXML('<div>Alice</div>'),
1047                 textNode = doc.root.contents()[0];
1048
1049             expect(doc.undoStack).to.have.length(0);
1050             
1051             textNode.wrapWith({tagName: 'span', start:1, end:2});
1052             expect(doc.undoStack).to.have.length(1, '1');
1053             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1054
1055             doc.undo();
1056             expect(doc.undoStack).to.have.length(0, '2');
1057             expect(doc.toXML()).to.equal('<div>Alice</div>');
1058
1059             doc.redo();
1060             expect(doc.undoStack).to.have.length(1, '3');
1061             expect(doc.toXML()).to.equal('<div>A<span>l</span>ice</div>');
1062
1063             doc.undo();
1064             expect(doc.undoStack).to.have.length(0, '4');
1065             expect(doc.toXML()).to.equal('<div>Alice</div>');
1066
1067             doc.undo();
1068             expect(doc.undoStack).to.have.length(0, '5');
1069             expect(doc.toXML()).to.equal('<div>Alice</div>');
1070         });
1071
1072         it('smoke tests 2', function() {
1073             var doc = getDocumentFromXML('<div>Alice</div>'),
1074                 textNode = doc.root.contents()[0],
1075                 path = textNode.getPath();
1076
1077             textNode.setText('Alice ');
1078             textNode.setText('Alice h');
1079             textNode.setText('Alice ha');
1080             textNode.setText('Alice has');
1081
1082             expect(textNode.getText()).to.equal('Alice has');
1083
1084             doc.undo();
1085             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '1');
1086
1087             doc.undo();
1088             expect(doc.root.contents()[0].getText()).to.equal('Alice h', '2');
1089
1090             doc.redo();
1091             expect(doc.root.contents()[0].getText()).to.equal('Alice ha', '3');
1092
1093             doc.redo();
1094             expect(doc.root.contents()[0].getText()).to.equal('Alice has', '4');
1095
1096             doc.undo();
1097             doc.undo();
1098             textNode = doc.getNodeByPath(path);
1099             textNode.setText('Cat');
1100             doc.undo();
1101             textNode = doc.getNodeByPath(path);
1102             expect(textNode.getText()).to.equal('Alice h');
1103         });
1104
1105         
1106         var sampleMethod = function(val) {
1107             this._$.attr('x', val);
1108         };
1109
1110         var transformations = {
1111             'unaware': sampleMethod,
1112             'returning change root': {
1113                 impl: sampleMethod,
1114                 getChangeRoot: function() {
1115                     return this.context;
1116                 }
1117             },
1118             'implementing undo operation': {
1119                 impl: function(t, val) {
1120                     t.oldVal = this.getAttr('x');
1121                     sampleMethod.call(this, val);
1122                 },
1123                 undo: function(t) {
1124                     this.setAttr('x', t.oldVal);
1125                 }
1126             }
1127         };
1128
1129         _.pairs(transformations).forEach(function(pair) {
1130             var name = pair[0],
1131                 transformaton = pair[1];
1132
1133             describe(name + ' transformation: ', function() {
1134                 var doc, node, nodePath;
1135
1136                 beforeEach(function() {
1137                     doc = getDocumentFromXML('<div><test x="old"></test></div>');
1138
1139                     doc.registerExtension({elementNode: {transformations: {
1140                         test: transformaton
1141                     }}});
1142
1143                     node = doc.root.contents()[0];
1144                     nodePath = node.getPath();
1145                 });
1146
1147                 it('transforms as expected', function() {
1148                     node.test('new');
1149                     expect(node.getAttr('x')).to.equal('new');
1150                 });
1151
1152                 it('can be undone', function() {
1153                     node.test('new');
1154                     doc.undo();
1155                     node = doc.getNodeByPath(nodePath);
1156                     expect(node.getAttr('x')).to.equal('old');
1157                 });
1158
1159                 it('can be undone and then redone', function() {
1160                     node.test('new');
1161                     doc.undo();
1162                     doc.redo();
1163                     node = doc.getNodeByPath(nodePath);
1164                     expect(node.getAttr('x')).to.equal('new');
1165                 });
1166
1167                 it('handles a sample scenario', function() {
1168                     doc.root.contents()[0].test('1');
1169                     doc.root.contents()[0].test('2');
1170                     doc.root.contents()[0].test('3');
1171                     doc.root.contents()[0].test('4');
1172                     doc.root.contents()[0].test('5');
1173
1174                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'after initial transformations');
1175                     doc.undo();
1176                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 1.1');
1177                     doc.undo();
1178                     expect(doc.root.contents()[0].getAttr('x')).to.equal('3', 'undo 1.2');
1179                     doc.redo();
1180                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'redo 1.1');
1181                     doc.redo();
1182                     expect(doc.root.contents()[0].getAttr('x')).to.equal('5', 'redo 1.2');
1183                     doc.undo();
1184                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undo 2.1');
1185                     doc.root.contents()[0].test('10');
1186                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'additional transformation');
1187                     expect(doc.redoStack.length).to.equal(0, 'transformation cleared redo stack');
1188                     doc.redo();
1189                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'empty redoStack so redo was noop');
1190                     doc.undo();
1191                     expect(doc.root.contents()[0].getAttr('x')).to.equal('4', 'undoing additional transformation');
1192                     doc.redo();
1193                     expect(doc.root.contents()[0].getAttr('x')).to.equal('10', 'redoing additional transformation');
1194                 });
1195             });
1196         });
1197
1198         it('smoke tests nested transformations', function() {
1199             var doc = getDocumentFromXML('<div></div>');
1200
1201             doc.registerExtension({elementNode: {transformations: {
1202                 nested: function(v) {
1203                     this._$.attr('innerAttr', v);
1204                 },
1205                 outer: function(v) {
1206                     this.nested(v);
1207                     this._$.attr('outerAttr', v);
1208                 }
1209             }}});
1210
1211             doc.root.outer('test1');
1212             doc.root.outer('test2');
1213
1214             expect(doc.root.getAttr('innerAttr')).to.equal('test2');
1215             expect(doc.root.getAttr('outerAttr')).to.equal('test2');
1216
1217             doc.undo();
1218
1219             expect(doc.root.getAttr('innerAttr')).to.equal('test1');
1220             expect(doc.root.getAttr('outerAttr')).to.equal('test1');
1221
1222             doc.undo();
1223
1224             expect(doc.root.getAttr('innerAttr')).to.equal(undefined);
1225             expect(doc.root.getAttr('outerAttr')).to.equal(undefined);
1226
1227             doc.redo();
1228
1229             expect(doc.root.getAttr('innerAttr')).to.equal('test1');
1230             expect(doc.root.getAttr('outerAttr')).to.equal('test1');
1231
1232             doc.redo();
1233
1234             expect(doc.root.getAttr('innerAttr')).to.equal('test2');
1235             expect(doc.root.getAttr('outerAttr')).to.equal('test2');
1236
1237         });
1238     });
1239
1240 });
1241
1242 });