Added copy link component

This commit is contained in:
Alexis
2025-03-26 15:43:20 +01:00
parent 3460689d3d
commit 15f18a8f95
5 changed files with 142 additions and 29 deletions

View File

@@ -0,0 +1,81 @@
---
import { t } from '@/i18n/store';
import { getLangFromUrl } from '@/i18n/utils';
interface Props {
text: string,
}
const { text } = Astro.props
const lang = getLangFromUrl(Astro.url);
const placeholder = t('common.copyLink', lang)
const message = t('common.copiedLink', lang)
---
<button data-target={text} data-copy={placeholder} data-copy-message={message}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path d="M240,88.23a54.43,54.43,0,0,1-16,37L189.25,160a54.27,54.27,0,0,1-38.63,16h-.05A54.63,54.63,0,0,1,96,119.84a8,8,0,0,1,16,.45A38.62,38.62,0,0,0,150.58,160h0a38.39,38.39,0,0,0,27.31-11.31l34.75-34.75a38.63,38.63,0,0,0-54.63-54.63l-11,11A8,8,0,0,1,135.7,59l11-11A54.65,54.65,0,0,1,224,48,54.86,54.86,0,0,1,240,88.23ZM109,185.66l-11,11A38.41,38.41,0,0,1,70.6,208h0a38.63,38.63,0,0,1-27.29-65.94L78,107.31A38.63,38.63,0,0,1,144,135.71a8,8,0,0,0,16,.45A54.86,54.86,0,0,0,144,96a54.65,54.65,0,0,0-77.27,0L32,130.75A54.62,54.62,0,0,0,70.56,224h0a54.28,54.28,0,0,0,38.64-16l11-11A8,8,0,0,0,109,185.66Z"></path></svg>
<span data-copy-text>
{placeholder}
</span>
</button>
<script>
const copyColor = 'initial'
const copyColorSuccess = 'var(--green-500)'
const copyTimeout = 2000
const dataCopyButtons = document.querySelectorAll<HTMLButtonElement>('button[data-copy]')
dataCopyButtons.forEach(button => {
button.addEventListener('click', () => {
const copyText = button.getAttribute('data-target')
navigator.clipboard.writeText(copyText!)
changeCopyText(button)
})
})
function changeCopyText(copyButton: HTMLButtonElement) {
const copyPlaceholder = copyButton.getAttribute('data-copy')
const copyPlaceholderSuccess = copyButton.getAttribute('data-copy-message')
const dataText = copyButton.querySelector<HTMLSpanElement>('[data-copy-text]')
const svg = copyButton.querySelector<SVGElement>('svg')
if (!dataText || !svg) return
dataText.textContent = copyPlaceholderSuccess
dataText.style.color = copyColorSuccess
svg.style.fill = copyColorSuccess
setTimeout(() => {
dataText.textContent = copyPlaceholder
dataText.style.color = copyColor
svg.style.fill = copyColor
}, copyTimeout)
}
</script>
<style lang="scss">
button {
display: inline-flex;
align-items: center;
gap: .5ch;
color: var(--slate-700);
cursor: pointer;
text-underline-offset: 2px;
text-decoration: none;
&:hover,
&:focus-visible {
text-decoration: underline;
}
svg {
width: 1rem;
height: 1rem;
fill: var(--slate-700);
}
}
</style>