think/packages/client/src/hooks/use-dragable-width.ts

58 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-05-01 14:07:22 +00:00
import { useCallback, useEffect, useRef } from 'react';
2022-03-12 02:31:03 +00:00
import useSWR from 'swr';
2022-03-27 07:43:06 +00:00
import { useWindowSize } from 'hooks/use-window-size';
2022-03-12 02:31:03 +00:00
import { setStorage, getStorage } from 'helpers/storage';
2022-02-20 11:51:55 +00:00
2022-03-12 02:31:03 +00:00
const key = 'dragable-menu-width';
2022-02-20 11:51:55 +00:00
export const MIN_WIDTH = 240;
export const MAX_WIDTH = 600;
const COLLAPSED_WIDTH = 24;
export const useDragableWidth = () => {
const runTimeWidthRef = useRef(null);
const { data, mutate } = useSWR<number>(key, getStorage);
const windowSize = useWindowSize();
const isCollapsed = data <= COLLAPSED_WIDTH;
const updateWidth = (size) => {
setStorage(key, size);
mutate();
runTimeWidthRef.current = size;
};
2022-05-01 14:07:22 +00:00
const toggleCollapsed = useCallback(
(collapsed = null) => {
const isBool = typeof collapsed === 'boolean';
const nextCollapsed = isBool ? collapsed : !isCollapsed;
const nextWidth = nextCollapsed ? COLLAPSED_WIDTH : MIN_WIDTH;
setStorage(key, nextWidth);
mutate();
runTimeWidthRef.current = nextWidth;
},
[isCollapsed, mutate]
);
2022-02-20 11:51:55 +00:00
useEffect(() => {
mutate();
return () => {
runTimeWidthRef.current = null;
};
2022-05-01 14:07:22 +00:00
}, [mutate]);
2022-02-20 11:51:55 +00:00
useEffect(() => {
if (!windowSize.width) return;
if (windowSize.width <= 765) {
toggleCollapsed(true);
}
2022-05-01 14:07:22 +00:00
}, [windowSize.width, toggleCollapsed]);
2022-02-20 11:51:55 +00:00
return {
width: data,
isCollapsed,
toggleCollapsed,
updateWidth,
};
};