svelteuidev / svelteui

SvelteUI Monorepo
https://svelteui.dev
MIT License
1.28k stars 64 forks source link

[Feature Request] Support dynamic text (function) for use-clipboard action #348

Closed resah closed 1 year ago

resah commented 1 year ago

Usage example, including component, action, motion, or utility API

I tried to use the clipboard action for a "share link" button in a map. When clicked, it should read the current map center and zoom level and create a URL from that information. Since clipboard can only handle a fix string, I can't evaluate the text right on click.

It would be great to alternatively support a function which creates the text on the fly.

Possible implementation - describe how the feature can be implemented

Right now I implemented this feature in my project in the following way:

export const clipboard = (node: HTMLElement, text: string | (() => string)): ReturnType<Action> => {
  const click = async () => {
    const detailText = typeof text === 'string' ? text : text();
    if (detailText)
      try {
        await navigator.clipboard.writeText(detailText);

        node.dispatchEvent(new CustomEvent('useclipboard', { detail: detailText }));
      } catch (e) {
        node.dispatchEvent(new CustomEvent('useclipboard-error', { detail: e }));
      }
  };

  node.addEventListener('click', click, true);

  return {
    update: (t: string | (() => string)) => (text = t),
    destroy: () => node.removeEventListener('click', click, true),
  };
};
 <button use:clipboard={() => `This text will be copied at ${new Date().toUTCString()}`}>Copy Me</button>

I would love to contribute, if this is a feature, you would like to include.

Do you want to contribute this feature and create a pull request

Yes

BeeMargarida commented 1 year ago

If you would like to tackle this one, please go for it 😄 I would greatly appreciate it!

BeeMargarida commented 1 year ago

Thank you @resah! It will be available next release!