All files / src/composables useEnvironmentSelector.js

83.33% Statements 20/24
64.7% Branches 11/17
85.71% Functions 6/7
82.6% Lines 19/23

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                28x 28x   28x 28x 1x   27x     28x 28x   28x   19x     12x 5x     7x   7x         7x 3x         28x 28x                       28x          
import { ref, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {
  getAvailableEnvironmentOptions,
  getDefaultEnvironment,
} from '../utils/environmentHelper';
 
export default function useEnvironmentSelector(onChangeCallback = null) {
  const route = useRoute();
  const router = useRouter();
 
  const getInitialEnvironment = () => {
    if (typeof window === 'undefined') {
      return getDefaultEnvironment();
    }
    return route.query.env || getDefaultEnvironment();
  };
 
  const rawSelectedEnvironment = ref(getInitialEnvironment());
  const environmentOptions = computed(() => getAvailableEnvironmentOptions());
 
  const selectedEnvironment = computed({
    get() {
      return rawSelectedEnvironment.value;
    },
    set(newValue) {
      if (!newValue || newValue === rawSelectedEnvironment.value) {
        return;
      }
 
      rawSelectedEnvironment.value = newValue;
 
      router.push({
        path: route.path,
        query: { ...route.query, env: newValue },
      });
 
      if (typeof onChangeCallback === 'function') {
        onChangeCallback(newValue);
      }
    },
  });
 
  watch(
    () => route.query.env,
    (newEnv) => {
      if (newEnv && newEnv !== rawSelectedEnvironment.value) {
        rawSelectedEnvironment.value = newEnv;
 
        if (typeof onChangeCallback === 'function') {
          onChangeCallback(newEnv);
        }
      }
    },
  );
 
  return {
    selectedEnvironment,
    environmentOptions,
  };
}