<template>
  <div
    :class="`mm-tabs-active-bar__${rootTabs.tabPosition}`"
    :style="barStyle"
    class="mm-tabs-active-bar">
  </div>
</template>

<script>
const firstUpperCase = str => {
  return str.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

export default {
  name: "mm-tab-active-bar",
  props: {
    tabs: Array,
  },
  inject: {
    rootTabs: {
      from: "mm-tabs",
      default: null,
    },
  },
  computed: {
    barStyle() {
      const tabs = this.tabs
      const refs = this.$parent.$refs.tabs || []
      const sizeName = ["top", "bottom"].includes(this.rootTabs.tabPosition) ? "width" : "height"
      const sizeDir = sizeName === "width" ? "x" : "y"

      let style = {}
      let offset = 0
      let tabSize = 0

      tabs.every((tab, index) => {
        let $el = refs[index]
        if (!$el) {
          return false
        }

        if (!tab.active) {
          offset += $el[`client${firstUpperCase(sizeName)}`]
          return true
        } else {
          tabSize = $el[`client${firstUpperCase(sizeName)}`]
          return false
        }
      })

      const transform = `translate${firstUpperCase(sizeDir)}(${offset}px)`

      style[sizeName] = tabSize + "px"
      style.transform = transform
      style.msTransform = transform
      style.webkitTransform = transform

      return style
    },
  },
}
</script>
