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