11ty / eleventy-plugin-syntaxhighlight

A pack of Eleventy plugins for syntax highlighting in Markdown, Liquid, and Nunjucks templates.
https://www.11ty.dev/docs/plugins/syntaxhighlight/
MIT License
130 stars 32 forks source link

Is there a copy button? #63

Open jeffski opened 2 years ago

jeffski commented 2 years ago

Not an issue, but I was wondering if there are any code examples or plugins that would add a copy button/icon to the code block so you can copy it to the clipboard?

christopherpickering commented 1 year ago

I made a pretty simple way to do it using some javascript and tailwindcss -

in the .eleventy.js I add a few classes to the pre:

eleventyConfig.addPlugin(syntaxHighlight, {
    preAttributes: {
      class: ({ language }) => `group/code animate-fade rounded-lg bg-slate-900/80 language-${language || 'plain'}`,
    },
  });

Then I have a copy_code.js file I include in all my pages:

(() => {
  const code = document.querySelectorAll('pre[class*="language"]');

  const buttonClasses = [
    'absolute',
    'right-4',
    'top-4',
    'border',
    'rounded-md',
    'p-2',
    'bg-white/80',
    'hover:bg-white',
    'text-slate-800',
    'hover:text-slate-900',
    'opacity-0',
    'group-hover/code:opacity-100',
    'transition-opacity',
    'transition-colors',
  ];

  code.forEach((pre) => {
    pre.classList.add('relative');

    const button = document.createElement('button');
    button.classList.add(...buttonClasses);
    button.innerHTML =
      '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>';

    button.addEventListener('click', () => {
      navigator.clipboard.writeText(pre.textContent);
    });
    pre.appendChild(button);
  });
})();

Now when I hover over the code block I get a nice button:

image

Ps, I'm using eleventy-plugin-rollup, you might need to tweak the js to run properly in your browser.