-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
112 lines (86 loc) · 2.58 KB
/
index.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const isAlphabetical = require('is-alphabetical')
const {isImportOrExport, EMPTY_NEWLINE} = require('@mdx-js/util')
const extractImportsAndExports = require('./extract-imports-and-exports')
const block = require('./block')
const {tag} = require('./tag')
const LESS_THAN = '<'
const GREATER_THAN = '>'
const SLASH = '/'
const EXCLAMATION = '!'
module.exports = mdx
mdx.default = mdx
tokenizeEsSyntax.locator = tokenizeEsSyntaxLocator
function mdx(_options) {
const parser = this.Parser
const compiler = this.Compiler
if (parser && parser.prototype && parser.prototype.blockTokenizers) {
attachParser(parser)
}
if (compiler && compiler.prototype && compiler.prototype.visitors) {
attachCompiler(compiler)
}
}
function attachParser(parser) {
const blocks = parser.prototype.blockTokenizers
const inlines = parser.prototype.inlineTokenizers
const methods = parser.prototype.blockMethods
blocks.esSyntax = tokenizeEsSyntax
blocks.html = wrap(block)
inlines.html = wrap(inlines.html, inlineJsx)
tokenizeEsSyntax.notInBlock = true
methods.splice(methods.indexOf('paragraph'), 0, 'esSyntax')
function wrap(original, customTokenizer) {
const tokenizer = customTokenizer || tokenizeJsx
tokenizer.locator = original.locator
return tokenizer
function tokenizeJsx() {
const node = original.apply(this, arguments)
if (node) {
node.type = 'jsx'
}
return node
}
}
function inlineJsx(eat, value) {
if (value.charAt(0) !== LESS_THAN) {
return
}
const nextChar = value.charAt(1)
if (
nextChar !== GREATER_THAN &&
nextChar !== SLASH &&
nextChar !== EXCLAMATION &&
!isAlphabetical(nextChar)
) {
return
}
const subvalueMatches = value.match(tag)
if (!subvalueMatches) {
return
}
const subvalue = subvalueMatches[0]
return eat(subvalue)({type: 'jsx', value: subvalue})
}
}
function attachCompiler(compiler) {
const proto = compiler.prototype
proto.visitors = Object.assign({}, proto.visitors, {
import: stringifyEsSyntax,
export: stringifyEsSyntax,
jsx: stringifyEsSyntax
})
}
function stringifyEsSyntax(node) {
return node.value.trim()
}
function tokenizeEsSyntax(eat, value) {
const index = value.indexOf(EMPTY_NEWLINE)
const subvalue = index !== -1 ? value.slice(0, index) : value
if (isImportOrExport(subvalue)) {
const nodes = extractImportsAndExports(subvalue, this.file)
nodes.map(node => eat(node.value)(node))
}
}
function tokenizeEsSyntaxLocator(value, _fromIndex) {
return isImportOrExport(value) ? -1 : 1
}