<!--
Example implementation of a Vue V3 component wrapper for the spin.js library
https://spin.js.org/
-->

<template>
  <div ref="spinDiv"></div>
</template>

<style lang="scss">
@import '~spin.js/spin.css';
</style>

<script lang="ts">
import { defineComponent, PropType, ref, unref } from 'vue';
import { Spinner, SpinnerOptions } from 'spin.js';

/**
 * Options that will be applied by default to all spinners.
 * Can be overridden using the 'opts' component prop.
 */
const defaultOptions: SpinnerOptions = {
  color: '#112233',
};

export default defineComponent({
  setup() {
    return {
      // This is necessary so that we can access the div to which the spinner is attached
      spinDiv: ref<HTMLElement>(),
    };
  },

  props: {
    opts: {
      // Spinner options (overrides defaults)
      type: Object as PropType<SpinnerOptions>,
    },
  },

  data: () => ({
    spinner: null as Spinner | null,
  }),

  mounted() {
    const opts = Object.assign({}, defaultOptions, this.opts);
    this.spinner = new Spinner(opts).spin(unref(this.spinDiv));
  },

  unmounted() {
    this.spinner?.stop();
  },
});
</script>
