swyxio / svelte-actions

prototype official actions for Svelte
MIT License
228 stars 9 forks source link

action: copy to clipboard on click #17

Open kindoflew opened 3 years ago

kindoflew commented 3 years ago

Copies text to clipboard when clicked. Attach to the node you want to copy or, with the optional target parameter, attach to a button to copy the desired text. I've seen this used a lot for coding tutorials, specifically for copying long terminal commands.


<p use:clickToCopy> Click to copy this text </p>

or

<button use:clickToCopy={'p'}> Click to copy that text </button>

...

export function clickToCopy(node, target) {
  async function copyText(event) {
    const text = target 
      ? document.querySelector(target).innerText 
      : event.target.innerText;

    try {
      await navigator.clipboard.writeText(text);
    } catch(e) {
    // not sure what kind of error handling.
    // could have try/catch dispatch
    // success/failure events so the dev
    // can use it to alert users of the outcome?
    }
  }

  node.addEventListener('click', copyText);

  return {
    destroy() {
      node.removeEventListener('click', copyText);
    }
  }
}

REPL example: https://svelte.dev/repl/667d8ac94e2349f3a1b7b8c5fa4c0082?version=3.32.1

Would be happy to try a PR if people like this.

swyxio commented 2 years ago

sorry for the delayed response - interesting idea! not sure about the a11y angle of offering it for a button or a p tag. but i like it that its not trivial to implement so it could be helpful in a library.

leaving it open for people to find.

kindoflew commented 2 years ago

no worries! it gave me time to actually learn how to use jsdom properly 😂