useClipboard Hook - Guida Utilizzo β
β οΈ [DEV-166] Documentazione obsoleta. L'API
copy(text, context?)descritta in questo file non Γ¨ piΓΉ disponibile. Consultare lo Storybook di@elerama/uiβ sezione Hooks/useClipboard per la documentazione aggiornata. Vedere README.md per i dettagli della migrazione.
π Descrizione (storica) β
useClipboard() Γ¨ un hook React per copiare testo negli appunti con feedback visivo automatico e gestione dello stato.
File: app/hooks/useClipboard.ts
π― Caratteristiche β
β
Hook React nativo - Integrazione perfetta con React components β
Stato automatico - Gestisce copied, error automaticamente β
Auto-reset - Resetta lo stato dopo timeout configurabile β
Clipboard API moderna - HTTPS ready β
Fallback automatico - Supporta HTTP e browser vecchi β
Error handling - Gestione completa degli errori β
TypeScript - Full type safety
π Utilizzo Base β
Componente Simple β
import { useClipboard } from "@/hooks/utils/useClipboard";
export function CopyButton() {
const { copy, copied } = useClipboard();
const handleCopy = async () => {
await copy("Testo da copiare", "CopyButton");
};
return (
<button onClick={handleCopy}>
{copied ? "β
Copiato!" : "π Copia"}
</button>
);
}Con Error Handling β
import { useClipboard } from "@/hooks/utils/useClipboard";
export function AdvancedCopy() {
const { copy, copied, error } = useClipboard(3000); // 3 secondi di timeout
const handleCopy = async () => {
const success = await copy("Testo", "AdvancedCopy");
if (!success && error) {
alert(`Errore: ${error}`);
}
};
return (
<div>
<button onClick={handleCopy}>Copia</button>
{copied && <span>β
Copiato negli appunti!</span>}
{error && <span style={{color: 'red'}}>β {error}</span>}
</div>
);
}π Signature Hook β
export function useClipboard(resetTimeMs = 2000) {
// resetTimeMs: tempo (ms) prima di resettare lo stato 'copied'
// Default: 2000ms (2 secondi)
return {
copy, // (text: string, context?: string) => Promise<boolean>
copied, // boolean - true se il testo Γ¨ stato copiato
error, // string | null - messaggio di errore (se presente)
};
}Parametri β
| Parametro | Tipo | Default | Descrizione |
|---|---|---|---|
resetTimeMs | number | 2000 | Millisecondi prima di resettare copied a false |
Ritorno β
| Chiave | Tipo | Descrizione |
|---|---|---|
copy(text, context?) | async function | Funzione per copiare testo |
copied | boolean | true se ultimo copy Γ¨ riuscito |
error | string | null | Messaggio errore (se presente) |
π‘ Esempi Pratici β
1. Badge con Feedback β
export function CopyWithBadge() {
const { copy, copied } = useClipboard();
return (
<button onClick={() => copy("Code123")}>
π {copied ? "β
" : "Copy"}
</button>
);
}2. Multi-Copy β
export function MultiCopy() {
const { copy, copied } = useClipboard(2000);
return (
<div>
<button onClick={() => copy("Fastlabel", "fastlabel")}>
Fastlabel {copied ? "β
" : ""}
</button>
<button onClick={() => copy("Offline", "offline")}>
Offline {copied ? "β
" : ""}
</button>
</div>
);
}3. Con Loader β
import { useState } from "react";
import { useClipboard } from "@/hooks/utils/useClipboard";
export function CopyWithLoader() {
const { copy, copied, error } = useClipboard();
const [loading, setLoading] = useState(false);
const handleCopy = async () => {
setLoading(true);
await copy("Large text...", "loader");
setLoading(false);
};
return (
<button onClick={handleCopy} disabled={loading}>
{loading ? "Copiando..." : copied ? "β
Copiato" : "π Copia"}
</button>
);
}4. Uso in Hook (useTopbarCart) β
// Nel hook useTopbarCart
const { copy } = useClipboard();
const fastlabel = async () => {
const fastlabelText = iframeWindow.fastlabel_response;
const success = await copy(fastlabelText, 'useTopbarCart');
if (success) {
notifySuccess();
}
};π Debug e Logging β
L'hook logga automaticamente nel console:
[useClipboard] β
Testo copiato negli appunti (Clipboard API)
[useClipboard] β οΈ Clipboard API error: NotAllowedError
[useClipboard] β
Testo copiato negli appunti (legacy method)π Troubleshooting β
"Errore: Impossibile copiare negli appunti" β
Cause comuni:
- Mancanza di permessi clipboard (browser chiede primo accesso)
- Ambiente non-HTTPS senza fallback disponibile
- Browser non supportato (molto raro)
Soluzione:
const { copy, error } = useClipboard();
await copy('text');
if (error) {
console.log(`Fallback usato: ${error}`);
}Copy non funziona in iframe β
Possibili cause:
- CORS policy
- Same-origin requirement
Test:
// Controlla se Γ¨ iframe
console.log(window !== window.parent);State non si resetta β
Soluzione: Aumenta il timeout
const { copy, copied } = useClipboard(5000); // 5 secondiπ Riferimenti Tecnici β
Versione: 2.0.0 (Hook React) Ultima Aggiornamento: 2025-10-21
if (success) { // Notificare all'iframe che la copia Γ¨ riuscita notifyClipboardSuccess(); } else { // Mostrare errore all'utente showError("Impossibile copiare negli appunti"); } }
## π Debug e Logging
La funzione registra automaticamente nel console:[useTopbarCart] β Testo copiato negli appunti (Clipboard API) [useTopbarCart] β οΈ Clipboard API error: ... Trying legacy method... [useTopbarCart] β Testo copiato negli appunti (legacy method) [useTopbarCart] β Errore metodo legacy: ...
## π§© Componenti che Usano
- `useTopbarCart.ts` - Hook per il carrello della topbar
- `test-iframe.html` - Pagina di test iframe
## π‘ Note Tecniche
### Fallback Legacy (execCommand)
Il fallback utilizza `document.execCommand('copy')` che:
- β
Funziona in HTTP (non secure)
- β
Funziona in iframe cross-origin (con restrizioni)
- β οΈ Γ deprecato ma ampiamente supportato
- β οΈ Potrebbe non funzionare in alcuni browser ultra-moderni
### Permessi Richiesti
La Clipboard API richiede:
- HTTPS (in ambienti di produzione)
- Permesso dell'utente (mostrato dal browser al primo utilizzo)
- Stesso origin (non cross-domain)
Il fallback **non** richiede permessi espliciti.
## π Troubleshooting
### Errore: "navigator.clipboard is undefined"
β La Clipboard API non Γ¨ disponibile, ma il fallback legacy funzionerΓ automaticamente
### Errore: "Failed to copy text with legacy method"
β Il browser potrebbe non supportare `execCommand('copy')`. Verifica che:
- Il testo Γ¨ valido (non null/undefined)
- Il browser Γ¨ supportato (IE 9+)
- Non stai operando in un worker thread
### Errore: "Clipboard is not available"
β Potresti avere CORS issues. Il fallback dovrebbe funzionare comunque.
## π Riferimenti
- [MDN - Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API)
- [MDN - document.execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand)