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
5 changes: 5 additions & 0 deletions .changeset/base-codebox-copy-text.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@node-core/ui-components': minor
---

Add an optional `copyText` prop to `BaseCodeBox` so callers can provide a custom string to copy instead of the rendered `textContent`.
1 change: 1 addition & 0 deletions apps/site/components/Common/CodeBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { FC, PropsWithChildren } from 'react';
type CodeBoxProps = {
language: string;
className?: string;
copyText?: string;
};

const CodeBox: FC<PropsWithChildren<CodeBoxProps>> = props => {
Expand Down
25 changes: 18 additions & 7 deletions apps/site/components/Downloads/Release/ReleaseCodeBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
ReleasesContext,
} from '#site/providers/releaseProvider';
import { INSTALL_METHODS } from '#site/util/download';
import { stripShellComments } from '#site/util/download/snippet';
import createInterpreter from '#site/util/interpreter';

import type { DownloadSnippet } from '#site/types/download';
Expand Down Expand Up @@ -56,7 +57,7 @@ const useSnippetProcessor = (

// Only process if both snippets are available
if (!installMethodSnippet || !packageManagerSnippet) {
return '';
return { html: '', copyText: '' };
}

const verifyNodeSnippet = snippets.find(({ name }) => name === 'node');
Expand Down Expand Up @@ -84,10 +85,13 @@ const useSnippetProcessor = (

// Convert to HTML using Shiki's highlighter
// This is faster than JSX rendering as it avoids React runtime overhead
return highlightToHtml(
parsedContent,
context.os === 'WIN' ? 'ps1' : 'bash'
);
return {
html: highlightToHtml(
parsedContent,
context.os === 'WIN' ? 'ps1' : 'bash'
),
copyText: stripShellComments(parsedContent),
};
}, [snippets, context]);
};

Expand Down Expand Up @@ -123,7 +127,10 @@ const ReleaseCodeBox: FC = () => {
const platformInfo = usePlatformInfo(context.installMethod);

// Process snippets
const parsedSnippets = useSnippetProcessor(snippets, context);
const { html: parsedSnippets, copyText } = useSnippetProcessor(
snippets,
context
);

// UI state calculations
const displayLanguage = context.os === 'WIN' ? 'PowerShell' : 'Bash';
Expand Down Expand Up @@ -164,7 +171,11 @@ const ReleaseCodeBox: FC = () => {

{/* Code display with skeleton loading */}
<Skeleton loading={isLoading}>
<CodeBox language={displayLanguage} className="min-h-[19rem]">
<CodeBox
language={displayLanguage}
copyText={copyText}
className="min-h-[19rem]"
>
{/* eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml */}
<code dangerouslySetInnerHTML={{ __html: parsedSnippets }} />
</CodeBox>
Expand Down
78 changes: 78 additions & 0 deletions apps/site/util/__tests__/snippet.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import { stripShellComments } from '../download/snippet';

describe('stripShellComments', () => {
it('removes full-line and trailing inline comments while preserving commands', () => {
const input = [
'# Download and install nvm:',
'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.41.0/install.sh | bash',
'',
'# in lieu of restarting the shell',
'\\. "$HOME/.nvm/nvm.sh"',
'',
'# Verify the Node.js version:',
'node -v # Should print "v26.13.1".',
'',
'# Verify npm version:',
'npm -v # Should print "11.20.0".',
].join('\n');

assert.equal(
stripShellComments(input),
[
'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.41.0/install.sh | bash',
'',
'\\. "$HOME/.nvm/nvm.sh"',
'',
'node -v',
'',
'npm -v',
].join('\n')
);
});

it('preserves # inside quoted strings and parameter expansions', () => {
const input = [
'echo "hello # world" # trailing comment',
"echo 'single # quote'",
'echo ${VAR#prefix}',
'curl https://example.com/page#anchor',
'echo escaped \\# hash',
].join('\n');

assert.equal(
stripShellComments(input),
[
'echo "hello # world"',
"echo 'single # quote'",
'echo ${VAR#prefix}',
'curl https://example.com/page#anchor',
'echo escaped \\# hash',
].join('\n')
);
});

it('collapses blank lines left behind by consecutive comment-only sections', () => {
const input = [
'# Section A',
'cmd-a',
'',
'# Comment-only section',
'# commented-out command',
'',
'# Section B',
'cmd-b',
'',
'# Trailing comment only',
].join('\n');

assert.equal(stripShellComments(input), ['cmd-a', '', 'cmd-b'].join('\n'));
});

it('returns an empty string when input contains only comments or whitespace', () => {
assert.equal(stripShellComments('# only a comment\n\n # another'), '');
assert.equal(stripShellComments(''), '');
});
});
70 changes: 70 additions & 0 deletions apps/site/util/download/snippet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/**
* Removes shell `#` comments from a single line while preserving `#` characters
* inside quoted strings or inside words (e.g. `${VAR#prefix}`).
*/
const stripInlineComment = (line: string): string => {
let quote: "'" | '"' | '`' | null = null;
let escaped = false;

for (let i = 0; i < line.length; i++) {
const ch = line[i];

if (escaped) {
escaped = false;
continue;
}

if (ch === '\\' && quote !== "'") {
escaped = true;
continue;
}

if (quote) {
if (ch === quote) {
quote = null;
}
continue;
}

if (ch === "'" || ch === '"' || ch === '`') {
quote = ch;
continue;
}

if (ch === '#' && (i === 0 || /\s/.test(line[i - 1]!))) {
return line.slice(0, i).trimEnd();
}
}

return line.trimEnd();
};

/**
* Strips shell `#` comment lines and trailing inline `#` comments from a
* download snippet so copying and pasting it into shells where interactive
* comments are disabled by default (such as macOS's default `zsh`) runs cleanly
* without `zsh: command not found: #` errors.
*/
export const stripShellComments = (snippet: string): string => {
const result: Array<string> = [];

for (const rawLine of snippet.split(/\r?\n/)) {
if (rawLine.trim().length === 0) {
if (result.length > 0 && result[result.length - 1] !== '') {
result.push('');
}
continue;
}

const stripped = stripInlineComment(rawLine);
if (stripped.trim().length > 0) {
result.push(stripped);
}
}

while (result.length > 0 && result[result.length - 1] === '') {
result.pop();
}

return result.join('\n');
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';

import { fireEvent, render, screen } from '@testing-library/react';

import BaseCodeBox from '../';

navigator.clipboard = { writeText: () => Promise.resolve() };

describe('BaseCodeBox', () => {
it('copies the rendered textContent by default', async t => {
const writeText = t.mock.method(navigator.clipboard, 'writeText', () =>
Promise.resolve()
);

render(
<BaseCodeBox
language="Bash"
copyButtonLabel="Copy"
copiedButtonLabel="Copied"
>
<code>{'# comment\nnode -v'}</code>
</BaseCodeBox>
);

fireEvent.click(screen.getByRole('button', { name: /copy/i }));

assert.equal(writeText.mock.callCount(), 1);
assert.deepEqual(writeText.mock.calls[0].arguments, [
'# comment\nnode -v\n',
]);
});

it('copies custom copyText instead of rendered textContent when provided', async t => {
const writeText = t.mock.method(navigator.clipboard, 'writeText', () =>
Promise.resolve()
);

render(
<BaseCodeBox
language="Bash"
copyButtonLabel="Copy"
copiedButtonLabel="Copied"
copyText="node -v"
>
<code>{'# Verify Node.js:\nnode -v # comment'}</code>
</BaseCodeBox>
);

fireEvent.click(screen.getByRole('button', { name: /copy/i }));

assert.equal(writeText.mock.callCount(), 1);
assert.deepEqual(writeText.mock.calls[0].arguments, ['node -v']);
});
});
4 changes: 3 additions & 1 deletion packages/ui-components/src/Common/BaseCodeBox/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type CodeBoxProps = {
as?: LinkLike;
copyButtonLabel: ReactNode;
copiedButtonLabel: ReactNode;
copyText?: string;
};

const BaseCodeBox: FC<PropsWithChildren<CodeBoxProps>> = ({
Expand All @@ -80,13 +81,14 @@ const BaseCodeBox: FC<PropsWithChildren<CodeBoxProps>> = ({
className,
copyButtonLabel,
copiedButtonLabel,
copyText,
as = 'a',
}: PropsWithChildren<CodeBoxProps>) => {
const [copied, copy] = useCopy();

const containerRef = useRef<HTMLPreElement>(null);

const handleCopy = () => copy(containerRef.current?.textContent);
const handleCopy = () => copy(copyText ?? containerRef.current?.textContent);

const ButtonIcon = copied ? DocumentDuplicateIcon : CodeBracketIcon;

Expand Down