2021-08-25 10:38:33 +02:00
|
|
|
import { createMemoryHistory } from 'history'
|
|
|
|
import { initKea } from '~/initKea'
|
2022-02-02 17:05:37 +01:00
|
|
|
import { combineUrl, router } from 'kea-router'
|
2021-08-25 10:38:33 +02:00
|
|
|
import { getContext, Provider } from 'kea'
|
|
|
|
import React, { useEffect, useState } from 'react'
|
|
|
|
import { App } from 'scenes/App'
|
2022-03-15 17:36:51 +01:00
|
|
|
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
|
|
|
|
import { worker } from '~/mocks/browser'
|
|
|
|
import { teamLogic } from 'scenes/teamLogic'
|
|
|
|
import { userLogic } from 'scenes/userLogic'
|
2021-08-25 10:38:33 +02:00
|
|
|
|
2022-02-02 17:05:37 +01:00
|
|
|
export function resetKeaStory(url?: string, state?: Record<string, any>): void {
|
2022-03-15 17:36:51 +01:00
|
|
|
worker.resetHandlers()
|
|
|
|
|
2022-02-02 17:05:37 +01:00
|
|
|
const initialLocation = url ? combineUrl(url) : state?.kea?.router?.location
|
|
|
|
const history = createMemoryHistory(initialLocation ? { initialEntries: [initialLocation] } : {})
|
2021-09-28 16:15:54 +02:00
|
|
|
;(history as any).pushState = history.push
|
|
|
|
;(history as any).replaceState = history.replace
|
2021-08-25 10:38:33 +02:00
|
|
|
initKea({ state, routerLocation: history.location, routerHistory: history })
|
2021-09-30 00:43:40 +02:00
|
|
|
featureFlagLogic.mount()
|
2022-03-15 17:36:51 +01:00
|
|
|
teamLogic.mount()
|
|
|
|
userLogic.mount()
|
2021-08-25 10:38:33 +02:00
|
|
|
router.mount()
|
|
|
|
const { store } = getContext()
|
2022-02-02 17:05:37 +01:00
|
|
|
store.dispatch({ type: 'storybook init' })
|
2021-08-25 10:38:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export function KeaStory<T = React.ReactNode>({
|
2022-02-02 17:05:37 +01:00
|
|
|
url,
|
2021-08-25 10:38:33 +02:00
|
|
|
state,
|
2022-02-02 17:05:37 +01:00
|
|
|
onInit,
|
2021-08-25 10:38:33 +02:00
|
|
|
children,
|
|
|
|
}: {
|
2022-02-02 17:05:37 +01:00
|
|
|
url?: string
|
|
|
|
state?: Record<string, any>
|
|
|
|
onInit?: () => void
|
2021-08-25 10:38:33 +02:00
|
|
|
children: T
|
|
|
|
}): T | JSX.Element | null {
|
2022-02-02 17:05:37 +01:00
|
|
|
const [didReset, setDidReset] = useState(false)
|
2021-11-03 22:44:41 +01:00
|
|
|
useEffect(() => {
|
2022-02-02 17:05:37 +01:00
|
|
|
if (!didReset) {
|
|
|
|
resetKeaStory(url, state)
|
|
|
|
onInit?.()
|
|
|
|
setDidReset(true)
|
2021-11-03 22:44:41 +01:00
|
|
|
}
|
2022-02-02 17:05:37 +01:00
|
|
|
}, [didReset])
|
2021-08-25 10:38:33 +02:00
|
|
|
|
2022-02-02 17:05:37 +01:00
|
|
|
return didReset ? <Provider>{children || <App />}</Provider> : null
|
2021-08-25 10:38:33 +02:00
|
|
|
}
|
2021-09-08 12:05:39 +02:00
|
|
|
|
|
|
|
export function keaStory(Component: any, json: any): () => JSX.Element {
|
|
|
|
return function KeaStoryInstance() {
|
|
|
|
return (
|
|
|
|
<KeaStory state={json}>
|
|
|
|
<Component />
|
|
|
|
</KeaStory>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|