copy-to-clipboard.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { FC, memo, MouseEventHandler, useCallback, useState } from 'react'
  2. import { Button } from 'react-bootstrap'
  3. import { useTranslation } from 'react-i18next'
  4. import Tooltip from './tooltip'
  5. import Icon from './icon'
  6. export const CopyToClipboard = memo<{
  7. content: string
  8. tooltipId: string
  9. kind?: 'text' | 'icon'
  10. }>(({ content, tooltipId, kind = 'icon' }) => {
  11. const { t } = useTranslation()
  12. const [copied, setCopied] = useState(false)
  13. const handleClick = useCallback(() => {
  14. navigator.clipboard.writeText(content).then(() => {
  15. setCopied(true)
  16. window.setTimeout(() => {
  17. setCopied(false)
  18. }, 1500)
  19. })
  20. }, [content])
  21. if (!navigator.clipboard?.writeText) {
  22. return null
  23. }
  24. return (
  25. <Tooltip
  26. id={tooltipId}
  27. description={copied ? `${t('copied')}!` : t('copy')}
  28. overlayProps={{
  29. delayHide: copied ? 1000 : 250,
  30. shouldUpdatePosition: true,
  31. }}
  32. >
  33. <span>
  34. {kind === 'text' ? (
  35. <TextButton handleClick={handleClick} />
  36. ) : (
  37. <IconButton handleClick={handleClick} copied={copied} />
  38. )}
  39. </span>
  40. </Tooltip>
  41. )
  42. })
  43. CopyToClipboard.displayName = 'CopyToClipboard'
  44. const TextButton: FC<{
  45. handleClick: MouseEventHandler<Button>
  46. }> = ({ handleClick }) => {
  47. const { t } = useTranslation()
  48. return (
  49. <Button
  50. onClick={handleClick}
  51. bsSize="xsmall"
  52. bsStyle={null}
  53. className="copy-button btn-secondary"
  54. >
  55. {t('copy')}
  56. </Button>
  57. )
  58. }
  59. const IconButton: FC<{
  60. handleClick: MouseEventHandler<Button>
  61. copied: boolean
  62. }> = ({ handleClick, copied }) => {
  63. const { t } = useTranslation()
  64. return (
  65. <Button
  66. onClick={handleClick}
  67. bsSize="xsmall"
  68. bsStyle="link"
  69. className="copy-button"
  70. aria-label={t('copy')}
  71. >
  72. <Icon type={copied ? 'check' : 'clipboard'} />
  73. </Button>
  74. )
  75. }