Skip to content

Commit 212818e

Browse files
code-qtzlCopilot
andcommitted
fix(packages/components/src): MDX indentation
Co-authored-by: Copilot <copilot@github.com>
1 parent ded8eaf commit 212818e

2 files changed

Lines changed: 71 additions & 1 deletion

File tree

packages/components/src/components/code-block/code-block.stories.tsx

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,3 +464,43 @@ export const WithCustomClassName: Story = {
464464
</CodeBlock>
465465
),
466466
};
467+
468+
export const MDXIndents: Story = {
469+
render: () => (
470+
<CodeBlock filename="example.ts" language="ts">
471+
{`import {
472+
a,
473+
b,
474+
} from 'pkg';
475+
476+
async function main() {
477+
console.log('hello');
478+
}`}
479+
</CodeBlock>
480+
),
481+
};
482+
483+
export const MDXIndentsDeeplyNested: Story = {
484+
render: () => (
485+
<CodeBlock filename="nested.ts" language="ts">
486+
{`function outer() {
487+
function middle() {
488+
function inner() {
489+
function deepest() {
490+
if (true) {
491+
for (let i = 0; i < 10; i++) {
492+
while (i > 0) {
493+
return 42;
494+
}
495+
}
496+
}
497+
}
498+
return deepest();
499+
}
500+
return inner();
501+
}
502+
return middle();
503+
}`}
504+
</CodeBlock>
505+
),
506+
};

packages/components/src/utils/shiki/lib.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { type ReactNode, useMemo } from "react";
33
import { getNodeText } from "@/utils/get-node-text";
44
import { SHIKI_CLASSNAME } from "@/utils/shiki/constants";
55

6+
const lineIndentRegex = /^( *)/;
7+
68
function findShikiClassName(children: unknown): boolean {
79
if (!children || typeof children !== "object") {
810
return false;
@@ -37,6 +39,34 @@ function findShikiClassName(children: unknown): boolean {
3739
return false;
3840
}
3941

42+
function dedentCode(code: string): string {
43+
const lines = code.split("\n");
44+
if (lines.length <= 1) {
45+
return code;
46+
}
47+
48+
const relevantLines = lines.slice(1).filter((line) => line.trim() !== "");
49+
if (relevantLines.length === 0) {
50+
return code;
51+
}
52+
53+
const minIndent = Math.min(
54+
...relevantLines.map((line) => {
55+
const match = line.match(lineIndentRegex);
56+
return match ? match[1].length : 0;
57+
})
58+
);
59+
60+
if (minIndent === 0) {
61+
return code;
62+
}
63+
64+
return [
65+
lines[0],
66+
...lines.slice(1).map((line) => line.slice(minIndent)),
67+
].join("\n");
68+
}
69+
4070
function getCodeString(
4171
children: ReactNode,
4272
className?: string,
@@ -50,7 +80,7 @@ function getCodeString(
5080

5181
const codeString = getNodeText(children);
5282

53-
return codeString;
83+
return dedentCode(codeString);
5484
}
5585

5686
function calculateCodeLinesFromHtml(html: string | undefined): number {

0 commit comments

Comments
 (0)