From dd772e79112f0016adaec03be96ea39246f0de19 Mon Sep 17 00:00:00 2001 From: Darsh Poddar <114983070+drPod@users.noreply.github.com> Date: Thu, 27 Aug 2026 15:27:19 -0700 Subject: [PATCH] fix(code-block): size line-number gutter to the widest line number The line number was a fixed-width inline-block (w-8, 32px) followed by a 16px margin. A 14px mono digit is ~8.4px, so three digits fit but longer numbers spill past the box into the gap: at four digits the gap shrinks to ~14px, at five to ~6px, and at six the number overlaps the code. Make a two-column grid with line numbers on, render each line as display: contents, and let the ::before number and the content span be grid items. The number column now sizes to the widest line number, with min-w-12 (48px, incl. 16px padding) keeping blocks up to 999 lines pixel-identical to before. --- .changeset/code-block-line-number-gutter.md | 5 ++++ packages/elements/src/code-block.tsx | 29 +++++++++++++-------- 2 files changed, 23 insertions(+), 11 deletions(-) create mode 100644 .changeset/code-block-line-number-gutter.md diff --git a/.changeset/code-block-line-number-gutter.md b/.changeset/code-block-line-number-gutter.md new file mode 100644 index 00000000..db8da1e6 --- /dev/null +++ b/.changeset/code-block-line-number-gutter.md @@ -0,0 +1,5 @@ +--- +"ai-elements": patch +--- + +Size the CodeBlock line-number column to the widest line number instead of a fixed width, so 4+ digit line numbers no longer spill into the code diff --git a/packages/elements/src/code-block.tsx b/packages/elements/src/code-block.tsx index 820142d2..9494cd20 100644 --- a/packages/elements/src/code-block.tsx +++ b/packages/elements/src/code-block.tsx @@ -78,12 +78,11 @@ const TokenSpan = ({ token }: { token: ThemedToken }) => ( // Line number styles using CSS counters const LINE_NUMBER_CLASSES = cn( - "block", + "contents", "before:content-[counter(line)]", - "before:inline-block", "before:[counter-increment:line]", - "before:w-8", - "before:mr-4", + "before:min-w-12", + "before:pr-4", "before:text-right", "before:text-muted-foreground/50", "before:font-mono", @@ -97,15 +96,22 @@ const LineSpan = ({ }: { keyedLine: KeyedLine; showLineNumbers: boolean; -}) => ( - - {keyedLine.tokens.length === 0 +}) => { + const content = + keyedLine.tokens.length === 0 ? "\n" : keyedLine.tokens.map(({ token, key }) => ( - ))} - -); + )); + + return showLineNumbers ? ( + + {content} + + ) : ( + {content} + ); +}; // Types type CodeBlockProps = HTMLAttributes & { @@ -279,7 +285,8 @@ const CodeBlockBody = memo( {keyedLines.map((keyedLine) => (