<!--
    #VUE3 Todo

    Automatically computes line clamp based on the available height and current line height.
-->
<template>
    <component :is="tag" :class="bem()">
        <span
            v-if="enabled"
            :class="bem('clamp')"
            :style="{
                '-webkit-line-clamp': enabled ? lineCount : null,
                'line-clamp': enabled ? lineCount : null,
                height: enabled ? cssPx(maxHeight) : null,
            }"
        >
            <slot>
                {{ text }}
            </slot>
        </span>
        <span v-else>
            <slot>
                {{ text }}
            </slot>
        </span>
    </component>
</template>

<script>
import PxBaseResize from '../bases/PxBaseResize.vue';

export default {
    name: 'px-auto-clamp',
    mixins: [PxBaseResize],
    props: {
        enabled: { type: Boolean, default: true },
        text: { type: String, default: null },
        tag: { type: String, default: 'div' },
    },
    data() {
        return {
            lineCount: 0,
            maxHeight: null,
        };
    },
    computed: {},
    watch: {
        enabled() {
            this.resize();
        },
    },
    methods: {
        resize() {
            if (!this.$el) {
                return;
            }

            let availableHeight = this.$el.clientHeight;
            let lineHeight = parseFloat(window.getComputedStyle(this.$el).lineHeight);

            if (isNaN(lineHeight)) {
                lineHeight = parseFloat(window.getComputedStyle(this.$el).fontSize) * 1.33;
            }

            this.lineCount = Math.floor(availableHeight / lineHeight);
            this.height = this.lineCount * this.lineHeight;
        },
    },
};
</script>

<style lang="scss">
.px-auto-clamp {
    // required
    padding: 0;
    display: block;
    display: -webkit-box;
    position: relative;
    width: 100%;
    height: 100%;

    &__clamp {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        display: block;
        display: -webkit-box;
        overflow: hidden;
        max-height: 100%;
        height: auto;
        overflow: hidden;
        -webkit-box-orient: vertical;
    }
}
</style>
