Skip to content
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

Fix downloading monaco twice per load #267

Merged
merged 5 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 1 addition & 1 deletion gui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
"@octokit/rest": "^21.0.0",
"@vercel/analytics": "^1.3.1",
"jszip": "^3.10.1",
"monaco-editor": "^0.52.2",
"plotly.js-cartesian-dist": "^2.35.2",
"pyodide": "^0.27.2",
"react": "^19.0.0",
Expand Down Expand Up @@ -58,6 +57,7 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"jsdom": "^24.1.0",
"monaco-editor": "^0.52.2",
"prettier": "^3.3.2",
"typescript": "^5.0.2",
"vite": "^6.0.11",
Expand Down
29 changes: 19 additions & 10 deletions gui/src/app/components/FileEditor/ScriptEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { FunctionComponent, RefObject, useCallback, use, useMemo } from "react";

import { Help, PlayArrow } from "@mui/icons-material";
import Box from "@mui/material/Box";
import TextEditor from "@SpComponents/FileEditor/TextEditor";
import { Split } from "@geoffcox/react-splitter";
import { useMonaco } from "@monaco-editor/react";
import { type editor } from "monaco-editor";

import { ColorOptions, ToolbarItem } from "@SpComponents/FileEditor/ToolBar";
import { FileNames } from "@SpCore/Project/FileMapping";
import { ProjectContext } from "@SpCore/Project/ProjectContextProvider";
import { ProjectKnownFiles } from "@SpCore/Project/ProjectDataModel";
import { normalizeLineEndings } from "@SpUtil/normalizeLineEndings";
import { FunctionComponent, RefObject, useCallback, use, useMemo } from "react";
import { InterpreterStatus } from "@SpCore/Scripting/InterpreterTypes";
import { Split } from "@geoffcox/react-splitter";
import { editor, KeyCode, KeyMod } from "monaco-editor";
import TextEditor from "@SpComponents/FileEditor/TextEditor";

const interpreterNames = { python: "pyodide", r: "webR" } as const;

Expand Down Expand Up @@ -69,21 +72,27 @@ const ScriptEditor: FunctionComponent<ScriptEditorProps> = ({
return content !== editedContent;
}, [content, editedContent]);

const runCtrlEnter: editor.IActionDescriptor[] = useMemo(
() => [
const monacoInstance = useMonaco();

const runCtrlEnter: editor.IActionDescriptor[] = useMemo(() => {
if (!monacoInstance) {
return [];
}
return [
{
id: "run-script",
label: "Run Script",
keybindings: [KeyMod.CtrlCmd | KeyCode.Enter],
keybindings: [
monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter,
],
run: () => {
if (runnable && !unsavedChanges) {
runCode();
}
},
},
],
[runCode, runnable, unsavedChanges],
);
];
}, [monacoInstance, runCode, runnable, unsavedChanges]);

const toolbarItems: ToolbarItem[] = useMemo(() => {
return makeToolbar({
Expand Down
92 changes: 60 additions & 32 deletions gui/src/app/components/FileEditor/TextEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,3 @@
import { Editor, loader, useMonaco } from "@monaco-editor/react";

import { UserSettingsContext } from "@SpCore/Settings/UserSettings";
import { CodeMarker } from "@SpCore/Stanc/Linting";
import {
editor,
IDisposable,
KeyCode,
KeyMod,
MarkerSeverity,
} from "monaco-editor";
import {
FunctionComponent,
use,
Expand All @@ -18,9 +7,27 @@ import {
useState,
} from "react";

import monacoAddStanLang from "./monacoStanLanguage";
import Loading from "@SpComponents/Loading";
import { UserSettingsContext } from "@SpCore/Settings/UserSettings";
import { CodeMarker } from "@SpCore/Stanc/Linting";
import { unreachable } from "@SpUtil/unreachable";

import { Editor, loader, useMonaco, type Monaco } from "@monaco-editor/react";
import type { editor, IDisposable } from "monaco-editor";

import { ToolBar, ToolbarItem } from "./ToolBar";

import monacoAddStanLang from "./monacoStanLanguage";
// loader from @monaco-editor/react handles the loading of the monaco editor
// importantly, it downloads from a CDN, so we need to make sure we
// only depend on types from the monaco-editor package to avoid
// downloading twice.

loader.config({
paths: {
vs: "https://cdn.jsdelivr.net/npm/[email protected]/min/vs",
},
});
loader.init().then(monacoAddStanLang);

type Props = {
Expand Down Expand Up @@ -86,7 +93,7 @@ const TextEditor: FunctionComponent<Props> = ({

const modelMarkers = codeMarkers.map((marker) => ({
...marker,
severity: toMonacoMarkerSeverity[marker.severity],
severity: toMonacoMarkerSeverity(marker.severity, monacoInstance),
}));

monacoInstance.editor.setModelMarkers(
Expand All @@ -97,24 +104,34 @@ const TextEditor: FunctionComponent<Props> = ({
}, [codeMarkers, monacoInstance, editorInstance]);

useEffect(() => {
if (!editorInstance) return;
if (!editorInstance || !monacoInstance) return;
if (!contentOnEmpty) return;
if (text || editedText) {
return;
}
const contentWidget = createHintTextContentWidget(contentOnEmpty);
const widgetPosition = {
position: { lineNumber: 1, column: 1 },
preference: [monacoInstance.editor.ContentWidgetPositionPreference.EXACT],
};
Comment on lines +112 to +115
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like this ought to be const-able, but the linter doesn't like it. Probably doesn't matter anyway...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I follow what you mean by const-able in this context?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean annotated as as const, since its members don't seem to be able to be changed anywhere in the code. But that conflicts with the looser typing further down.

(The larger context was me wondering if it should be memoized, before realizing this was already in a useEffect hook, so it doesn't matter.)

const contentWidget = createHintTextContentWidget(
contentOnEmpty,
widgetPosition,
);
editorInstance.addContentWidget(contentWidget);
return () => {
editorInstance.removeContentWidget(contentWidget);
};
}, [text, editorInstance, editedText, contentOnEmpty]);
}, [text, editorInstance, editedText, contentOnEmpty, monacoInstance]);

useEffect(() => {
if (!editorInstance) return;
if (!editorInstance || !monacoInstance) return;

const disposable = editorInstance.addAction({
id: "save",
label: "Save",
keybindings: [KeyMod.CtrlCmd | KeyCode.KeyS],
keybindings: [
monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyS,
],
run: () => {
if (!readOnly) {
onSaveText();
Expand All @@ -124,7 +141,7 @@ const TextEditor: FunctionComponent<Props> = ({
return () => {
disposable.dispose();
};
}, [editorInstance, onSaveText, readOnly]);
}, [editorInstance, monacoInstance, onSaveText, readOnly]);

useEffect(() => {
if (!editorInstance) return;
Expand Down Expand Up @@ -160,8 +177,10 @@ const TextEditor: FunctionComponent<Props> = ({
/>
<Editor
defaultLanguage={language}
aria-label={label}
onChange={handleChange}
onMount={(editor, _) => setEditor(editor)}
loading={<Loading name="Monaco Editor" />}
options={{
readOnly,
domReadOnly: readOnly,
Expand All @@ -175,14 +194,28 @@ const TextEditor: FunctionComponent<Props> = ({
);
};

const toMonacoMarkerSeverity = {
error: MarkerSeverity.Error,
warning: MarkerSeverity.Warning,
hint: MarkerSeverity.Hint,
info: MarkerSeverity.Info,
} as const;
const toMonacoMarkerSeverity = (
severity: CodeMarker["severity"],
monacoInstance: Monaco,
) => {
switch (severity) {
case "error":
return monacoInstance.MarkerSeverity.Error;
case "warning":
return monacoInstance.MarkerSeverity.Warning;
case "hint":
return monacoInstance.MarkerSeverity.Hint;
case "info":
return monacoInstance.MarkerSeverity.Info;
default:
return unreachable(severity);
}
};

const createHintTextContentWidget = (content: string | HTMLSpanElement) => {
const createHintTextContentWidget = (
content: string | HTMLSpanElement,
position: editor.IContentWidgetPosition,
) => {
return {
getDomNode: () => {
const node = document.createElement("div");
Expand All @@ -197,12 +230,7 @@ const createHintTextContentWidget = (content: string | HTMLSpanElement) => {
return node;
},
getId: () => "hintText",
getPosition: () => {
return {
position: { lineNumber: 1, column: 1 },
preference: [editor.ContentWidgetPositionPreference.EXACT],
};
},
getPosition: () => position,
};
};

Expand Down
4 changes: 2 additions & 2 deletions gui/src/app/components/FileEditor/monacoStanLanguage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
// See https://microsoft.github.io/monaco-editor/monarch.html
// Adapted in part from https://github.com/WardBrian/vscode-stan-extension/blob/main/lang/syntaxes/stan.json

import { Monaco } from "@monaco-editor/react";
import { languages } from "monaco-editor";
import type { Monaco } from "@monaco-editor/react";
import type { languages } from "monaco-editor";

const BLOCKS = [
"functions",
Expand Down
12 changes: 3 additions & 9 deletions gui/src/app/components/LazyPlotlyPlot.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import CircularProgress from "@mui/material/CircularProgress";
import React, { FunctionComponent, Suspense, useMemo } from "react";
import useMeasure from "react-use-measure";

import Loading from "@SpComponents/Loading";

import type { PlotParams } from "react-plotly.js";
import createPlotlyComponent from "react-plotly.js/factory";
const Plot = React.lazy(async () => {
Expand All @@ -23,14 +24,7 @@ const LazyPlotlyPlot: FunctionComponent<PlotParams> = ({ data, layout }) => {

return (
<div ref={ref}>
<Suspense
fallback={
<div className="PlotLoader">
<CircularProgress color="info" />
<p className="details">Loading Plotly.js</p>
</div>
}
>
<Suspense fallback={<Loading name="Plotly.js" />}>
<Plot data={data} layout={layoutWithWidth} />
</Suspense>
</div>
Expand Down
18 changes: 18 additions & 0 deletions gui/src/app/components/Loading.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { FunctionComponent } from "react";

import CircularProgress from "@mui/material/CircularProgress";

type Props = {
name: string;
};

const Loading: FunctionComponent<Props> = ({ name }) => {
return (
<div className="Loading">
<CircularProgress color="info" />
<p className="details">Loading {name}</p>
</div>
);
};

export default Loading;
2 changes: 1 addition & 1 deletion gui/src/localStyles.css
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ span.EditorTitle {
padding: 5px;
}

.PlotLoader {
.Loading {
padding: 10px;
display: grid;
place-items: center;
Expand Down
10 changes: 8 additions & 2 deletions gui/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ export default defineConfig({
rollupOptions: {
output: {
manualChunks: {
monaco: ["monaco-editor", "@monaco-editor/react"],
utilities: ["jszip", "@octokit/rest"],
utilities: [
"jszip",
"@octokit/rest",
"react-dropzone",
"pyodide",
"webr",
],
mui: ["@mui/material", "@mui/icons-material"],
},
},
},
Expand Down