-
Notifications
You must be signed in to change notification settings - Fork 2.9k
feat: port codesandbox addon #26810
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ling1726
merged 6 commits into
microsoft:master
from
ling1726:feat/storybook-addon-codesandbox
Feb 20, 2023
Merged
feat: port codesandbox addon #26810
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
db6650c
feat: Port codesandbox addon
ling1726 c3885c7
fix syncpack
ling1726 f40a6b8
remove references to old addong
ling1726 2ef72c1
Merge remote-tracking branch 'origin/master' into feat/storybook-addo…
ling1726 8b28f9f
build esm
ling1726 42edd6a
Merge branch 'master' into feat/storybook-addon-codesandbox
ling1726 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
packages/react-components/react-storybook-addon-codesandbox/preset.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| function config(entry = []) { | ||
| return [...entry, require.resolve('./lib/preset/preview')]; | ||
| } | ||
|
|
||
| module.exports = { config }; |
61 changes: 61 additions & 0 deletions
61
packages/react-components/react-storybook-addon-codesandbox/src/getDepdencies.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| export type PackageDependencies = { [dependencyName: string]: string }; | ||
|
|
||
| function matchAll(str: string, re: RegExp) { | ||
| const regexp = new RegExp(re, 'g'); | ||
| let match: RegExpExecArray | null = null; | ||
| const matches: RegExpExecArray[] = []; | ||
|
|
||
| while ((match = regexp.exec(str))) { | ||
| matches.push(match); | ||
| } | ||
|
|
||
| return matches; | ||
| } | ||
|
|
||
| /** | ||
| * | ||
| * @param fileContent - code | ||
| * @param requiredDependencies - dependencies that will always be incldued in package.json | ||
| * @param optionalDependencies - whose versions will override those found in the code | ||
| * @returns - Map of dependencies and their versions to include in package.json | ||
| */ | ||
| export const getDependencies = ( | ||
| fileContent: string, | ||
| requiredDependencies: PackageDependencies, | ||
| optionalDependencies: PackageDependencies, | ||
| ) => { | ||
| const matches = matchAll(fileContent, /from ['"](.*?)['"];/g); | ||
|
|
||
| const dependenciesInCode = Array.from(matches).reduce((dependencies, match) => { | ||
| if (!match[1].startsWith('react/')) { | ||
| const dependency = parsePackageName(match[1]).name; | ||
|
|
||
| if (!dependencies.hasOwnProperty(dependency)) { | ||
| dependencies[dependency] = optionalDependencies[dependency] ?? 'latest'; | ||
| } | ||
| } | ||
|
|
||
| return dependencies; | ||
| }, {} as PackageDependencies); | ||
|
|
||
| return { ...dependenciesInCode, ...requiredDependencies }; | ||
| }; | ||
|
|
||
| // Parsed a scoped package name into name, version, and path. | ||
| const RE_SCOPED = /^(@[^\/]+\/[^@\/]+)(?:@([^\/]+))?(\/.*)?$/; | ||
| // Parsed a non-scoped package name into name, version, path | ||
| const RE_NON_SCOPED = /^([^@\/]+)(?:@([^\/]+))?(\/.*)?$/; | ||
|
|
||
| function parsePackageName(input: string) { | ||
| const m = RE_SCOPED.exec(input) || RE_NON_SCOPED.exec(input); | ||
|
|
||
| if (!m) { | ||
| throw new Error(`[parse-package-name] invalid package name: ${input}`); | ||
| } | ||
|
|
||
| return { | ||
| name: m[1] || '', | ||
| version: m[2] || 'latest', | ||
| path: m[3] || '', | ||
| }; | ||
| } |
75 changes: 75 additions & 0 deletions
75
packages/react-components/react-storybook-addon-codesandbox/src/getDependencies.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import { getDependencies } from './getDepdencies'; | ||
|
|
||
| describe('getDependencies', () => { | ||
| it('should find all dependencies in a file', () => { | ||
| const code = ` | ||
| import { stuff } from 'dependency'; | ||
| import * as allStuff from 'dependency1'; | ||
| import { moreStuff } from '@dependency/dependency'; | ||
| import { | ||
| someOtherStuff, | ||
| } from "@multiline/importDouble"; | ||
| import { | ||
| someOtherStuff, | ||
| } from '@multiline/import'; | ||
| `; | ||
| const deps = getDependencies(code, {}, {}); | ||
|
|
||
| expect(deps).toEqual({ | ||
| '@dependency/dependency': 'latest', | ||
| '@multiline/importDouble': 'latest', | ||
| '@multiline/import': 'latest', | ||
| dependency: 'latest', | ||
| dependency1: 'latest', | ||
| }); | ||
| }); | ||
|
|
||
| it('should ignore separate entrypoints', () => { | ||
| const code = ` | ||
| import { stuff } from 'dependency/unstable'; | ||
| import { moreStuff } from 'dependency/unstable/component'; | ||
| import { moreStuff2 } from '@dependency/unstable'; | ||
| import { moreStuff3 } from '@dependency/unstable/component'; | ||
| `; | ||
| const deps = getDependencies(code, {}, {}); | ||
|
|
||
| expect(deps).toEqual({ | ||
| dependency: 'latest', | ||
| '@dependency/unstable': 'latest', | ||
| }); | ||
| }); | ||
|
|
||
| it('versions in optionalDependencies should win ', () => { | ||
| const code = ` | ||
| import { stuff } from 'dependency'; | ||
| `; | ||
| const deps = getDependencies(code, {}, { dependency: '1.0.0' }); | ||
|
|
||
| expect(deps).toEqual({ | ||
| dependency: '1.0.0', | ||
| }); | ||
| }); | ||
|
|
||
| it('versions in requiredDependencies should win ', () => { | ||
| const code = ` | ||
| import { stuff } from 'dependency'; | ||
| `; | ||
| const deps = getDependencies(code, { dependency: '1.0.0' }, {}); | ||
|
|
||
| expect(deps).toEqual({ | ||
| dependency: '1.0.0', | ||
| }); | ||
| }); | ||
|
|
||
| it('versions in requiredDependencies should win ', () => { | ||
| const code = ` | ||
| import { stuff } from 'dependency'; | ||
| `; | ||
| const deps = getDependencies(code, { required: '1.0.0' }, {}); | ||
|
|
||
| expect(deps).toEqual({ | ||
| dependency: 'latest', | ||
| required: '1.0.0', | ||
| }); | ||
| }); | ||
| }); |
3 changes: 3 additions & 0 deletions
3
packages/react-components/react-storybook-addon-codesandbox/src/preset/preview.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import { withCodeSandboxButton } from '../withCodeSandboxButton'; | ||
|
|
||
| export const decorators = [withCodeSandboxButton]; |
102 changes: 102 additions & 0 deletions
102
packages/react-components/react-storybook-addon-codesandbox/src/withCodeSandboxButton.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| import { StoryContext, useEffect } from '@storybook/addons'; | ||
| import { getParameters } from 'codesandbox-import-utils/lib/api/define'; | ||
| import * as dedent from 'dedent'; | ||
| import { getDependencies } from './getDepdencies'; | ||
| import type { PackageDependencies } from './getDepdencies'; | ||
|
|
||
| export const withCodeSandboxButton = (storyFn: (context: StoryContext) => JSX.Element, context: StoryContext) => { | ||
| useEffect(() => { | ||
| if (context.viewMode === 'docs') { | ||
| displayToolState(`#anchor--${context.id} .docs-story`, context); | ||
| } | ||
| }, [context]); | ||
|
|
||
| return storyFn(context); | ||
| }; | ||
|
|
||
| const displayToolState = (selector: string, context: StoryContext) => { | ||
| const exportLink = document.createElement('a'); | ||
| exportLink.className = 'with-code-sandbox-button'; | ||
| exportLink.style.setProperty('position', 'absolute'); | ||
| exportLink.style.setProperty('bottom', '0'); | ||
| exportLink.style.setProperty('right', '90px'); | ||
| exportLink.style.setProperty('border', '1px solid rgba(0,0,0,.1)'); | ||
| exportLink.style.setProperty('border-bottom', 'none'); | ||
| exportLink.style.setProperty('border-radius', '4px 4px 0 0'); | ||
| exportLink.style.setProperty('padding', '4px 10px'); | ||
| exportLink.style.setProperty('background', 'white'); | ||
| exportLink.style.setProperty( | ||
| 'font-family', | ||
| '"Nunito Sans",-apple-system,".SFNSText-Regular","San Francisco",BlinkMacSystemFont,"Segoe UI","Helvetica Neue",Helvetica,Arial,sans-serif', | ||
| ); | ||
| exportLink.style.setProperty('font-weight', '700'); | ||
| exportLink.style.setProperty('font-size', '12px'); | ||
| exportLink.style.setProperty('text-decoration', 'none'); | ||
| exportLink.style.setProperty('line-height', '16px'); | ||
| exportLink.setAttribute('target', '_blank'); | ||
|
|
||
| // set to error state by default, overwritten later | ||
| exportLink.style.setProperty('color', 'darkred'); | ||
| exportLink.innerText = `CodeSandbox Error: See console`; | ||
|
|
||
| const rootElement = document.querySelector(selector); | ||
| rootElement?.appendChild(exportLink); | ||
|
|
||
| const storyFile = context.parameters?.fullSource; | ||
|
|
||
| if (!storyFile) { | ||
| console.error( | ||
| `Export to CodeSandbox: Couldn’t find source for story ${context.story}. Did you install the babel plugin?`, | ||
| ); | ||
| return false; | ||
| } | ||
|
|
||
| const requiredDependencies: PackageDependencies = context.parameters?.exportToCodeSandbox?.requiredDependencies ?? {}; | ||
| const optionalDependencies: PackageDependencies = context.parameters?.exportToCodeSandbox?.optionalDependencies ?? {}; | ||
|
|
||
| const dependencies = getDependencies(storyFile, requiredDependencies, optionalDependencies); | ||
|
|
||
| const indexTsx = context.parameters?.exportToCodeSandbox?.indexTsx; | ||
| if (indexTsx === null) { | ||
| console.error( | ||
| dedent`Export to CodeSandbox: Please set parameters.exportToCodeSandbox.indexTsx | ||
| to the desired content of index.tsx file.`, | ||
| ); | ||
| return false; | ||
| } | ||
| console.log(context); | ||
|
|
||
| const defaultFileToPreview = encodeURIComponent('/example.tsx'); | ||
| const codeSandboxParameters = getParameters({ | ||
| files: { | ||
| 'example.tsx': { | ||
| isBinary: false, | ||
| content: storyFile, | ||
| }, | ||
| 'index.html': { | ||
| isBinary: false, | ||
| content: '<div id="root"></div>', | ||
| }, | ||
| 'index.tsx': { | ||
| isBinary: false, | ||
| // use originalStoryFn because users can override the `storyName` property. | ||
| // We need the name of the exported function, not the actual story | ||
| // https://github.com/microsoft/fluentui-storybook-addons/issues/12 | ||
| // originalStoryFn.name someties looks like this: ProgressBarDefault_stories_Default | ||
| // just get the "Default" | ||
| content: indexTsx.replace('STORY_NAME', context.originalStoryFn.name.split('_stories_').slice(-1).pop()), | ||
| }, | ||
| 'package.json': { | ||
| isBinary: false, | ||
| content: JSON.stringify({ dependencies }), | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| exportLink.setAttribute( | ||
| 'href', | ||
| `https://codesandbox.io/api/v1/sandboxes/define?parameters=${codeSandboxParameters}&query=file%3D${defaultFileToPreview}`, | ||
| ); | ||
| exportLink.style.setProperty('color', '#333333'); | ||
| exportLink.innerText = `Open in CodeSandbox`; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.