storybook: DocsPage code preview indentation is wrong

Issuehunt badges

Describe the bug When creating stories for a DocsPage with an MDX file, the code preview underneath the story seems to have the wrong indentation, even though it’s correct in the file.

To Reproduce Steps to reproduce the behavior:

  1. Create a Component.stories.mdx file
  2. Output a <Story name="default"><Preview><Component /></Preview></Story>
  3. Go to DocsPage for that component
  4. Click “Code” button to bring up code preview
  5. See wrong indentation for code preview

Expected behavior The indentation (and line breaks) would be identical to how it shows up in the MDX file.

Screenshots The code:

and how it shows up in the DocsPage <Preview>:

Code snippets If applicable, add code samples to help explain your problem.

System: Environment Info:

System: OS: macOS 10.14.6 CPU: (8) x64 Intel® Core™ i7-4870HQ CPU @ 2.50GHz Binaries: Node: 12.6.0 - /usr/local/bin/node Yarn: 1.17.3 - /usr/local/bin/yarn npm: 6.9.0 - /usr/local/bin/npm Browsers: Chrome: 76.0.3809.87 Firefox: 68.0.1 Safari: 12.1.2 npmPackages: @storybook/addon-actions: ^5.2.0-rc.10 => 5.2.0-rc.11 @storybook/addon-docs: ^5.2.0-rc.11 => 5.2.0-rc.11 @storybook/addon-links: ^5.2.0-rc.10 => 5.2.0-rc.11 @storybook/addons: ^5.2.0-rc.10 => 5.2.0-rc.11 @storybook/react: ^5.2.0-rc.10 => 5.2.0-rc.11

Additional context The same exact indentation abnormality (2nd through 2nd last lines are indented one tab too far left, and last line indented two tabs too far right) seems to happen for all my DocsPage code previews, so I figured it’s either a configuration issue somewhere on my end, or a bug with the DocsPage code preview.

Thanks!


IssueHunt Summary

Backers (Total: $20.00)

Become a backer now!

Or submit a pull request to get the deposits!

Tips

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 43
  • Comments: 42 (18 by maintainers)

Commits related to this issue

Most upvoted comments

Indentation still wrong for *.mdx files in storybook v5.3.8

Source: Screenshot 2020-01-22 at 17 29 38

Result: Screenshot 2020-01-22 at 17 29 22

Here is a workaround for now, by editing your preview.js

import prettier from 'prettier/standalone';
import prettierBabel from 'prettier/parser-babel';

export const parameters = {
  docs: {
    transformSource: input =>
      prettier.format(input, {
        parser: 'babel',
        plugins: [prettierBabel],
      }),
  },
};

Hope it can help!

@kylemh has funded $20.00 to this issue.


Ridiculous, this problem still has not been solved in 2023!

yup, this is the current formatter.

import memoize from 'memoizerific';
import dedent from 'ts-dedent';

export const formatter = memoize(2)((code: string) => dedent(code));

I like the code a lot, but dedent just isn’t the big gun we need.


Okay, the work can be split in two parts.

1. if format is false, preserve user’s source code as written

I think zero formatting option is broken ATM in MDX stories @shilman. The parentheses are removed, newlines are added. If it were only spaces, it could be some dedent issue or CSS tab-size problem.

The source code of the story is altered before getting to Source component. I think we should detect why it happens and preserve user’s formatting if possible.

This fixes the bottom example in picture 2 above and leaves the first preview source (“Counter w/ Code”) as is.

2. if format is true format with Prettier

This improves the case in “Counter w/ Code” story and “repairs” the alteration which is root cause of this issue if we force format == true in MDX stories.

I consider both the fix (1) and the feature (2) worth implementing.

@coreybruyere this issue is still open. PRs welcome!

It seems like the solution which uses prettier/standalone and prettier/parser-babel above do not work if you use prettier v3 or later. This is because from v3, prettier’s format function is asychrnous returning a promise (see release note). However, Storybook’s transformSource is expected to be a function which returns a string.

Using ‘prettier-synchronized’ didn’t work for me either, since it looks like it needs to be used in a node environment

This is fixed in 7.0 beta

Hi, I tried the workaround by @frassinier. But, it added semicolon at the end of the code block and also it did not parse a component with a prop which passes a component, and doc breaks.

Instead, I did below using pretty library:

import pretty from 'pretty';
...
export const parameters = {
  docs: {
     transformSource: input => pretty(input)
  }
  ...
}

For your information. This worked for me.

I’ve made the following patch-package until the correct fix is done. It works in my case (having prettier already installed). Use at your own risk. @storybook+components+5.3.18.patch

index 6a56b1b..457af0d 100644
--- a/node_modules/@storybook/components/dist/blocks/Preview.js
+++ b/node_modules/@storybook/components/dist/blocks/Preview.js
@@ -51,6 +51,17 @@ var _ActionBar = require("../ActionBar/ActionBar");
 
 var _Toolbar = require("./Toolbar");
 
+var prettier = require("prettier/standalone");
+var plugins = [require("prettier/parser-babel")];
+
+function funkyFormattingHack(code) {
+  var formatted = prettier.format(code, {plugins}).trim();
+    if(formatted.endsWith(';')) {
+      formatted = formatted.slice(0, -1);
+    }
+    return formatted;
+}
+
 function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
 
 function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
@@ -125,6 +136,9 @@ var PreviewContainer = _theming.styled.div(function (_ref3) {
 });
 
 var getSource = function getSource(withSource, expanded, setExpanded) {
+  if(withSource && withSource.code) {
+    withSource.code = funkyFormattingHack(withSource.code)
+  }
   switch (true) {
     case !!(withSource && withSource.error):
       {
diff --git a/node_modules/@storybook/components/dist/blocks/Source.js b/node_modules/@storybook/components/dist/blocks/Source.js
index ecfb5d7..eb3eea1 100644
--- a/node_modules/@storybook/components/dist/blocks/Source.js
+++ b/node_modules/@storybook/components/dist/blocks/Source.js
@@ -73,7 +73,7 @@ var Source = function Source(props) {
   var syntaxHighlighter = _react["default"].createElement(StyledSyntaxHighlighter, _extends({
     bordered: true,
     copyable: true,
-    format: format,
+    format: false,
     language: language,
     className: "docblock-source"
   }, rest), code);

Create the file .storybook/preview-head.html which includes the following style block.

<style> pre code { tab-size: 2 !important; } </style>

@frassinier

Whilst this solution did work for me, running Storybook took a lot longer and I see this getting logged for a number of different files:

Note: The code generator has deoptimised the styling of /PATH/node_modules/prettier/standalone.js as it exceeds the max of 500KB.

It seems the issue occurs as soon as I add the prettier/standalone import.

The problem still exists in 5.3.9.

This code:

<div
  prop1="prop stay inline"
  prop2="prop stay inline"
  content2={{
    type: "indent ignored",
    value: "indent ignored",
    obj: {
      type2: "indent accepted from here"
    }
  }}
/>

is transformed to:

<div prop1="prop stay inline" prop2="prop stay inline" content2={{
type: "indent ignored",
value: "indent ignored",
obj: {
  type2: "indent accepted from here"
}
}} />

I tried the @sezeregrek workaround, but I’m still getting indentation error in this case when I use MDX:

<Preview>
  <Story name="Single">
    {() => {
        const [isActive, setActive] = useSingle(1);
      
        return (
            <Accordion>
                {items.map((item, idx) => {
                    const active = isActive(idx)
                    return (
                        <div key={item.id}>
                            {item.title}
                        </div>
                    )
                })}
            </Accordion>
        )
    }}
  </Story>
</Preview>

image

If I define the same code using CSF, it works fine.

Having the same issue, looks especially strange with render prop components… 😆 Screenshot 2019-11-19 at 11 46 01

I’m on the latest version of storybook and am still seeing incorrect indentation. Am I missing something?

Here’s what my MDX looks like: Screen Shot 2020-08-25 at 9 29 10 AM

And here’s the output: Screen Shot 2020-08-25 at 9 28 59 AM

Hi @shilman, @keyboard-clacker. Yeah, the pandemic happened and life got a bit more complicated for me. I think I stopped on the problem with dynamic imports and code splitting. The components are in separate library, so Prettier can’t be code splitted by webpack, and we should do something manually to lazily include prettier parsers. I dived into storybook’s build system and didn’t figure how to solve this.

I’d like to take this one. I did some quick research.

I’ve added a repro story (picture 1) to get the most hideous formatting. You can notice in the picture 2, that the code is altered not only in whitespace. It has also one pair of parentheses less.

I logged the source around addons/docs/src/blocks/Source.tsx#L45. We can already see the change in formatting there, this is before the Source from the components package renders.

I don’t know yet where docs.source.code is assigned so I’ll need to debug a bit.

@shilman Would you prefer to leave the story code as written or format it with prettier/standalone? Or maybe make it configurable in Source and Preview props? (There is a format prop in Source already, but it’s only calling dedent.)

Formatting would also be useful for cases like “Counter w/ Code” story. It’s 80 chars long, but it wraps in the docs page. (pictures 1 and 2)

Pictures

1. input

image

2. output

image

Whoopee!! I just released https://github.com/storybookjs/storybook/releases/tag/v5.3.7 containing PR #9513 that references this issue. Upgrade today to try it out!

Closing this issue. Please re-open if you think there’s still more to do.

Hello there! Stuck with the indentation issue. When using the control panel and the following code

const props = {
  phoneSize: 'm',
  icon: false,
  phoneNumber: '11111',
}

const Template = (args: any) => (
  <PhoneNumber {...args} />
)

export const Default = Template.bind({})
Default.args = props

I get the following preview: image

Has anyone come across a similar one? Thanks!

I had this issue. I had a style that was over-riding the css display property. Make sure you have display: inline or display: inline-block or display: initial.

yup, this is the current formatter.

import memoize from 'memoizerific';
import dedent from 'ts-dedent';

export const formatter = memoize(2)((code: string) => dedent(code));

I like the code a lot, but dedent just isn’t the big gun we need.

Okay, the work can be split in two parts.

1. if format is false, preserve user’s source code as written

I think zero formatting option is broken ATM in MDX stories @shilman. The parentheses are removed, newlines are added. If it were only spaces, it could be some dedent issue or CSS tab-size problem.

The source code of the story is altered before getting to Source component. I think we should detect why it happens and preserve user’s formatting if possible.

This fixes the bottom example in picture 2 above and leaves the first preview source (“Counter w/ Code”) as is.

2. if format is true format with Prettier

This improves the case in “Counter w/ Code” story and “repairs” the alteration which is root cause of this issue if we force format == true in MDX stories.

I consider both the fix (1) and the feature (2) worth implementing.

I set the format = false, fixed the indent problem, I also run well in my custom components below when I use react-syntax-highlighter originally.

import React from 'react'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { atomDark } from 'react-syntax-highlighter/dist/esm/styles/prism'

const Highlighter = (props: any) => {
  const { language, children } = props
  return (
    <SyntaxHighlighter
      format={false}
      showLineNumbers
      startingLineNumber={0}
      useInlineStyles
      language={language}
      style={atomDark}
      customStyle={{ fontSize: '12px' }}
      wrapLines>
      {children}
    </SyntaxHighlighter>
  )
}
const CodePreview = () => {
  return <Highlighter language={'tsx'}>{String(require('!!raw-loader!@/Avatar').default)}</Highlighter>
}
export default CodePreview

so, just remove the formatter to fix this problem?