File size: 2,089 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use client"

import { useChakraContext } from "../styled-system"
import { type Dict } from "../utils"
import { useMediaQuery } from "./use-media-query"

/* -----------------------------------------------------------------------------
 * useBreakpoint
 * -----------------------------------------------------------------------------*/

export interface UseBreakpointOptions {
  fallback?: string | undefined
  ssr?: boolean | undefined
  getWindow?: () => typeof window | undefined
  breakpoints?: string[] | undefined
}

export function useBreakpoint(options: UseBreakpointOptions = {}) {
  options.fallback ||= "base"
  const sys = useChakraContext()

  let fallbackPassed = false
  const allBreakpoints = sys.breakpoints.values

  const breakpoints = allBreakpoints
    .map(({ min, name: breakpoint }) => {
      const item = {
        breakpoint,
        query: `(min-width: ${min})`,
        fallback: !fallbackPassed,
      }

      if (breakpoint === options.fallback) {
        fallbackPassed = true
      }

      return item
    })
    .filter(({ breakpoint }) => !!options.breakpoints?.includes(breakpoint))

  const fallback = breakpoints.map(({ fallback }) => fallback)

  const values = useMediaQuery(
    breakpoints.map((bp) => bp.query),
    { fallback, ssr: options.ssr },
  )

  // find highest matched breakpoint
  const index = values.lastIndexOf(true)

  return breakpoints[index]?.breakpoint ?? options.fallback
}

/* -----------------------------------------------------------------------------
 * useBreakpointValue
 * -----------------------------------------------------------------------------*/

export type UseBreakpointValueOptions = Omit<
  UseBreakpointOptions,
  "breakpoints"
>

type Value<T> = Dict<T> | Array<T | null>

export function useBreakpointValue<T = any>(
  value: Value<T>,
  opts?: UseBreakpointValueOptions,
): T | undefined {
  const sys = useChakraContext()
  const normalized = sys.normalizeValue(value)
  const breakpoint = useBreakpoint({
    breakpoints: Object.keys(normalized),
    ...opts,
  })

  return normalized[breakpoint]
}