Icon.tsx 985 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import React, { useEffect, useState } from "react"
  2. interface IconProps {
  3. src: string
  4. srcDark?: string
  5. alt?: string
  6. size?: string
  7. }
  8. export function Icon({ src, srcDark, alt = "icon", size = "1.2em" }: IconProps) {
  9. const [isDark, setIsDark] = useState(false)
  10. useEffect(() => {
  11. // Check initial dark mode state
  12. const checkDarkMode = () => {
  13. setIsDark(document.documentElement.classList.contains("dark"))
  14. }
  15. checkDarkMode()
  16. // Watch for dark mode changes
  17. const observer = new MutationObserver((mutations) => {
  18. mutations.forEach((mutation) => {
  19. if (mutation.attributeName === "class") {
  20. checkDarkMode()
  21. }
  22. })
  23. })
  24. observer.observe(document.documentElement, { attributes: true })
  25. return () => observer.disconnect()
  26. }, [])
  27. const imageSrc = isDark && srcDark ? srcDark : src
  28. return (
  29. <img
  30. src={imageSrc}
  31. alt={alt}
  32. style={{
  33. height: size,
  34. width: "auto",
  35. verticalAlign: "middle",
  36. display: "inline",
  37. }}
  38. />
  39. )
  40. }