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,43 @@ export const WithCustomClassName: Story = {
</CodeBlock>
),
};

export const MDXIndents: Story = {
render: () => (
<CodeBlock filename="example.ts" language="ts">
{`import {
a,
b,
} from 'pkg';

async function main() {
console.log('hello');
}`}
</CodeBlock>
),
};

export const MDXIndentsDeeplyNested: Story = {
render: () => (
<CodeBlock filename="nested.ts" language="ts">
{`function outer() {
function middle() {
function inner() {
function deepest() {
if (true) {
for (let i = 0; i < 10; i++) {
while (i > 0) {
return 42;
}
}
}
}
return deepest();
}
return inner();
}
return middle();
}`}
</CodeBlock>
),
};
4 changes: 2 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,8 +2,8 @@ import type { ReactNode, RefObject } from "react";

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

import { BaseCodeBlock } from "./base-code-block";
import { CodeHeader } from "./code-header";
Expand Down Expand Up @@ -98,7 +98,7 @@ const CodeBlock = function CodeBlock(params: CodeBlockProps) {
copyButtonProps,
} = params;

const codeString = getNodeText(children);
const codeString = getCodeString(children, className, true);
const hasGrayBackgroundContainer = !!filename || !!icon;

return (
Expand Down
8 changes: 6 additions & 2 deletions packages/components/src/components/code-group/code-group.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import {
import { Icon as ComponentIcon } from "@/components/icon";
import { Classes } from "@/constants/selectors";
import { cn } from "@/utils/cn";
import { getNodeText } from "@/utils/get-node-text";
import type { CodeBlockTheme, CodeStyling } from "@/utils/shiki/code-styling";
import { getCodeString } from "@/utils/shiki/lib";

import { LanguageDropdown } from "./language-dropdown";

Expand Down Expand Up @@ -220,7 +220,11 @@ const CodeGroup = ({
{feedbackButton && feedbackButton}
<CopyToClipboardButton
codeBlockTheme={codeBlockTheme}
textToCopy={getNodeText(childArr[selectedIndex]?.props?.children)}
textToCopy={getCodeString(
childArr[selectedIndex]?.props?.children,
childArr[selectedIndex]?.props?.className,
true
)}
{...copyButtonProps}
/>
{askAiButton && askAiButton}
Expand Down
53 changes: 52 additions & 1 deletion packages/components/src/utils/shiki/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import { type ReactNode, useMemo } from "react";
import { getNodeText } from "@/utils/get-node-text";
import { SHIKI_CLASSNAME } from "@/utils/shiki/constants";

const lineIndentRegex = /^( *)/;
const closingStructureRegex = /^([}\])]|<\/)/;

function getIndent(line: string): number {
const match = line.match(lineIndentRegex);
return match ? match[1].length : 0;
}

function findShikiClassName(children: unknown): boolean {
if (!children || typeof children !== "object") {
return false;
Expand Down Expand Up @@ -37,6 +45,49 @@ function findShikiClassName(children: unknown): boolean {
return false;
}

function dedentCode(code: string): string {
const lines = code.split("\n");
if (lines.length <= 1) {
return code;
}

const relevantLines = lines.filter((line) => line.trim() !== "");
if (relevantLines.length === 0) {
return code;
}

const firstLine = relevantLines[0];
const lastLine = relevantLines.at(-1) ?? firstLine;
const firstIndent = getIndent(firstLine);
const lastIndent = getIndent(lastLine);
const isTemplatePolluted =
firstIndent < lastIndent && closingStructureRegex.test(lastLine.trim());

if (isTemplatePolluted) {
const firstNonEmptyIndex = lines.findIndex((line) => line.trim() !== "");
const tail = relevantLines.slice(1);
if (tail.length === 0) {
return code;
}
const minIndent = Math.min(...tail.map(getIndent));
if (minIndent === 0) {
return code;
}
return lines
.map((line, i) =>
i <= firstNonEmptyIndex ? line : line.slice(minIndent)
)
.join("\n");
}

const minIndent = Math.min(...relevantLines.map(getIndent));
if (minIndent === 0) {
return code;
}

return lines.map((line) => line.slice(minIndent)).join("\n");
}
Comment thread
cursor[bot] marked this conversation as resolved.

function getCodeString(
children: ReactNode,
className?: string,
Expand All @@ -50,7 +101,7 @@ function getCodeString(

const codeString = getNodeText(children);

return codeString;
return dedentCode(codeString);
Comment thread
cursor[bot] marked this conversation as resolved.
}

function calculateCodeLinesFromHtml(html: string | undefined): number {
Expand Down