Skip to content

Commit

Permalink
Merge pull request #462 from 1chooo/feat/#460
Browse files Browse the repository at this point in the history
feat(markdown): refactor paragraph rendering and add Paragraph component (#460)
  • Loading branch information
1chooo authored Nov 20, 2024
2 parents dd15f3c + 30e859f commit 4579a9c
Showing 2 changed files with 42 additions and 12 deletions.
15 changes: 3 additions & 12 deletions apps/web/src/components/markdown/markdown-renderer.tsx
Original file line number Diff line number Diff line change
@@ -8,16 +8,13 @@ import Anchor from './anchor';
import BlockQuote from './block-quote';
import CodeBlock from './code-block';
import MarkdownImage from './markdown-image';
import Paragraph from './paragraph';

interface MarkdownRendererProps {
className?: string;
content: string;
}

const isImageNode = (node: any): node is Element => {
return node && node.type === 'element' && node.tagName === 'img';
};

const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
className,
content
@@ -27,14 +24,8 @@ const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw, rehypeGithubAlerts]}
components={{
p: (props) => {
const { node, children, ...rest } = props;
const hasImage = node && node.children && node.children.some(isImageNode);
if (hasImage) {
return <>{children}</>;
}
return <p {...rest}>{children}</p>;
},
p: ({ node, children, ...props }) =>
<Paragraph node={node} children={children} {...props} />,
a: (props) => <Anchor {...props} />,
sup: 'sup',
sub: 'sub',
39 changes: 39 additions & 0 deletions apps/web/src/components/markdown/paragraph.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from 'react';

interface ParagraphProps {
node: any;
children: React.ReactNode;
[key: string]: any;
}

const isImageNode = (node: any): boolean => {
return node &&
node.type === 'element' &&
node.tagName === 'img';
};

/**
* A functional component that renders a paragraph element.
* If the paragraph contains an image node, it will render the children directly without a <p> tag.
*
* @param props - The properties passed to the component.
* @param props.node - The node object which may contain children nodes.
* @param props.children - The child elements to be rendered inside the paragraph.
* @param rest - Any additional properties passed to the paragraph element.
*
* @returns A JSX element representing the paragraph or its children.
*/
const Paragraph: React.FC<ParagraphProps> = (props) => {
const { node, children, ...rest } = props;
const hasImage = node &&
node.children &&
node.children.some(isImageNode);

if (hasImage) {
return <>{children}</>;
}

return <p {...rest}>{children}</p>;
};

export default Paragraph;

0 comments on commit 4579a9c

Please sign in to comment.