Files
juip-web/src/lib/hooks/useMediaQuery.ts
2026-08-25 18:32:22 +08:00

37 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 { useSyncExternalStore } from "react"
const subscribeMediaQuery = (query: string) => (callback: () => void) => {
if (typeof window === "undefined") return () => {}
const mql = window.matchMedia(query)
mql.addEventListener("change", callback)
return () => mql.removeEventListener("change", callback)
}
const getMediaQuerySnapshot = (query: string) => () => {
if (typeof window === "undefined") return false
return window.matchMedia(query).matches
}
export function useMediaQuery(query: string): boolean {
return useSyncExternalStore(
subscribeMediaQuery(query),
getMediaQuerySnapshot(query),
() => false,
)
}
// 移动端:< 768px(对应 Tailwind md 断点以下)
export function useIsMobile(): boolean {
return useMediaQuery("(max-width: 47.999rem)")
}
// 桌面端:>= 768px
export function useIsDesktop(): boolean {
return useMediaQuery("(min-width: 48rem)")
}
// 窄桌面/平板横屏:< 1280px(对应 Tailwind xl 断点以下)
export function useIsNarrowDesktop(): boolean {
return useMediaQuery("(max-width: 79.999rem)")
}