From 23f76e38e01f525da6c41bd69e8ce233cd7c2296 Mon Sep 17 00:00:00 2001 From: Michael Shilman Date: Wed, 15 May 2024 17:55:24 +0800 Subject: [PATCH] Merge pull request #27147 from storybookjs/jeppe/27139-bug-unable-to-use-subtitle-doc-block-in-mdx-without-a-story Docs: Fix Subtitle block when no `of` prop passed (cherry picked from commit 1ba1a7efd8397a1a893409577893449a7683b719) --- code/ui/blocks/src/blocks/Subtitle.stories.tsx | 2 +- code/ui/blocks/src/blocks/Subtitle.tsx | 13 +++++++++++-- code/ui/blocks/src/blocks/Title.tsx | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/code/ui/blocks/src/blocks/Subtitle.stories.tsx b/code/ui/blocks/src/blocks/Subtitle.stories.tsx index 4fe4a2ef6a1..6ee1e865bab 100644 --- a/code/ui/blocks/src/blocks/Subtitle.stories.tsx +++ b/code/ui/blocks/src/blocks/Subtitle.stories.tsx @@ -99,6 +99,6 @@ export const OfStringMetaAttached: Story = { parameters: { relativeCsfPaths: ['../examples/Button.stories'], attached: true }, }; export const Children: Story = { - parameters: { relativeCsfPaths: ['../examples/Button.stories'], attached: true }, + parameters: { relativeCsfPaths: ['../examples/Button.stories'], attached: false }, render: () => This subtitle is a string passed as a children, }; diff --git a/code/ui/blocks/src/blocks/Subtitle.tsx b/code/ui/blocks/src/blocks/Subtitle.tsx index 9b7556e9c7c..055ed047cc1 100644 --- a/code/ui/blocks/src/blocks/Subtitle.tsx +++ b/code/ui/blocks/src/blocks/Subtitle.tsx @@ -25,8 +25,17 @@ export const Subtitle: FunctionComponent = (props) => { throw new Error('Unexpected `of={undefined}`, did you mistype a CSF file reference?'); } - const { preparedMeta } = useOf(of || 'meta', ['meta']); - const { componentSubtitle, docs } = preparedMeta.parameters || {}; + let preparedMeta; + try { + preparedMeta = useOf(of || 'meta', ['meta']).preparedMeta; + } catch (error) { + if (children && !error.message.includes('did you forget to use ?')) { + // ignore error about unattached CSF since we can still render children + throw error; + } + } + + const { componentSubtitle, docs } = preparedMeta?.parameters || {}; if (componentSubtitle) { deprecate( diff --git a/code/ui/blocks/src/blocks/Title.tsx b/code/ui/blocks/src/blocks/Title.tsx index 55b85ebad71..28ac06136ef 100644 --- a/code/ui/blocks/src/blocks/Title.tsx +++ b/code/ui/blocks/src/blocks/Title.tsx @@ -42,7 +42,7 @@ export const Title: FunctionComponent = (props) => { } } - const content = children || extractTitle(preparedMeta.title); + const content = children || extractTitle(preparedMeta?.title); return content ? {content} : null; };