All files / hooks / useToggle.ts

100.00% Branches 0/0
2.86% Lines 1/35
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
x3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 






















































import { useCallback, useState } from "preact/hooks";

/**
 * 布尔值切换Hook
 * @param initialValue 初始值
 * @returns [value, toggle, setTrue, setFalse, setValue]
 */
export function useToggle(initialValue: boolean = false) {
  const [value, setValue] = useState<boolean>(initialValue);

  const toggle = useCallback(() => {
    setValue((prev) => !prev);
  }, []);

  const setTrue = useCallback(() => {
    setValue(true);
  }, []);

  const setFalse = useCallback(() => {
    setValue(false);
  }, []);

  return [value, toggle, setTrue, setFalse, setValue] as const;
}

/**
 * 多状态切换Hook
 * @param states 状态数组
 * @param initialIndex 初始状态索引
 * @returns [currentState, currentIndex, next, previous, setIndex]
 */
export function useCycleToggle<T>(states: T[], initialIndex: number = 0) {
  const [currentIndex, setCurrentIndex] = useState<number>(initialIndex);

  const next = useCallback(() => {
    setCurrentIndex((prev) => (prev + 1) % states.length);
  }, [states.length]);

  const previous = useCallback(() => {
    setCurrentIndex((prev) => (prev - 1 + states.length) % states.length);
  }, [states.length]);

  const setIndex = useCallback((index: number) => {
    if (index >= 0 && index < states.length) {
      setCurrentIndex(index);
    }
  }, [states.length]);

  return [
    states[currentIndex],
    currentIndex,
    next,
    previous,
    setIndex,
  ] as const;
}