Skip to content

Prevent the Monaco editor from being recreated on every keystroke. #10

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

Merged
merged 1 commit into from
Aug 10, 2025
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
25 changes: 15 additions & 10 deletions src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,20 @@ function AppContent() {
}
}, [amaranthSource, amaranthVersion]);

const runCodeRef = useRef(runCode);
runCodeRef.current = runCode;

const amaranthSourceEditorActions = React.useMemo(() => [
{
id: 'amaranth-playground.run',
label: 'Run Code',
keybindings: [
monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter,
],
run: runCodeRef.current,
}
], [runCodeRef]);

function tabAndPanel({ key, title, titleStyle = {}, content }) {
return [
<Tab key={`${key}-tab`} value={key} style={titleStyle}>{title}</Tab>,
Expand Down Expand Up @@ -307,16 +321,7 @@ function AppContent() {
title: 'Amaranth Source',
content: <Editor
state={amaranthSourceEditorState.current}
actions={[
{
id: 'amaranth-playground.run',
label: 'Run Code',
keybindings: [
monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter,
],
run: runCode,
}
]}
actions={amaranthSourceEditorActions}
padding={{ top: 10, bottom: 10 }}
focus
/>
Expand Down
10 changes: 9 additions & 1 deletion src/monaco.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ export function Editor({ state, actions = [], padding, focus = false }: EditorPr
readOnly: state.readOnly,
padding,
});
actions.forEach(action => editorRef.current?.addAction(action));
const resizeObserver = new ResizeObserver(events => editorRef.current?.layout());
resizeObserver.observe(containerRef.current!);
editorRef.current.restoreViewState(state.viewState);
Expand All @@ -63,6 +62,15 @@ export function Editor({ state, actions = [], padding, focus = false }: EditorPr
resizeObserver.disconnect();
editorRef.current?.dispose();
};
}, []);

useEffect(() => {
if (!editorRef.current)
return;
const disposables = actions.map(action => editorRef.current!.addAction(action));
return () => {
disposables.forEach(disposable => disposable.dispose());
};
}, [actions]);

return <div style={{ height: '100%' }} ref={containerRef}/>;
Expand Down