fix: display tooltip to the left of the cursor if not enough space

This commit is contained in:
Valentin Kaelin 2019-11-29 18:08:23 +01:00
parent 8e61783c9a
commit bf589f636b

View file

@ -2,6 +2,7 @@
<div> <div>
<!-- trigger --> <!-- trigger -->
<div <div
ref="trigger"
@mouseenter="showDropdown" @mouseenter="showDropdown"
@mousemove="mousemove" @mousemove="mousemove"
@mouseleave="hideDropdown" @mouseleave="hideDropdown"
@ -16,7 +17,7 @@
v-show="isOpen" v-show="isOpen"
ref="content" ref="content"
class="fixed z-40 bg-blue-1000 py-2 rounded-md shadow" class="fixed z-40 bg-blue-1000 py-2 rounded-md shadow"
:style="{ width, ...position }" :style="{ ...position }"
> >
<slot></slot> <slot></slot>
</div> </div>
@ -25,13 +26,6 @@
<script> <script>
export default { export default {
props: {
width: {
type: String,
default: 'auto'
}
},
data() { data() {
return { return {
isOpen: false, isOpen: false,
@ -39,15 +33,18 @@ export default {
offset: 12, offset: 12,
top: 0, top: 0,
directionBottom: true, directionBottom: true,
directionRight: true,
directionChecked: false, directionChecked: false,
width: 0
} }
}, },
computed: { computed: {
position() { position() {
const valuetoRemove = this.directionBottom ? 0 : this.height() const valuetoRemove = this.directionBottom ? 0 : this.height()
const leftValue = this.directionRight ? this.left + this.offset : this.left - this.width - this.offset / 2
return { return {
left: `${this.left + this.offset}px`, left: `${leftValue}px`,
top: `${this.top + this.offset - valuetoRemove}px`, top: `${this.top + this.offset - valuetoRemove}px`,
} }
} }
@ -63,9 +60,13 @@ export default {
methods: { methods: {
checkDropdownVisibility() { checkDropdownVisibility() {
this.directionChecked = true this.directionChecked = true
const rect = this.$refs.content.getBoundingClientRect() const contentRect = this.$refs.content.getBoundingClientRect()
const triggerRect = this.$refs.trigger.getBoundingClientRect()
this.width = contentRect.width
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight) const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight)
this.directionBottom = (rect.bottom + this.offset) < viewHeight const viewWidth = Math.max(document.documentElement.clientWidth, window.innerWidth)
this.directionBottom = (contentRect.bottom + this.offset) < viewHeight
this.directionRight = (this.left + this.width + triggerRect.width + this.offset) < viewWidth
}, },
handleScroll() { handleScroll() {
this.isOpen = false this.isOpen = false
@ -76,6 +77,7 @@ export default {
hideDropdown() { hideDropdown() {
this.isOpen = false this.isOpen = false
this.directionBottom = true this.directionBottom = true
this.directionRight = true
this.directionChecked = false this.directionChecked = false
}, },
async mousemove(event) { async mousemove(event) {