Skip to content

Commit d95a75e

Browse files
feat(ch-copy-button): copy value to clipboard with feedback (#137)
Composes ch-button so variant, size, disabled and label behave as there. The slot content is the label; on a successful clipboard write the button shows copiedLabel and a check icon for copiedDuration ms, then reverts. Emits chCopy on success and chCopyError when the clipboard API is missing (insecure context) or the write rejects. Slot forwarding through two shadow roots is covered in the browser project, which mock-doc cannot project.
1 parent 2c251ba commit d95a75e

12 files changed

Lines changed: 457 additions & 1 deletion

File tree

‎docs-site/assets/js/app.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ customElements.whenDefined('ch-combobox').then(() => {
5252
bind('demo-combobox', [{ name: 'chChange', format: ev => `chChange: ${ev.detail}` }]);
5353
});
5454

55+
customElements.whenDefined('ch-copy-button').then(() => {
56+
bind('demo-copy', [{ name: 'chCopy', format: () => 'chCopy' }]);
57+
});
58+
5559
customElements.whenDefined('ch-confirm-dialog').then(() => {
5660
const dialog = document.getElementById('demo-confirm');
5761
const trigger = document.getElementById('demo-confirm-open');

‎docs-site/index.html‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,13 @@ <h2 class="side-heading" id="side-components-heading">Componentes</h2>
128128
>
129129
<a class="side-link" href="#ch-combobox">ch-combobox</a>
130130
</li>
131+
<li
132+
class="side-item"
133+
data-name="ch-copy-button"
134+
data-desc="Botón que copia value al portapapeles sobre ch-button (hereda variant, size, disabled y label). El contenido del slot es la etiqueta; al copiar muestra copiedLabel y un check durante copiedDuration ms. Emite chCopy al escribir y chCopyError si el portapapeles no está disponible (contexto no seguro) o rechaza."
135+
>
136+
<a class="side-link" href="#ch-copy-button">ch-copy-button</a>
137+
</li>
131138
<li
132139
class="side-item"
133140
data-name="ch-confirm-dialog"
@@ -590,6 +597,27 @@ <h3>ch-combobox</h3>
590597
<span class="t">&lt;ch-combobox</span> <span class="a">id</span>="demo-combobox-multi" <span class="a">label</span>="Clientes" <span class="a">multiple</span> <span class="a">placeholder</span>="Agrega clientes"<span class="t">&gt;</span><span class="t">&lt;/ch-combobox</span><span class="t">&gt;</span></code></pre>
591598
</div>
592599

600+
<div class="comp" id="ch-copy-button" tabindex="-1">
601+
<div class="comp-head">
602+
<h3>ch-copy-button</h3>
603+
<span class="tag">@devschile/chucao/ch-copy-button</span>
604+
</div>
605+
<p class="comp-desc">
606+
Botón que copia <code>value</code> al portapapeles sobre <code>ch-button</code> (hereda <code>variant</code>, <code>size</code>, <code>disabled</code> y
607+
<code>label</code>). El contenido del slot es la etiqueta; al copiar muestra <code>copiedLabel</code> y un check durante <code>copiedDuration</code> ms. Emite
608+
<code>chCopy</code> al escribir y <code>chCopyError</code> si el portapapeles no está disponible (contexto no seguro) o rechaza.
609+
</p>
610+
<div class="comp-demo">
611+
<ch-copy-button id="demo-copy" value="ch-9f2k-demo" variant="secondary" copied-label="¡Copiado!">Copiar ID</ch-copy-button>
612+
<ch-copy-button value="https://devschile.cl/chucao" label="Copiar enlace">Copiar enlace</ch-copy-button>
613+
<div id="demo-copy-log" class="event-log"></div>
614+
</div>
615+
<pre
616+
class="comp-code"
617+
><code><span class="t">&lt;ch-copy-button</span> <span class="a">id</span>="demo-copy" <span class="a">value</span>="ch-9f2k-demo" <span class="a">variant</span>="secondary" <span class="a">copied-label</span>="¡Copiado!"<span class="t">&gt;</span>Copiar ID<span class="t">&lt;/ch-copy-button</span><span class="t">&gt;</span>
618+
<span class="t">&lt;ch-copy-button</span> <span class="a">value</span>="https://devschile.cl/chucao" <span class="a">label</span>="Copiar enlace"<span class="t">&gt;</span>Copiar enlace<span class="t">&lt;/ch-copy-button</span><span class="t">&gt;</span></code></pre>
619+
</div>
620+
593621
<div class="comp" id="ch-confirm-dialog" tabindex="-1">
594622
<div class="comp-head">
595623
<h3>ch-confirm-dialog</h3>

‎docs/ai.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ and code generators.
66

77
## Component allow-list
88

9-
Chucao exposes exactly 39 components. Nothing else exists — do not invent
9+
Chucao exposes exactly 40 components. Nothing else exists — do not invent
1010
tags.
1111

1212
| Tag | Purpose |
@@ -19,6 +19,7 @@ tags.
1919
| `ch-checkbox` | Checkbox input |
2020
| `ch-cluster` | Horizontal wrapping flow |
2121
| `ch-combobox` | Filterable picker, single or multiple |
22+
| `ch-copy-button` | Copies `value` to the clipboard |
2223
| `ch-confirm-dialog` | Confirmation over `ch-modal`, one outcome |
2324
| `ch-description-list` | Label/value pairs on a native `<dl>` |
2425
| `ch-divider` | Visual separator |

‎llms.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
- [ch-cluster](https://devschile.github.io/chucao/components/ch-cluster/): Horizontal flow that wraps when it runs out of room, with a token-driven
2020
- [ch-combobox](https://devschile.github.io/chucao/components/ch-combobox/): A text field that filters a list of options and commits a choice.
2121
- [ch-confirm-dialog](https://devschile.github.io/chucao/components/ch-confirm-dialog/): A confirmation dialog over `ch-modal`.
22+
- [ch-copy-button](https://devschile.github.io/chucao/components/ch-copy-button/): A button that copies `value` to the clipboard and confirms it visually.
2223
- [ch-description-list](https://devschile.github.io/chucao/components/ch-description-list/): Label/value pairs for detail views, on a native `<dl>`.
2324
- [ch-divider](https://devschile.github.io/chucao/components/ch-divider/): ch-divider component
2425
- [ch-drawer](https://devschile.github.io/chucao/components/ch-drawer/): Sliding side panel for navigation, editing forms and quick detail views.

‎package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@
5858
"import": "./dist/components/ch-combobox.js",
5959
"types": "./dist/components/ch-combobox.d.ts"
6060
},
61+
"./ch-copy-button": {
62+
"import": "./dist/components/ch-copy-button.js",
63+
"types": "./dist/components/ch-copy-button.d.ts"
64+
},
6165
"./ch-description-list": {
6266
"import": "./dist/components/ch-description-list.js",
6367
"types": "./dist/components/ch-description-list.d.ts"

‎scripts/gallery-data.mjs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,17 @@ export const gallery = [
162162
if (combo) combo.options = clientes;
163163
}`,
164164
},
165+
{
166+
tag: 'ch-copy-button',
167+
description:
168+
'Botón que copia <code>value</code> al portapapeles sobre <code>ch-button</code> (hereda <code>variant</code>, <code>size</code>, <code>disabled</code> y <code>label</code>). El contenido del slot es la etiqueta; al copiar muestra <code>copiedLabel</code> y un check durante <code>copiedDuration</code> ms. Emite <code>chCopy</code> al escribir y <code>chCopyError</code> si el portapapeles no está disponible (contexto no seguro) o rechaza.',
169+
demos: [
170+
'<ch-copy-button id="demo-copy" value="ch-9f2k-demo" variant="secondary" copied-label="¡Copiado!">Copiar ID</ch-copy-button>',
171+
'<ch-copy-button value="https://devschile.cl/chucao" label="Copiar enlace">Copiar enlace</ch-copy-button>',
172+
'<div id="demo-copy-log" class="event-log"></div>',
173+
],
174+
bindings: [{ id: 'demo-copy', event: 'chCopy', format: "() => 'chCopy'" }],
175+
},
165176
{
166177
tag: 'ch-confirm-dialog',
167178
description:

‎src/components/ch-button/readme.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@
3434

3535
## Dependencies
3636

37+
### Used by
38+
39+
- [ch-copy-button](../ch-copy-button)
40+
3741
### Depends on
3842

3943
- [ch-spinner](../ch-spinner)
@@ -42,6 +46,7 @@
4246
```mermaid
4347
graph TD;
4448
ch-button --> ch-spinner
49+
ch-copy-button --> ch-button
4550
style ch-button fill:#f9f,stroke:#333,stroke-width:4px
4651
```
4752

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
:host {
2+
display: inline-block;
3+
}
4+
5+
.copy-icon {
6+
width: var(--icon-size-sm);
7+
height: var(--icon-size-sm);
8+
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { render, h, describe, it, expect, vi, beforeEach, afterEach } from '@stencil/vitest';
2+
3+
import '../ch-button/ch-button';
4+
import './ch-copy-button.tsx';
5+
6+
const settle = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
7+
8+
function innerButton(root: HTMLElement) {
9+
return root.shadowRoot.querySelector('ch-button') as HTMLElement & { shadowRoot: ShadowRoot; variant?: string; size?: string; disabled?: boolean; label?: string };
10+
}
11+
12+
// mock-doc does not project a <slot> that is itself assigned to another
13+
// component's slot, so the inner ch-button renders empty here. The real
14+
// projection is covered in tests/browser/ch-copy-button.browser.spec.ts;
15+
// these specs dispatch chClick on the ch-button host directly.
16+
function click(root: HTMLElement) {
17+
innerButton(root).dispatchEvent(new CustomEvent('chClick'));
18+
}
19+
20+
describe('ch-copy-button', () => {
21+
const writeText = vi.fn();
22+
23+
beforeEach(() => {
24+
writeText.mockReset().mockResolvedValue(undefined);
25+
Object.defineProperty(globalThis.navigator, 'clipboard', { value: { writeText }, configurable: true });
26+
});
27+
28+
afterEach(() => {
29+
Object.defineProperty(globalThis.navigator, 'clipboard', { value: undefined, configurable: true });
30+
});
31+
32+
it('renders on top of ch-button', async () => {
33+
const { root } = await render(<ch-copy-button value="abc">Copiar</ch-copy-button>);
34+
35+
expect(innerButton(root)).not.toBeNull();
36+
expect(innerButton(root).variant).toBe('ghost');
37+
});
38+
39+
it('forwards variant, size, disabled and label to the inner button', async () => {
40+
const { root } = await render(
41+
<ch-copy-button value="abc" variant="secondary" size="sm" label="Copiar clave">
42+
Copiar
43+
</ch-copy-button>,
44+
);
45+
const button = innerButton(root);
46+
47+
expect(button.variant).toBe('secondary');
48+
expect(button.size).toBe('sm');
49+
expect(button.label).toBe('Copiar clave');
50+
});
51+
52+
it('is disabled when there is no value to copy', async () => {
53+
const { root } = await render(<ch-copy-button value="">Copiar</ch-copy-button>);
54+
55+
expect(innerButton(root).disabled).toBe(true);
56+
});
57+
58+
it('writes the value, emits chCopy and shows the copied label', async () => {
59+
const { root, waitForChanges } = await render(
60+
<ch-copy-button value="secreto" copiedLabel="¡Copiado!" copiedDuration={50}>
61+
Copiar
62+
</ch-copy-button>,
63+
);
64+
const spy = vi.fn();
65+
root.addEventListener('chCopy', spy as EventListener);
66+
67+
click(root);
68+
await waitForChanges();
69+
await settle(10);
70+
71+
expect(writeText).toHaveBeenCalledWith('secreto');
72+
expect(spy).toHaveBeenCalledTimes(1);
73+
expect(root.shadowRoot.textContent).toContain('¡Copiado!');
74+
});
75+
76+
it('reverts to the slot after copiedDuration', async () => {
77+
const { root, waitForChanges } = await render(
78+
<ch-copy-button value="secreto" copiedLabel="¡Copiado!" copiedDuration={30}>
79+
Copiar
80+
</ch-copy-button>,
81+
);
82+
83+
click(root);
84+
await waitForChanges();
85+
await settle(80);
86+
await waitForChanges();
87+
88+
expect(root.shadowRoot.textContent).not.toContain('¡Copiado!');
89+
expect(root.shadowRoot.querySelector('slot')).not.toBeNull();
90+
});
91+
92+
it('emits chCopyError when the clipboard is unavailable', async () => {
93+
Object.defineProperty(globalThis.navigator, 'clipboard', { value: undefined, configurable: true });
94+
const { root, waitForChanges } = await render(<ch-copy-button value="x">Copiar</ch-copy-button>);
95+
const copied = vi.fn();
96+
const failed = vi.fn();
97+
root.addEventListener('chCopy', copied as EventListener);
98+
root.addEventListener('chCopyError', failed as EventListener);
99+
100+
click(root);
101+
await waitForChanges();
102+
await settle(10);
103+
104+
expect(copied).not.toHaveBeenCalled();
105+
expect(failed).toHaveBeenCalledTimes(1);
106+
});
107+
108+
it('emits chCopyError when the write rejects', async () => {
109+
writeText.mockRejectedValue(new Error('denied'));
110+
const { root, waitForChanges } = await render(<ch-copy-button value="x">Copiar</ch-copy-button>);
111+
const copied = vi.fn();
112+
const failed = vi.fn();
113+
root.addEventListener('chCopy', copied as EventListener);
114+
root.addEventListener('chCopyError', failed as EventListener);
115+
116+
click(root);
117+
await waitForChanges();
118+
await settle(10);
119+
120+
expect(copied).not.toHaveBeenCalled();
121+
expect(failed).toHaveBeenCalledTimes(1);
122+
});
123+
});
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import { Component, Element, Event, type EventEmitter, Host, Prop, State, h } from '@stencil/core';
2+
3+
import { hasLightDomText, warnMissingName } from '../../utils/accessibility';
4+
import { chIcons } from '../../utils/icons';
5+
import type { ChButtonSize, ChButtonVariant } from '../ch-button/ch-button';
6+
7+
/**
8+
* A button that copies `value` to the clipboard and confirms it visually.
9+
*
10+
* Rendered on top of `ch-button`, so `variant` and `size` behave exactly as
11+
* there. The label is the default slot; while the copied feedback is showing,
12+
* `copiedLabel` replaces it and the icon swaps from copy to check. The
13+
* feedback reverts after `copiedDuration` milliseconds, and a new copy
14+
* restarts the window.
15+
*
16+
* `navigator.clipboard` only exists in secure contexts; when it is missing or
17+
* rejects, nothing is copied and `chCopyError` fires instead of `chCopy`.
18+
*/
19+
@Component({
20+
tag: 'ch-copy-button',
21+
styleUrl: 'ch-copy-button.css',
22+
shadow: true,
23+
})
24+
export class ChCopyButton {
25+
@Element() private el: HTMLElement;
26+
27+
/**
28+
* The text written to the clipboard on click. An empty `value` disables
29+
* the button — there is nothing meaningful to copy.
30+
*/
31+
@Prop() value = '';
32+
33+
/**
34+
* Text shown instead of the slot content while the copied feedback is
35+
* visible.
36+
*/
37+
@Prop() copiedLabel = 'Copied';
38+
39+
/**
40+
* How long the copied feedback stays visible, in milliseconds.
41+
*/
42+
@Prop() copiedDuration = 2000;
43+
44+
/** Visual style, forwarded to the inner `ch-button`. */
45+
@Prop() variant: ChButtonVariant = 'ghost';
46+
47+
/** Size, forwarded to the inner `ch-button`. */
48+
@Prop() size: ChButtonSize = 'md';
49+
50+
/** Whether the button is disabled. */
51+
@Prop() disabled = false;
52+
53+
/**
54+
* Accessible label forwarded to the inner `ch-button`'s native button. Use
55+
* it when the visible content does not say what gets copied.
56+
*/
57+
@Prop() label?: string;
58+
59+
/** Emitted after the clipboard write resolves. */
60+
@Event() chCopy: EventEmitter<void>;
61+
62+
/** Emitted when the clipboard is unavailable or the write rejects. */
63+
@Event() chCopyError: EventEmitter<void>;
64+
65+
@State() private copied = false;
66+
67+
private resetTimer?: ReturnType<typeof setTimeout>;
68+
69+
disconnectedCallback() {
70+
if (this.resetTimer) {
71+
clearTimeout(this.resetTimer);
72+
}
73+
}
74+
75+
private handleClick = async () => {
76+
if (this.disabled || !this.value) {
77+
return;
78+
}
79+
const { clipboard } = navigator;
80+
if (!clipboard) {
81+
this.chCopyError.emit();
82+
return;
83+
}
84+
try {
85+
await clipboard.writeText(this.value);
86+
} catch {
87+
this.chCopyError.emit();
88+
return;
89+
}
90+
this.copied = true;
91+
this.chCopy.emit();
92+
if (this.resetTimer) {
93+
clearTimeout(this.resetTimer);
94+
}
95+
this.resetTimer = setTimeout(() => {
96+
this.copied = false;
97+
}, this.copiedDuration);
98+
};
99+
100+
render() {
101+
if (!this.label && !hasLightDomText(this.el)) {
102+
warnMissingName(this.el, 'ch-copy-button', 'pass label so the button has an accessible name');
103+
}
104+
105+
const icon = this.copied ? chIcons.check : chIcons.copy;
106+
107+
return (
108+
<Host>
109+
<ch-button variant={this.variant} size={this.size} disabled={this.disabled || !this.value} label={this.label} onChClick={this.handleClick}>
110+
<svg
111+
slot="start"
112+
class="copy-icon"
113+
viewBox="0 0 24 24"
114+
fill="none"
115+
stroke="currentColor"
116+
stroke-width="2"
117+
stroke-linecap="round"
118+
stroke-linejoin="round"
119+
aria-hidden="true"
120+
focusable="false"
121+
>
122+
{icon.map(shape => h(shape.tag, shape.attrs))}
123+
</svg>
124+
{this.copied ? this.copiedLabel : <slot></slot>}
125+
</ch-button>
126+
</Host>
127+
);
128+
}
129+
}

0 commit comments

Comments
 (0)