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

55 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-03-12 02:31:03 +00:00
import { useEffect, useRef } from 'react';
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;
};
const toggleCollapsed = (collapsed = null) => {
2022-03-12 02:31:03 +00:00
const isBool = typeof collapsed === 'boolean';
2022-02-20 11:51:55 +00:00
const nextCollapsed = isBool ? collapsed : !isCollapsed;
let nextWidth = nextCollapsed ? COLLAPSED_WIDTH : MIN_WIDTH;
setStorage(key, nextWidth);
mutate();
runTimeWidthRef.current = nextWidth;
};
useEffect(() => {
mutate();
return () => {
runTimeWidthRef.current = null;
};
}, []);
useEffect(() => {
if (!windowSize.width) return;
if (windowSize.width <= 765) {
toggleCollapsed(true);
}
2022-02-20 11:51:55 +00:00
}, [windowSize.width]);
return {
width: data,
isCollapsed,
toggleCollapsed,
updateWidth,
};
};