File size: 1,482 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
 * Credit to https://ped.ro/writing/code-blocks-but-better
 */

import rangeParser from 'parse-numeric-range'
import { visit } from 'unist-util-visit'
import { toString } from 'hast-util-to-string'
import { refractor } from 'refractor'
import tsx from 'refractor/lang/tsx'
import jsx from 'refractor/lang/jsx'
import highlightLine from './rehype-highlight-line.js'
import highlightWord from './rehype-highlight-word.js'

export default () => {
  refractor.register(tsx)
  refractor.register(jsx)

  return tree => {
    visit(tree, 'element', visitor)
  }

  function visitor(node, index, parentNode) {
    if (parentNode.tagName === 'pre' && node.tagName === 'code') {
      // syntax highlight
      const lang = node.properties.className
        ? node.properties.className[0].split('-')[1]
        : 'md'
      const data = toString(node)
      let result = refractor.highlight(data, lang)

      const linesToHighlight = [0]

      // line highlight
      if (node.data?.meta) {
        node.data.meta.split(' ').forEach(bit => {
          if (bit.includes('line')) {
            const [_, lineRange] = bit.split('=')
            linesToHighlight.push(...rangeParser(lineRange || '0'))
          }
          if (bit.includes('live')) {
            parentNode.properties.code = data
          }
        })
      }

      result = highlightLine(result, linesToHighlight)

      // word highlight
      result = highlightWord(result)

      node.children = result
    }
  }
}