From 03b71d95b6d18816bd2fc27751c6184b4998f790 Mon Sep 17 00:00:00 2001 From: Tushar <80577646+TusharThakur04@users.noreply.github.com> Date: Fri, 7 Feb 2025 20:06:20 +0530 Subject: [PATCH] feat: add copy-button for codeBlocks --- src/components/CodeBlock/CodeBlock.jsx | 65 ++++++++++++++++++++++++++ src/components/Page/Page.jsx | 9 +++- 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 src/components/CodeBlock/CodeBlock.jsx diff --git a/src/components/CodeBlock/CodeBlock.jsx b/src/components/CodeBlock/CodeBlock.jsx new file mode 100644 index 000000000000..ceb6cfdeaeec --- /dev/null +++ b/src/components/CodeBlock/CodeBlock.jsx @@ -0,0 +1,65 @@ +import { useState } from 'react'; +import PropTypes from 'prop-types'; + +function CopyButton({ text }) { + const [copied, setCopied] = useState(false); + + const handleCopy = () => { + navigator.clipboard.writeText(text).then(() => { + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }); + }; + + const buttonStyle = { + position: 'absolute', + top: '0.5rem', + right: '0.5rem', + backgroundColor: '#e5e7eb', + fontSize: '0.875rem', + padding: '0.25rem 0.5rem', + borderRadius: '0.25rem', + cursor: 'pointer', + transition: 'background-color 0.3s ease', + }; + + const handleMouseOver = (e) => { + e.target.style.backgroundColor = '#d1d5db'; + }; + + const handleMouseOut = (e) => { + e.target.style.backgroundColor = '#e5e7eb'; + }; + + return ( + + ); +} +CopyButton.propTypes = { + text: PropTypes.string.isRequired, +}; + +//integrating the CopyButton component into the CodeBlock component + +export default function CodeBlock({ children }) { + const codeText = children?.props?.children?.toString() || ''; + + return ( +
+ +
{children}
+
+ ); +} + +CodeBlock.propTypes = { + children: PropTypes.node.isRequired, +}; diff --git a/src/components/Page/Page.jsx b/src/components/Page/Page.jsx index da6e72f32620..0291643da414 100644 --- a/src/components/Page/Page.jsx +++ b/src/components/Page/Page.jsx @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import { useLocation } from 'react-router-dom'; +import { MDXProvider } from '@mdx-js/react'; // Import Components import PageLinks from '../PageLinks/PageLinks'; @@ -9,10 +10,14 @@ import Markdown from '../Markdown/Markdown'; import Contributors from '../Contributors/Contributors'; import { PlaceholderString } from '../Placeholder/Placeholder'; import AdjacentPages from './AdjacentPages'; +import CodeBlock from '../CodeBlock/CodeBlock'; // Load Styling import './Page.scss'; import Link from '../Link/Link'; + +const components = { pre: CodeBlock }; + export default function Page(props) { const { title, @@ -113,7 +118,9 @@ export default function Page(props) { ) : null} -
{contentRender}
+ +
{contentRender}
+
{loadRelated && (