diff --git a/.changeset/base-codebox-copy-text.md b/.changeset/base-codebox-copy-text.md new file mode 100644 index 0000000000000..875999662bd8f --- /dev/null +++ b/.changeset/base-codebox-copy-text.md @@ -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`. diff --git a/apps/site/components/Common/CodeBox.tsx b/apps/site/components/Common/CodeBox.tsx index 5ef26c06342b5..f6b0eb0b62cd3 100644 --- a/apps/site/components/Common/CodeBox.tsx +++ b/apps/site/components/Common/CodeBox.tsx @@ -10,6 +10,7 @@ import type { FC, PropsWithChildren } from 'react'; type CodeBoxProps = { language: string; className?: string; + copyText?: string; }; const CodeBox: FC> = props => { diff --git a/apps/site/components/Downloads/Release/ReleaseCodeBox.tsx b/apps/site/components/Downloads/Release/ReleaseCodeBox.tsx index a652f97c467a9..ca868e9d6f26d 100644 --- a/apps/site/components/Downloads/Release/ReleaseCodeBox.tsx +++ b/apps/site/components/Downloads/Release/ReleaseCodeBox.tsx @@ -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'; @@ -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'); @@ -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]); }; @@ -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'; @@ -164,7 +171,11 @@ const ReleaseCodeBox: FC = () => { {/* Code display with skeleton loading */} - + {/* eslint-disable-next-line @eslint-react/dom-no-dangerously-set-innerhtml */} diff --git a/apps/site/util/__tests__/snippet.test.mjs b/apps/site/util/__tests__/snippet.test.mjs new file mode 100644 index 0000000000000..4ca2a4c8926cf --- /dev/null +++ b/apps/site/util/__tests__/snippet.test.mjs @@ -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(''), ''); + }); +}); diff --git a/apps/site/util/download/snippet.ts b/apps/site/util/download/snippet.ts new file mode 100644 index 0000000000000..4fe61824ace44 --- /dev/null +++ b/apps/site/util/download/snippet.ts @@ -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 = []; + + 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'); +}; diff --git a/packages/ui-components/src/Common/BaseCodeBox/__tests__/index.test.jsx b/packages/ui-components/src/Common/BaseCodeBox/__tests__/index.test.jsx new file mode 100644 index 0000000000000..c0355f5aecc4f --- /dev/null +++ b/packages/ui-components/src/Common/BaseCodeBox/__tests__/index.test.jsx @@ -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( + + {'# comment\nnode -v'} + + ); + + 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( + + {'# Verify Node.js:\nnode -v # comment'} + + ); + + fireEvent.click(screen.getByRole('button', { name: /copy/i })); + + assert.equal(writeText.mock.callCount(), 1); + assert.deepEqual(writeText.mock.calls[0].arguments, ['node -v']); + }); +}); diff --git a/packages/ui-components/src/Common/BaseCodeBox/index.tsx b/packages/ui-components/src/Common/BaseCodeBox/index.tsx index af31bcdf3c37f..71409e9b773ec 100644 --- a/packages/ui-components/src/Common/BaseCodeBox/index.tsx +++ b/packages/ui-components/src/Common/BaseCodeBox/index.tsx @@ -72,6 +72,7 @@ type CodeBoxProps = { as?: LinkLike; copyButtonLabel: ReactNode; copiedButtonLabel: ReactNode; + copyText?: string; }; const BaseCodeBox: FC> = ({ @@ -80,13 +81,14 @@ const BaseCodeBox: FC> = ({ className, copyButtonLabel, copiedButtonLabel, + copyText, as = 'a', }: PropsWithChildren) => { const [copied, copy] = useCopy(); const containerRef = useRef(null); - const handleCopy = () => copy(containerRef.current?.textContent); + const handleCopy = () => copy(copyText ?? containerRef.current?.textContent); const ButtonIcon = copied ? DocumentDuplicateIcon : CodeBracketIcon;