diff --git a/__tests__/renderer-spec.tsx b/__tests__/renderer-spec.tsx index 0c320b0..3a6fb20 100644 --- a/__tests__/renderer-spec.tsx +++ b/__tests__/renderer-spec.tsx @@ -175,3 +175,19 @@ test('should render blockquote with mixed text', () => { ) as string).trim() ).toBe('> This is _hello_ **world**'); }); + +test('should render code tag with text', () => { + expect( + (render( + const a = 1; + ) as string).trim() + ).toBe('```js\nconst a = 1;\n```'); +}); + +test('should render code tag without text', () => { + expect( + (render( + + ) as string).trim() + ).toBe('```js\n\n```'); +}); diff --git a/src/tagHandler.ts b/src/tagHandler.ts index 3c721e9..2f9ffd5 100644 --- a/src/tagHandler.ts +++ b/src/tagHandler.ts @@ -1,5 +1,6 @@ import { blockquote, + code, emphasis, heading, image, @@ -9,7 +10,11 @@ import { paragraph, strong, } from 'mdast-builder'; -import { AnchorHTMLAttributes, ImgHTMLAttributes } from 'react'; +import { + HTMLAttributes, + AnchorHTMLAttributes, + ImgHTMLAttributes, +} from 'react'; // tslint:disable-next-line: no-implicit-dependencies import { Node as MDASTNode, Parent as MDASTParent } from 'unist'; @@ -105,6 +110,28 @@ export default function handleTag( } // END - Handle blockquote + // START - Handle code + case 'code': { + const props = node.props as HTMLAttributes; + + let lang = ''; + if (props.lang !== undefined) { + lang = props.lang; + } + + let value = ''; + if (props.children !== undefined) { + const onlyChild = props.children; + if (typeof onlyChild === 'string' || typeof onlyChild === 'number') { + value = onlyChild.toString(); + } + } + + childASTNode = code(lang, value); + break; + } + // END - Handle code + default: newParentASTNode = parentASTNode; break;