Skip to content

Commit

Permalink
fix(docz-core): create plugin to fix paragraph parse on mdx
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed May 9, 2018
1 parent ed65a80 commit 42b4f05
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
14 changes: 13 additions & 1 deletion examples/basic/src/components/Alert.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const meta = doc('Alert')
## Basic usage

<Playground>
<Alert>Other message</Alert>
<Alert>Some message</Alert>
</Playground>

## Using different kinds
Expand All @@ -20,3 +20,15 @@ export const meta = doc('Alert')
<Alert kind="negative">Some message</Alert>
<Alert kind="warning">Some message</Alert>
</Playground>

## Use with children as a function

<Playground>
{() => {
const message = 'Hello world'

return (
<Alert>{message}</Alert>
)
}}
</Playground>
61 changes: 61 additions & 0 deletions packages/docz-core/src/utils/plugin-mdast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import visit from 'unist-util-visit'
import remove from 'unist-util-remove'

const componentName = (value: string) => {
const match = value.match(/^\<\\?(\w+)/)
return match && match[1]
}

const valuesFromTreeNodes = (tree: any) => (first: number, last: number) => {
const values: string[] = []

if (first !== last) {
for (let i = last; i >= first; i--) {
const found = tree.children[i]

if (found.children && found.children.length > 0) {
values.push(...found.children.map((child: any) => child.value))
}

if (found.value && found.value.length > 0) {
values.push(found.value)
}

if (i !== first) remove(tree, found)
}
}

return values
}

export const plugin = () => (tree: any, file: any) => {
visit(tree, 'html', visitor)

function visitor(node: any, idx: any, parent: any): void {
try {
if (!node.value || typeof node.value !== 'string') return

const component = componentName(node.value)
const tagOpen = new RegExp(`^\\<${component}`)
const tagClose = new RegExp(`\\<\\/${component}\\>$`)

const hasOpenTag = (value: string) => tagOpen.test(value)
const hasCloseTag = (value: string) => tagClose.test(value)

if (!component || (hasOpenTag(node.value) && hasCloseTag(node.value)))
return

const tagCloseIdx = tree.children.findIndex(
({ value }: any) => value && !hasOpenTag(value) && hasCloseTag(value)
)

const mergeUntilCloseTag = valuesFromTreeNodes(tree)
const values = mergeUntilCloseTag(idx, tagCloseIdx)

node.value = values.reverse().join('\n')
} catch (err) {
console.log(err)
return
}
}
}

0 comments on commit 42b4f05

Please sign in to comment.