copy-to-clipboard.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { memo, useCallback, useState } from 'react'
  2. import { useTranslation } from 'react-i18next'
  3. import OLButton from '@/shared/components/ol/ol-button'
  4. import OLTooltip from '@/shared/components/ol/ol-tooltip'
  5. import OLIconButton from '@/shared/components/ol/ol-icon-button'
  6. export const CopyToClipboard = memo<{
  7. content: string
  8. tooltipId: string
  9. kind?: 'text' | 'icon'
  10. unfilled?: boolean
  11. onClick?: () => void
  12. }>(({ content, tooltipId, kind = 'icon', unfilled = false, onClick }) => {
  13. const { t } = useTranslation()
  14. const [copied, setCopied] = useState(false)
  15. const handleClick = useCallback(() => {
  16. navigator.clipboard.writeText(content).then(() => {
  17. setCopied(true)
  18. window.setTimeout(() => {
  19. setCopied(false)
  20. }, 1500)
  21. })
  22. if (onClick) {
  23. onClick()
  24. }
  25. }, [content, onClick])
  26. if (!navigator.clipboard?.writeText) {
  27. return null
  28. }
  29. return (
  30. <OLTooltip
  31. id={tooltipId}
  32. description={copied ? `${t('copied')}!` : t('copy')}
  33. overlayProps={{ delay: copied ? 1000 : 250 }}
  34. >
  35. {kind === 'text' ? (
  36. <OLButton
  37. onClick={handleClick}
  38. size="sm"
  39. variant="secondary"
  40. className="copy-button"
  41. >
  42. {t('copy')}
  43. </OLButton>
  44. ) : (
  45. <OLIconButton
  46. onClick={handleClick}
  47. variant="link"
  48. size="sm"
  49. accessibilityLabel={t('copy')}
  50. className="copy-button"
  51. icon={copied ? 'check' : 'content_copy'}
  52. unfilled={unfilled}
  53. />
  54. )}
  55. </OLTooltip>
  56. )
  57. })
  58. CopyToClipboard.displayName = 'CopyToClipboard'