Browse Source

Merge pull request #24 from timlrx/refactor/generator

Refactor/generator
Timothy 4 năm trước cách đây
mục cha
commit
159d972c87
3 tập tin đã thay đổi với 146 bổ sung105 xóa
  1. 101 70
      index.js
  2. 44 34
      package-lock.json
  3. 1 1
      package.json

+ 101 - 70
index.js

@@ -13,7 +13,8 @@
 
 import { visit } from 'unist-util-visit'
 import { toString } from 'hast-util-to-string'
-import { refractor } from 'refractor/lib/all.js'
+import { refractor as refractorAll } from 'refractor/lib/all.js'
+import { refractor as refractorCommon } from 'refractor/lib/common.js'
 import { toHtml } from 'hast-util-to-html'
 import { filter } from 'unist-util-filter'
 import { unified } from 'unified'
@@ -157,94 +158,124 @@ const splitTextByLine = (ast) => {
 }
 
 /**
- * Rehype plugin that highlights code blocks with refractor (prismjs)
+ * Rehype prism plugin generator that highlights code blocks with refractor (prismjs)
  *
- * @type {import('unified').Plugin<[Options?], Root>}
+ * Pass in your own refractor object with the required languages registered:
+ * https://github.com/wooorm/refractor#refractorregistersyntax
+ *
+ * @param {import('refractor/lib/core').Refractor} refractor
+ * @return {import('unified').Plugin<[Options?], Root>}
  */
-const rehypePrism = (options = {}) => {
-  return (tree) => {
-    // @ts-ignore
-    visit(tree, 'element', visitor)
-  }
-
-  /**
-   * @param {Node} node
-   * @param {number} index
-   * @param {Parent} parent
-   */
-  function visitor(node, index, parent) {
-    if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') {
-      return
+const rehypePrismGenerator = (refractor) => {
+  return (options = {}) => {
+    return (tree) => {
+      // @ts-ignore
+      visit(tree, 'element', visitor)
     }
 
-    const lang = getLanguage(node)
+    /**
+     * @param {Node} node
+     * @param {number} index
+     * @param {Parent} parent
+     */
+    function visitor(node, index, parent) {
+      if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') {
+        return
+      }
+
+      const lang = getLanguage(node)
 
-    /** @type {string} */
-    // @ts-ignore
-    let meta = node.data && node.data.meta ? node.data.meta : ''
-    node.properties.className = node.properties.className || []
-    node.properties.className.push('code-highlight')
+      /** @type {string} */
+      // @ts-ignore
+      let meta = node.data && node.data.meta ? node.data.meta : ''
+      node.properties.className = node.properties.className || []
+      node.properties.className.push('code-highlight')
 
-    let refractorRoot
-    let langError = false
+      let refractorRoot
+      let langError = false
 
-    // Syntax highlight
-    if (lang) {
-      try {
-        // @ts-ignore
-        refractorRoot = refractor.highlight(toString(node), lang)
-        parent.properties.className = (parent.properties.className || []).concat('language-' + lang)
-      } catch (err) {
-        if (options.ignoreMissing && /Unknown language/.test(err.message)) {
-          langError = true
-          refractorRoot = node.children
-        } else {
-          throw err
+      // Syntax highlight
+      if (lang) {
+        try {
+          // @ts-ignore
+          refractorRoot = refractor.highlight(toString(node), lang)
+          parent.properties.className = (parent.properties.className || []).concat(
+            'language-' + lang
+          )
+        } catch (err) {
+          if (options.ignoreMissing && /Unknown language/.test(err.message)) {
+            langError = true
+            refractorRoot = node.children
+          } else {
+            throw err
+          }
         }
+      } else {
+        refractorRoot = node.children
       }
-    } else {
-      refractorRoot = node.children
-    }
 
-    // @ts-ignore
-    refractorRoot = getNodePosition(refractorRoot)
-    refractorRoot.children = splitTextByLine(refractorRoot.children)
+      // @ts-ignore
+      refractorRoot = getNodePosition(refractorRoot)
+      refractorRoot.children = splitTextByLine(refractorRoot.children)
 
-    const shouldHighlightLine = calculateLinesToHighlight(meta)
-    const startingLineNumber = calculateStartingLine(meta)
-    // @ts-ignore
-    const codeLineArray = splitLine(toString(node))
+      const shouldHighlightLine = calculateLinesToHighlight(meta)
+      const startingLineNumber = calculateStartingLine(meta)
+      // @ts-ignore
+      const codeLineArray = splitLine(toString(node))
 
-    for (const [i, line] of codeLineArray.entries()) {
-      // Code lines
-      if (meta.toLowerCase().includes('showLineNumbers'.toLowerCase()) || options.showLineNumbers) {
-        line.properties.line = [(i + startingLineNumber).toString()]
-        line.properties.className.push('line-number')
-      }
+      for (const [i, line] of codeLineArray.entries()) {
+        // Code lines
+        if (
+          meta.toLowerCase().includes('showLineNumbers'.toLowerCase()) ||
+          options.showLineNumbers
+        ) {
+          line.properties.line = [(i + startingLineNumber).toString()]
+          line.properties.className.push('line-number')
+        }
 
-      // Line highlight
-      if (shouldHighlightLine(i)) {
-        line.properties.className.push('highlight-line')
-      }
+        // Line highlight
+        if (shouldHighlightLine(i)) {
+          line.properties.className.push('highlight-line')
+        }
 
-      // @ts-ignore
-      if (lang === 'diff' && toString(line).substring(0, 1) === '-') {
-        line.properties.className.push('deleted')
         // @ts-ignore
-      } else if (lang === 'diff' && toString(line).substring(0, 1) === '+') {
-        line.properties.className.push('inserted')
+        if (lang === 'diff' && toString(line).substring(0, 1) === '-') {
+          line.properties.className.push('deleted')
+          // @ts-ignore
+        } else if (lang === 'diff' && toString(line).substring(0, 1) === '+') {
+          line.properties.className.push('inserted')
+        }
+
+        // Syntax highlight
+        const treeExtract = filter(
+          refractorRoot,
+          (node) => node.position.start.line <= i + 1 && node.position.end.line >= i + 1
+        )
+        line.children = treeExtract.children
       }
 
-      // Syntax highlight
-      const treeExtract = filter(
-        refractorRoot,
-        (node) => node.position.start.line <= i + 1 && node.position.end.line >= i + 1
-      )
-      line.children = treeExtract.children
+      node.children = codeLineArray
     }
-
-    node.children = codeLineArray
   }
 }
 
+/**
+ * Rehype prism plugin that highlights code blocks with refractor (prismjs)
+ * This supports all the languages and should be used on the server side.
+ *
+ * Consider using rehypePrismCommon or rehypePrismGenerator to generate a plugin
+ * that supports your required languages.
+ */
+const rehypePrism = rehypePrismGenerator(refractorAll)
+
+/**
+ * Rehype prism plugin that highlights code blocks with refractor (prismjs)
+ * Supported languages: https://github.com/wooorm/refractor#data
+ *
+ * Consider using rehypePrismGenerator to generate a plugin
+ * that supports your required languages.
+ */
+const rehypePrismCommon = rehypePrismGenerator(refractorCommon)
+
+export { rehypePrismGenerator, rehypePrismCommon }
 export default rehypePrism

+ 44 - 34
package-lock.json

@@ -1,6 +1,6 @@
 {
   "name": "rehype-prism-plus",
-  "version": "1.1.2",
+  "version": "1.1.3",
   "lockfileVersion": 1,
   "requires": true,
   "dependencies": {
@@ -1811,9 +1811,9 @@
       }
     },
     "character-entities": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.0.tgz",
-      "integrity": "sha512-oHqMj3eAuJ77/P5PaIRcqk+C3hdfNwyCD2DAUcD5gyXkegAuF2USC40CEqPscDk4I8FRGMTojGJQkXDsN5QlJA=="
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.1.tgz",
+      "integrity": "sha512-OzmutCf2Kmc+6DrFrrPS8/tDh2+DpnrfzdICHWhcVC9eOd0N1PXmQEE1a8iM4IziIAG+8tmTq3K+oo0ubH6RRQ=="
     },
     "character-entities-html4": {
       "version": "2.0.0",
@@ -1826,9 +1826,9 @@
       "integrity": "sha512-YwaEtEvWLpFa6Wh3uVLrvirA/ahr9fki/NUd/Bd4OR6EdJ8D22hovYQEOUCBfQfcqnC4IAMGMsHXY1eXgL4ZZA=="
     },
     "character-reference-invalid": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.0.tgz",
-      "integrity": "sha512-pE3Z15lLRxDzWJy7bBHBopRwfI20sbrMVLQTC7xsPglCHf4Wv1e167OgYAFP78co2XlhojDyAqA+IAJse27//g=="
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
+      "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="
     },
     "clean-stack": {
       "version": "2.2.0",
@@ -2147,6 +2147,14 @@
         "ms": "2.1.2"
       }
     },
+    "decode-named-character-reference": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.0.1.tgz",
+      "integrity": "sha512-YV/0HQHreRwKb7uBopyIkLG17jG6Sv2qUchk9qSoVJ2f+flwRsPNBO0hAnjt6mTNYUT+vw9Gy2ihXg4sUWPi2w==",
+      "requires": {
+        "character-entities": "^2.0.0"
+      }
+    },
     "dedent": {
       "version": "0.7.0",
       "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz",
@@ -3264,14 +3272,14 @@
       "dev": true
     },
     "is-alphabetical": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.0.tgz",
-      "integrity": "sha512-5OV8Toyq3oh4eq6sbWTYzlGdnMT/DPI5I0zxUBxjiigQsZycpkKF3kskkao3JyYGuYDHvhgJF+DrjMQp9SX86w=="
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
+      "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="
     },
     "is-alphanumerical": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.0.tgz",
-      "integrity": "sha512-t+2GlJ+hO9yagJ+jU3+HSh80VKvz/3cG2cxbGGm4S0hjKuhWQXgPVUVOZz3tqZzMjhmphZ+1TIJTlRZRoe6GCQ==",
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
+      "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
       "requires": {
         "is-alphabetical": "^2.0.0",
         "is-decimal": "^2.0.0"
@@ -3332,9 +3340,9 @@
       }
     },
     "is-decimal": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.0.tgz",
-      "integrity": "sha512-QfrfjQV0LjoWQ1K1XSoEZkTAzSa14RKVMa5zg3SdAfzEmQzRM4+tbSFWb78creCeA9rNBzaZal92opi1TwPWZw=="
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
+      "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A=="
     },
     "is-extglob": {
       "version": "2.1.1",
@@ -3358,9 +3366,9 @@
       }
     },
     "is-hexadecimal": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.0.tgz",
-      "integrity": "sha512-vGOtYkiaxwIiR0+Ng/zNId+ZZehGfINwTzdrDqc6iubbnQWhnPuYymOzOKUDqa2cSl59yHnEh2h6MvRLQsyNug=="
+      "version": "2.0.1",
+      "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+      "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg=="
     },
     "is-module": {
       "version": "1.0.0",
@@ -4292,22 +4300,24 @@
       }
     },
     "parse-entities": {
-      "version": "3.0.0",
-      "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-3.0.0.tgz",
-      "integrity": "sha512-AJlcIFDNPEP33KyJLguv0xJc83BNvjxwpuUIcetyXUsLpVXAUCePJ5kIoYtEN2R1ac0cYaRu/vk9dVFkewHQhQ==",
+      "version": "4.0.0",
+      "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.0.tgz",
+      "integrity": "sha512-5nk9Fn03x3rEhGaX1FU6IDwG/k+GxLXlFAkgrbM1asuAFl3BhdQWvASaIsmwWypRNcZKHPYnIuOSfIWEyEQnPQ==",
       "requires": {
+        "@types/unist": "^2.0.0",
         "character-entities": "^2.0.0",
-        "character-entities-legacy": "^2.0.0",
+        "character-entities-legacy": "^3.0.0",
         "character-reference-invalid": "^2.0.0",
+        "decode-named-character-reference": "^1.0.0",
         "is-alphanumerical": "^2.0.0",
         "is-decimal": "^2.0.0",
         "is-hexadecimal": "^2.0.0"
       },
       "dependencies": {
         "character-entities-legacy": {
-          "version": "2.0.0",
-          "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-2.0.0.tgz",
-          "integrity": "sha512-YwaEtEvWLpFa6Wh3uVLrvirA/ahr9fki/NUd/Bd4OR6EdJ8D22hovYQEOUCBfQfcqnC4IAMGMsHXY1eXgL4ZZA=="
+          "version": "3.0.0",
+          "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+          "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ=="
         }
       }
     },
@@ -4764,9 +4774,9 @@
       "dev": true
     },
     "prismjs": {
-      "version": "1.25.0",
-      "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.25.0.tgz",
-      "integrity": "sha512-WCjJHl1KEWbnkQom1+SzftbtXMKQoezOCYs5rECqMN+jP+apI7ftoflyqigqzopSO3hMhTEb0mFClA8lkolgEg=="
+      "version": "1.26.0",
+      "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.26.0.tgz",
+      "integrity": "sha512-HUoH9C5Z3jKkl3UunCyiD5jwk0+Hz0fIgQ2nbwU2Oo/ceuTAQAg+pPVnfdt2TJWRVLcxKh9iuoYDUSc8clb5UQ=="
     },
     "progress": {
       "version": "2.0.3",
@@ -4801,15 +4811,15 @@
       }
     },
     "refractor": {
-      "version": "4.2.1",
-      "resolved": "https://registry.npmjs.org/refractor/-/refractor-4.2.1.tgz",
-      "integrity": "sha512-UhtiILJUJiKquZZPtPokJZAKu2a35cT6gPBXyv2FJj+3T+AC8fyUzVUvA0lyiiYNl9m2ShCW/SSDC9us/FsuvQ==",
+      "version": "4.4.0",
+      "resolved": "https://registry.npmjs.org/refractor/-/refractor-4.4.0.tgz",
+      "integrity": "sha512-JmpsdoB9Va7BxQAAsuFW4cvN6plRKmSVNua8vUjbB6uRv+9cwm5JDH67P8qYr0OAFXWE1D4WlrIAPzQNcyEaoQ==",
       "requires": {
         "@types/hast": "^2.0.0",
         "@types/prismjs": "^1.0.0",
         "hastscript": "^7.0.0",
-        "parse-entities": "^3.0.0",
-        "prismjs": "~1.25.0"
+        "parse-entities": "^4.0.0",
+        "prismjs": "~1.26.0"
       }
     },
     "regenerate": {

+ 1 - 1
package.json

@@ -44,7 +44,7 @@
     "hast-util-to-html": "^8.0.1",
     "hast-util-to-string": "^2.0.0",
     "parse-numeric-range": "^1.3.0",
-    "refractor": "^4.2.1",
+    "refractor": "^4.4.0",
     "rehype-parse": "^8.0.2",
     "unified": "^10.1.0",
     "unist-util-filter": "^4.0.0",