All files / src/composables useToolGroup.ts

100% Statements 20/20
100% Branches 10/10
100% Functions 9/9
100% Lines 14/14

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                    227x   601x 75x     319x 129x 318x 129x       227x 418x 180x       9x 9x 9x     227x    
import { ViewerTool } from '@/types/viewer-tool';
import { computed } from 'vue';
 
type Tool<T extends ViewerTool[]> = T extends ViewerTool[] ? T[number] : never;
 
/**
 * Create a tool group where only one tool can be active at a time.
 * @param tools The tools.
 */
export function useToolGroup<T extends ViewerTool[]>(...tools: T) {
  const activeTool = computed({
    get(): Tool<T> | null {
      const idx = tools.findIndex((tool) => tool.isActive.value);
      return idx !== -1 ? (tools[idx] as Tool<T>) : null;
    },
    set(tool: Tool<T> | null): void {
      const prev = tools.find((t) => t.isActive.value);
      if (prev) prev.isActive.value = false;
      const next = tools.find((t) => t === tool);
      if (next) next.isActive.value = true;
    },
  });
 
  const activeIndex = computed(() => {
    const idx = tools.findIndex((tool) => tool.isActive.value);
    return idx !== -1 ? idx : null;
  });
 
  function toggleTool(tool: Tool<T>): boolean {
    const state = activeTool.value !== tool;
    activeTool.value = state ? tool : null;
    return state;
  }
 
  return { activeTool, activeIndex, toggleTool };
}