index.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use client'
  2. import React, { useEffect, useRef, useState } from 'react'
  3. import { useTranslation } from 'react-i18next'
  4. import QRCode from 'qrcode.react'
  5. import Tooltip from '../tooltip'
  6. import QrcodeStyle from './style.module.css'
  7. type Props = {
  8. content: string
  9. selectorId: string
  10. className?: string
  11. }
  12. const prefixEmbedded = 'appOverview.overview.appInfo.qrcode.title'
  13. const ShareQRCode = ({ content, selectorId, className }: Props) => {
  14. const { t } = useTranslation()
  15. const [isShow, setIsShow] = useState<boolean>(false)
  16. const qrCodeRef = useRef<HTMLDivElement>(null)
  17. const toggleQRCode = (event: React.MouseEvent) => {
  18. event.stopPropagation()
  19. setIsShow(prev => !prev)
  20. }
  21. useEffect(() => {
  22. const handleClickOutside = (event: MouseEvent) => {
  23. if (qrCodeRef.current && !qrCodeRef.current.contains(event.target as Node))
  24. setIsShow(false)
  25. }
  26. if (isShow)
  27. document.addEventListener('click', handleClickOutside)
  28. return () => {
  29. document.removeEventListener('click', handleClickOutside)
  30. }
  31. }, [isShow])
  32. const downloadQR = () => {
  33. const canvas = document.getElementsByTagName('canvas')[0]
  34. const link = document.createElement('a')
  35. link.download = 'qrcode.png'
  36. link.href = canvas.toDataURL()
  37. link.click()
  38. }
  39. const handlePanelClick = (event: React.MouseEvent) => {
  40. event.stopPropagation()
  41. }
  42. return (
  43. <Tooltip
  44. selector={`common-qrcode-show-${selectorId}`}
  45. content={t(`${prefixEmbedded}`) || ''}
  46. >
  47. <div
  48. className={`w-8 h-8 cursor-pointer rounded-lg ${className ?? ''}`}
  49. onClick={toggleQRCode}
  50. >
  51. <div className={`w-full h-full ${QrcodeStyle.QrcodeIcon} ${isShow ? QrcodeStyle.show : ''}`} />
  52. {isShow && (
  53. <div
  54. ref={qrCodeRef}
  55. className={QrcodeStyle.qrcodeform}
  56. onClick={handlePanelClick}
  57. >
  58. <QRCode size={160} value={content} className={QrcodeStyle.qrcodeimage}/>
  59. <div className={QrcodeStyle.text}>
  60. <div className={`text-gray-500 ${QrcodeStyle.scan}`}>{t('appOverview.overview.appInfo.qrcode.scan')}</div>
  61. <div className={`text-gray-500 ${QrcodeStyle.scan}`}>·</div>
  62. <div className={QrcodeStyle.download} onClick={downloadQR}>{t('appOverview.overview.appInfo.qrcode.download')}</div>
  63. </div>
  64. </div>
  65. )}
  66. </div>
  67. </Tooltip>
  68. )
  69. }
  70. export default ShareQRCode