|
| 1 | +import { MDXRemote as MDX, MDXRemoteSerializeResult } from 'next-mdx-remote' |
| 2 | +import Image from 'next/image' |
| 3 | +import Link from 'next/link' |
| 4 | +import { FiCopy } from 'react-icons/fi' |
| 5 | + |
| 6 | +interface ImageProps { |
| 7 | + src: string |
| 8 | + alt: string |
| 9 | +} |
| 10 | +function CustomImg({ src, alt }: ImageProps) { |
| 11 | + return ( |
| 12 | + <div className='relative w-full h-[60vh]'> |
| 13 | + <Image |
| 14 | + src={process.env.NEXT_PUBLIC_IMAGE_LOADER_URL + src} |
| 15 | + alt={alt} |
| 16 | + layout='fill' |
| 17 | + objectFit='contain' |
| 18 | + /> |
| 19 | + </div> |
| 20 | + ) |
| 21 | +} |
| 22 | + |
| 23 | +interface MDXContent { |
| 24 | + content: MDXRemoteSerializeResult<Record<string, unknown>> |
| 25 | +} |
| 26 | +export default function MDXRemote({ content }: MDXContent) { |
| 27 | + return ( |
| 28 | + <MDX |
| 29 | + {...content} |
| 30 | + components={{ |
| 31 | + a: (props) => { |
| 32 | + const href = props.href |
| 33 | + const isInternalLink = |
| 34 | + href && (href.startsWith('/') || href.startsWith('#')) |
| 35 | + |
| 36 | + if (isInternalLink) { |
| 37 | + return ( |
| 38 | + <Link href={href}> |
| 39 | + <a {...props}>{props.children}</a> |
| 40 | + </Link> |
| 41 | + ) |
| 42 | + } |
| 43 | + |
| 44 | + return ( |
| 45 | + <a |
| 46 | + target='_blank' |
| 47 | + rel='noopener noreferrer' |
| 48 | + {...props} |
| 49 | + /> |
| 50 | + ) |
| 51 | + }, |
| 52 | + h2: ({ children }) => { |
| 53 | + const id = children |
| 54 | + ?.toString() |
| 55 | + .replace(/[\[\]$&+,:;=?@#| '<>.^*()%!-]/g, '-') |
| 56 | + .toLowerCase() |
| 57 | + |
| 58 | + return ( |
| 59 | + <h2 id={id} className='h2'> |
| 60 | + {children} |
| 61 | + </h2> |
| 62 | + ) |
| 63 | + }, |
| 64 | + h3: ({ children }) => { |
| 65 | + const id = children |
| 66 | + ?.toString() |
| 67 | + .replace(/[\[\]$&+,:;=?@#| '<>.^*()%!-]/g, '-') |
| 68 | + .toLowerCase() |
| 69 | + |
| 70 | + return ( |
| 71 | + <h3 id={id} className='h3'> |
| 72 | + {children} |
| 73 | + </h3> |
| 74 | + ) |
| 75 | + }, |
| 76 | + img: ({ src, alt }) => { |
| 77 | + return <CustomImg src={src!} alt={alt!} /> |
| 78 | + }, |
| 79 | + code: ({ children }) => { |
| 80 | + const id = Date.now().toString() |
| 81 | + const copyCode = () => { |
| 82 | + const code = document.getElementById(id)!.innerText |
| 83 | + navigator.clipboard.writeText(code) |
| 84 | + } |
| 85 | + return ( |
| 86 | + <div id={id}> |
| 87 | + <button |
| 88 | + className='absolute w-7 h-7 top-5 right-5 border-2 border-gray-700 active:border-green-200 rounded-md' |
| 89 | + onClick={copyCode} |
| 90 | + > |
| 91 | + <FiCopy className='w-5 h-5 mx-auto my-auto' /> |
| 92 | + </button> |
| 93 | + {children} |
| 94 | + </div> |
| 95 | + ) |
| 96 | + }, |
| 97 | + }} |
| 98 | + /> |
| 99 | + ) |
| 100 | +} |
0 commit comments