diff --git a/components/utils/collections.ts b/components/utils/collections.ts index 87a1dc0..04b6aae 100644 --- a/components/utils/collections.ts +++ b/components/utils/collections.ts @@ -101,29 +101,3 @@ export const setChildrenIndex = ( return item }) } - -export type ShapeType = { - width: number - height: number -} - -export const getRealShape = (el: HTMLElement | null): ShapeType => { - const defaultShape: ShapeType = { width: 0, height: 0 } - if (!el || typeof window === 'undefined') return defaultShape - - const rect = el.getBoundingClientRect() - const { width, height } = window.getComputedStyle(el) - - const getCSSStyleVal = (str: string, parentNum: number) => { - if (!str) return 0 - const strVal = str.includes('px') ? +str.split('px')[0] - : str.includes('%') ? +str.split('%')[0] * parentNum * 0.01 : str - - return Number.isNaN(+strVal) ? 0 : +strVal - } - - return { - width: getCSSStyleVal(`${width}`, rect.width), - height: getCSSStyleVal(`${height}`, rect.height), - } -} diff --git a/components/utils/use-current-state.ts b/components/utils/use-current-state.ts index cc9308b..757f5cd 100644 --- a/components/utils/use-current-state.ts +++ b/components/utils/use-current-state.ts @@ -5,8 +5,8 @@ export type CurrentStateType = [ ] const useCurrentState = (initialState: S): CurrentStateType => { - const [state, setState] = useState(initialState) - const ref = useRef(initialState) + const [state, setState] = useState(initialState as S) + const ref = useRef(initialState as S) useEffect(() => { ref.current = state diff --git a/components/utils/use-real-shape.ts b/components/utils/use-real-shape.ts new file mode 100644 index 0000000..2875457 --- /dev/null +++ b/components/utils/use-real-shape.ts @@ -0,0 +1,46 @@ +import { MutableRefObject, useEffect, useState } from 'react' + +export type ShapeType = { + width: number + height: number +} + +export const getRealShape = (el: HTMLElement | null): ShapeType => { + const defaultShape: ShapeType = { width: 0, height: 0 } + if (!el || typeof window === 'undefined') return defaultShape + + const rect = el.getBoundingClientRect() + const { width, height } = window.getComputedStyle(el) + + const getCSSStyleVal = (str: string, parentNum: number) => { + if (!str) return 0 + const strVal = str.includes('px') ? +str.split('px')[0] + : str.includes('%') ? +str.split('%')[0] * parentNum * 0.01 : str + + return Number.isNaN(+strVal) ? 0 : +strVal + } + + return { + width: getCSSStyleVal(`${width}`, rect.width), + height: getCSSStyleVal(`${height}`, rect.height), + } +} + +export type ShapeResult = [ShapeType, () => void] + +const useRealShape = (ref: MutableRefObject): ShapeResult => { + const [state, setState] = useState({ + width: 0, + height: 0, + }) + const update = () => { + const { width, height } = getRealShape(ref.current) + console.log(123, 'update') + setState({ width, height }) + } + useEffect(() => update(), [ref.current]) + + return [state, update] +} + +export default useRealShape