UI: Improve syntax-highlighter bundling#32776
Conversation
📝 WalkthroughWalkthroughExtracts clipboard logic into a new Changes
Sequence Diagram(s)sequenceDiagram
participant UI as UI (copy button)
participant SH as SyntaxHighlighter
participant CB as createCopyToClipboardFunction
participant Win as globalWindow / top
participant Doc as document (via Storybook globals)
UI->>SH: user clicks copy
SH->>CB: invoke copy function with text
CB->>Win: check navigator?.clipboard
alt navigator.clipboard available
CB->>Win: try top.navigator.clipboard.writeText(text)
alt succeeds
CB-->>SH: resolved (success)
else fails
CB->>Win: fallback to globalWindow.navigator.clipboard.writeText(text)
CB-->>SH: resolved/rejected
end
else navigator.clipboard unavailable
CB->>Doc: create textarea, set value, append
CB->>Doc: select & document.execCommand('copy')
CB->>Doc: remove textarea, restore focus
CB-->>SH: resolved/rejected
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes ✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
Comment |
|
View your CI Pipeline Execution ↗ for commit 61894dc
☁️ Nx Cloud last updated this comment at |
Package BenchmarksCommit: The following packages have significant changes to their size or dependencies:
|
| Before | After | Difference | |
|---|---|---|---|
| Dependency count | 43 | 43 | 0 |
| Self size | 30.19 MB | 30.14 MB | 🎉 -51 KB 🎉 |
| Dependency size | 17.36 MB | 17.36 MB | 0 B |
| Bundle Size Analyzer | Link | Link |
@storybook/cli
| Before | After | Difference | |
|---|---|---|---|
| Dependency count | 187 | 187 | 0 |
| Self size | 927 KB | 927 KB | 🚨 +84 B 🚨 |
| Dependency size | 79.97 MB | 79.92 MB | 🎉 -51 KB 🎉 |
| Bundle Size Analyzer | Link | Link |
@storybook/codemod
| Before | After | Difference | |
|---|---|---|---|
| Dependency count | 169 | 169 | 0 |
| Self size | 35 KB | 35 KB | 🚨 +42 B 🚨 |
| Dependency size | 76.40 MB | 76.35 MB | 🎉 -51 KB 🎉 |
| Bundle Size Analyzer | Link | Link |
create-storybook
| Before | After | Difference | |
|---|---|---|---|
| Dependency count | 44 | 44 | 0 |
| Self size | 1.55 MB | 1.55 MB | 🎉 -30 B 🎉 |
| Dependency size | 47.55 MB | 47.50 MB | 🎉 -51 KB 🎉 |
| Bundle Size Analyzer | node | node |
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
code/core/src/components/components/syntaxhighlighter/clipboard.ts(1 hunks)code/core/src/components/components/syntaxhighlighter/syntaxhighlighter.tsx(1 hunks)code/core/src/components/components/typography/elements/Code.tsx(1 hunks)code/core/src/components/index.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,json,html,ts,tsx,mjs}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{js,jsx,json,html,ts,tsx,mjs}: Run Prettier formatting on changed files before committing
Run ESLint on changed files and fix all errors/warnings before committing (useyarn lint:js:cmd <file>)
Files:
code/core/src/components/components/typography/elements/Code.tsxcode/core/src/components/components/syntaxhighlighter/clipboard.tscode/core/src/components/components/syntaxhighlighter/syntaxhighlighter.tsxcode/core/src/components/index.ts
**/*.{ts,tsx,js,jsx,mjs}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Export functions from modules when they need to be unit-tested
Files:
code/core/src/components/components/typography/elements/Code.tsxcode/core/src/components/components/syntaxhighlighter/clipboard.tscode/core/src/components/components/syntaxhighlighter/syntaxhighlighter.tsxcode/core/src/components/index.ts
code/**/*.{ts,tsx,js,jsx,mjs}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
In application code, use Storybook loggers instead of
console.*(client code:storybook/internal/client-logger; server code:storybook/internal/node-logger)
Files:
code/core/src/components/components/typography/elements/Code.tsxcode/core/src/components/components/syntaxhighlighter/clipboard.tscode/core/src/components/components/syntaxhighlighter/syntaxhighlighter.tsxcode/core/src/components/index.ts
{code/**,scripts/**}/**/*.{ts,tsx,js,jsx,mjs}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Do not use
console.log,console.warn, orconsole.errordirectly unless in isolated files where importing loggers would significantly increase bundle size
Files:
code/core/src/components/components/typography/elements/Code.tsxcode/core/src/components/components/syntaxhighlighter/clipboard.tscode/core/src/components/components/syntaxhighlighter/syntaxhighlighter.tsxcode/core/src/components/index.ts
🧬 Code graph analysis (1)
code/core/src/components/components/syntaxhighlighter/clipboard.ts (1)
code/core/src/components/index.ts (1)
createCopyToClipboardFunction(40-40)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: normal
- GitHub Check: Core Unit Tests, windows-latest
🔇 Additional comments (4)
code/core/src/components/components/typography/elements/Code.tsx (1)
6-6: LGTM! Lazy-loading path correctly applied.The import path change to
lazy-syntaxhighlighterenables lazy-loading of the SyntaxHighlighter component, which aligns with the PR objective to improve bundling and avoid side-effect imports.code/core/src/components/index.ts (1)
40-40: LGTM! Export path updated to new clipboard module.The export path correctly points to the new dedicated clipboard module while preserving the public API surface.
code/core/src/components/components/syntaxhighlighter/syntaxhighlighter.tsx (2)
29-29: LGTM! Correctly imports from new clipboard module.The import change properly delegates clipboard functionality to the dedicated clipboard module, supporting the modularization effort.
36-36: LGTM! Proper usage of extracted clipboard function.The removal of
documentfrom the global destructuring (line 36) is correct since it's no longer needed in this file. Line 60 correctly creates thecopyToClipboardfunction using the importedcreateCopyToClipboardFunction.Also applies to: 60-60
| return async (text: string) => { | ||
| try { | ||
| await globalWindow.top?.navigator.clipboard.writeText(text); | ||
| } catch { | ||
| await globalWindow.navigator.clipboard.writeText(text); | ||
| } | ||
| }; |
There was a problem hiding this comment.
Fix silent failure when top is nullish.
If globalWindow.top is nullish, the optional chaining on line 9 returns undefined. Awaiting undefined succeeds immediately without actually writing to the clipboard, causing the function to silently fail.
Apply this diff to properly handle the fallback:
- try {
- await globalWindow.top?.navigator.clipboard.writeText(text);
- } catch {
- await globalWindow.navigator.clipboard.writeText(text);
- }
+ try {
+ if (globalWindow.top?.navigator.clipboard) {
+ await globalWindow.top.navigator.clipboard.writeText(text);
+ } else {
+ await globalWindow.navigator.clipboard.writeText(text);
+ }
+ } catch {
+ await globalWindow.navigator.clipboard.writeText(text);
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| return async (text: string) => { | |
| try { | |
| await globalWindow.top?.navigator.clipboard.writeText(text); | |
| } catch { | |
| await globalWindow.navigator.clipboard.writeText(text); | |
| } | |
| }; | |
| return async (text: string) => { | |
| try { | |
| if (globalWindow.top?.navigator.clipboard) { | |
| await globalWindow.top.navigator.clipboard.writeText(text); | |
| } else { | |
| await globalWindow.navigator.clipboard.writeText(text); | |
| } | |
| } catch { | |
| await globalWindow.navigator.clipboard.writeText(text); | |
| } | |
| }; |
🤖 Prompt for AI Agents
In code/core/src/components/components/syntaxhighlighter/clipboard.ts around
lines 7 to 13, the optional chaining on
globalWindow.top?.navigator.clipboard.writeText can return undefined and be
awaited (no-op) when top is nullish; change the implementation to first check
whether top.navigator.clipboard.writeText is a callable function and call/await
it if present, otherwise call/await
globalWindow.navigator.clipboard.writeText(text) as the fallback, and keep the
try/catch to handle runtime exceptions.
| return async (text: string) => { | ||
| const tmp = document.createElement('TEXTAREA') as HTMLTextAreaElement; | ||
| const focus = document.activeElement as HTMLTextAreaElement; | ||
|
|
||
| tmp.value = text; | ||
|
|
||
| document.body.appendChild(tmp); | ||
| tmp.select(); | ||
| document.execCommand('copy'); | ||
| document.body.removeChild(tmp); | ||
| focus.focus(); | ||
| }; |
There was a problem hiding this comment.
Add null check for activeElement before calling focus().
Line 17 assigns document.activeElement to focus, which can be null. Line 25 calls focus.focus() without checking, which will throw a TypeError if activeElement was null.
Apply this diff to add a null check:
return async (text: string) => {
const tmp = document.createElement('TEXTAREA') as HTMLTextAreaElement;
const focus = document.activeElement as HTMLTextAreaElement;
tmp.value = text;
document.body.appendChild(tmp);
tmp.select();
document.execCommand('copy');
document.body.removeChild(tmp);
- focus.focus();
+ focus?.focus();
};📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| return async (text: string) => { | |
| const tmp = document.createElement('TEXTAREA') as HTMLTextAreaElement; | |
| const focus = document.activeElement as HTMLTextAreaElement; | |
| tmp.value = text; | |
| document.body.appendChild(tmp); | |
| tmp.select(); | |
| document.execCommand('copy'); | |
| document.body.removeChild(tmp); | |
| focus.focus(); | |
| }; | |
| return async (text: string) => { | |
| const tmp = document.createElement('TEXTAREA') as HTMLTextAreaElement; | |
| const focus = document.activeElement as HTMLTextAreaElement; | |
| tmp.value = text; | |
| document.body.appendChild(tmp); | |
| tmp.select(); | |
| document.execCommand('copy'); | |
| document.body.removeChild(tmp); | |
| focus?.focus(); | |
| }; |
🤖 Prompt for AI Agents
In code/core/src/components/components/syntaxhighlighter/clipboard.ts around
lines 15 to 26, document.activeElement is assigned to focus which may be null;
add a null check before calling focus() to avoid a TypeError. Update the code to
only call focus.focus() when focus is non-null and is an element with a focus
method (e.g., check if focus !== null and typeof (focus as HTMLElement).focus
=== 'function'), so restore focus safely after removing the temporary textarea.
…se separate async functions for clipboard API and fallback method
What I did
Ensured no side-effect import of syntaxhighlighter from
storybook/internal/componentsbarrel fileChecklist for Contributors
Testing
The changes in this PR are covered in the following automated tests:
Manual testing
This section is mandatory for all contributions. If you believe no manual test is necessary, please state so explicitly. Thanks!
Documentation
MIGRATION.MD
Checklist for Maintainers
When this PR is ready for testing, make sure to add
ci:normal,ci:mergedorci:dailyGH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found incode/lib/cli-storybook/src/sandbox-templates.tsMake sure this PR contains one of the labels below:
Available labels
bug: Internal changes that fixes incorrect behavior.maintenance: User-facing maintenance tasks.dependencies: Upgrading (sometimes downgrading) dependencies.build: Internal-facing build tooling & test updates. Will not show up in release changelog.cleanup: Minor cleanup style change. Will not show up in release changelog.documentation: Documentation only changes. Will not show up in release changelog.feature request: Introducing a new feature.BREAKING CHANGE: Changes that break compatibility in some way with current major version.other: Changes that don't fit in the above categories.🦋 Canary release
This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the
@storybookjs/coreteam here.core team members can create a canary release here or locally with
gh workflow run --repo storybookjs/storybook publish.yml --field pr=<PR_NUMBER>Summary by CodeRabbit
Performance
Refactor