All files / src/hooks useFilterGroupSort.ts

98.36% Statements 60/61
100% Branches 24/24
100% Functions 17/17
98.33% Lines 59/60

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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198                                                                                                              19x 19x 19x 1x         18x         5x 5x 2x   3x                 38x 38x               12x 12x 6x   6x                         34x 34x 34x   34x 34x 19x 19x 1x 1x   18x   34x 19x 19x 1x 1x   18x     34x   4x 4x 4x 1x   3x   4x 4x           34x 1x 1x     34x   4x 4x 4x 4x           34x 1x 1x     34x   4x 4x 4x 4x           34x 1x 1x     34x                              
/**
 * useFilterGroupSort -- shared localStorage-persisted filter, group, and sort state
 * for sidebar nav components.
 *
 * @module
 */
 
import { useCallback, useState } from "react";
 
/** Options for {@link useFilterGroupSort}. */
export interface UseFilterGroupSortOptions {
  /** localStorage key prefix (e.g., "grackle-env-nav"). Keys are suffixed with "-filter", "-group", "-sort". */
  storagePrefix: string;
  /**
   * If provided, any persisted `groupBy` value not in this list is treated as stale,
   * cleared from storage, and reset to "". Useful when valid group keys change between releases.
   */
  validGroupKeys?: ReadonlyArray<string>;
  /**
   * If provided, any persisted `sortBy` value not in this list is treated as stale,
   * cleared from storage, and reset to "". Useful when valid sort keys change between releases.
   */
  validSortKeys?: ReadonlyArray<string>;
}
 
/** Return type of {@link useFilterGroupSort}. */
export interface UseFilterGroupSortReturn {
  /** Currently selected filter keys (read-only to prevent accidental mutation). */
  filterValues: ReadonlySet<string>;
  /** Whether any filter is active. */
  filterActive: boolean;
  /** Toggle a filter key on/off. */
  toggleFilter: (key: string) => void;
  /** Clear all filter selections. */
  clearFilter: () => void;
  /** Current group-by key, or "" for ungrouped. */
  groupBy: string;
  /** Whether grouping is active. */
  groupActive: boolean;
  /** Toggle a group-by key (same key again clears it). */
  toggleGroup: (key: string) => void;
  /** Clear grouping. */
  clearGroup: () => void;
  /** Current sort key, or "" for default order. */
  sortBy: string;
  /** Whether sorting is active. */
  sortActive: boolean;
  /** Toggle a sort key (same key again clears it). */
  toggleSort: (key: string) => void;
  /** Clear sorting. */
  clearSort: () => void;
}
 
/** Read a Set from localStorage. */
function loadSet(key: string): Set<string> {
  try {
    const raw = localStorage.getItem(key);
    if (raw) {
      return new Set(JSON.parse(raw) as string[]);
    }
  } catch {
    /* ignore */
  }
  return new Set();
}
 
/** Persist a Set to localStorage. */
function saveSet(key: string, values: Set<string>): void {
  try {
    if (values.size === 0) {
      localStorage.removeItem(key);
    } else {
      localStorage.setItem(key, JSON.stringify([...values]));
    }
  } catch {
    /* ignore */
  }
}
 
/** Read a string from localStorage. */
function loadString(key: string): string {
  try {
    return localStorage.getItem(key) ?? "";
  } catch {
    return "";
  }
}
 
/** Persist a string to localStorage. */
function saveString(key: string, value: string): void {
  try {
    if (value) {
      localStorage.setItem(key, value);
    } else {
      localStorage.removeItem(key);
    }
  } catch {
    /* ignore */
  }
}
 
/** Shared filter/group/sort state with localStorage persistence. */
export function useFilterGroupSort({
  storagePrefix,
  validGroupKeys,
  validSortKeys,
}: UseFilterGroupSortOptions): UseFilterGroupSortReturn {
  const filterKey = `${storagePrefix}-filter`;
  const groupKey = `${storagePrefix}-group`;
  const sortKey = `${storagePrefix}-sort`;
 
  const [filterValues, setFilterValues] = useState(() => loadSet(filterKey));
  const [groupBy, setGroupBy] = useState(() => {
    const value = loadString(groupKey);
    if (value && validGroupKeys && !validGroupKeys.includes(value)) {
      saveString(groupKey, "");
      return "";
    }
    return value;
  });
  const [sortBy, setSortBy] = useState(() => {
    const value = loadString(sortKey);
    if (value && validSortKeys && !validSortKeys.includes(value)) {
      saveString(sortKey, "");
      return "";
    }
    return value;
  });
 
  const toggleFilter = useCallback(
    (key: string) => {
      setFilterValues((prev) => {
        const next = new Set(prev);
        if (next.has(key)) {
          next.delete(key);
        } else {
          next.add(key);
        }
        saveSet(filterKey, next);
        return next;
      });
    },
    [filterKey],
  );
 
  const clearFilter = useCallback(() => {
    setFilterValues(new Set());
    saveSet(filterKey, new Set());
  }, [filterKey]);
 
  const toggleGroup = useCallback(
    (key: string) => {
      setGroupBy((prev) => {
        const next = prev === key ? "" : key;
        saveString(groupKey, next);
        return next;
      });
    },
    [groupKey],
  );
 
  const clearGroup = useCallback(() => {
    setGroupBy("");
    saveString(groupKey, "");
  }, [groupKey]);
 
  const toggleSort = useCallback(
    (key: string) => {
      setSortBy((prev) => {
        const next = prev === key ? "" : key;
        saveString(sortKey, next);
        return next;
      });
    },
    [sortKey],
  );
 
  const clearSort = useCallback(() => {
    setSortBy("");
    saveString(sortKey, "");
  }, [sortKey]);
 
  return {
    filterValues,
    filterActive: filterValues.size > 0,
    toggleFilter,
    clearFilter,
    groupBy,
    groupActive: groupBy !== "",
    toggleGroup,
    clearGroup,
    sortBy,
    sortActive: sortBy !== "",
    toggleSort,
    clearSort,
  };
}