koel/resources/assets/js/components/ui/ContextMenuBase.vue

94 lines
2.1 KiB
Vue
Raw Normal View History

2022-04-15 14:24:30 +00:00
<template>
<nav
2022-04-24 08:29:14 +00:00
v-if="shown"
ref="el"
v-koel-clickaway="close"
v-koel-focus
2022-04-15 14:24:30 +00:00
:class="extraClass"
:style="{ top: `${top}px`, left: `${left}px` }"
2022-04-24 08:29:14 +00:00
class="menu context-menu"
2022-04-15 14:24:30 +00:00
tabindex="0"
2022-04-24 08:29:14 +00:00
@contextmenu.prevent
2022-04-15 14:24:30 +00:00
@keydown.esc="close"
>
<ul>
<slot>Menu items go here.</slot>
</ul>
</nav>
</template>
2022-04-15 17:00:08 +00:00
<script lang="ts" setup>
import { nextTick, ref, toRefs } from 'vue'
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
const props = defineProps<{ extraClass: string }>()
const { extraClass } = toRefs(props)
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
const el = ref<HTMLElement>()
const shown = ref(false)
const top = ref(0)
const left = ref(0)
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
const preventOffScreen = async (element: HTMLElement, isSubmenu = false) => {
const { bottom, right } = element.getBoundingClientRect()
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
if (bottom > window.innerHeight) {
element.style.top = 'auto'
element.style.bottom = '0'
} else {
element.style.bottom = 'auto'
2022-04-15 14:24:30 +00:00
}
2022-04-15 17:00:08 +00:00
if (right > window.innerWidth) {
element.style.right = isSubmenu ? `${el.value?.getBoundingClientRect().width}px` : '0'
element.style.left = 'auto'
} else {
element.style.right = 'auto'
}
}
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
const initSubmenus = () => {
Array.from(el.value?.querySelectorAll('.has-sub') as NodeListOf<HTMLElement>).forEach(item => {
const submenu = item.querySelector<HTMLElement>('.submenu')
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
if (!submenu) {
return
2022-04-15 14:24:30 +00:00
}
2022-04-15 17:00:08 +00:00
item.addEventListener('mouseenter', async () => {
submenu.style.display = 'block'
await nextTick()
await preventOffScreen(submenu, true)
})
item.addEventListener('mouseleave', () => {
submenu.style.top = '0'
submenu.style.bottom = 'auto'
submenu.style.display = 'none'
})
})
}
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
const open = async (_top = 0, _left = 0) => {
top.value = _top
left.value = _left
shown.value = true
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
await nextTick()
2022-04-15 14:24:30 +00:00
2022-04-15 17:00:08 +00:00
try {
await preventOffScreen(el.value!)
await initSubmenus()
} catch (e) {
console.error(e)
2022-04-15 17:00:08 +00:00
// in a non-browser environment (e.g., unit testing), these two functions are broken due to calls to
// getBoundingClientRect() and querySelectorAll
2022-04-15 14:24:30 +00:00
}
}
2022-04-15 17:00:08 +00:00
const close = () => {
shown.value = false
}
defineExpose({ open, close, shown })
</script>