Sharkey/packages/frontend/src/components/MkMenu.child.vue

92 lines
2 KiB
Vue
Raw Normal View History

<!--
SPDX-FileCopyrightText: syuilo and other misskey contributors
SPDX-License-Identifier: AGPL-3.0-only
-->
2022-07-17 15:06:33 +03:00
<template>
<div ref="el" :class="$style.root">
2023-05-19 07:58:09 +03:00
<MkMenu :items="items" :align="align" :width="width" :asDrawer="false" @close="onChildClosed"/>
2022-07-17 15:06:33 +03:00
</div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, shallowRef, watch } from 'vue';
import MkMenu from './MkMenu.vue';
2022-07-17 15:06:33 +03:00
import { MenuItem } from '@/types/menu';
const props = defineProps<{
items: MenuItem[];
targetElement: HTMLElement;
2022-07-17 17:18:05 +03:00
rootElement: HTMLElement;
2022-07-17 15:06:33 +03:00
width?: number;
viaKeyboard?: boolean;
}>();
const emit = defineEmits<{
(ev: 'closed'): void;
(ev: 'actioned'): void;
}>();
const el = shallowRef<HTMLElement>();
2022-07-17 15:06:33 +03:00
const align = 'left';
const SCROLLBAR_THICKNESS = 16;
2022-07-17 15:06:33 +03:00
function setPosition() {
2022-07-17 17:18:05 +03:00
const rootRect = props.rootElement.getBoundingClientRect();
const parentRect = props.targetElement.getBoundingClientRect();
const myRect = el.value.getBoundingClientRect();
let left = props.targetElement.offsetWidth;
let top = (parentRect.top - rootRect.top) - 8;
if (rootRect.left + left + myRect.width >= (window.innerWidth - SCROLLBAR_THICKNESS)) {
left = -myRect.width;
}
if (rootRect.top + top + myRect.height >= (window.innerHeight - SCROLLBAR_THICKNESS)) {
top = top - ((rootRect.top + top + myRect.height) - (window.innerHeight - SCROLLBAR_THICKNESS));
}
2022-07-17 15:06:33 +03:00
el.value.style.left = left + 'px';
el.value.style.top = top + 'px';
}
function onChildClosed(actioned?: boolean) {
if (actioned) {
emit('actioned');
} else {
emit('closed');
}
}
watch(() => props.targetElement, () => {
setPosition();
});
const ro = new ResizeObserver((entries, observer) => {
setPosition();
});
2022-07-17 15:06:33 +03:00
onMounted(() => {
ro.observe(el.value);
2022-07-17 15:06:33 +03:00
setPosition();
nextTick(() => {
setPosition();
});
});
onUnmounted(() => {
ro.disconnect();
});
2022-07-17 15:06:33 +03:00
defineExpose({
checkHit: (ev: MouseEvent) => {
return (ev.target === el.value || el.value.contains(ev.target));
},
});
</script>
<style lang="scss" module>
.root {
2022-07-17 17:18:05 +03:00
position: absolute;
2022-07-17 15:06:33 +03:00
}
</style>