<CodeBlock> adds and removes spaces arbitrarily at the start of lines #2374
Replies: 2 comments
-
|
We hit the indentation issue from #2374. Spent way too long trying to figure out the pattern before realizing we could just strip it out. The ProblemWrite code in a template literal for CodeBlock and you get random indentation artifacts: <CodeBlock language="bash">
{`CLICKHOUSE_USERNAME=main
CLICKHOUSE_FRAGMENT=
CLICKHOUSE_IP=123.456.78.90`}
</CodeBlock>First line renders fine. Lines 2 and 3? Extra spaces. No idea why, doesn't matter. Annoying either way. The FixMade a wrapper that removes common indentation before passing code to CodeBlock: let code = typeof children === 'string' ? children : String(children || '');
const codeLines = code.split('\n');
// Remove leading/trailing empty lines
while (codeLines.length > 0 && codeLines[0].trim() === '') codeLines.shift();
while (codeLines.length > 0 && codeLines[codeLines.length - 1].trim() === '') codeLines.pop();
if (codeLines.length > 0) {
// Find minimum indentation of non-empty lines
const indents = codeLines
.filter(line => line.trim().length > 0)
.map(line => line.match(/^[ \t]*/)[0].length);
const minIndent = Math.min(...indents);
// Remove that amount from all lines
code = codeLines
.map(line => line.slice(minIndent))
.join('\n');
}How to Use ItIndent everything in your template by 2 spaces: <DynamicCodeBlock language="bash">{`
CLICKHOUSE_USERNAME=main
CLICKHOUSE_FRAGMENT=
CLICKHOUSE_IP=123.456.78.90
`}</DynamicCodeBlock>Dedent finds the minimum (2 spaces), strips it from every line. All lines end up at column 0. YAML example: <DynamicCodeBlock language="yaml">{`
applications:
myapp:
source:
root: "/"
`}</DynamicCodeBlock>Renders as: applications:
myapp:
source:
root: "/"Relative indentation stays intact. How It Works
That's it. No heuristics. Just find the common base indent and strip it. |
Beta Was this translation helpful? Give feedback.
-
|
I have this issue as well. Whitespace gets stripped so formatted tables don't show correctly: |
Beta Was this translation helpful? Give feedback.

Uh oh!
There was an error while loading. Please reload this page.
-
The
<CodeBlock>component seems to be adding and removing whitespace at the start of lines arbitrarily.It always seems to strip two spaces from the start of every line. This is not documented, but it's not a huge deal.
More strangely, in one snippet, it seems to arbitrarily indent every line after the first by four spaces and I cannot figure out why it is this snippet specifically or how to turn it off.
Using fenced markdown code blocks fixes this, but we need the code snippet to include a prop dynamically from the parent page.
Things that don't seem to fix this:
<CodeBlock>into the page from the snippetBeta Was this translation helpful? Give feedback.
All reactions