Skip to content

Commit

Permalink
feat(#202): Add code copy button layout renderer
Browse files Browse the repository at this point in the history
  • Loading branch information
Tweekism committed Feb 22, 2025
1 parent 668de49 commit ce7a6ba
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/parser/copycode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import MarkdownIt from 'markdown-it';
import octicons from '@primer/octicons';

const copyIcon = octicons['copy'].toSVG({ class: 'icon-copy' });

export default function copycode(md: MarkdownIt) {
const defaultRender = md.renderer.rules.fence!;
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
const renderedPreBlock = defaultRender(tokens, idx, options, env, self);
return `
<div class="pre-wrapper" style="position: relative">
${renderedPreBlock}
<div class="copy-wrapper">
<button class="copy-button">${copyIcon}</button>
</div>
</div>
`;
};
}
2 changes: 2 additions & 0 deletions src/parser/markdown.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import MarkdownIt from 'markdown-it';
import anchor from 'markdown-it-anchor';
import copycode from './copycode.js';
import frontMatter from 'markdown-it-front-matter';
import highlight from './highlight.js';
import graphviz from './dot.js';
Expand Down Expand Up @@ -68,6 +69,7 @@ mdit.use(anchor, {
placement: 'before',
}),
});
mdit.use(copycode);
mdit.use(graphviz);
mdit.use(githubAlerts);
mdit.use(mermaid);
Expand Down
29 changes: 29 additions & 0 deletions static/markdown.css
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,35 @@ blockquote {
color: var(--alert-caution);
}

/* --------------------------------------------------------------------------
* COPY-CODE-BUTTON --------------------------------------------------------- */

.copy-wrapper {
position: absolute;
top: 0.5rem;
right: 0.5rem;
}
.copy-button {
padding: 0.4rem;
border: 0;
border-radius: 0.4rem;
background: none;
opacity: 0;
outline: none;
cursor: pointer;
transition: opacity 0.2s, background 0.2s;
}
pre:hover + .copy-wrapper .copy-button {
opacity: 0.3;
}
.copy-button:hover {
opacity: 1;
background-color: var(--border-regular);
}
.copy-button {
fill: var(--text-primary);
}

/* --------------------------------------------------------------------------
* MISCELLANEOUS ------------------------------------------------------------ */

Expand Down

0 comments on commit ce7a6ba

Please sign in to comment.