All files / src/sources BaseInterval.vue.js

7.4% Statements 2/27
0% Branches 0/8
0% Functions 0/10
7.69% Lines 2/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                  1x           1x                                                                                                                                              
// @ts-check
import { get, invoke } from "lodash";
import Vue from "vue";
import d from "debug";
 
import { BaseStoreMixin } from "../store/utils";
import BaseIntervalSource from "../store/sources/BaseIntervalSource";
import logger from "../Logger/BaseLogger";
 
const debug = d("base:interval");
 
/**
 * @typedef {{ source: BaseIntervalSource|null }} Opts
 */
 
const component = /** @type {V.Constructor<Opts, any>} */(Vue).extend({
  name: "BaseInterval",
  mixins: [ BaseStoreMixin ],
  props: {
    interval: { type: Number, default: 1000 },
    store: { type: String, default: null }
  },
  /** @return {{ localCount: number }} */
  data() {
    return { localCount: 0 };
  },
  computed: {
    /**
     * @return {number}
     */
    count() {
      return get(this.getBaseStore()?.state, this.store?.split("/"))?.count ?? this.localCount;
    }
  },
  watch: {
    interval: "restart",
    store: function(_, old) {
      // @ts-ignore
      this.getBaseStore()?.sources[old]?.destroy();
      this.restart();
    }
  },
  mounted() { this.restart(); },
  beforeDestroy() { this.stop(); },
  methods: {
    stop() {
      this.$options.source?.removeEventListener("tick", this.onTick);
      this.$options.source?.destroy();
      this.$options.source = null;
    },
    start() {
      if (this.$options.source) { return; }
      const store = this.getBaseStore();
      if (store && this.store) {
        try {
          BaseIntervalSource.register(store, this.store, this.interval);
        }
        catch (e) { logger.error(`failed to create source: ${e}`); }
        // @ts-ignore
        this.$options.source = store.sources?.[this.store];
      }
      else {
        this.$options.source = new BaseIntervalSource(undefined, undefined,
          this.interval);
      }
      this.$options.source?.addEventListener("tick", this.onTick);
    },
    restart() {
      this.stop();
      this.start();
    },
    onTick() {
      ++this.localCount;
      debug("tick %i", this.count);
      this.$emit("tick", this.count);
    }
  },
  /**
   * @return {Vue.VNode}
   */
  render() {
    /* render-less component, renders its default slot */
    return invoke(this.$scopedSlots, "default", { count: this.count });
  }
});
export default component;