use-head-state.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { useCallback, useEffect, useState } from "react";
  2. import { useRecoilValue } from "recoil";
  3. import { atomCurrentProfile } from "@/services/states";
  4. import { ProxySortType } from "./use-filter-sort";
  5. export interface HeadState {
  6. open?: boolean;
  7. showType: boolean;
  8. sortType: ProxySortType;
  9. filterText: string;
  10. textState: "url" | "filter" | null;
  11. testUrl: string;
  12. }
  13. type HeadStateStorage = Record<string, Record<string, HeadState>>;
  14. const HEAD_STATE_KEY = "proxy-head-state";
  15. const DEFAULT_STATE: HeadState = {
  16. open: false,
  17. showType: false,
  18. sortType: 0,
  19. filterText: "",
  20. textState: null,
  21. testUrl: "",
  22. };
  23. export default function useHeadState(groupName: string) {
  24. const current = useRecoilValue(atomCurrentProfile);
  25. const [state, setState] = useState<HeadState>(DEFAULT_STATE);
  26. useEffect(() => {
  27. if (!current) {
  28. setState(DEFAULT_STATE);
  29. return;
  30. }
  31. try {
  32. const data = JSON.parse(
  33. localStorage.getItem(HEAD_STATE_KEY)!
  34. ) as HeadStateStorage;
  35. const value = data[current][groupName] || DEFAULT_STATE;
  36. if (value && typeof value === "object") {
  37. setState({ ...DEFAULT_STATE, ...value });
  38. } else {
  39. setState(DEFAULT_STATE);
  40. }
  41. } catch {}
  42. }, [current, groupName]);
  43. const setHeadState = useCallback(
  44. (obj: Partial<HeadState>) => {
  45. setState((old) => {
  46. const ret = { ...old, ...obj };
  47. setTimeout(() => {
  48. try {
  49. const item = localStorage.getItem(HEAD_STATE_KEY);
  50. let data = (item ? JSON.parse(item) : {}) as HeadStateStorage;
  51. if (!data || typeof data !== "object") data = {};
  52. if (!data[current]) data[current] = {};
  53. data[current][groupName] = ret;
  54. localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data));
  55. } catch {}
  56. });
  57. return ret;
  58. });
  59. },
  60. [current, groupName]
  61. );
  62. return [state, setHeadState] as const;
  63. }