Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -464,3 +464,52 @@ export const WithCustomClassName: Story = {
</CodeBlock>
),
};
export const TemplateLiteralSimple: Story = {
render: () => (
<CodeBlock language="bash" lines>
{`
echo hello
echo world
echo storybook
`}
</CodeBlock>
),
};
export const TemplateLiteralYaml: Story = {
render: () => (
<CodeBlock language="yaml" lines>
{`
applications:
myapp:
source:
root: "/"
`}
</CodeBlock>
),
};
export const TemplateLiteralJavascript: Story = {
render: () => (
<CodeBlock language="javascript" lines>
{`
function greet(name) {
console.log("Hello " + name);
}

greet("Mintlify");
`}
</CodeBlock>
),
};
export const TemplateLiteralWithEmptyLines: Story = {
render: () => (
<CodeBlock language="bash" lines>
{`

npm install

npm run build

`}
</CodeBlock>
),
};
13 changes: 11 additions & 2 deletions packages/components/src/components/code-block/code-block.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ReactNode, RefObject } from "react";

import { Classes } from "@/constants/selectors";
import { cn } from "@/utils/cn";
import { dedent } from "@/utils/dedent";
import { getNodeText } from "@/utils/get-node-text";
import type { CodeBlockTheme, CodeStyling } from "@/utils/shiki/code-styling";

Expand Down Expand Up @@ -98,7 +99,12 @@ const CodeBlock = function CodeBlock(params: CodeBlockProps) {
copyButtonProps,
} = params;

const codeString = getNodeText(children);
let codeString = getNodeText(children);

if (typeof codeString === "string") {
codeString = dedent(codeString);
}

const hasGrayBackgroundContainer = !!filename || !!icon;

return (
Expand Down Expand Up @@ -146,13 +152,16 @@ const CodeBlock = function CodeBlock(params: CodeBlockProps) {
{askAiButton && askAiButton}
</div>
)}

<BaseCodeBlock
codeBlockTheme={codeBlockTheme}
codeBlockThemeObject={codeBlockThemeObject}
hideAskAiButton={hideAskAiButton}
isSmallText={isSmallText}
{...params}
/>
>
{codeString}
</BaseCodeBlock>
</div>
);
};
Expand Down
25 changes: 25 additions & 0 deletions packages/components/src/utils/dedent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const INDENT_REGEX = /^[ ]*/;

export function dedent(code: string): string {
const lines = code.split("\n");

while (lines.length && lines[0].trim() === "") {
lines.shift();
}

while (lines.length && lines.at(-1)?.trim() === "") {
lines.pop();
}

if (lines.length === 0) {
return "";
}

const indents = lines
.filter((line) => line.trim().length > 0)
.map((line) => line.match(INDENT_REGEX)?.[0].length ?? 0);

const minIndent = Math.min(...indents);

return lines.map((line) => line.slice(minIndent)).join("\n");
}