ryangjchandler/alpine-clipboard

Inline onCopy hook

azmy60 opened this issue · 5 comments

I propose a feature of attaching the onCopy hook by using an x-on attribute in the same element of the $clipboard was from.

This will allow custom behavior on desired elements instead of the global behavior.

<button
  type="button"
  x-data
  @click="$clipboard('Alpine.js is awesome!', true)"
  @clipboard-copy="console.log('Copied!')"
>
  Copy
</button>

To make this happen, we have to assign the second argument of $clipboard to true, so it will trigger @clipboard-copy instead of the global onCopy.

If you accept this idea, I would love to work on this. 😄

Why do we need to specify true as the second argument? Random boolean arguments like this are weird I think.

I'd say dispatching a copied event or something similar all the time is fine.

Oh, you're right! I missed this part. We can dispatch all the time without the second argument. Do we need to prevent the onCopy from running while the x-on:copied is specified?

For reference, here is I how implement the feature:

return window.navigator.clipboard.writeText(target)
  .then(() => {
    if(el.dispatchEvent(new Event('copy', {cancelable: true}))) {
      onCopy()
    }
})

Also, I just noticed that we could use the await $clipboard() to wait for it to finish, so I guess implementing this feature would not be necessary(?) For that case, I'm not sure this issue should stay open so I will close it.

You can do $clipboard(target).then(() => {}) as well.

I wanted feedback on the click, using picocss that worked very neat like this in the button's markup:

        @click="$clipboard(xdatavalue).then(() => { $event.target.dataset.tooltip='Copied!' })"
        @blur="delete($event.target.dataset.tooltip)"

Thank you all!