Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): align CodeBlock line numbers with wrapped lines (#3925)

Andrew Prasetyo06b5c6e8dafa
diff --git a/.changeset/codeblock-wrapped-line-numbers.md b/.changeset/codeblock-wrapped-line-numbers.md
new file mode 100644
index 0000000000..b4cb1a495f
--- /dev/null
+++ b/.changeset/codeblock-wrapped-line-numbers.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] CodeBlock keeps line numbers aligned with wrapped lines when `isWrapped` is enabled
+@zeroryu
diff --git a/packages/core/src/CodeBlock/CodeBlock.tsx b/packages/core/src/CodeBlock/CodeBlock.tsx
index bb06e54663..ddbe2b6b8a 100644
--- a/packages/core/src/CodeBlock/CodeBlock.tsx
+++ b/packages/core/src/CodeBlock/CodeBlock.tsx
@@ -78,6 +78,13 @@ const dynamicStyles = stylex.create({
minWidth: value === 'fit-content' ? 'min(100%, 400px)' : null,
maxWidth: value === 'fit-content' ? '100%' : null,
}),
+ // Width of the line-number column, sized to the widest number. `ch` is the
+ // advance of "0" in the (monospace) code font, so N digits => N ch. Set on
+ // <code>; `--_codeblock-gutter-width` is unregistered so it inherits (with its var()
+ // substituted) down to the line divs that read it for their grid track.
+ gutterWidth: (digits: number) => ({
+ '--_codeblock-gutter-width': `${digits}ch`,
+ }),
});
const styles = stylex.create({
@@ -188,22 +195,6 @@ const styles = stylex.create({
':focus-visible': '2px',
},
},
- gutter: {
- flexShrink: 0,
- paddingBlock: spacingVars['--spacing-3'],
- paddingInlineStart: spacingVars['--spacing-4'],
- paddingInlineEnd: spacingVars['--spacing-3'],
- textAlign: 'end',
- userSelect: 'none',
- color: 'var(--color-syntax-punctuation)',
- borderRightWidth: borderVars['--border-width'],
- borderRightStyle: 'solid',
- borderRightColor: colorVars['--color-border'],
- },
- gutterLine: {
- fontFamily: typographyVars['--font-family-code'],
- lineHeight: typeScaleVars['--text-code-leading'],
- },
code: {
display: 'block',
flex: 1,
@@ -222,9 +213,53 @@ const styles = stylex.create({
wordBreak: 'break-all',
overflowWrap: 'break-word',
},
+ // With line numbers on, the <code> element hosts the full-height divider
+ // between the number gutter and the code. It spans the code's block padding
+ // too (inset-block: 0), so the rule reaches the top and bottom edges the way
+ // the old separate gutter column did. The numbers themselves are drawn per
+ // line (see `lineNumbered`) — a separate column can't track wrap height.
+ codeNumbered: {
+ position: 'relative',
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ insetBlock: 0,
+ insetInlineStart: `calc(${spacingVars['--spacing-4']} + var(--_codeblock-gutter-width) + ${spacingVars['--spacing-3']})`,
+ width: 0,
+ borderInlineStartWidth: borderVars['--border-width'],
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: colorVars['--color-border'],
+ pointerEvents: 'none',
+ },
+ },
line: {
lineHeight: typeScaleVars['--text-code-leading'],
},
+ // Per-line number gutter: a two-column grid ([number] [code]). The number is
+ // a ::before generated from the data-line attribute. Because the number and
+ // its code occupy one grid row, the row grows to fit wrapped code while the
+ // number stays pinned to the row's first visual line (alignSelf: start) —
+ // this is what keeps numbers aligned when isWrapped wraps a line.
+ lineNumbered: {
+ display: 'grid',
+ gridTemplateColumns: 'var(--_codeblock-gutter-width) 1fr',
+ columnGap: `calc(${spacingVars['--spacing-3']} + ${borderVars['--border-width']} + ${spacingVars['--spacing-4']})`,
+ '::before': {
+ content: 'attr(data-line)',
+ gridColumn: '1',
+ alignSelf: 'start',
+ textAlign: 'end',
+ color: 'var(--color-syntax-punctuation)',
+ userSelect: 'none',
+ fontFamily: typographyVars['--font-family-code'],
+ },
+ },
+ // In span mode the tokens are wrapped in this element so they form a single
+ // grid item in column 2 (otherwise each token span would flow into its own
+ // grid cell). minWidth:0 lets it shrink so long lines wrap within the track.
+ lineContent: {
+ minWidth: 0,
+ },
lineChunk: {
contentVisibility: 'auto',
},
@@ -239,12 +274,6 @@ const styles = stylex.create({
sizeMd: {
fontSize: typeScaleVars['--text-code-size'],
},
- gutterSm: {
- fontSize: typeScaleVars['--text-supporting-size'],
- },
- gutterMd: {
- fontSize: typeScaleVars['--text-code-size'],
- },
copyButton: {
display: 'inline-flex',
alignItems: 'center',
@@ -285,11 +314,13 @@ const CodeChunk = React.memo(function CodeChunk({
startIndex,
highlightSet,
renderLineContent,
+ lineNumbers,
}: {
lines: string[];
startIndex: number;
highlightSet: Set<number> | null;
renderLineContent: (line: string, lineIndex: number) => React.ReactNode;
+ lineNumbers: boolean;
}) {
return (
<>
@@ -301,6 +332,7 @@ const CodeChunk = React.memo(function CodeChunk({
data-line={i + 1}
{...stylex.props(
styles.line,
+ lineNumbers && styles.lineNumbered,
(highlightSet?.has(i + 1) ?? false) && styles.lineHighlighted,
)}>
{renderLineContent(line, i)}
@@ -315,6 +347,7 @@ function renderLines(
lines: string[],
highlightSet: Set<number> | null,
renderLineContent: (line: string, lineIndex: number) => React.ReactNode,
+ lineNumbers: boolean,
chunkSize: number = LINE_CHUNK_SIZE,
): React.ReactNode {
chunkSize = Math.max(1, Math.floor(chunkSize));
@@ -326,6 +359,7 @@ function renderLines(
startIndex={0}
highlightSet={highlightSet}
renderLineContent={renderLineContent}
+ lineNumbers={lineNumbers}
/>
);
}
@@ -347,6 +381,7 @@ function renderLines(
startIndex={start}
highlightSet={highlightSet}
renderLineContent={renderLineContent}
+ lineNumbers={lineNumbers}
/>
</div>,
);
@@ -542,12 +577,16 @@ function SpanCodeContent({
highlightSet,
isWrapped,
sizeStyle,
+ hasLineNumbers,
+ maxDigits,
}: {
lines: string[];
tokenLines: TokenLine[];
highlightSet: Set<number> | null;
isWrapped: boolean;
sizeStyle: stylex.StyleXStyles;
+ hasLineNumbers: boolean;
+ maxDigits: number;
}) {
useInsertionEffect(() => {
ensureHighlightStyles();
@@ -556,7 +595,13 @@ function SpanCodeContent({
const renderLineContent = useCallback(
(line: string, lineIndex: number): React.ReactNode => {
const tokens = tokenLines[lineIndex] ?? [];
- return buildSpanLine(line, tokens);
+ // Wrap tokens in a single element so they occupy one grid cell when line
+ // numbers are on (see `lineNumbered`); an inline span is a no-op when off.
+ return (
+ <span {...stylex.props(styles.lineContent)}>
+ {buildSpanLine(line, tokens)}
+ </span>
+ );
},
[tokenLines],
);
@@ -567,8 +612,10 @@ function SpanCodeContent({
styles.code,
sizeStyle,
isWrapped && styles.codeWrapped,
+ hasLineNumbers && styles.codeNumbered,
+ hasLineNumbers && dynamicStyles.gutterWidth(maxDigits),
)}>
- {renderLines(lines, highlightSet, renderLineContent)}
+ {renderLines(lines, highlightSet, renderLineContent, hasLineNumbers)}
</code>
);
}
@@ -583,12 +630,16 @@ function RangeCodeContent({
highlightSet,
isWrapped,
sizeStyle,
+ hasLineNumbers,
+ maxDigits,
}: {
lines: string[];
tokenLines: TokenLine[];
highlightSet: Set<number> | null;
isWrapped: boolean;
sizeStyle: stylex.StyleXStyles;
+ hasLineNumbers: boolean;
+ maxDigits: number;
}) {
const codeRef = useRef<HTMLElement>(null);
@@ -606,6 +657,9 @@ function RangeCodeContent({
return applyHighlightRangesChunked(codeEl, tokenLines);
}, [tokenLines]);
+ // Range mode keeps the line's text as a bare text node (its firstChild) so
+ // applyHighlightRangesChunked can map token offsets onto it \u2014 no wrapper. The
+ // number ::before is a pseudo-element, so it never becomes a child node here.
const renderLineContent = useCallback(
(line: string): React.ReactNode => line || '\u200b',
[],
@@ -618,8 +672,10 @@ function RangeCodeContent({
styles.code,
sizeStyle,
isWrapped && styles.codeWrapped,
+ hasLineNumbers && styles.codeNumbered,
+ hasLineNumbers && dynamicStyles.gutterWidth(maxDigits),
)}>
- {renderLines(lines, highlightSet, renderLineContent)}
+ {renderLines(lines, highlightSet, renderLineContent, hasLineNumbers)}
</code>
);
}
@@ -718,7 +774,8 @@ export function CodeBlock({
}, [code, onCopy, announce]);
const sizeStyle = size === 'sm' ? styles.sizeSm : styles.sizeMd;
- const gutterSizeStyle = size === 'sm' ? styles.gutterSm : styles.gutterMd;
+ // Digits in the largest line number — sizes the gutter column width.
+ const maxLineDigits = String(lines.length).length;
const languageLabel =
hasLanguageLabel && language !== 'plaintext' ? language : null;
const showHeader = title != null || languageLabel != null;
@@ -820,18 +877,6 @@ export function CodeBlock({
styles.codeWrapper,
showHeader && !hasLineNumbers && styles.codeWrapperCompact,
)}>
- {hasLineNumbers && (
- <div
- {...stylex.props(styles.gutter, gutterSizeStyle)}
- aria-hidden="true">
- {lines.map((_, i) => (
- // eslint-disable-next-line @eslint-react/no-array-index-key -- gutter line numbers are positional by definition
- <div key={i} {...stylex.props(styles.gutterLine)}>
- {i + 1}
- </div>
- ))}
- </div>
- )}
{useSpans ? (
<SpanCodeContent
lines={lines}
@@ -839,6 +884,8 @@ export function CodeBlock({
highlightSet={highlightSet}
isWrapped={isWrapped}
sizeStyle={sizeStyle}
+ hasLineNumbers={hasLineNumbers}
+ maxDigits={maxLineDigits}
/>
) : (
<RangeCodeContent
@@ -847,6 +894,8 @@ export function CodeBlock({
highlightSet={highlightSet}
isWrapped={isWrapped}
sizeStyle={sizeStyle}
+ hasLineNumbers={hasLineNumbers}
+ maxDigits={maxLineDigits}
/>
)}
</div>