All files / hooks/use-selection/src useSelection.ts

100% Statements 75/75
100% Branches 34/34
100% Functions 15/15
100% Lines 75/75

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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255                                                                                                                                                                                                      59x   59x 24x         59x 59x   59x 59x   59x 59x   59x 59x       59x 214x 214x     59x   6x 6x 6x 2x 1x   1x 1x 1x     4x 1x   3x           59x   2x 2x 2x 1x   1x 1x 1x           59x   15x 15x 15x 2x 2x 2x   13x 11x 11x 11x     2x           59x   7x 1x   6x 6x 6x 1x   5x 5x 5x 15x 15x 12x 12x     5x       59x 2x 2x       59x 7x               59x   59x 59x 169x 41x     59x 59x 59x               59x                            
import { useCallback, useMemo, useRef, useState } from "react";
import type {
  SelectionKey,
  UseSelectionOptions,
  UseSelectionReturn,
} from "./types";
 
/**
 * Manage multi- or single-selection state for a list or table, backed by a
 * `Set` of keys.
 *
 * The `Set` stores **keys** (see the `getKey` option), never the items
 * themselves, so a selection survives new object identities across renders —
 * rebuilding the `items` array every render will not lose the selection as long
 * as `getKey` maps the same logical item to the same key. Every item-facing
 * value (`selected`, `isAllSelected`, `isPartiallySelected`, …) is **derived
 * from the current `items`**, so removing a selected row from `items` makes it
 * disappear from `selected` and recomputes the aggregate flags automatically —
 * no manual reconciliation needed.
 *
 * Features:
 * - `Set`-backed, immutable updates (a fresh `Set` on every change)
 * - No-op skipping — `selectAll` when all are already selected, and `clear`
 *   when already empty, bail out without a re-render
 * - Single-selection mode (`multiple: false`) that replaces the selection
 * - Stable action identities (`toggle`/`select`/`deselect`/`selectAll`/`clear`
 *   and `isSelected`) — safe as effect dependencies
 * - `isPartiallySelected` for a header checkbox's indeterminate state
 * - SSR-safe (pure state) and StrictMode/concurrent-safe (no mutation of prior
 *   state, callbacks never fire from inside a `setState` updater)
 *
 * @template T - The item type.
 * @param items - The current list of items the selection is scoped to.
 * @param options - {@link UseSelectionOptions} (`getKey`, `multiple`).
 * @returns {@link UseSelectionReturn}
 *
 * @example
 * ```tsx
 * type User = { id: number; name: string };
 *
 * function UserTable({ users }: { users: User[] }) {
 *   const {
 *     selected,
 *     isSelected,
 *     toggle,
 *     selectAll,
 *     clear,
 *     isAllSelected,
 *     isPartiallySelected,
 *   } = useSelection(users, { getKey: (u) => u.id });
 *
 *   return (
 *     <table>
 *       <thead>
 *         <tr>
 *           <th>
 *             <input
 *               type="checkbox"
 *               checked={isAllSelected}
 *               ref={(el) => {
 *                 if (el) el.indeterminate = isPartiallySelected;
 *               }}
 *               onChange={() => (isAllSelected ? clear() : selectAll())}
 *             />
 *           </th>
 *           <th>Name ({selected.length} selected)</th>
 *         </tr>
 *       </thead>
 *       <tbody>
 *         {users.map((user) => (
 *           <tr key={user.id}>
 *             <td>
 *               <input
 *                 type="checkbox"
 *                 checked={isSelected(user)}
 *                 onChange={() => toggle(user)}
 *               />
 *             </td>
 *             <td>{user.name}</td>
 *           </tr>
 *         ))}
 *       </tbody>
 *     </table>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // Single-selection mode (radio-like): selecting replaces the previous choice.
 * const { selected, isSelected, select } = useSelection(options, {
 *   multiple: false,
 * });
 * ```
 */
export function useSelection<T>(
  items: T[],
  options: UseSelectionOptions<T> = {}
): UseSelectionReturn<T> {
  const { multiple = true } = options;
 
  const [selectedKeys, setSelectedKeys] = useState<Set<SelectionKey>>(
    () => new Set()
  );
 
  // Mirror the latest inputs so the stable actions can read fresh values
  // without being recreated each render.
  const getKeyOptionRef = useRef(options.getKey);
  getKeyOptionRef.current = options.getKey;
 
  const itemsRef = useRef(items);
  itemsRef.current = items;
 
  const multipleRef = useRef(multiple);
  multipleRef.current = multiple;
 
  const selectedKeysRef = useRef(selectedKeys);
  selectedKeysRef.current = selectedKeys;
 
  // A stable key resolver that always uses the latest `getKey`. Falls back to
  // identity (works for primitive items) when no `getKey` is provided.
  const getKey = useCallback((item: T): SelectionKey => {
    const fn = getKeyOptionRef.current;
    return fn ? fn(item) : (item as unknown as SelectionKey);
  }, []);
 
  const select = useCallback(
    (item: T) => {
      const key = getKey(item);
      setSelectedKeys((prev) => {
        if (multipleRef.current) {
          if (prev.has(key)) {
            return prev; // already selected — no-op
          }
          const next = new Set(prev);
          next.add(key);
          return next;
        }
        // single-selection: replace with just this key
        if (prev.size === 1 && prev.has(key)) {
          return prev; // already the sole selection — no-op
        }
        return new Set<SelectionKey>([key]);
      });
    },
    [getKey]
  );
 
  const deselect = useCallback(
    (item: T) => {
      const key = getKey(item);
      setSelectedKeys((prev) => {
        if (!prev.has(key)) {
          return prev; // not selected — no-op
        }
        const next = new Set(prev);
        next.delete(key);
        return next;
      });
    },
    [getKey]
  );
 
  const toggle = useCallback(
    (item: T) => {
      const key = getKey(item);
      setSelectedKeys((prev) => {
        if (prev.has(key)) {
          const next = new Set(prev);
          next.delete(key);
          return next;
        }
        if (multipleRef.current) {
          const next = new Set(prev);
          next.add(key);
          return next;
        }
        // single-selection: replace with just this key
        return new Set<SelectionKey>([key]);
      });
    },
    [getKey]
  );
 
  const selectAll = useCallback(() => {
    // Selecting "all" is a multi-selection concept.
    if (!multipleRef.current) {
      return;
    }
    setSelectedKeys((prev) => {
      const currentItems = itemsRef.current;
      if (currentItems.length === 0) {
        return prev; // nothing to select — no-op
      }
      let changed = false;
      const next = new Set(prev);
      for (const item of currentItems) {
        const key = getKey(item);
        if (!next.has(key)) {
          next.add(key);
          changed = true;
        }
      }
      return changed ? next : prev; // no-op when all already selected
    });
  }, [getKey]);
 
  const clear = useCallback(() => {
    setSelectedKeys((prev) =>
      prev.size === 0 ? prev : new Set<SelectionKey>()
    );
  }, []);
 
  const isSelected = useCallback(
    (item: T) => selectedKeysRef.current.has(getKey(item)),
    [getKey]
  );
 
  // Derive item-facing values from the current items ∩ selected keys. This is
  // what drops stale keys and keeps the aggregate flags in sync when `items`
  // changes. `getKey` is stable, so this recomputes only when `items` or the
  // selection changes.
  const { selected, isAllSelected, isPartiallySelected, isNoneSelected } =
    useMemo(() => {
      const sel: T[] = [];
      for (const item of items) {
        if (selectedKeys.has(getKey(item))) {
          sel.push(item);
        }
      }
      const count = sel.length;
      const total = items.length;
      return {
        selected: sel,
        isAllSelected: total > 0 && count === total,
        isPartiallySelected: count > 0 && count < total,
        isNoneSelected: count === 0,
      };
    }, [items, selectedKeys, getKey]);
 
  return {
    selected,
    selectedKeys,
    isSelected,
    toggle,
    select,
    deselect,
    selectAll,
    clear,
    isAllSelected,
    isPartiallySelected,
    isNoneSelected,
  };
}