-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathtoggle-storybook.tsx
70 lines (60 loc) · 2.08 KB
/
toggle-storybook.tsx
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
import React, { useState, useEffect, useRef } from 'react'
import { DevSettings } from 'react-native'
import { loadString, saveString } from '../app/utils/storage'
const DEFAULT_REACTOTRON_WS_URI = 'ws://localhost:9090'
/**
* 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)
const ws = useRef(new WebSocket(DEFAULT_REACTOTRON_WS_URI))
useEffect(() => {
if (!__DEV__) {
return undefined
}
// Load the setting from storage if it's there
loadString('devStorybook').then(storedSetting => {
// Set the initial value
setShowStorybook(storedSetting === 'on')
if (DevSettings) {
// 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)
// Behave as Reactotron.storybookSwitcher(), not a HOC way.
ws.current.onmessage = e => {
const data = JSON.parse(e.data)
if (data.type === 'storybook') {
saveString('devStorybook', data.payload ? 'on' : 'off')
setShowStorybook(data.payload)
}
}
ws.current.onerror = e => {
console.tron.error(e, null)
setShowStorybook(storedSetting === 'on')
}
})
}, [])
if (showStorybook) {
return StorybookUIRoot ? <StorybookUIRoot /> : null
}
return props.children
}