import { useUserHasResponded } from 'domains/app/hooks' import { useConfig } from 'domains/config/hooks' import { useI18n } from 'domains/i18n/hooks' import { useVisibility } from 'domains/visibility/hooks' import { createFocusTrap } from 'focus-trap' import { className } from 'lib/css' import { ComponentChildren } from 'preact' import { forwardRef, useLayoutEffect } from 'preact/compat' import Suggestions from 'ui/components/suggestions' import { useSeamlyAppContainerClassNames } from 'ui/hooks/component-helper-hooks' import { useWindowOpenButtonFocusing } from 'ui/hooks/focus-helper-hooks' import { useSeamlyLayoutMode } from 'ui/hooks/seamly-state-hooks' import { useGeneratedId } from 'ui/hooks/utility-hooks' const Chat = forwardRef< HTMLElement, { children: ComponentChildren; className?: string } >(({ children, className: givenClassName = '' }, forwardedRef) => { const { closeChat, isOpen, isVisible } = useVisibility() const focusWindowOpenButton = useWindowOpenButtonFocusing() const { namespace, layoutMode } = useConfig() const { isInline } = useSeamlyLayoutMode() const appContainerClassNames = useSeamlyAppContainerClassNames() const chatSectionId = useGeneratedId() const headingId = useGeneratedId() const userHasResponded = useUserHasResponded() const { t } = useI18n() const defaultClassNames = [ 'chat', `chat--layout-${layoutMode}`, `namespace--${namespace}`, ] const classNames = [...defaultClassNames, givenClassName] if (typeof appContainerClassNames !== 'function') { classNames.push(...appContainerClassNames) } if (!isOpen && layoutMode !== 'app') { classNames.push('chat--collapsed') } if (userHasResponded) { classNames.push('chat--user-responded') } const onKeyDownHandler = (e) => { if ((e.code && e.code === 'Escape') || e.keyCode === 27) if (!isInline && isOpen) { closeChat() focusWindowOpenButton() } } // Stop trapping focus when closing starts, before the animation ends. // Otherwise, the trap can pull focus away from the chat open button. useLayoutEffect(() => { if (isOpen && layoutMode === 'window') { const focusTrap = createFocusTrap(`#${chatSectionId}`, { // WindowOpenButton chooses where to put focus when the chat opens. initialFocus: false, // The chat handles Escape and returns focus to the open button. // Do not let the trap move focus back to the app container: // Safari may scroll to it at the bottom of the page. escapeDeactivates: false, returnFocusOnDeactivate: false, // Let users click outside the chat to use the rest of the page. clickOutsideDeactivates: true, }) focusTrap.activate() return () => { focusTrap.deactivate() } } }, [chatSectionId, isOpen, layoutMode]) return ( isVisible && (

{t('window.srModalLayoutLabel')}

{children}
{layoutMode === 'inline' && isOpen && }
) ) }) export default Chat