|
1 // -*- Mode: js2; tab-width: 2; indent-tabs-mode: nil; js2-basic-offset: 2; js2-skip-preprocessor-directives: t; -*- |
|
2 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 "use strict"; |
|
7 |
|
8 Components.utils.import("resource:///modules/ContentUtil.jsm"); |
|
9 let Util = ContentUtil; |
|
10 |
|
11 function empty_node(node) { |
|
12 let cnode; |
|
13 while((cnode = node.firstChild)) |
|
14 node.removeChild(cnode); |
|
15 return node; |
|
16 } |
|
17 |
|
18 function DOMSerializer() { |
|
19 return Components.classes["@mozilla.org/xmlextras/xmlserializer;1"] |
|
20 .createInstance(Components.interfaces.nsIDOMSerializer); |
|
21 } |
|
22 |
|
23 function serializeContents(node) { |
|
24 let str = DOMSerializer().serializeToString(node); |
|
25 return str.replace(/^<[^>]+>/, '') |
|
26 .replace(/<\/[^>]+>$/, ''); |
|
27 } |
|
28 |
|
29 function run_test() { |
|
30 let doc, body, str, expectedResult, frag; |
|
31 |
|
32 do_print("Testing Util.populateFragmentFromString"); |
|
33 |
|
34 do_check_true(!!Util.populateFragmentFromString); |
|
35 |
|
36 do_print("Loading blank document"); |
|
37 doc = do_parse_document("blank.xhtml", "application/xhtml+xml"); |
|
38 |
|
39 // sanity check |
|
40 do_check_eq(doc.nodeType, 9); |
|
41 do_check_true(doc.documentElement.localName != "parsererror"); |
|
42 |
|
43 body = doc.documentElement.getElementsByTagName("body")[0]; |
|
44 do_check_eq(1, body.nodeType); |
|
45 |
|
46 frag = doc.createDocumentFragment(); |
|
47 |
|
48 // test proper handling of leading and trailing text |
|
49 str = "Before, #2, #1. After"; |
|
50 Util.populateFragmentFromString( |
|
51 frag, str, |
|
52 { text: "One", className: "text-one"}, |
|
53 { text: "Two", className: "text-two"} |
|
54 ); |
|
55 |
|
56 empty_node(body); |
|
57 body.appendChild(frag); |
|
58 |
|
59 expectedResult = 'Before, <span class="text-two">Two</span>, <span class="text-one">One</span>. After'; |
|
60 do_check_eq(serializeContents(body), expectedResult); |
|
61 |
|
62 // test proper handling of unspecified markers |
|
63 str = "#8080: #1. http://localhost/#bar"; |
|
64 Util.populateFragmentFromString( |
|
65 frag, str, |
|
66 { text: "One" } |
|
67 ); |
|
68 |
|
69 empty_node(body); |
|
70 body.appendChild(frag); |
|
71 |
|
72 expectedResult = '#8080: <span>One</span>. http://localhost/#bar'; |
|
73 do_check_eq(serializeContents(body), expectedResult); |
|
74 |
|
75 // test proper handling of markup in strings |
|
76 str = "#1 <body> tag. © 2000 - Some Corp\u2122"; |
|
77 Util.populateFragmentFromString( |
|
78 frag, str, |
|
79 { text: "About the" } |
|
80 ); |
|
81 |
|
82 empty_node(body); |
|
83 body.appendChild(frag); |
|
84 expectedResult = "<span>About the</span> <body> tag. &copy; 2000 - Some Corp™" |
|
85 do_check_eq(serializeContents(body), expectedResult); |
|
86 } |