'use client'; import Link from 'next/link'; import { useSearchParams } from 'next/navigation'; import type { Language } from 'prism-react-renderer'; import { Highlight } from 'prism-react-renderer'; import { Fragment, useEffect, useRef } from 'react'; import { useFragmentIdentifier } from '../hooks/use-fragment-identifier'; import { cn } from '../utils'; interface CodeProps { children: string; className?: string; language?: Language; } export const codeTheme = { plain: { color: '#EDEDEF', fontSize: 13, fontFamily: 'MonoLisa, Menlo, monospace', }, styles: [ { types: ['comment'], style: { color: '#706F78', }, }, { types: ['atrule', 'keyword', 'attr-name', 'selector'], style: { color: '#7E7D86', }, }, { types: ['punctuation', 'operator'], style: { color: '#706F78', }, }, { types: ['class-name', 'function', 'tag', 'key-white'], style: { color: '#EDEDEF', }, }, ], }; const lineHashRegex = /#L(?\d+)(?:,(?\d+))?/; export const Code: React.FC> = ({ children, language = 'html', }) => { const locationHash = useFragmentIdentifier(); const highlight = (() => { if (locationHash) { const match = locationHash.match(lineHashRegex); if (match?.groups?.start) { const start = Number.parseInt(match.groups.start, 10); const end = match.groups.end ? Number.parseInt(match.groups.end, 10) : start; return [start, end] as const; } } })(); const isHighlighting = (line: number) => { if (!highlight) return false; return highlight[0] <= line && highlight[1] >= line; }; const scrollerRef = useRef(null); useEffect(() => { const scroller = scrollerRef.current; if (highlight && scroller) { const lineElement = scroller.querySelector(`#L${highlight[0]}`); if (lineElement instanceof HTMLAnchorElement) { scroller.scrollTo({ top: Math.max(lineElement.offsetTop - 325, 0), behavior: 'smooth', }); } } }, [highlight]); const searchParams = useSearchParams(); const value = children.trim(); return ( {({ tokens, getLineProps, getTokenProps }) => ( <>
{tokens.map((line, i) => { const lineProps = getLineProps({ line, key: i, }); const isHighlighted = isHighlighting(i + 1); const isHighlightStart = highlight && highlight[0] === i + 1; const isHighlightEnd = highlight && highlight[1] === i + 1; return ( {/* Line number cell */} {i + 1} {/* Code content cell */}
{line.map((token, key) => { const tokenProps = getTokenProps({ token, }); const isException = token.content === 'from' && line[key + 1]?.content === ':'; const newTypes = isException ? [...token.types, 'key-white'] : token.types; token.types = newTypes; return ( ); })}
); })}
)} ); };