Skip to content

Commit

Permalink
CopyButton enhancements (#346)
Browse files Browse the repository at this point in the history
* Allow CopyButton to take a function that returns a string

* allow customizing message
  • Loading branch information
dimfeld authored May 10, 2024
1 parent f4198f4 commit 725fdcf
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/perfect-dogs-behave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte-ux": minor
---

Allow customizing CopyButton notification
5 changes: 5 additions & 0 deletions .changeset/shy-oranges-float.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte-ux": minor
---

Allow CopyButton to take a function that returns a string
18 changes: 13 additions & 5 deletions packages/svelte-ux/src/lib/components/CopyButton.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
import Button from './Button.svelte';
import { getComponentSettings } from './settings.js';
import { slide } from 'svelte/transition';
import { createEventDispatcher } from 'svelte';
let className: string | undefined = undefined;
export { className as class };
const dispatch = createEventDispatcher<{ click: void }>();
const { classes: settingsClasses, defaults } = getComponentSettings('CopyButton');
export let value: string;
export let value: string | (() => string);
export let message: string | null = 'Copied!';
let showMessage = false;
$: if (showMessage) {
Expand All @@ -25,11 +29,15 @@
{...restProps}
class={cls('CopyButton', settingsClasses.root, className)}
on:click={() => {
navigator.clipboard.writeText(value);
showMessage = true;
let copyValue = typeof value === 'function' ? value() : value;
navigator.clipboard.writeText(copyValue);
dispatch('click');
if (message) {
showMessage = true;
}
}}
>
{#if showMessage}
<span transition:slide={{ axis: 'x', duration: 200 }}>Copied!</span>
{#if showMessage && message}
<span transition:slide={{ axis: 'x', duration: 200 }}>{message}</span>
{/if}
</Button>
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,21 @@
</div>
</div>
</Preview>

<h2>Using a Function</h2>

<Preview>
<CopyButton value={() => 'Stop copying me!'} />
</Preview>

<h2>With Custom Message</h2>

<Preview>
<CopyButton value="Stop copying me!" message="I copied it..." />
</Preview>

<h2>With Alternate Notification</h2>

<Preview>
<CopyButton value="Stop copying me!" on:click={() => alert('Copied!')} message={null} />
</Preview>

0 comments on commit 725fdcf

Please sign in to comment.