<template>
  <component
    :is="to ? 'router-link' : 'a'"
    :to="to"
    :href="href"
    class="_link"
    :target="external ? '_blank' : '_self'"
  >
    <!-- Slot -->
    <slot></slot>
    <!-- 'External' link icon -->
    <v-icon v-if="external" scale=0.8 name="external-link-alt" class="ml-1"></v-icon>
    <!-- Bottom animated border -->
    <div v-if="!noUnderline" class="_link-bottom-border"></div>
  </component>
</template>

<script>
/**
 * Link component
 */
export default {
  name: 'Link',
  props: {
    /**
     * 'To', if link is a router-link
     */
    to: {
      type: String,
      default: undefined
    },
    /**
     * 'href', if link is an anchor
     */
    href: {
      type: String,
      default: undefined
    },
    /**
     * Define if the link is external (add indicator icon)
     */
    external: {
      type: Boolean,
      default: false
    },
    /**
     * Define if not apply 'underline' effect
     */
    noUnderline: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    cleanWhitespaceNodes () {
      const childNodes = this.$el.childNodes
      for (const node of childNodes) {
        // If nodeType === 3 (TEXT_NODE, see https://developer.mozilla.org/fr/docs/Web/API/Node/nodeType)
        if (node.nodeType === 3) {
          node.nodeValue = node.nodeValue.trim() // Remove whitespaces
        }
      }
    }
  },
  mounted () {
    this.cleanWhitespaceNodes()
  },
  updated () {
    this.cleanWhitespaceNodes()
  }
}
</script>

<style lang="scss">
._link {
  @apply relative;
  @apply cursor-pointer;

  ._link-bottom-border {
    @apply w-0;
    @apply h-0.5;
    @apply bg-@dark-primary;
    @apply opacity-0;
    @apply rounded-full;
    @apply absolute;
    @apply left-1/2 -bottom-1;
    @apply mx-auto;
    transition: all 200ms;
  }

  &:hover {
    ._link-bottom-border {
      @apply w-full;
      @apply left-0;
      @apply opacity-100;
    }
  }
}
</style>
