Browse Source

Allow for self-closing tags

master
Dylan Baker 5 years ago
parent
commit
31f584d688
2 changed files with 47 additions and 1 deletions
  1. 30
    1
      src/compiler.js
  2. 17
    0
      test/compiler.js

+ 30
- 1
src/compiler.js View File

6
   }
6
   }
7
 
7
 
8
   compile() {
8
   compile() {
9
+    const selfClosingTags = [
10
+      'area',
11
+      'base',
12
+      'br',
13
+      'col',
14
+      'command',
15
+      'embed',
16
+      'hr',
17
+      'img',
18
+      'input',
19
+      'keygen',
20
+      'link',
21
+      'menuitem',
22
+      'meta',
23
+      'param',
24
+      'source',
25
+      'track',
26
+      'wbr',
27
+    ]
28
+
9
     this.tree.forEach(node => {
29
     this.tree.forEach(node => {
10
       if (node.type === 'functionCall') {
30
       if (node.type === 'functionCall') {
11
         const attributes = node.args.map(
31
         const attributes = node.args.map(
18
         const content = compiler.compile()
38
         const content = compiler.compile()
19
         this.result += `<${node.functionName}${
39
         this.result += `<${node.functionName}${
20
           attributes.length ? ' ' : ''
40
           attributes.length ? ' ' : ''
21
-        }${attributes.join(' ')}>${content}</${node.functionName}>`
41
+        }${attributes.join(' ')}>`
42
+
43
+        if (content) {
44
+          this.result += content
45
+        }
46
+
47
+        if (!selfClosingTags.includes(node.functionName)) {
48
+          this.result += `</${node.functionName}>`
49
+        }
50
+
22
       } else if (node.type === 'string') {
51
       } else if (node.type === 'string') {
23
         this.result += node.content
52
         this.result += node.content
24
       } else if (node.type === 'identifier') {
53
       } else if (node.type === 'identifier') {

+ 17
- 0
test/compiler.js View File

62
     '<ul><li>one</li><li>two</li><li>three</li></ul>',
62
     '<ul><li>one</li><li>two</li><li>three</li></ul>',
63
   )
63
   )
64
 })
64
 })
65
+
66
+test('self closing tags are respected', function(t) {
67
+  t.plan(1)
68
+  const lexer = new Lexer()
69
+  const tokenStream = lexer.scan(`
70
+    (meta :charset "UTF-8")
71
+    (img :src "test.png")
72
+  `)
73
+  const parser = new Parser(tokenStream)
74
+  const tree = parser.parse()
75
+  const compiler = new Compiler(tree)
76
+  const result = compiler.compile()
77
+  t.deepEqual(
78
+    result.replace(/\n/g, '').replace(/  +/g, ''),
79
+    '<meta charset="UTF-8"><img src="test.png">',
80
+  )
81
+})

Loading…
Cancel
Save