diff --git a/src/components/SideBarResizeHandler.tsx b/src/components/SideBarResizeHandler.tsx index 1d73ec5..3255f91 100644 --- a/src/components/SideBarResizeHandler.tsx +++ b/src/components/SideBarResizeHandler.tsx @@ -4,19 +4,10 @@ import { useDebounce, useWindowSize } from 'react-use' import { getDefaultConfigs } from 'utils/config/helper' import * as DOMHelper from 'utils/DOMHelper' import { useAfterRedirect } from 'utils/hooks/useFastRedirect' +import { getSafeWidth } from '../utils/getSafeWidth' import { ResizeHandler } from './ResizeHandler' import { Size, Size2D } from './Size' -const MINIMAL_CONTENT_VIEWPORT_WIDTH = 100 -const MINIMAL_WIDTH = 240 - -function getSafeWidth(width: Size, windowWidth: number) { - if (width > windowWidth - MINIMAL_CONTENT_VIEWPORT_WIDTH) - return windowWidth - MINIMAL_CONTENT_VIEWPORT_WIDTH - if (width < MINIMAL_WIDTH) return MINIMAL_WIDTH - return width -} - function useSidebarWidth() { const configContext = useConfigs() diff --git a/src/utils/getSafeWidth.test.ts b/src/utils/getSafeWidth.test.ts new file mode 100644 index 0000000..3fa04f6 --- /dev/null +++ b/src/utils/getSafeWidth.test.ts @@ -0,0 +1,28 @@ +import { getSafeWidth, MINIMAL_CONTENT_VIEWPORT_WIDTH, MINIMAL_WIDTH } from './getSafeWidth' + +it(`should shrink when window is being resized smaller`, () => { + const randomGrow = 100 * Math.random() + expect( + getSafeWidth( + MINIMAL_WIDTH + MINIMAL_CONTENT_VIEWPORT_WIDTH + randomGrow * 2, + MINIMAL_WIDTH + MINIMAL_CONTENT_VIEWPORT_WIDTH + randomGrow, + ), + ).toBe(MINIMAL_WIDTH + randomGrow) +}) + +it(`should not shrink when window is being resized smaller than minimal size`, () => { + const randomGrow = 100 * Math.random() + expect(getSafeWidth(0, MINIMAL_WIDTH + MINIMAL_CONTENT_VIEWPORT_WIDTH - randomGrow)).toBe( + MINIMAL_WIDTH, + ) +}) + +it(`should return user-preferred size if not reaching bounds`, () => { + const randomGrow = 100 * Math.random() + expect( + getSafeWidth( + MINIMAL_WIDTH + randomGrow, + MINIMAL_WIDTH + MINIMAL_CONTENT_VIEWPORT_WIDTH + randomGrow * 2, + ), + ).toBe(MINIMAL_WIDTH + randomGrow) +}) diff --git a/src/utils/getSafeWidth.ts b/src/utils/getSafeWidth.ts new file mode 100644 index 0000000..4fec42c --- /dev/null +++ b/src/utils/getSafeWidth.ts @@ -0,0 +1,14 @@ +import { Size } from '../components/Size' + +export const MINIMAL_CONTENT_VIEWPORT_WIDTH = 100 +export const MINIMAL_WIDTH = 240 + +export function getSafeWidth(width: Size, windowWidth: number) { + // if window width is too small, prevent reducing anymore + if (windowWidth < MINIMAL_WIDTH + MINIMAL_CONTENT_VIEWPORT_WIDTH) return MINIMAL_WIDTH + // if trying to enlarge to much, leave some space + if (width > windowWidth - MINIMAL_CONTENT_VIEWPORT_WIDTH) + return windowWidth - MINIMAL_CONTENT_VIEWPORT_WIDTH + if (width < MINIMAL_WIDTH) return MINIMAL_WIDTH + return width +}