import { useLayoutEffect, useState } from "react" import { readCoarsePointerMatches } from "@/hooks/use-touch-nav" import { readLgMatches } from "@/hooks/use-lg-breakpoint" import { MD_MIN_PX } from "@/hooks/use-md-breakpoint" import { getDemoMailPreviewLayout } from "@/lib/demo/demo-mail-preview" import { useMailSettingsStore } from "@/lib/stores/mail-settings-store" import type { ReadingPaneMode } from "@/lib/mail-settings/types" const MD_MQ = `(min-width: ${MD_MIN_PX}px)` const LG_MQ = "(min-width: 1024px)" const LANDSCAPE_MQ = "(orientation: landscape)" export function readMailSplitViewMatches( readingPane: ReadingPaneMode = "none" ): boolean { if (typeof window === "undefined") return false const preview = getDemoMailPreviewLayout() if (preview === "tablet") { return window.matchMedia(MD_MQ).matches } if (preview === "desktop") return false if (preview === "phone") return false if (!window.matchMedia(MD_MQ).matches) return false const coarse = readCoarsePointerMatches() const tabletLandscape = coarse && window.matchMedia(LANDSCAPE_MQ).matches if (readLgMatches()) { if (readingPane === "right") return true if (readingPane === "none") return tabletLandscape return false } return tabletLandscape } export function useMailSplitView() { const readingPane = useMailSettingsStore((s) => s.readingPane) const [splitView, setSplitView] = useState(false) useLayoutEffect(() => { const mqlMd = window.matchMedia(MD_MQ) const mqlLandscape = window.matchMedia(LANDSCAPE_MQ) const mqlCoarse = window.matchMedia( "(hover: none) and (pointer: coarse)" ) const mqlLg = window.matchMedia(LG_MQ) let raf = 0 const update = () => { cancelAnimationFrame(raf) raf = requestAnimationFrame(() => { const next = readMailSplitViewMatches(readingPane) setSplitView((prev) => (prev === next ? prev : next)) }) } update() mqlMd.addEventListener("change", update) mqlLandscape.addEventListener("change", update) mqlCoarse.addEventListener("change", update) mqlLg.addEventListener("change", update) return () => { mqlMd.removeEventListener("change", update) mqlLandscape.removeEventListener("change", update) mqlCoarse.removeEventListener("change", update) mqlLg.removeEventListener("change", update) cancelAnimationFrame(raf) } }, [readingPane]) return splitView }