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

47 lines
1.5 KiB
JavaScript
Raw Normal View History

import React, { useContext, useState } from 'react'
2024-12-21 14:25:49 +01:00
import ReactDOMServer from 'react-dom/server'
import { CopyIcon, OkIcon } from '@freesewing/react/components/Icon'
import { CopyToClipboard as Copy } from 'react-copy-to-clipboard'
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 || ''
const handleCopied = (setCopied, setLoadingStatus, label) => {
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)
}
2024-12-23 10:54:13 +01:00
export const CopyToClipboard = ({ 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 (
<Copy text={text} onCopy={() => handleCopied(setCopied, setLoadingStatus, label)}>
<button className={copied ? 'tw-text-success' : ''}>
2024-12-21 14:25:49 +01:00
{copied ? (
2024-12-23 10:54:13 +01:00
<OkIcon
className={`${style} tw-text-success-content tw-bg-success tw-rounded-full tw-p-1`}
2024-12-23 10:54:13 +01:00
stroke={4}
/>
2024-12-21 14:25:49 +01:00
) : (
<CopyIcon className={`${style} tw-text-inherit`} />
2024-12-21 14:25:49 +01:00
)}
</button>
</Copy>
)
}