All files / app/assets/javascripts/popovers/components popovers.vue

100% Statements 26/26
100% Branches 9/9
100% Functions 14/14
100% Lines 26/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 88 89 90  2x   2x 19x   19x                                   15x       15x 15x 2x 2x         15x     27x 27x 30x 11x   19x 19x 19x     27x     19x         5x 1x   9x   4x 3x         46x                 140x                        
<script>
import { GlPopover, GlSafeHtmlDirective } from '@gitlab/ui';
 
const newPopover = (element) => {
  const { content, html, placement, title, triggers = 'focus' } = element.dataset;
 
  return {
    target: element,
    content,
    html,
    placement,
    title,
    triggers,
  };
};
 
export default {
  components: {
    GlPopover,
  },
  directives: {
    SafeHtml: GlSafeHtmlDirective,
  },
  data() {
    return {
      popovers: [],
    };
  },
  created() {
    this.observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.removedNodes.forEach(this.dispose);
      });
    });
  },
  beforeDestroy() {
    this.observer.disconnect();
  },
  methods: {
    addPopovers(elements) {
      const newPopovers = elements.reduce((acc, element) => {
        if (this.popoverExists(element)) {
          return acc;
        }
        const popover = newPopover(element);
        this.observe(popover);
        return [...acc, popover];
      }, []);
 
      this.popovers.push(...newPopovers);
    },
    observe(popover) {
      this.observer.observe(popover.target.parentElement, {
        childList: true,
      });
    },
    dispose(target) {
      if (!target) {
        this.popovers = [];
      } else {
        const index = this.popovers.findIndex((popover) => popover.target === target);
 
        if (index > -1) {
          this.popovers.splice(index, 1);
        }
      }
    },
    popoverExists(element) {
      return this.popovers.some((popover) => popover.target === element);
    },
  },
  safeHtmlConfig: {
    ADD_TAGS: ['use'], // to support icon SVGs
  },
};
</script>
 
<template>
  <div>
    <gl-popover v-for="(popover, index) in popovers" :key="index" v-bind="popover">
      <template #title>
        <span v-if="popover.html" v-safe-html:[$options.safeHtmlConfig]="popover.title"></span>
        <span v-else>{{ popover.title }}</span>
      </template>
      <span v-if="popover.html" v-safe-html:[$options.safeHtmlConfig]="popover.content"></span>
      <span v-else>{{ popover.content }}</span>
    </gl-popover>
  </div>
</template>