<!-- Simple tooltip styled to look like an abbr.
     Modeled after https://github.com/nico3333fr/van11y-accessible-simple-tooltip-aria
-->
<span class="tooltip-button"
      aria-describedby="tooltip-{id}"
      role="button"
      tabindex="0"
      on:mouseover="set({shown: true, mouseover: true})"
      on:mouseleave="set({shown: false, mouseover: false})"
      on:click="toggle(event)"
      on:keydown="onKeydown(event)"
>
  {text}
</span>
<span id="tooltip-{id}"
      class="tooltip {shown ? 'shown' : ''}"
      role="tooltip"
      aria-hidden={!shown}
>
  {tooltipText}
</span>
<Shortcut scope="global" key="Escape" on:pressed="dismiss()" />
<style>
  .tooltip-button {
    border-bottom: 1px dotted;
  }
  .tooltip {
    display: none;
    position: absolute;
    background: var(--tooltip-bg);
    color: var(--tooltip-color);
    padding: 5px 10px;
    font-size: 0.9em;
    border-radius: 4px;
  }
  .tooltip.shown {
    display: inline-block;
  }

  @media (max-width: 767px) {
    .tooltip {
      left: 0;
      transform: translateY(calc(-100% - 5px));
    }
  }

</style>
<script>
  import Shortcut from './shortcut/Shortcut.html'

  let counter = 0

  export default {
    data: () => ({
      id: ++counter,
      shown: false,
      mouseover: false
    }),
    methods: {
      toggle (e) {
        e.preventDefault()
        e.stopPropagation()
        let { shown, mouseover } = this.get()
        if (!mouseover) {
          this.set({ shown: !shown })
        }
      },
      onKeydown (e) {
        if (e.keyCode === 32 || e.keyCode === 13) { // enter or space
          this.toggle(e)
        }
      },
      dismiss () {
        this.set({ shown: false })
      }
    },
    components: {
      Shortcut
    }
  }
</script>