-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.tsx
97 lines (88 loc) · 2.36 KB
/
index.tsx
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use client'
import React, { useEffect, useRef, useState } from 'react'
import Styles from './WidgetDropdown.module.css'
import { useTranslations } from 'next-intl'
import { ICredits } from '../WidgetTemplate'
type WidgetDropdownProps = {
title: string | undefined
ariaLabel?: string
icon?: React.ReactNode
children: React.ReactNode
credits?: ICredits
isWidgetOpen?: (isOpen: boolean) => void
className?: string
position?: 'right' | 'left'
}
export default function WidgetDropdown({
title,
ariaLabel,
icon,
credits,
children,
isWidgetOpen = () => {}, // setting a default value
className = '',
position = 'right',
...props
}: WidgetDropdownProps) {
const t = useTranslations('t')
const [isOpen, setIsOpen] = useState<boolean>(false)
const containerRef = useRef<HTMLDivElement | null>(null)
const showCredits = credits?.title && credits?.url ? true : false
const handleClick = () => {
setIsOpen(!isOpen)
isWidgetOpen(!isOpen)
}
const handleOutsideClick = (event: MouseEvent) => {
if (
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setIsOpen(false)
}
}
useEffect(() => {
if (isOpen) {
document.addEventListener('mousedown', handleOutsideClick)
} else {
document.removeEventListener('mousedown', handleOutsideClick)
}
}, [isOpen])
return (
<div
className={`${Styles.container} ${className}`}
ref={containerRef}
{...props}>
<button
onClick={handleClick}
aria-expanded={isOpen}
className={isOpen ? Styles.opened : ''}
aria-label={ariaLabel ?? undefined}>
<figure>
{icon && icon}
{title}
</figure>
</button>
{isOpen && (
<div
className={Styles.containerDropdown}
style={{
right: position === 'right' ? 0 : 'auto',
left: position === 'left' ? '-4.75rem' : 'auto',
}}>
<div>{children}</div>
{showCredits && (
<p className={Styles.credits}>
{t('powered') ?? 'Powered by'}{' '}
<a
href={credits?.url + '/?utm_source=findto_app'}
target="_blank"
rel="noopener">
{credits?.title ?? ''}
</a>
</p>
)}
</div>
)}
</div>
)
}