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

42 lines
1.4 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)
}
export const CopyToClipboard = ({ content, label = 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))
return (
<Copy text={text} onCopy={() => handleCopied(setCopied, setLoadingStatus, label)}>
2024-12-21 14:25:49 +01:00
<button className={copied ? 'text-success' : ''}>
{copied ? (
<OkIcon className="w-5 h-5 text-success-content bg-success rounded-full p-1" stroke={4} />
) : (
<CopyIcon className="w-5 h-5 text-inherit" />
)}
</button>
</Copy>
)
}