tahamajs's picture
download
raw
8.48 kB
// src/components/article/ArticleBody.tsx
import { useEffect, useRef } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import rehypeKatex from "rehype-katex";
import rehypeHighlight from "rehype-highlight";
import rehypeSlug from "rehype-slug";
import rehypeAutolinkHeadings from "rehype-autolink-headings";
import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; // Added for security
import { MathRenderer } from "./MathRenderer";
import "katex/dist/katex.min.css";
import "highlight.js/styles/github-dark.css";
interface ArticleBodyProps {
body: string;
isMarkdown?: boolean;
}
export function ArticleBody({ body, isMarkdown = true }: ArticleBodyProps) {
const containerRef = useRef<HTMLDivElement>(null);
const url = typeof window !== "undefined" ? window.location.href : "";
// Add heading anchors and tweet embed detection after render
useEffect(() => {
if (!containerRef.current) return;
const headings = containerRef.current.querySelectorAll("h1, h2, h3, h4, h5, h6");
headings.forEach((heading) => {
if (!heading.id) return;
const link = document.createElement("a");
link.href = `#${heading.id}`;
link.className = "heading-anchor ml-2 text-gray-400 opacity-0 hover:opacity-100 transition";
link.innerHTML = "🔗";
link.setAttribute("aria-label", "Copy link to heading");
heading.appendChild(link);
});
// Convert plain tweet links to embeds
const tweetLinks = containerRef.current.querySelectorAll('a[href*="twitter.com"], a[href*="x.com"]');
tweetLinks.forEach(link => {
const href = link.getAttribute('href');
if (href && href.includes('/status/')) {
const tweetBlock = document.createElement('div');
tweetBlock.className = 'tweet-embed-placeholder';
tweetBlock.setAttribute('data-tweet-url', href);
link.parentNode?.replaceChild(tweetBlock, link);
// Note: For a real implementation, you'd load the X widget script here
}
});
}, [body]);
// Empty state
if (!body || body.trim() === "") {
return (
<div className="premium-glass rounded-[2rem] hover-lift shadow-lg overflow-hidden mt-6 p-8 text-center text-gray-500">
This article has no content yet.
</div>
);
}
// Plain text fallback
if (!isMarkdown) {
return (
<div className="premium-glass rounded-[2rem] hover-lift shadow-lg overflow-hidden mt-6 border border-white/10 dark:border-white/5">
<div className="p-6 sm:p-8 lg:p-10">
<div className="prose dark:prose-invert max-w-none">
{body.split("\n").map((para, idx) => (
<p key={idx}>{para}</p>
))}
</div>
</div>
</div>
);
}
// Enhanced sanitization schema - allows only safe attributes
const sanitizeSchema = {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
'*': ['className', 'class', 'id', 'style'],
a: [...(defaultSchema.attributes?.a || []), 'target', 'rel', 'href', 'title'],
img: ['src', 'alt', 'title', 'width', 'height', 'loading'],
iframe: ['src', 'title', 'width', 'height', 'allow', 'allowfullscreen', 'loading'],
},
tagNames: [...(defaultSchema.tagNames || []), 'iframe'],
};
return (
<div className="premium-glass rounded-[2rem] hover-lift shadow-lg overflow-hidden mt-6 border border-white/10 dark:border-white/5">
<div className="p-6 sm:p-8 lg:p-10" ref={containerRef}>
<div className="prose dark:prose-invert max-w-none prose-headings:scroll-mt-20 prose-a:text-primary prose-img:rounded-xl prose-img:shadow-md prose-pre:bg-gray-900 prose-pre:text-gray-100">
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[
rehypeKatex,
rehypeHighlight,
rehypeSlug,
[rehypeSanitize, sanitizeSchema], // Added security layer
[rehypeAutolinkHeadings, { behavior: "wrap" }],
]}
urlTransform={(href) => {
// Enhanced URL sanitization
if (!href) return "#";
if (href.startsWith("#")) return href;
try {
const parsed = new URL(href, url);
if (!["http:", "https:", "mailto:", "ftp:"].includes(parsed.protocol)) return "#";
return parsed.href;
} catch {
return "#";
}
}}
components={{
// Image component with lazy loading and lightbox placeholder
img: ({ node, src, alt, ...props }) => (
<img
src={src}
alt={alt || "Article image"}
loading="lazy"
className="rounded-xl shadow-md max-w-full h-auto cursor-pointer hover:opacity-95 transition"
onClick={() => window.open(src, "_blank")}
{...props}
/>
),
// Custom code block with language label
code: ({ className, children, ...props }: any) => {
const match = /language-(\w+)/.exec(className || "");
return match ? (
<div className="relative">
<div className="absolute top-0 right-0 text-xs bg-gray-700 text-gray-300 px-2 py-1 rounded-bl">
{match[1]}
</div>
<pre className="rounded-lg overflow-x-auto p-4">
<code className={className} {...props}>
{children}
</code>
</pre>
</div>
) : (
<code className="bg-gray-100 dark:bg-gray-800 rounded px-1 py-0.5" {...props}>
{children}
</code>
);
},
// Table wrapper for horizontal scroll on mobile
table: ({ children }) => (
<div className="overflow-x-auto">
<table className="min-w-full border-collapse border border-gray-200 dark:border-gray-700">
{children}
</table>
</div>
),
// External link handling (security + UX)
a: ({ href, children, ...props }) => {
const isExternal = href?.startsWith("http");
return (
<a
href={href}
target={isExternal ? "_blank" : undefined}
rel={isExternal ? "noopener noreferrer ugc" : undefined}
className="text-primary hover:underline"
{...props}
>
{children}
{isExternal && <span className="ml-1 text-xs">↗</span>}
</a>
);
},
// YouTube embed
iframe: ({ src, title, ...props }) => {
if (src?.includes('youtube.com/embed/') || src?.includes('youtu.be')) {
const videoId = src.split('/').pop()?.split('?')[0];
const embedSrc = `https://www.youtube.com/embed/${videoId}`;
return (
<div className="aspect-video my-4">
<iframe
src={embedSrc}
title={title || "YouTube video"}
className="w-full h-full rounded-lg"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
loading="lazy"
{...props}
/>
</div>
);
}
return (
<div className="my-4">
<iframe
src={src}
title={title || "Embedded content"}
className="w-full rounded-lg"
allowFullScreen
loading="lazy"
{...props}
/>
</div>
);
},
}}
>
{body}
</ReactMarkdown>
</div>
</div>
</div>
);
}

Xet Storage Details

Size:
8.48 kB
·
Xet hash:
201dadaebfb5233236daed23e733203d2f18ca0b1797d89c5d1d985956d0dcf9

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.