Created
November 12, 2018 03:09
-
-
Save phobon/5c989f11fd08ca627d131965afe13dc4 to your computer and use it in GitHub Desktop.
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
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { makeDecorator } from '@storybook/addons'; | |
import reactElementToJSXString from 'react-element-to-jsx-string' | |
import base64url from 'base64-url'; | |
const renderJsx = (code, options = {}) => { | |
if (typeof code === 'undefined') { | |
return console.warn('Undefined component'); | |
} | |
while (typeof code.type === 'function' && code.type.name === '') { | |
code = code.type(code.props); | |
} | |
const ooo = typeof options.displayName === 'string' | |
? Object.assign({}, options, { showFunctions: false, displayName: () => options.displayName }) | |
: options | |
return React.Children.map(code, c => | |
reactElementToJSXString(c, ooo), options, | |
).join('\n') | |
}; | |
const linkStyles = { position: 'absolute', right: '2rem', bottom: '2rem' }; | |
const OpenInPlayroom = ({ children, url, label }) => ( | |
<React.Fragment> | |
{children} | |
<a href={url} target="_blank" rel="noopener noreferrer" style={linkStyles}> | |
{label} | |
</a> | |
</React.Fragment> | |
); | |
OpenInPlayroom.propTypes = { | |
children: PropTypes.node.isRequired, | |
url: PropTypes.string.isRequired, | |
label: PropTypes.string.isRequired, | |
}; | |
export default makeDecorator({ | |
name: 'withPlayroomLink', | |
parameterName: 'playroom', | |
allowDeprecatedUsage: true, | |
wrapper: (getStory, context, { options = { url: '/playroom', label: 'Open in Playroom' }, parameters }) => { | |
const storyOptions = parameters || options; | |
const infoOptions = typeof storyOptions === 'string' ? { text: storyOptions } : storyOptions; | |
const mergedOptions = typeof infoOptions === 'string' ? infoOptions : { ...options, ...infoOptions }; | |
const story = getStory(context); | |
const jsx = renderJsx(story); | |
const encoded = base64url.encode(jsx); | |
const url = `${mergedOptions.url}/#?code=${encoded}`; | |
return <OpenInPlayroom url={url} label={mergedOptions.label}>{story}</OpenInPlayroom>; | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment