File size: 2,425 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { useEffect, useLayoutEffect, useState } from "react"
import { createPortal } from "react-dom"
import Frame, { type FrameContextProps, useFrame } from "react-frame-component"
import { EnvironmentProvider, useEnvironmentContext } from "../src"

export default {
  title: "Components / Environment",
}

const Portal = (props: React.PropsWithChildren<{}>) => {
  useDefer(true)
  const { getRootNode } = useEnvironmentContext()
  const doc: any = getRootNode?.() ?? globalThis.document
  return createPortal(props.children, doc.body)
}

function useDefer(defer?: boolean) {
  const [ready, setReady] = useState(false)
  useLayoutEffect(() => {
    if (!defer) return
    setReady(true)
  }, [defer])
  return ready
}

function useWindow() {
  const { getRootNode } = useEnvironmentContext()
  const doc: any = getRootNode?.() ?? globalThis.document
  const win = doc.defaultView ?? globalThis.window

  const [match, setMatch] = useState(false)

  useEffect(() => {
    const handler = (query: MediaQueryListEvent) => {
      setMatch(query.matches)
    }

    const mql = win.matchMedia("(min-width: 600px)")
    setMatch(mql.matches)

    mql.addEventListener("change", handler)
    return () => {
      mql.removeEventListener("change", handler)
    }
  }, [win])

  return {
    w: win.innerWidth,
    h: win.innerHeight,
    match,
  }
}

function FrameContext(props: {
  children: (ctx: FrameContextProps) => React.ReactNode
}) {
  const ctx = useFrame()
  return props.children(ctx)
}

function WindowSize() {
  const data = useWindow()
  return <pre>{JSON.stringify(data)}</pre>
}

export const WithPortal = () => {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Portal>Outside iframe</Portal>
      <Frame style={{ background: "yellow" }}>
        <EnvironmentProvider>
          <span>Welcome home</span>
          <Portal>Inside iframe</Portal>
        </EnvironmentProvider>
      </Frame>
    </div>
  )
}

export const WithSize = () => {
  return (
    <>
      <WindowSize />
      <Frame style={{ background: "yellow", width: "100%", maxWidth: "300px" }}>
        <FrameContext>
          {({ document }) => (
            <EnvironmentProvider value={() => document ?? globalThis.document}>
              <WindowSize />
            </EnvironmentProvider>
          )}
        </FrameContext>
      </Frame>
    </>
  )
}