2024-12-22 16:32:46 +01:00
|
|
|
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'
|
2024-12-22 16:32:46 +01:00
|
|
|
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 || ''
|
|
|
|
|
2024-12-22 16:32:46 +01:00
|
|
|
const handleCopied = (setCopied, setLoadingStatus, label) => {
|
2024-12-21 14:25:49 +01:00
|
|
|
setCopied(true)
|
2024-12-22 16:32:46 +01:00
|
|
|
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-22 16:32:46 +01:00
|
|
|
export const CopyToClipboard = ({ content, label = false }) => {
|
2024-12-21 14:25:49 +01:00
|
|
|
const [copied, setCopied] = useState(false)
|
2024-12-22 16:32:46 +01:00
|
|
|
const { setLoadingStatus } = useContext(LoadingStatusContext)
|
2024-12-21 14:25:49 +01:00
|
|
|
|
|
|
|
const text =
|
|
|
|
typeof content === 'string' ? content : strip(ReactDOMServer.renderToStaticMarkup(content))
|
|
|
|
|
|
|
|
return (
|
2024-12-22 16:32:46 +01:00
|
|
|
<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>
|
|
|
|
)
|
|
|
|
}
|