fix: prevent sidebar tremor

fixes #269
This commit is contained in:
EnixCoda 2022-12-24 17:07:19 +08:00
parent 39f82a8739
commit c2a261e681
3 changed files with 43 additions and 10 deletions

View file

@ -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()

View file

@ -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)
})

14
src/utils/getSafeWidth.ts Normal file
View file

@ -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
}