All files / client/src/hooks use-sketch-tabs.ts

100% Statements 26/26
85.71% Branches 6/7
100% Functions 11/11
100% Lines 23/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 63                  51x 51x   51x 2x     51x 23x 23x         23x 23x 23x     51x 5x 5x       51x 4x 8x   4x 2x 2x   4x       51x 1x     51x                        
import { useState, useCallback } from "react";
 
export interface SketchTab {
  id: string;
  name: string;
  content: string;
}
 
export function useSketchTabs() {
  const [tabs, setTabs] = useState<SketchTab[]>([]);
  const [activeTabId, setActiveTabId] = useState<string | null>(null);
 
  const selectTab = useCallback((tabId: string) => {
    setActiveTabId(tabId);
  }, []);
 
  const createTab = useCallback((name: string, content: string = ""): string => {
    const newTabId = `tab-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
    const newTab: SketchTab = {
      id: newTabId,
      name,
      content,
    };
    setTabs((prevTabs) => [...prevTabs, newTab]);
    setActiveTabId(newTabId);
    return newTabId;
  }, []);
 
  const updateTab = useCallback((tabId: string, updates: Partial<SketchTab>) => {
    setTabs((prevTabs) =>
      prevTabs.map((tab) => (tab.id === tabId ? { ...tab, ...updates } : tab)),
    );
  }, []);
 
  const deleteTab = useCallback((tabId: string) => {
    setTabs((prevTabs) => {
      const newTabs = prevTabs.filter((tab) => tab.id !== tabId);
      // If we deleted the active tab, select another one
      if (activeTabId === tabId) {
        const nextTab = newTabs[0];
        setActiveTabId(nextTab ? nextTab.id : null);
      }
      return newTabs;
    });
  }, [activeTabId]);
 
  const renameTab = useCallback((tabId: string, newName: string) => {
    updateTab(tabId, { name: newName });
  }, [updateTab]);
 
  return {
    tabs,
    setTabs,
    activeTabId,
    setActiveTabId,
    selectTab,
    createTab,
    updateTab,
    deleteTab,
    renameTab,
  };
}