-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(docz-core): create plugin to fix paragraph parse on mdx
- Loading branch information
1 parent
ed65a80
commit 42b4f05
Showing
2 changed files
with
74 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
} |