CodeCopy - goobz22/goobs-frontend GitHub Wiki
The CodeCopy component in goobs-frontend is a specialized component for displaying code snippets with syntax highlighting and providing a convenient copy-to-clipboard functionality. It's particularly useful for documentation, tutorials, or any scenario where you need to present and share code examples.
To use the CodeCopy component in your project, import it from the goobs-frontend package:
import { CodeCopy } from 'goobs-frontend';
Here's a basic example of how to use the CodeCopy component:
import React from 'react';
import { CodeCopy } from 'goobs-frontend';
const CodeCopyExample: React.FC = () => {
const codeSnippet = `
function greet(name) {
console.log(\`Hello, \${name}!\`);
}
greet('World');
`.trim();
return (
<CodeCopy
code={codeSnippet}
language="javascript"
/>
);
};
export default CodeCopyExample;
The CodeCopy component accepts the following props:
-
code
: string (required) - The code snippet to be displayed and copied. -
language
: string (required) - The programming language of the code (for syntax highlighting).
- Syntax Highlighting: The component uses highlight.js for syntax highlighting, supporting a wide range of programming languages.
- Copy to Clipboard: A "Copy Code" button is provided, allowing users to easily copy the entire code snippet to their clipboard.
- Responsive Design: The component is designed to be responsive and work well on various screen sizes.
The CodeCopy component comes with built-in styling to provide a consistent and attractive appearance. However, you can customize its look using the sx
prop or styled-components. Here's an example of custom styling:
import React from 'react';
import { CodeCopy } from 'goobs-frontend';
import { Box } from '@mui/material';
const StyledCodeCopyExample: React.FC = () => {
const codeSnippet = `
const StyledComponent = styled.div\`
background-color: #f0f0f0;
padding: 16px;
border-radius: 8px;
\`;
`.trim();
return (
<Box sx={{ maxWidth: '600px', margin: '0 auto' }}>
<CodeCopy
code={codeSnippet}
language="javascript"
sx={{
'& pre': {
backgroundColor: '#2b2b2b',
color: '#f8f8f2',
padding: '16px',
borderRadius: '8px',
},
'& .hljs': {
background: 'transparent',
},
'& .MuiButton-root': {
backgroundColor: '#4caf50',
color: 'white',
'&:hover': {
backgroundColor: '#45a049',
},
},
}}
/>
</Box>
);
};
export default StyledCodeCopyExample;
You can use the CodeCopy component to display code snippets in various programming languages. The language
prop determines the syntax highlighting:
import React from 'react';
import { CodeCopy } from 'goobs-frontend';
import { Stack } from '@mui/material';
const MultiLanguageExample: React.FC = () => {
const pythonCode = `
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
`.trim();
const cppCode = `
#include <iostream>
int main() {
std::cout << "Hello, C++!" << std::endl;
return 0;
}
`.trim();
return (
<Stack spacing={2}>
<CodeCopy code={pythonCode} language="python" />
<CodeCopy code={cppCode} language="cpp" />
</Stack>
);
};
export default MultiLanguageExample;
You can use the CodeCopy component to display dynamically generated code or code fetched from an API:
import React, { useState, useEffect } from 'react';
import { CodeCopy } from 'goobs-frontend';
import { CircularProgress } from '@mui/material';
const DynamicCodeExample: React.FC = () => {
const [code, setCode] = useState<string | null>(null);
useEffect(() => {
// Simulating an API call
const fetchCode = async () => {
// Replace this with your actual API call
const response = await fetch('https://api.example.com/get-code-snippet');
const data = await response.json();
setCode(data.codeSnippet);
};
fetchCode();
}, []);
if (!code) {
return <CircularProgress />;
}
return (
<CodeCopy
code={code}
language="javascript"
/>
);
};
export default DynamicCodeExample;
The CodeCopy component is designed with accessibility in mind:
- The code is displayed in a
<pre>
tag, which preserves formatting and is recognized by screen readers as preformatted text. - The "Copy Code" button is properly labeled and can be accessed via keyboard navigation.
- When the code is copied, a console log message is displayed (in the future, this could be enhanced to provide a more accessible notification).
However, to ensure maximum accessibility:
- Provide context around the CodeCopy component, explaining what the code represents.
- If the code contains important visual elements (e.g., ASCII art), consider providing an additional text description.
- Language Specification: Always specify the correct language for accurate syntax highlighting.
- Code Formatting: Ensure your code snippets are properly formatted before passing them to the component.
- Context: Provide explanations or context around the code snippets to help users understand their purpose.
- Responsive Design: Consider the component's width when placing it in your layout, especially for mobile devices.
- Error Handling: When fetching code dynamically, implement proper error handling to gracefully manage failed requests.
The CodeCopy component uses highlight.js for syntax highlighting, which is applied client-side. For large code snippets or pages with many CodeCopy components, consider the following:
- Lazy loading: If the code snippets are not immediately visible, consider lazy loading the CodeCopy components.
- Memoization: If the code prop doesn't change frequently, wrap the CodeCopy component with React.memo to prevent unnecessary re-renders.
import React, { memo } from 'react';
import { CodeCopy } from 'goobs-frontend';
const MemoizedCodeCopy = memo(CodeCopy);
const PerformantCodeCopy: React.FC = () => {
const code = `// Your code here`;
return (
<MemoizedCodeCopy
code={code}
language="javascript"
/>
);
};
export default PerformantCodeCopy;
- Syntax Highlighting Not Working: Ensure you've specified the correct language. If the language is correct, check if it's supported by highlight.js.
- Copy Functionality Not Working: The copy functionality uses the document.execCommand('copy') method. Ensure you're using the component in a secure context (HTTPS) as some browsers restrict this functionality in non-secure contexts.
-
Styling Issues: If custom styles are not applying correctly, check the specificity of your CSS selectors. You may need to use more specific selectors or the
!important
flag in some cases.
By following these guidelines and leveraging the features of the CodeCopy component, you can effectively display and share code snippets in your goobs-frontend projects, enhancing the user experience for developers and technical users.