Building a Live Editor

Published

As I have been working on my personal blog, I wanted to include the ability to edit code on site, and also preview it live. I started using react-live which I have had prior experience using and setting up, however I wanted to customize the theme of the editor a bit and try to work on a new and challenging task over the weekend.

So I decided to build @matthamlin/react-preview-editor (see the project here).

Starting Off with Executing Code

I started off by looking at the source of react-live to figure out how they are able to actually call the code that you edit inline. It turns out, that they use the new Function contructor to pass the code as a string along with an assortment of the keys of the things within scope for the code, and then call the function.

1function evaluateCode(code, scope) {
2 // scope looks like this: { variableName: 'value' }
3 // construct a new function with the code
4 const func = new Function(...Object.keys(scope), code);
5 // Call the function
6 func(...Object.values(scope));
7}
1function evaluateCode(code, scope) {
2 // scope looks like this: { variableName: 'value' }
3 // construct a new function with the code
4 const func = new Function(...Object.keys(scope), code);
5 // Call the function
6 func(...Object.values(scope));
7}

This allows us to evaluate code that the user types within the editor on the site, and probably goes without saying but could be a really bad™️ thing to do with live user input.

So now that we know how to actually execute the users code, how do we build the editor part?

The Code Editor

Well that part is actually pretty simple, because other awesome developers out there, have already shared open source projects for editing code within the browser. Since I wanted to keep the project fairly small, I went with react-simple-code-editor.

This editor allows me to control the highlighting of the code complete, and also is really easy to just start using:

1<Editor
2 // Give it a value
3 value={code}
4 // Handle changes to the code
5 onValueChange={(code) => updateCode(code)}
6 // Provider it a function that returns a string or a React Node
7 // to highlight the code
8 highlight={highlighter}
9/>;
1<Editor
2 // Give it a value
3 value={code}
4 // Handle changes to the code
5 onValueChange={(code) => updateCode(code)}
6 // Provider it a function that returns a string or a React Node
7 // to highlight the code
8 highlight={highlighter}
9/>;

Great, so we have a way to execute the code, and a way to edit the code, what about the syntax highlighting though?

Highlighting the Code

Well we are just as lucky as we were before, thanks to the prism-react-renderer library, we are able to use a React wrapping API around the prismjs library.

This ends up looking like:

1// This is the same function we pass to the Editor component above
2function highlighter(code) {
3 return (
4 <Highlight {...defaultProps} code={code} language='jsx'>
5 {({ className, style, tokens, getLineProps, getTokenProps }) => (
6 <pre className={className} style={style}>
7 {tokens.map((line, i) => (
8 <div {...getLineProps({ line, key: i })}>
9 {line.map((token, key) => (
10 <span {...getTokenProps({ token, key })} />
11 ))}
12 </div>
13 ))}
14 </pre>
15 )}
16 </Highlight>
17 );
18}
1// This is the same function we pass to the Editor component above
2function highlighter(code) {
3 return (
4 <Highlight {...defaultProps} code={code} language='jsx'>
5 {({ className, style, tokens, getLineProps, getTokenProps }) => (
6 <pre className={className} style={style}>
7 {tokens.map((line, i) => (
8 <div {...getLineProps({ line, key: i })}>
9 {line.map((token, key) => (
10 <span {...getTokenProps({ token, key })} />
11 ))}
12 </div>
13 ))}
14 </pre>
15 )}
16 </Highlight>
17 );
18}

Wrapping Up

So wrapping it all up, we end up with an API that looks like this:

1import { transform } from '@babel/standalone';
2import { Editor, Preview, Provider } from '@matthamlin/react-preview-editor';
3
4function transformCode(code) {
5 return transform(code, {
6 presets: [['stage-0', { decoratorsLegacy: true }], 'react'],
7 }).code;
8}
9
10const code = `
11function App() {
12 return (
13 <p>Code Here!</p>
14 )
15};
16render(<App />);
17`;
18
19export default function App() {
20 return (
21 <Provider code={code} transformCode={transformCode}>
22 <Preview />
23 <Editor />
24 </Provider>
25 );
26}
1import { transform } from '@babel/standalone';
2import { Editor, Preview, Provider } from '@matthamlin/react-preview-editor';
3
4function transformCode(code) {
5 return transform(code, {
6 presets: [['stage-0', { decoratorsLegacy: true }], 'react'],
7 }).code;
8}
9
10const code = `
11function App() {
12 return (
13 <p>Code Here!</p>
14 )
15};
16render(<App />);
17`;
18
19export default function App() {
20 return (
21 <Provider code={code} transformCode={transformCode}>
22 <Preview />
23 <Editor />
24 </Provider>
25 );
26}

Be sure to checkout the project here: github.com/hamlim/react-preview-editor on GitHub (make sure to ⭐ it too 😆).

And check it out in CodeSandbox here.