Skip to content

feat: Add copy button to highlighted code lines #12983

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions src/components/codeBlock/code-blocks.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,6 @@
}
}

:global(.highlight-line) {
background-color: rgba(239, 239, 239, 0.06);
/* Set highlight bg color */
border-left: 4px solid var(--brandPink);
}

/* Diff highlighting, classes provided by rehype-prism-plus */
/* Set inserted line (+) color */
Expand Down
5 changes: 4 additions & 1 deletion src/components/codeBlock/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {Clipboard} from 'react-feather';

import styles from './code-blocks.module.scss';

import {makeHighlightBlocks} from '../codeHighlights';
import {makeKeywordsClickable} from '../codeKeywords';

export interface CodeBlockProps {
Expand Down Expand Up @@ -57,7 +58,9 @@ export function CodeBlock({filename, language, children}: CodeBlockProps) {
<div className={styles.copied} style={{opacity: showCopied ? 1 : 0}}>
Copied
</div>
<div ref={codeRef}>{makeKeywordsClickable(children)}</div>
<div ref={codeRef}>
{makeKeywordsClickable(makeHighlightBlocks(children, language))}
</div>
</div>
);
}
Expand Down
149 changes: 149 additions & 0 deletions src/components/codeHighlights/codeHighlights.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
'use client';

import {Children, cloneElement, ReactElement, useEffect, useRef, useState} from 'react';
import {Check, Clipboard} from 'react-feather';
import styled from '@emotion/styled';
import * as Sentry from '@sentry/nextjs';

import {cleanCodeSnippet, useCleanSnippetInClipboard} from '../codeBlock';

type ChildrenItem = ReturnType<typeof Children.toArray>[number] | React.ReactNode;

export function makeHighlightBlocks(
children: React.ReactNode,
language: string | undefined
) {
const items = Children.toArray(children);

let highlightedLineElements: ReactElement[] = [];
let highlightElementGroupCounter = 0;

return items.reduce((arr: ChildrenItem[], child) => {
if (typeof child !== 'object') {
arr.push(child);
return arr;
}

const element = child as ReactElement;
const classes = element.props.className;

const isCodeLine = classes && classes.includes('code-line');
if (!isCodeLine) {
const updatedChild = cloneElement(
child as ReactElement,
element.props,
makeHighlightBlocks((child as ReactElement).props.children, language)
);
arr.push(updatedChild);
return arr;
}

const isHighlightedLine = isCodeLine && classes.includes('highlight-line');

if (isHighlightedLine) {
highlightedLineElements.push(element);
} else {
if (highlightedLineElements.length > 0) {
arr.push(
<HighlightBlock key={highlightElementGroupCounter} language={language}>
{...highlightedLineElements}
</HighlightBlock>
);
highlightedLineElements = [];
++highlightElementGroupCounter;
}
arr.push(child);
}

return arr;
}, [] as ChildrenItem[]);
}

export function HighlightBlock({
children,
language,
}: {
children: React.ReactNode;
language: string | undefined;
}) {
const codeRef = useRef<HTMLDivElement>(null);

useCleanSnippetInClipboard(codeRef, {language});

// Show the copy button after js has loaded
// otherwise the copy button will not work
const [showCopyButton, setShowCopyButton] = useState(false);
useEffect(() => {
setShowCopyButton(true);
}, []);

const [copied, setCopied] = useState(false);

async function copyCodeOnClick() {
if (codeRef.current === null) {
return;
}

const code = cleanCodeSnippet(codeRef.current.innerText, {language});

try {
setCopied(false);
await navigator.clipboard.writeText(code);
setCopied(true);
setTimeout(() => setCopied(false), 1200);
} catch (error) {
Sentry.captureException(error);
setCopied(false);
}
}

return (
<HighlightBlockContainer>
<CodeLinesContainer ref={codeRef}>{children}</CodeLinesContainer>
<ClipBoardContainer onClick={copyCodeOnClick}>
{showCopyButton && !copied && (
<Clipboard size={16} opacity={0.15} stroke={'white'} />
)}
{showCopyButton && copied && <Check size={16} stroke={'green'} />}
</ClipBoardContainer>
</HighlightBlockContainer>
);
}

const HighlightBlockContainer = styled('div')`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: stretch;
float: left;
min-width: 100%;
box-sizing: border-box;
background-color: rgba(239, 239, 239, 0.06);
position: relative;

border-left: 4px solid var(--brandPink);

:hover svg {
opacity: 1;
}
svg {
transition: all 150ms linear;
}
`;

const CodeLinesContainer = styled('div')`
padding: 8px 0;
width: calc(100% - 48px);
`;

const ClipBoardContainer = styled('div')`
position: absolute;
right: 0;
top: 0;
bottom: 0;
width: 48px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
`;
1 change: 1 addition & 0 deletions src/components/codeHighlights/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {makeHighlightBlocks} from './codeHighlights';
Loading