<!--
    #VUE3 Done
-->

<template>
    <transition
        name="px-transition-expand"
        @before-enter="beforeEnterOrLeave"
        @before-leave="beforeEnterOrLeave"
        @enter="enter"
        @after-enter="afterEnter"
        @leave="leave"
    >
        <slot class="test" />
    </transition>
</template>

<script>
export default {
    props: {
        /**
         * Override the transition duration (in seconds)
         */
        duration: { type: Number, default: null },
    },

    methods: {
        beforeEnterOrLeave(element) {
            if (this.duration) {
                element.style.transitionDuration = this.duration + 's';
            } else {
                element.style.transitionDuration = null;
            }
        },

        enter(element) {
            // cache width
            const width = getComputedStyle(element).width;

            // height prep
            element.style.width = width;
            element.style.position = 'absolute';
            element.style.visibility = 'hidden';
            element.style.height = 'auto';
            element.style.opacity = 0;

            // cache height
            const height = getComputedStyle(element).height;

            // restore
            element.style.width = null;
            element.style.position = null;
            element.style.visibility = null;
            element.style.height = null;
            element.style.opacity = null;

            // force repaint
            void getComputedStyle(element).height;

            // trigger the animation
            //setTimeout(() => {
            this.$emit('height-computed', height);
            element.style.height = height;
            //}, 10);
        },

        afterEnter(element) {
            element.style.height = null;
            element.style.opacity = null;
        },

        leave(element) {
            const height = getComputedStyle(element).height;

            element.style.height = height;
            element.style.opacity = 0;

            // force repaint
            void getComputedStyle(element).height;

            //setTimeout(() => {
            element.style.height = 0;
            //}, 10);
        },
    },
};
</script>

<style lang="scss">
@use '../styles/px.scss' as *;

.px-transition-expand-enter-active,
.px-transition-expand-leave-active {
    transition:
        height 500ms $ease-out-cubic,
        opacity 500ms $ease-out-cubic;
}

.px-transition-expand-enter-from,
.px-transition-expand-enter,
.px-transition-expand-leave-to {
    opacity: 0;
    height: 0;
}
</style>
