Skip to content

Commit

Permalink
refactor: Better editor mount/unmount setup
Browse files Browse the repository at this point in the history
  • Loading branch information
rschristian committed Jun 19, 2024
1 parent e945649 commit 24a21c8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/components/code-editor/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,15 @@ const highlightStyle = HighlightStyle.define([
]);

export default function CodeEditor(props) {
const ref = useRef(null);
const editorParent = useRef(null);
const editor = useRef(null);
// eslint-disable-next-line no-unused-vars
const [_, setEditor] = useState(null);

useEffect(() => {
if (editor.current && !props.baseExampleSlug) return;
if (editor.current) editor.current.destroy();

const theme = EditorView.theme({}, { dark: true });

const state = EditorState.create({
Expand All @@ -56,18 +60,20 @@ export default function CodeEditor(props) {
]
});

const view = new EditorView({
editor.current = new EditorView({
state,
parent: ref.current
parent: editorParent.current
});

setEditor(view);
setEditor(editor.current);
}, [props.baseExampleSlug]);

return () => {
view.destroy();
useEffect(() => (
() => {
editor.current.destroy();
setEditor(null);
};
}, [props.baseExampleSlug]);
}
), []);

return <div ref={ref} class={cx(style.codeEditor, props.class)} />;
return <div ref={editorParent} class={cx(style.codeEditor, props.class)} />;
}
2 changes: 2 additions & 0 deletions src/components/controllers/repl/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,8 @@ export class Repl extends Component {
if (this.state.exampleSlug) {
const example = getExample(this.state.exampleSlug, EXAMPLES);
if (code !== example.code && this.state.exampleSlug !== '') {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({ exampleSlug: '' });
history.replaceState(null, null, '/repl');
}
}
Expand Down

0 comments on commit 24a21c8

Please sign in to comment.