All files / src/hooks useEventSelection.ts

100% Statements 60/60
100% Branches 18/18
100% Functions 13/13
100% Lines 54/54

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                                                                                                            37x 37x   37x   37x   37x 12x 12x 9x 9x   3x 3x       37x 1x 1x 1x     37x   8x   2x 2x 2x 2x 2x 9x 7x     2x       6x 6x 6x 2x   4x   6x 1x 1x   5x   6x             37x 1x 1x 6x 5x     1x     37x 1x     37x 3x 3x 3x 1x   2x 2x 2x 1x   1x       37x                        
/**
 * Selection state management for the multi-select feature in EventStream.
 *
 * Manages entering/exiting selection mode, toggling individual events,
 * shift-click range selection, select all, and clipboard copy.
 *
 * @module
 */
 
import { useState, useRef, useCallback, useMemo } from "react";
import type { DisplayEvent } from "../utils/sessionEvents.js";
import { isContentBearingEvent } from "../utils/eventContent.js";
 
/** Options for the useEventSelection hook. */
export interface UseEventSelectionOptions {
  /** All events currently in the stream. */
  events: DisplayEvent[];
  /** Formats events as text for the clipboard. */
  formatForClipboard: (events: DisplayEvent[]) => string;
}
 
/** Return value of the useEventSelection hook. */
export interface UseEventSelectionReturn {
  /** Whether selection mode is active. */
  isSelecting: boolean;
  /** Set of selected event indices (from the events array). */
  selectedIndices: ReadonlySet<number>;
  /** Number of selected events. */
  selectedCount: number;
  /** Enter selection mode, optionally selecting an initial event. */
  enterSelectionMode: (initialIndex?: number) => void;
  /** Exit selection mode and clear all selections. */
  cancelSelection: () => void;
  /** Toggle an event at the given index. When shiftKey is true, selects the range from the last-toggled anchor. */
  toggleEvent: (index: number, shiftKey?: boolean) => void;
  /** Select all content-bearing events. */
  selectAll: () => void;
  /** Deselect all events but stay in selection mode. */
  deselectAll: () => void;
  /** Copy selected events to clipboard. Returns true on success. */
  copySelected: () => Promise<boolean>;
}
 
/**
 * Hook that manages event selection state for the EventStream multi-select feature.
 *
 * The caller is responsible for rendering checkboxes, highlights, and action bars
 * based on the returned state. The `copySelected` method uses `navigator.clipboard`
 * and will return `false` in environments where the Clipboard API is unavailable.
 */
export function useEventSelection({
  events,
  formatForClipboard,
}: UseEventSelectionOptions): UseEventSelectionReturn {
  const [isSelecting, setIsSelecting] = useState(false);
  const [selectedIndices, setSelectedIndices] = useState<ReadonlySet<number>>(new Set());
  /** Anchor index for shift-click range selection. */
  const anchorRef = useRef<number | undefined>(undefined);
 
  const selectedCount = useMemo(() => selectedIndices.size, [selectedIndices]);
 
  const enterSelectionMode = useCallback((initialIndex?: number) => {
    setIsSelecting(true);
    if (initialIndex !== undefined) {
      setSelectedIndices(new Set([initialIndex]));
      anchorRef.current = initialIndex;
    } else {
      setSelectedIndices(new Set());
      anchorRef.current = undefined;
    }
  }, []);
 
  const cancelSelection = useCallback(() => {
    setIsSelecting(false);
    setSelectedIndices(new Set());
    anchorRef.current = undefined;
  }, []);
 
  const toggleEvent = useCallback(
    (index: number, shiftKey?: boolean) => {
      if (shiftKey && anchorRef.current !== undefined) {
        // Range selection: select all content-bearing events between anchor and index
        const start = Math.min(anchorRef.current, index);
        const end = Math.max(anchorRef.current, index);
        setSelectedIndices((prev) => {
          const next = new Set(prev);
          for (let i = start; i <= end; i++) {
            if (i < events.length && isContentBearingEvent(events[i])) {
              next.add(i);
            }
          }
          return next;
        });
      } else {
        // Single toggle — exit selection mode if deselecting the last item
        setSelectedIndices((prev) => {
          const next = new Set(prev);
          if (next.has(index)) {
            next.delete(index);
          } else {
            next.add(index);
          }
          if (next.size === 0) {
            setIsSelecting(false);
            anchorRef.current = undefined;
          } else {
            anchorRef.current = index;
          }
          return next;
        });
      }
    },
    [events],
  );
 
  const selectAll = useCallback(() => {
    const all = new Set<number>();
    for (let i = 0; i < events.length; i++) {
      if (isContentBearingEvent(events[i])) {
        all.add(i);
      }
    }
    setSelectedIndices(all);
  }, [events]);
 
  const deselectAll = useCallback(() => {
    setSelectedIndices(new Set());
  }, []);
 
  const copySelected = useCallback(async (): Promise<boolean> => {
    const sorted = [...selectedIndices].sort((a, b) => a - b);
    const selectedEvents = sorted.filter((i) => i < events.length).map((i) => events[i]);
    if (selectedEvents.length === 0) {
      return false;
    }
    const text = formatForClipboard(selectedEvents);
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch {
      return false;
    }
  }, [selectedIndices, events, formatForClipboard]);
 
  return {
    isSelecting,
    selectedIndices,
    selectedCount,
    enterSelectionMode,
    cancelSelection,
    toggleEvent,
    selectAll,
    deselectAll,
    copySelected,
  };
}