Files
planet/frontend/src/hooks/useCollapsedActions.ts
2026-04-16 10:04:14 +08:00

40 lines
1.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useCallback, useEffect, useRef, useState } from 'react'
/**
* 监听容器宽度,宽时展开操作按钮,窄时收入 Dropdown。
* @param threshold 折叠阈值px默认 700
* @returns [collapsed, callbackRef]
*/
export function useCollapsedActions(threshold = 700) {
const [collapsed, setCollapsed] = useState(false)
const observerRef = useRef<ResizeObserver | null>(null)
const elementRef = useRef<HTMLElement | null>(null)
const ref = useCallback(
(el: HTMLElement | null) => {
observerRef.current?.disconnect()
observerRef.current = null
elementRef.current = el
if (!el || typeof ResizeObserver === 'undefined') return
const observer = new ResizeObserver(([entry]) => {
setCollapsed(entry.contentRect.width < threshold)
})
observer.observe(el)
observerRef.current = observer
},
[threshold],
)
useEffect(() => {
return () => {
observerRef.current?.disconnect()
observerRef.current = null
elementRef.current = null
}
}, [])
return [collapsed, ref] as const
}