index.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 QrcodeStyle from './style.module.css'
  6. import Tooltip from '@/app/components/base/tooltip'
  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. popupContent={t(`${prefixEmbedded}`) || ''}
  45. >
  46. <div
  47. className={`w-8 h-8 cursor-pointer rounded-lg ${className ?? ''}`}
  48. onClick={toggleQRCode}
  49. >
  50. <div className={`w-full h-full ${QrcodeStyle.QrcodeIcon} ${isShow ? QrcodeStyle.show : ''}`} />
  51. {isShow && (
  52. <div
  53. ref={qrCodeRef}
  54. className={QrcodeStyle.qrcodeform}
  55. onClick={handlePanelClick}
  56. >
  57. <QRCode size={160} value={content} className={QrcodeStyle.qrcodeimage}/>
  58. <div className={QrcodeStyle.text}>
  59. <div className={`text-gray-500 ${QrcodeStyle.scan}`}>{t('appOverview.overview.appInfo.qrcode.scan')}</div>
  60. <div className={`text-gray-500 ${QrcodeStyle.scan}`}>·</div>
  61. <div className={QrcodeStyle.download} onClick={downloadQR}>{t('appOverview.overview.appInfo.qrcode.download')}</div>
  62. </div>
  63. </div>
  64. )}
  65. </div>
  66. </Tooltip>
  67. )
  68. }
  69. export default ShareQRCode