![Visitors](https://visitor-badge.laobi.icu/badge?page_id=jpfulton.gatsby-remark-copy-button)
Add a copy button to markdown code snippets in
Gatsby sites with
compatibility for MDX and use of the browser
Clipboard API.
This package and implementation is discussed in this
blog post.
Install
yarn add @jpfulton/gatsby-remark-copy-button
How to Use
Add the configuration entry to your gatsby-config.js
file. This plugin
must be added before other plugins that operate on code
nodes and
markdown code snippets to operate correctly.
The following listing assumes you are using the gatsby-plugin-mdx
plugin.
However, this plugin may also be used with the gatsby-transformer-remark
plugin.
plugins: [
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.mdx`, `.md`],
gatsbyRemarkPlugins: [
{
resolve: `@jpfulton/gatsby-remark-copy-button`,
},
{
resolve: `gatsby-remark-code-titles`,
},
{
resolve: `gatsby-remark-prismjs`,
},
],
},
},
],
Options
All plugin options are optional. However, it is strongly suggested that
you customize them to override styling to fit your site's look, feel and layout.
{
resolve: `@jpfulton/gatsby-remark-copy-button`,
options: {
buttonText: null,
copySvg: null,
successSvg: null,
customButtonContainerClass: null,
customButtonClass: null,
},
},
Custom Styling
Custom styling may be applied to the default classes or using the options
above custom classes may be applied to the injected markup.
.gatsby-remark-copy-button-container {
}
.gatsby-remark-copy-button {
}
Apply custom styles by adding a style sheet to your gatsby-browser.js
file.
import "./src/styles/copy-button.scss";
Structure of the Injected Markup
When enabled on code snippet, the following HTML
will be injected into
the output of the page after parsing the Markdown AST using the default
plugin options. It will be injected above the code snippet in the
generated HTML
.
<div class="gatsby-remark-copy-button-container">
<button
class="gatsby-remark-copy-button"
onclick="copyToClipboard(`CLEANED CODE CONTENT TO COPY HERE`, this)"
>
<svg
class="copy-icon"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
>
...
</svg>
<svg
class="success-icon"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
>
...
</svg>
</button>
</div>
Usage in Markdown
Once installed, the copy button may optionally be enabled by adding
to the code snippet declaration within markdown files. When this plugin
is used in conjunction with the gatsby-remark-prismjs
plugin, the
{clipboardButton: true}
option may be provided in any order with other
prismjs options.
```js {clipboardButton: true}
const example = "This content will end up on the user's clipboard";
```
Further Information
For details on contributing to this project, reference both the
CONTRIBUTING.md and CODE_OF_CONDUCT.md
documentation.
To submit a bug or feature request, please open an issue
here.
To report create a security advisory, please reference the
SECURITY.md policy document.