micro-mdx-parser
Version:
A tiny parser to convert markdown or html into JSON
80 lines (66 loc) • 2.08 kB
JavaScript
const { inspect } = require('util')
const { test } = require('uvu')
const assert = require('uvu/assert')
const { format } = require('./format')
const { parse } = require('./index')
function deepLog(obj) {
console.log(inspect(obj, {showHidden: false, depth: null, colors: true}))
}
test('Exports format API', () => {
assert.equal(typeof format, 'function')
})
function slugify(str) {
return str
.replace(/[ÀÁÂÃÄÅàáâãä忯]/g, 'a')
.replace(/[çÇ]/g, 'c')
.replace(/[ðÐ]/g, 'd')
.replace(/[ÈÉÊËéèêë]/g, 'e')
.replace(/[ÏïÎîÍíÌì]/g, 'i')
.replace(/[Ññ]/g, 'n')
.replace(/[øØœŒÕõÔôÓóÒò]/g, 'o')
.replace(/[ÜüÛûÚúÙù]/g, 'u')
.replace(/[ŸÿÝý]/g, 'y')
.replace(/[^a-z0-9- ]/gi, '')
.replace(/ /gi, '-')
.toLowerCase()
}
const stringExample = `
Hello, world!
<h1>Heading</h1>
<h1 id='test'>Another Heading</h1>
<h1>Heading one two</h1>
<div style={{padding: '1rem', backgroundColor: 'violet'}}>
Try and change the background color to.
</div>
<MyComponent isCool />
<img src="w3schools.jpg" alt="W3Schools-img.com" width="104" height="142" />
`
test('transforms test', () => {
const formatted = parse(stringExample, {
transforms: {
h1: (node) => {
if (node && node.props && node.props.id) {
return node
}
if (node.children && node.children.length === 1 && node.children[0].type === 'text') {
node.props.id = slugify(node.children[0].content)
return node
}
const matchHtml = (node.tagValue || '').match(/<([a-zA-Z1-6]+)\b([^>]*)>*(?:>([\s\S]*?)<\/\1>|\s?\/>)/)
if (matchHtml && matchHtml[3]) {
node.props.id = slugify(matchHtml[3])
return node
}
return node
}
}
})
/*
console.log('formatted', formatted)
/** */
assert.ok(formatted)
assert.equal(formatted[1].props, { id: 'heading' })
assert.equal(formatted[3].props, { id: 'test' })
assert.equal(formatted[5].props, { id: 'heading-one-two' })
})
test.run()