Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

добавить закрытие по обертке #191

Merged
merged 5 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/features/Contacts/contacts.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
position: fixed;
right: 20px;
bottom: 20px;
z-index: 999;
z-index: 2;
}

.contactsMenu {
Expand Down
11 changes: 0 additions & 11 deletions src/shared/ui/Modal/Modal.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,6 @@
&.modal-zoom-out {
animation: zoom-out 300ms ease-in-out;
}

.cross-button {
cursor: pointer;
position: absolute;
top: 50px;
right: 56px;

path {
fill: var.$white;
}
}
}

@keyframes zoom-in {
Expand Down
50 changes: 34 additions & 16 deletions src/shared/ui/Modal/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import React, { HTMLAttributes, useCallback, useEffect, useRef, useState } from
import classNames from 'classnames'
import { createFocusTrap } from 'focus-trap'
import { createPortal } from 'react-dom'
import IconClose from '@/assets/icons/IconClose.svg'
import styles from './Modal.module.scss'
import { Button } from '@/shared/ui/Button/Button'

interface IModalProps extends HTMLAttributes<HTMLElement> {
isModalOpen: boolean
Expand All @@ -13,8 +11,6 @@ interface IModalProps extends HTMLAttributes<HTMLElement> {
}

// Поменял импорт на дефолтный, чтобы можно было использовать React.lazy
// @TODO: Ограничить перемещение табом внутри одного поп-апа
// https://github.com/Studio-Yandex-Practicum/maxboom_frontend/issues/106

/**
* Functional component for a modal window.
Expand All @@ -26,7 +22,6 @@ interface IModalProps extends HTMLAttributes<HTMLElement> {
export default function Modal({ isModalOpen, onClose, className, children }: IModalProps) {
const modalRef = useRef<HTMLDivElement>(null)
const [isModalClosing, setIsModalClosing] = useState(false)
const closeDelayTimeout = useRef<number | null>(null)

const handleClose = useCallback(() => {
setIsModalClosing(true)
Expand All @@ -45,8 +40,6 @@ export default function Modal({ isModalOpen, onClose, className, children }: IMo
className
)

// @TODO: Не работает клик по wrapper для закрытия модалки
// https://github.com/Studio-Yandex-Practicum/maxboom_frontend/issues/118
const handleContentClick = useCallback((event: React.MouseEvent) => {
event.stopPropagation()
}, [])
Expand All @@ -65,32 +58,60 @@ export default function Modal({ isModalOpen, onClose, className, children }: IMo
[handleClose, isModalOpen]
)

const handleClickWrapper = useCallback(
(event: MouseEvent) => {
if (modalRef.current === event.target && isModalOpen) {
const neighboringModals = document.querySelectorAll(`.${styles['modal-container']}`)
const lastNeighboringModal = neighboringModals[neighboringModals.length - 1]
const isLastModal = lastNeighboringModal && lastNeighboringModal.contains(modalRef.current)
if (isLastModal) {
handleClose()
}
}
},
[handleClose, isModalOpen]
)

// Для добавления слушателей событий при открытии модального окна и их удаления при его закрытии
// Позволяет избежать возможных проблем с утечками памяти или продолжительной работы слушателей, когда они больше не нужны
// useEffect обеспечивает активацию и деактивацию (через return) обработчиков событий
useEffect(() => {
document.addEventListener('mousedown', handleClickWrapper)
document.addEventListener('keydown', handleKeyDown)

return () => {
document.removeEventListener('mousedown', handleClickWrapper)
document.removeEventListener('keydown', handleKeyDown)
}
}, [handleKeyDown])
}, [handleKeyDown, handleClickWrapper])

// Таймер затираем на стадии размонтирования, т.к. реакт много раз рендерится и глобальная область заполняется
useEffect(() => {
let closeTimeout: NodeJS.Timeout
if (isModalClosing) {
closeDelayTimeout.current = window.setTimeout(() => {
closeTimeout = setTimeout(() => {
closeModal()
}, 300)
} else if (closeDelayTimeout.current) {
clearTimeout(closeDelayTimeout.current)
closeDelayTimeout.current = null
}

return () => {
clearTimeout(closeTimeout)
}
}, [isModalClosing, closeModal])

useEffect(() => {
const trap = createFocusTrap(modalRef.current as HTMLDivElement, {
allowOutsideClick: true
allowOutsideClick: true,
checkCanFocusTrap: async (): Promise<void> => {
await new Promise<void>(resolve => {
// Таймер для включения ловушки фокуса. Без него выпадает ошибка для вложенных модальных окон
// о том что необходим хотя бы один node для фокусировки. Также решалось добавлением пустой кнопки,
// но на неё можно было табом перейти
setTimeout(() => {
resolve()
}, 400)
})
}
})

if (isModalOpen) {
Expand All @@ -105,9 +126,6 @@ export default function Modal({ isModalOpen, onClose, className, children }: IMo
return createPortal(
<div className={styles['modal-wrapper']} onClick={handleClose}>
<div ref={modalRef} className={modalContainerClass} onClick={handleContentClick}>
<Button className={styles['cross-button']}>
<IconClose onClick={handleClose} />
</Button>
{children}
</div>
</div>,
Expand Down
Loading