Live video on the AT Protocol
1import { useEffect } from "react";
2import { useWindowDimensions } from "react-native";
3import {
4 SharedValue,
5 useSharedValue,
6 withTiming,
7} from "react-native-reanimated";
8import { useStore } from "store";
9import {
10 useIsSidebarCollapsed,
11 useIsSidebarHidden,
12 useSidebarTargetWidth,
13} from "store/hooks";
14
15// Returns *true* if the screen is > 1024px
16function useIsLargeScreen() {
17 const { width } = useWindowDimensions();
18 // gtMd breakpoint
19 return width >= 980 + 1;
20}
21
22export interface UseSidebarOutput {
23 isActive: boolean;
24 isCollapsed: boolean;
25 isHidden: boolean;
26 animatedWidth: SharedValue<number>;
27 toggle: () => void;
28}
29
30/*
31 * useSidebarControl
32 * A hook to control the custom sidebar on desktop, using Redux for state.
33 *
34 * Returns: An interface containing:
35 * - isActive: boolean - True if the screen is considered large (width >= 1024px).
36 * - isCollapsed: boolean - The current collapsed state of the sidebar from Redux.
37 * - animatedWidth: SharedValue<number> - An animated value controlling the sidebar's width.
38 * - toggle: () => void - A function to dispatch the Redux action to toggle the sidebar.
39 */
40export function useSidebarControl(): UseSidebarOutput {
41 const toggleSidebar = useStore((state) => state.toggleSidebar);
42 const isCollapsed = useIsSidebarCollapsed();
43 const targetWidth = useSidebarTargetWidth();
44
45 const isHidden = useIsSidebarHidden();
46
47 const animatedWidth = useSharedValue(targetWidth);
48
49 const isActive = useIsLargeScreen();
50 useEffect(() => {
51 if (isActive) {
52 if (!isHidden && targetWidth < 64) targetWidth == 64;
53 // Only animate if the sidebar is active
54 animatedWidth.value = withTiming(targetWidth, { duration: 250 });
55 } else {
56 animatedWidth.value = targetWidth;
57 }
58 }, [targetWidth, isActive, animatedWidth]);
59
60 const handleToggle = () => {
61 if (isActive) {
62 // Only allow toggle if the sidebar functionality is active
63 toggleSidebar();
64 }
65 };
66
67 return {
68 isActive,
69 isCollapsed,
70 animatedWidth,
71 isHidden,
72 toggle: handleToggle,
73 };
74}