Skip to content

Commit

Permalink
refactor(markdown): extract MarkdownImage component for rendering ima…
Browse files Browse the repository at this point in the history
…ges in markdown (#218)
  • Loading branch information
1chooo committed Sep 11, 2024
1 parent 3495061 commit 79b9582
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 45 deletions.
55 changes: 55 additions & 0 deletions apps/web/src/components/markdown/markdown-image.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"use client";

import React, { useState } from 'react';
import Image from 'next/image';

interface MarkdownImageProps {
src: string;
alt?: string;
}

const MarkdownImage: React.FC<MarkdownImageProps> = ({ src, alt }) => {
const [imageSize, setImageSize] = useState({ width: 1, height: 1 });

return (
<div
style={{
marginTop: '1rem',
maxWidth: '80%',
margin: '0 auto',
textAlign: 'center',
}}
>
<Image
src={src}
alt={alt ?? 'Image'}
layout="responsive"
objectFit="contain"
priority={true}
onLoadingComplete={(target) => {
setImageSize({
width: target.naturalWidth,
height: target.naturalHeight,
});
}}
width={imageSize.width}
height={imageSize.height}
/>
{alt && (
<div
style={{
marginTop: '0.5rem',
fontSize: '0.9rem',
color: '#555',
textAlign: 'center',
marginBottom: '1rem',
}}
>
{alt}
</div>
)}
</div>
);
};

export default MarkdownImage;
48 changes: 3 additions & 45 deletions apps/web/src/components/markdown/markdown-renderer.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
"use client";

import React, { useState } from 'react';
import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import Image from 'next/image';

import Anchor from './anchor';
import BlockQuote from './block-quote';
import CodeBlock from './code-block';
import MarkdownImage from './markdown-image';

interface MarkdownRendererProps {
content: string;
Expand All @@ -33,47 +31,7 @@ const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content }) => (
a: (props) => <Anchor {...props} />,
sup: 'sup',
sub: 'sub',
img: (props) => {
const [imageSize, setImageSize] = useState({ width: 1, height: 1 });

return (
<div
style={{
marginTop: '1rem',
maxWidth: '80%',
margin: '0 auto',
textAlign: 'center',
}}
>
<Image
src={props.src ?? ''}
alt={props.alt ?? 'Image'}
layout="responsive"
objectFit="contain"
priority={true}
onLoadingComplete={(target) => {
setImageSize({
width: target.naturalWidth,
height: target.naturalHeight,
});
}}
width={imageSize.width}
height={imageSize.height}
/>
{props.alt && (
<div style={{
marginTop: '0.5rem',
fontSize: '0.9rem',
color: '#555',
textAlign: 'center',
marginBottom: '1rem',
}}>
{props.alt}
</div>
)}
</div>
);
},
img: (props) => <MarkdownImage src={props.src ?? ''} alt={props.alt} />,
ul: (props) => (
<ul
{...props}
Expand Down

0 comments on commit 79b9582

Please sign in to comment.