From 527f50371f54e02291e68bc27f0af1723540884e Mon Sep 17 00:00:00 2001 From: Admir Sabanovic Date: Thu, 12 Oct 2017 00:50:42 +0200 Subject: [PATCH] add non-jsx view to to interactive code samples --- src/components/CodeEditor/CodeEditor.js | 49 ++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/src/components/CodeEditor/CodeEditor.js b/src/components/CodeEditor/CodeEditor.js index cfe88135..652284e5 100644 --- a/src/components/CodeEditor/CodeEditor.js +++ b/src/components/CodeEditor/CodeEditor.js @@ -11,13 +11,20 @@ import ReactDOM from 'react-dom'; import Remarkable from 'remarkable'; // TODO: switch back to the upstream version of react-live // once https://github.com/FormidableLabs/react-live/issues/37 is fixed. -import {LiveProvider, LiveEditor} from '@gaearon/react-live'; +import {LiveEditor, LiveProvider} from '@gaearon/react-live'; import {colors, media} from 'theme'; import MetaTitle from 'templates/components/MetaTitle'; +import {highlight, languages} from 'prismjs/components/prism-core' +import 'prismjs/components/prism-javascript' const compile = code => Babel.transform(code, {presets: ['es2015', 'react']}).code; // eslint-disable-line no-undef +const compileJsxToJS = code => + Babel.transform(code, {presets: ['react']}).code; // eslint-disable-line no-undef + +const prism = code => highlight(code, languages.javascript); + class CodeEditor extends Component { constructor(props, context) { super(props, context); @@ -38,8 +45,8 @@ class CodeEditor extends Component { } render() { - const {children, code} = this.props; - const {error} = this.state; + const {children} = this.props; + const {error, code, showCompiledJsx, compiledJsx} = this.state; return ( @@ -112,7 +119,17 @@ class CodeEditor extends Component { background: colors.darker, color: colors.white, }}> - Live JSX Editor + Live JSX Editor + {!showCompiledJsx && ( + + View Compiled JSX + )} + {showCompiledJsx && ( + + Back to JSX Editor + + )} +
- + {!showCompiledJsx && ( + + )} + {showCompiledJsx && ( +
+                  
+ )}
{error && ( @@ -269,6 +292,8 @@ class CodeEditor extends Component { try { return { compiled: compile(code), + compiledJsx: compileJsxToJS(code), + code: code, error: null, }; } catch (error) { @@ -284,6 +309,20 @@ class CodeEditor extends Component { _onChange = code => { this.setState(this._updateState(code)); }; + + _showCompiledJsxPreview = () => { + this.setState({ + ...this.state, + showCompiledJsx: true, + }); + }; + + _hideCompiledJsxPreview = () => { + this.setState({ + ...this.state, + showCompiledJsx: false, + }); + }; } export default CodeEditor;