Skip to content

Commit

Permalink
Merge pull request #4119 from traPtitech/fix/modal_click_outside
Browse files Browse the repository at this point in the history
モーダル内でmousedownしてモーダル外でmouseupしたときはモーダルを閉じないように
  • Loading branch information
mehm8128 committed Dec 2, 2023
2 parents 07d2c54 + 80e8814 commit 972dd4c
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/components/UI/ClickOutside.ts
Expand Up @@ -6,7 +6,8 @@ import {
cloneVNode,
shallowRef,
onMounted,
onBeforeUnmount
onBeforeUnmount,
ref
} from 'vue'
import { isIOS } from '/@/lib/dom/browser'
import { useModalStore } from '/@/store/ui/modal'
Expand All @@ -23,7 +24,8 @@ const filterChildren = <T extends VNode>(vnodes: T[]) =>
return true
})

const eventName = isIOS() ? 'touchend' : 'click'
const startEventName = isIOS() ? 'touchstart' : 'mousedown'
const endEventName = isIOS() ? 'touchend' : 'mouseup'

/**
* そのデフォルトスロットに指定した要素の外でクリックされたときにclickOutsideイベントを発火する
Expand Down Expand Up @@ -51,8 +53,9 @@ export default defineComponent({
const element = shallowRef<Element | ComponentPublicInstance>()

const { shouldShowModal } = useModalStore()
const isMouseDown = ref(false)

const onClick = (e: MouseEvent | TouchEvent) => {
const onMouseDown = (e: MouseEvent | TouchEvent) => {
if (!element.value) return

if (props.unableWhileModalOpen && shouldShowModal.value) return
Expand All @@ -64,17 +67,36 @@ export default defineComponent({
return
}

isMouseDown.value = true
if (props.stop) {
e.stopPropagation()
}
}
const onMouseUp = (e: MouseEvent | TouchEvent) => {
if (!isMouseDown.value) return
isMouseDown.value = false

if (!element.value) return
const ele =
element.value instanceof Element ? element.value : element.value.$el

if (ele === e.target || e.composedPath().includes(ele)) {
return
}

emit('clickOutside', e)
if (props.stop) {
e.stopPropagation()
}
}

onMounted(() => {
window.addEventListener(eventName, onClick, { capture: true })
window.addEventListener(startEventName, onMouseDown, { capture: true })
window.addEventListener(endEventName, onMouseUp, { capture: true })
})
onBeforeUnmount(() => {
window.removeEventListener(eventName, onClick, { capture: true })
window.removeEventListener(startEventName, onMouseDown, { capture: true })
window.removeEventListener(endEventName, onMouseUp, { capture: true })
})

return () => {
Expand Down

0 comments on commit 972dd4c

Please sign in to comment.