<template>
    <component :class="bem({ active: !!text })" :is="tag" class="px-copy-text" @click="click">
        <slot>
            <span :class="bem('text')" v-if="showText">
                {{ text }}
            </span>
        </slot>
        <px-icon :class="iconClass" v-if="showIcon" :src="icon" :size="iconSize" />
    </component>
</template>

<script>
import PxIcon from './PxIcon.vue';
import iconCopy from '../assets/feather/copy.svg?url';
import isServer from '../utils/isServer.js';

export default {
    components: { PxIcon },
    name: 'px-copy-text',

    props: {
        // will always copy this text even if the slot content has been changed
        text: { type: String, default: '' },
        showText: { type: Boolean, default: true },

        // tag to generate
        tag: { type: String, default: 'span' },

        // show an inline icon after the text
        showIcon: { type: Boolean, default: true },
        icon: { type: String, default: iconCopy },
        iconSize: { default: 0.8 },
        iconClass: { type: String, default: 'px-copy-text__icon' },
    },

    computed: {
        canCopy() {
            return !isServer() && navigator?.clipboard;
        },
    },

    methods: {
        click() {
            if (this.canCopy) {
                navigator.clipboard?.writeText(this.text);
            }
        },
    },
};
</script>

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

.px-copy-text {
    &--active {
        cursor: pointer;
    }

    &__text {
        margin-right: 0.5em;
    }

    &__icon {
        opacity: 0.5;
        @include transition(transform opacity);

        @include hover() {
            transform: translateY(-1px);
        }

        @include active() {
            transform: translateY(1px);
        }
    }
    &:hover & {
        &__icon {
            opacity: 1;
        }
    }
}
</style>
