aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ColorSwatch.astro
blob: df01d5a3d0e463f8af9d1fe1fc7dce58e018b029 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
---
import { cn } from '@/lib/utils'

interface Props {
  class?: string
  color: string
  [key: string]: any
}

const { color: colorName, class: className, ...rest } = Astro.props
---

<button
  class={cn(
    'cursor-pointer bg-primary text-primary-foreground border-border border flex min-h-20  w-full items-center justify-center rounded font-mono text-sm font-bold',
    className,
  )}
  {...rest}
  title={'Click to copy: ' + colorName}
  data-color={colorName}
  data-color-swatch
>
  <span>{colorName}</span>
</button>

<script>
  const initClipboard = () => {
    const buttons = document.querySelectorAll(
      '[data-color-swatch]',
    ) as NodeListOf<HTMLButtonElement>

    buttons.forEach((button) => {
      const color = button?.dataset.color as string
      button?.addEventListener('click', async () => {
        try {
          await navigator.clipboard.writeText(color)
          button.innerText = 'Copied!'
          setTimeout(() => {
            button.innerText = color
          }, 1000)
        } catch (err) {
          console.error('Error copying to clipboard.', err)
        }
      })
    })
  }

  document.addEventListener('astro:page-load', initClipboard)
</script>