summaryrefslogtreecommitdiff
path: root/storybook/toggle-storybook.tsx
blob: 394ecf496da69ff0e3b5b95735be9648503aa8dd (about) (plain)
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
import React, { useState, useEffect } from "react"
import { DevSettings } from "react-native"
import { loadString, saveString } from "../app/utils/storage"

/**
 * Toggle Storybook mode, in __DEV__ mode only.
 *
 * In non-__DEV__ mode, or when Storybook isn't toggled on,
 * renders its children.
 *
 * The mode flag is persisted in async storage, which means it
 * persists across reloads/restarts - this is handy when developing
 * new components in Storybook.
 */
export function ToggleStorybook(props) {
  const [showStorybook, setShowStorybook] = useState(false)
  const [StorybookUIRoot, setStorybookUIRoot] = useState(null)

  useEffect(() => {
    if (__DEV__ && DevSettings) {
      // Load the setting from storage if it's there
      loadString("devStorybook").then((storedSetting) => {
        // Set the initial value
        setShowStorybook(storedSetting === "on")

        // Add our toggle command to the menu
        DevSettings.addMenuItem("Toggle Storybook", () => {
          setShowStorybook((show) => {
            // On toggle, flip the current value
            show = !show

            // Write it back to storage
            saveString("devStorybook", show ? "on" : "off")

            // Return it to change the local state
            return show
          })
        })

        // Load the storybook UI once
        setStorybookUIRoot(() => require("./storybook").StorybookUIRoot)
      })
    }
  }, [])

  if (showStorybook) {
    return StorybookUIRoot ? <StorybookUIRoot /> : null
  } else {
    return props.children
  }
}