1
0
Fork 0
freesewing/packages/react/components/CopyToClipboardButton/index.mjs

49 lines
1.5 KiB
JavaScript
Raw Normal View History

import React, { useContext, useState } from 'react'
2025-02-22 15:58:35 +01:00
import { copyToClipboard } from '@freesewing/utils'
2024-12-21 14:25:49 +01:00
import ReactDOMServer from 'react-dom/server'
import { CopyIcon, OkIcon } from '@freesewing/react/components/Icon'
import { LoadingStatusContext } from '@freesewing/react/context/LoadingStatus'
2024-12-21 14:25:49 +01:00
const strip = (html) =>
typeof DOMParser === 'undefined'
? html
: new DOMParser().parseFromString(html, 'text/html').body.textContent || ''
2025-02-22 15:58:35 +01:00
const handleCopied = (content, setCopied, setLoadingStatus, label) => {
copyToClipboard(content)
2024-12-21 14:25:49 +01:00
setCopied(true)
setLoadingStatus([
true,
label ? `${label} copied to clipboard` : 'Copied to clipboard',
true,
true,
])
2024-12-21 14:25:49 +01:00
setTimeout(() => setCopied(false), 1000)
}
2025-02-22 15:58:35 +01:00
export const CopyToClipboardButton = ({ content, label = false, sup = false }) => {
2024-12-21 14:25:49 +01:00
const [copied, setCopied] = useState(false)
const { setLoadingStatus } = useContext(LoadingStatusContext)
2024-12-21 14:25:49 +01:00
const text =
typeof content === 'string' ? content : strip(ReactDOMServer.renderToStaticMarkup(content))
2025-02-02 15:02:35 +01:00
const style = sup ? 'tw-w-4 tw-h-4 tw--mt-4' : 'tw-w-5 tw-h-5'
2024-12-23 10:54:13 +01:00
2024-12-21 14:25:49 +01:00
return (
2025-02-22 15:58:35 +01:00
<button
className={copied ? 'tw-text-success' : ''}
onClick={() => handleCopied(content, setCopied, setLoadingStatus, label)}
>
{copied ? (
<OkIcon
className={`${style} tw-text-success-content tw-bg-success tw-rounded-full tw-p-1`}
stroke={4}
/>
) : (
<CopyIcon className={`${style} tw-text-inherit`} />
)}
</button>
2024-12-21 14:25:49 +01:00
)
}