Skip to content
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

support multiple files for codesandbox import #5619

Merged
Merged
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
35 changes: 32 additions & 3 deletions packages/gatsby-remark-code-repls/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,30 +42,59 @@ to HTML links that open the embedded code examples in a REPL. For example:

```html
<!-- before -->
[See it in Babel](babel://hello-world)
[See it in Babel](babel://hello-world.js)

<!-- after -->
<a href="https://babeljs.io/repl/#?presets=react&code_lz=...">
See it in Babel
</a>

<!-- before -->
[Try it on CodePen](codepen://components-and-props/rendering-a-component)
[Try it on CodePen](codepen://components-and-props/rendering-a-component.js)

<!-- after -->
<a href="/redirect-to-codepen/components-and-props/rendering-a-component">
Try it on CodePen
</a>

<!-- before -->
[Try it on CodeSandbox](codesandbox://components-and-props/rendering-a-component)
[Try it on CodeSandbox](codesandbox://components-and-props/rendering-a-component.js)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's tell people to add explicit file extensions now that we support multiple types of files, even if we have a fallback mechanism for JavaScript files.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a good suggestion.


<!-- after -->
<a href="https://codesandbox.io/api/v1/sandboxes/define?parameters=...">
Try it on CodeSandbox
</a>
```

### Creating CodeSandbox Example With Multiple Files

Sometimes a larger code example would require more than a single file, with various types. For example, you might have an example folder like this:

```
├── my-example
│   ├── index.js
│   ├── util.js
│   └── index.css
```

CodeSandbox supports code example with multiple files. With this plugin, you can do:

```html
[Try it on CodeSandbox](codesandbox://my-example/index.js,my-example/util.js,my-example/index.css)
```

> Caveat
>
> The first file path you passed to `codesandbox://` will be the entry of your example, that is, the `main` field specified in your `package.json`.

And in `index.js`, you could import other files using the ES6 modules syntax:

```js
import { foo } from "./utils"

import "./index.css"
```

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice overview.

### How does it work?

Codepen links point to Gatsby pages (also created by this plug-in) that redirect
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-ggDQgI5NgA9iCZCBqMGTRHIpxaAAjClS6gLzqAOiABGaAE5GA3CH4ixkggAtaAWyjN59RkhAAeFhAAbuoQLLpGZtq0RgB8vgD0AYExNoJAA\\" >REPL</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqIQ6WgAsA9LVLzy8ei3mRYxBPyEgJbAB4FZtEVGY1GDJlIA8LCADcABBBYBeADogATqSktL4AfPbyTs4hIPoyCkoqajAaWoQkVnS2SCDWcLSuYIGunq6-AEZofr4A3DF6QA\\" >REPL</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -259,7 +259,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-ggDQgI5NgA9iCZCBqMGTRHIpxaAAjClS6gLzqAOiABGaAE5GA3CH4ixkggAtaAWyjN59RkhAAeFhAAbuoQLLpGZtq0RgB8vgD0AYExNoJAA\\" >REPL</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqJw0QiRD8hICWwAeBABa0RUZjUYMmUgDwsIANwAEEFgF4AOiABOpUrQcA-IwHpTZ9_OFIWGIEZBA9ekYkcIo4WgswFwsbCwcAIzRHBwBueQUgA\\" >REPL</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -301,7 +301,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-ggDQgI5NgA9iCZCBqMGTRHIpxaAAjClS6gLzqAOiABGaAE5GA3CH4ixkggAtaAWyjN59RkhAAeFhAAbuoQLLpGZtq0RgB8vgD0AYExNoJAA\\" >Click me</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqJw0QiRD8hICWwAeBABa0RUZjUYMmUgDwsIANwAEEFgF4AOiABOpUrQcA-IwHpTZ9_OFIWGIEZBA9ekYkcIo4WgswFwsbCwcAIzRHBwBueQUgA\\" >Click me</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -343,7 +343,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-ggDQgI5NgA9iCZCBqMGTRHIpxaAAjClS6gLzqAOiABGaAE5GA3CH4ixkggAtaAWyjN59RkhAAeFhAAbuoQLLpGZtq0RgB8vgD0AYExNoJAA\\" >Custom link text</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqJw0QiRD8hICWwAeBABa0RUZjUYMmUgDwsIANwAEEFgF4AOiABOpUrQcA-IwHpTZ9_OFIWGIEZBA9ekYkcIo4WgswFwsbCwcAIzRHBwBueQUgA\\" >Custom link text</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -385,7 +385,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-ggDQgI5NgA9iCZCBqMGTRHIpxaAAjClS6gLzqAOiABGaAE5GA3CH4ixkggAtaAWyjN59RkhAAeFhAAbuoQLLpGZtq0RgB8vgD0AYExNoJAA\\" target=\\"_blank\\" rel=\\"noreferrer\\">REPL</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqJw0QiRD8hICWwAeBABa0RUZjUYMmUgDwsIANwAEEFgF4AOiABOpUrQcA-IwHpTZ9_OFIWGIEZBA9ekYkcIo4WgswFwsbCwcAIzRHBwBueQUgA\\" target=\\"_blank\\" rel=\\"noreferrer\\">REPL</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -427,7 +427,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTzMBOMTE0QgoaenCYAaEIOEBaFqQC2SEORgAPGSBT9SKBbQCeHBKICMAVgLWQAXyeyI5NluIXqdBiJA1yKQACMFJSIIBeIIAdEAAjNH5YgG5HFzdtAgALWhUoZgD6RnUAHhYIADcgiBYI2INSWliAPhKAenKK5scnIA\\" >REPL</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTzMBOMTE0QgoaenCYAaEIOEBaFqQC2SEORgAPGSBT9SKBbQCeHBKICMAVgLWQAX1kq0ESqPS0AFgHpapH00pGBYfSFhiBAcnEDc2LQIvWhUoZhpGBhEQAB4WCAA3AAIIFgBeAB05UlJaSoA-bJ88_LrHWU9ff0D4elDwwhI0ukz1dKlCsGrC0sLKgCM0fkqAbkdooA\\" >REPL</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -469,7 +469,7 @@ Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-ggDQgI5NgA9iCZCBqMGTRHIpxaAAjClS6gLzqAOiABGaAE5GA3CH4ixkggAtaAWyjN59RkhAAeOOjk6hAsukZapEYAfL4A9AFo5FE2gkA\\" >REPL</a>",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqIQ6WgAsA9LVLzy8ei3mRYxBPyEgJbAB4FZtEVGY1GDJlIA8cdOQAEEFgF4AOuFKkfAHz28k5o5AEg-jIKSipqMBpahCRWdLZIINZwtC5gfi4eLj4ARmgATj4A3JF6QA\\" >REPL</a>",
},
],
"position": Position {
Expand Down Expand Up @@ -504,6 +504,48 @@ Object {
}
`;

exports[`gatsby-remark-code-repls CodeSandbox remark transform supports importing multiple files 1`] = `
Object {
"children": Array [
Object {
"children": Array [
Object {
"type": "html",
"value": "<a href=\\"https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSACYwoNvkYTxUC-AGhABbNBEqIQ6WgAsA9LVLzy8ei3mRYxBPyEgJbAB4FZtEVGY1GDJlIA8LCADcABBBYBeADogATqSktL4AfPbyTs4hIPoyCkoqajAaWoQkVnS2SCDWcLSuYIGunq6-AEZofr4A3DHCcYrKqnnJ8mjkQbIwfgBi0GkIyDmZjNm5-YWkxaUgFVUgtbFoco2JLSn9BBhwg9QjdsPkeQVFJeWVNTF6QA\\" >REPL</a>",
},
],
"position": Position {
"end": Object {
"column": 95,
"line": 1,
"offset": 94,
},
"indent": Array [],
"start": Object {
"column": 1,
"line": 1,
"offset": 0,
},
},
"type": "paragraph",
},
],
"position": Object {
"end": Object {
"column": 95,
"line": 1,
"offset": 94,
},
"start": Object {
"column": 1,
"line": 1,
"offset": 0,
},
},
"type": "root",
}
`;

exports[`gatsby-remark-code-repls Codepen remark transform generates a link for files in nested directories 1`] = `
Object {
"children": Array [
Expand Down
26 changes: 26 additions & 0 deletions packages/gatsby-remark-code-repls/src/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,24 @@ describe(`gatsby-remark-code-repls`, () => {
)
})

it(`errors if you provide multiple files in non-codesandbox examples`, () => {
const markdownAST = remark.parse(
`[](${protocol}path/to/nested/file.js,path/to/nested/anotherFile.js,path/to/nested/file.css)`
)
const runPlugin = () =>
plugin({ markdownAST }, { directory: `examples` })

if (protocol !== PROTOCOL_CODE_SANDBOX) {
expect(runPlugin).toThrow(
`Code example path should only contain a single file, but found more than one: ` +
`path/to/nested/file.js,path/to/nested/anotherFile.js,path/to/nested/file.css. ` +
`Only CodeSandbox REPL supports multiple files entries, the protocol prefix of which starts with codesandbox://`
)
} else {
expect(runPlugin).not.toThrow()
}
})

if (protocol === PROTOCOL_CODE_SANDBOX) {
it(`supports custom html config option for index html`, () => {
const markdownAST = remark.parse(
Expand Down Expand Up @@ -153,6 +171,14 @@ describe(`gatsby-remark-code-repls`, () => {

expect(transformed).toMatchSnapshot()
})

it(`supports importing multiple files`, () => {
const markdownAST = remark.parse(
`[](${protocol}path/to/nested/file.js,path/to/nested/anotherFile.js,path/to/nested/file.css)`
)
const transformed = plugin({ markdownAST }, { directory: `examples` })
expect(transformed).toMatchSnapshot()
})
}
})
})
Expand Down
59 changes: 46 additions & 13 deletions packages/gatsby-remark-code-repls/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,52 @@ module.exports = (

const getFilePath = (url, protocol, directory) => {
let filePath = url.replace(protocol, ``)
if (!filePath.endsWith(`.js`)) {
if (!filePath.includes(`.`)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for making this change! It was nagging me 😁

filePath += `.js`
}
filePath = normalizePath(join(directory, filePath))
return filePath
}

const verifyFile = path => {
const getMultipleFilesPaths = (urls, protocol, directory) =>
urls
.replace(protocol, ``)
.split(`,`)
.map(url => {
if (!url.includes(`.`)) {
url += `.js`
}

return {
url, // filename itself
filePath: normalizePath(join(directory, url)), // absolute path
}
})

const verifyFile = (path, protocol) => {
if (protocol !== PROTOCOL_CODE_SANDBOX && path.split(`,`).length > 1) {
throw Error(
`Code example path should only contain a single file, but found more than one: ${path.replace(
directory,
``
)}. ` +
`Only CodeSandbox REPL supports multiple files entries, the protocol prefix of which starts with ${PROTOCOL_CODE_SANDBOX}`
)
}
if (!fs.existsSync(path)) {
throw Error(`Invalid REPL link specified; no such file "${path}"`)
}
}

const verifyMultipleFiles = (paths, protocol) =>
paths.forEach(path => verifyFile(path.filePath, protocol))

map(markdownAST, (node, index, parent) => {
if (node.type === `link`) {
if (node.url.startsWith(PROTOCOL_BABEL)) {
const filePath = getFilePath(node.url, PROTOCOL_BABEL, directory)

verifyFile(filePath)
verifyFile(filePath, PROTOCOL_BABEL)

const code = compress(fs.readFileSync(filePath, `utf8`))
const href = `https://babeljs.io/repl/#?presets=react&code_lz=${code}`
Expand All @@ -86,19 +113,20 @@ module.exports = (
} else if (node.url.startsWith(PROTOCOL_CODEPEN)) {
const filePath = getFilePath(node.url, PROTOCOL_CODEPEN, directory)

verifyFile(filePath)
verifyFile(filePath, PROTOCOL_CODEPEN)

const href = node.url.replace(PROTOCOL_CODEPEN, `/redirect-to-codepen/`)
const text =
node.children.length === 0 ? defaultText : node.children[0].value

convertNodeToLink(node, text, href, target)
} else if (node.url.startsWith(PROTOCOL_CODE_SANDBOX)) {
const filePath = getFilePath(node.url, PROTOCOL_CODE_SANDBOX, directory)

verifyFile(filePath)

const code = fs.readFileSync(filePath, `utf8`)
const filesPaths = getMultipleFilesPaths(
node.url,
PROTOCOL_CODE_SANDBOX,
directory
)
verifyMultipleFiles(filesPaths, PROTOCOL_CODE_SANDBOX)

// CodeSandbox GET API requires a list of "files" keyed by name
let parameters = {
Expand All @@ -114,17 +142,22 @@ module.exports = (
}
return map
}, {}),
main: filesPaths[0].url,
},
},
"index.js": {
content: code,
},
"index.html": {
content: html,
},
},
}

filesPaths.forEach((path, i) => {
const code = fs.readFileSync(path.filePath, `utf8`)
parameters.files[path.url] = {
content: code,
}
})

// This config JSON must then be lz-string compressed
parameters = compress(JSON.stringify(parameters))

Expand All @@ -136,7 +169,7 @@ module.exports = (
} else if (node.url.startsWith(PROTOCOL_RAMDA)) {
const filePath = getFilePath(node.url, PROTOCOL_RAMDA, directory)

verifyFile(filePath)
verifyFile(filePath, PROTOCOL_RAMDA)

// Don't use `compress()` as the Ramda REPL won't understand the output.
// It uses URI to encode the code for its urls, so we do the same.
Expand Down