UNPKG

stream-chat-react

Version:

React components to create chat conversations or livestream style chat

50 lines (49 loc) 2.69 kB
import { useRef } from 'react'; import { useEffect } from 'react'; import React, { useState } from 'react'; import { DialogAnchor, useDialog, useDialogIsOpen } from '../Dialog'; import { DialogManagerProvider, useTranslationContext } from '../../context'; const DropdownContext = React.createContext({ close: () => null, }); const DropdownContextProvider = ({ children, ...props }) => (React.createElement(DropdownContext.Provider, { value: props }, children)); export const useDropdownContext = () => React.useContext(DropdownContext); export const Dropdown = (props) => { const dropdownDialogId = `dropdown`; return (React.createElement("div", { className: 'str-chat__dropdown' }, React.createElement(DialogManagerProvider, { id: dropdownDialogId }, React.createElement(DropdownInner, { ...props, dialogId: dropdownDialogId })))); }; const DropdownInner = ({ children, dialogId, openButtonProps, placement = 'bottom', }) => { const { t } = useTranslationContext(); const [openButton, setOpenButton] = useState(null); const [dropdownWidth, setDropdownWidth] = useState(''); const dropdownRef = useRef(null); const dialog = useDialog({ id: dialogId }); const dropdownDialogIsOpen = useDialogIsOpen(dialogId); useEffect(() => { if (!openButton || typeof ResizeObserver === 'undefined') return; let timeout; const observer = new ResizeObserver(([button]) => { if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { const width = button.target.getBoundingClientRect().width + 'px'; if (!dropdownRef.current) { setDropdownWidth(width); return; } dropdownRef.current.style.width = width; }, 100); }); observer.observe(openButton); return () => { observer.disconnect(); }; }, [openButton]); return (React.createElement(DropdownContextProvider, { close: dialog.close }, React.createElement("button", { "aria-expanded": dropdownDialogIsOpen, "aria-haspopup": 'true', "aria-label": t('aria/Open Menu'), className: 'str-chat__dropdown__open-button', "data-testid": 'dropdown-open-button', ...openButtonProps, onClick: () => dialog?.toggle(), ref: setOpenButton }), React.createElement(DialogAnchor, { allowFlip: false, id: dialogId, placement: placement, referenceElement: openButton, tabIndex: -1, trapFocus: true }, React.createElement("div", { className: 'str-chat__dropdown__items', ref: dropdownRef, style: { width: dropdownWidth } }, children)))); };