48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
|
|
export const PLATFORM_DESKTOP_LAYOUT_QUERY = '(min-width: 1024px)';
|
|
|
|
export function getInitialPlatformDesktopLayout() {
|
|
if (
|
|
typeof window === 'undefined' ||
|
|
typeof window.matchMedia !== 'function'
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
return window.matchMedia(PLATFORM_DESKTOP_LAYOUT_QUERY).matches;
|
|
}
|
|
|
|
export function usePlatformDesktopLayout() {
|
|
const [isDesktopLayout, setIsDesktopLayout] = useState(
|
|
getInitialPlatformDesktopLayout,
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (
|
|
typeof window === 'undefined' ||
|
|
typeof window.matchMedia !== 'function'
|
|
) {
|
|
return;
|
|
}
|
|
|
|
const mediaQuery = window.matchMedia(PLATFORM_DESKTOP_LAYOUT_QUERY);
|
|
const updateLayout = (event?: MediaQueryListEvent) => {
|
|
setIsDesktopLayout(event?.matches ?? mediaQuery.matches);
|
|
};
|
|
|
|
updateLayout();
|
|
|
|
// 平台页只挂载当前断点外壳,避免隐藏的移动端/桌面端内容重复抢占查询。
|
|
if (typeof mediaQuery.addEventListener === 'function') {
|
|
mediaQuery.addEventListener('change', updateLayout);
|
|
return () => mediaQuery.removeEventListener('change', updateLayout);
|
|
}
|
|
|
|
mediaQuery.addListener(updateLayout);
|
|
return () => mediaQuery.removeListener(updateLayout);
|
|
}, []);
|
|
|
|
return isDesktopLayout;
|
|
}
|