From a1d10a56519d71fb7a9fc0f3d71cc7a5269eb4d7 Mon Sep 17 00:00:00 2001 From: Eirik Sletteberg Date: Wed, 30 Jun 2021 00:11:28 +0200 Subject: [PATCH] Fix: cache DocsContext on window to prevent duplication This is intended to solve https://github.com/eirslett/storybook-builder-vite/issues/40 and related issues. --- addons/docs/src/blocks/DocsContext.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/addons/docs/src/blocks/DocsContext.ts b/addons/docs/src/blocks/DocsContext.ts index 0556b6304e39..9f66a2588552 100644 --- a/addons/docs/src/blocks/DocsContext.ts +++ b/addons/docs/src/blocks/DocsContext.ts @@ -1,4 +1,5 @@ import { Context, createContext } from 'react'; +import { window as globalWindow } from 'global'; export interface DocsContextProps { id?: string; @@ -17,4 +18,15 @@ export interface DocsContextProps { forceRender?: () => void; } -export const DocsContext: Context = createContext({}); +// We add DocsContext to window. The reason is that in case DocsContext.ts is +// imported multiple times (maybe once directly, and another time from a minified bundle) +// we will have multiple DocsContext definitions - leading to lost context in +// the React component tree. +// This was specifically a problem with the Vite builder. +/* eslint-disable no-underscore-dangle */ +if (globalWindow.__DOCS_CONTEXT__ === undefined) { + globalWindow.__DOCS_CONTEXT__ = createContext({}); + globalWindow.__DOCS_CONTEXT__.displayName = 'DocsContext'; +} + +export const DocsContext: Context = globalWindow.__DOCS_CONTEXT__;