1
0
Эх сурвалжийг харах

fix: add class info for default language

Timothy Lin 2 жил өмнө
parent
commit
1afe3ce35e
2 өөрчлөгдсөн 23 нэмэгдсэн , 2 устгасан
  1. 7 1
      src/generator.js
  2. 16 1
      test.js

+ 7 - 1
src/generator.js

@@ -198,8 +198,14 @@ const rehypePrismGenerator = (refractor) => {
       } else {
         node.properties.className = []
       }
+
+      let lang = getLanguage(node)
+      // If no language is set on the code block, use defaultLanguage if specified
+      if (!lang && options.defaultLanguage) {
+        lang = options.defaultLanguage
+        node.properties.className.push(`language-${lang}`)
+      }
       node.properties.className.push('code-highlight')
-      const lang = getLanguage(node) || options.defaultLanguage
 
       /** @type {Element} */
       let refractorRoot

+ 16 - 1
test.js

@@ -353,10 +353,25 @@ test('with options.defaultLanguage, it adds the correct language class tag', ()
   `,
     { defaultLanguage: 'py' }
   )
-  const expected = dedent`<pre class="language-py"><code class="code-highlight"><span class="code-line">x <span class="token operator">=</span> <span class="token number">6</span></span></code></pre>`
+  const expected = dedent`<pre class="language-py"><code class="language-py code-highlight"><span class="code-line">x <span class="token operator">=</span> <span class="token number">6</span></span></code></pre>`
   assert.is(result, expected)
 })
 
+test('defaultLanguage should produce the same syntax tree as if manually specified', () => {
+  const resultDefaultLanguage = processHtml(
+    dedent`
+    <pre><code>x = 6</code></pre>
+  `,
+    { defaultLanguage: 'py' }
+  )
+  const resultManuallySpecified = processHtml(
+    dedent`
+    <pre><code class="language-py">x = 6</code></pre>
+  `
+  )
+  assert.is(resultDefaultLanguage, resultManuallySpecified)
+})
+
 test('throws error if options.defaultLanguage is not registered with refractor', () => {
   assert.throws(
     () =>