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

Use CodeMirror 6 in REPL #3014

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
7 changes: 4 additions & 3 deletions js/cm6.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { basicSetup, EditorView } from "codemirror";
export { basicSetup } from "codemirror";
export { oneDark } from "@codemirror/theme-one-dark";
export { javascriptLanguage } from "@codemirror/lang-javascript";
export { EditorState } from "@codemirror/state";
export { javascriptLanguage, tsxLanguage } from "@codemirror/lang-javascript";
export { EditorState, Compartment } from "@codemirror/state";
export { EditorView, placeholder } from "@codemirror/view";
220 changes: 100 additions & 120 deletions js/repl/CodeMirror.tsx
Original file line number Diff line number Diff line change
@@ -1,138 +1,118 @@
import { injectGlobal, css } from "@emotion/css";
import CodeMirror from "codemirror";
import React from "react";
import { colors } from "./styles";
import {
Compartment,
EditorState,
basicSetup,
EditorView,
placeholder as placeholderExtension,
oneDark,
tsxLanguage,
} from "../cm6.mjs";
// Only use type imports for @codemirror/* so that CodeMirror.tsx can share
// the cm6.mjs with the mini-repl.js component
import { type EditorState as EditorStateType } from "@codemirror/state";
import {
type ViewUpdate,
type EditorView as EditorViewType,
} from "@codemirror/view";
import { preferDarkColorScheme } from "./Utils";

const DEFAULT_CODE_MIRROR_OPTIONS = {
autoCloseBrackets: true,
keyMap: "sublime",
lineNumbers: true,
matchBrackets: true,
mode: "text/jsx",
showCursorWhenSelecting: true,
styleActiveLine: true,
tabWidth: 2,
theme: preferDarkColorScheme() ? "darcula" : "default",
};
import React, { useRef, useEffect } from "react";

type Props = {
autoFocus: boolean;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The autoFocus prop is removed because we are not using this prop.

onChange: (value: string) => void;
options: any;
onChange: (value: string) => void | null;
options: {
lineWrapping: boolean;
readOnly: boolean;
};
parentRef: React.MutableRefObject<HTMLElement>;
placeholder?: string;
value: string | undefined | null;
preserveScrollPosition: boolean;
};

type State = {
isFocused: boolean;
};

export default class ReactCodeMirror extends React.Component<Props, State> {
static defaultProps = {
autoFocus: false,
preserveScrollPosition: false,
// eslint-disable-next-line no-unused-vars
onChange: (value: string) => {},
};

state = {
isFocused: false,
};

_codeMirror: any;
_textAreaRef: HTMLTextAreaElement | null;

componentDidMount() {
this._codeMirror = CodeMirror.fromTextArea(this._textAreaRef, {
...DEFAULT_CODE_MIRROR_OPTIONS,
...this.props.options,
export default function ReactCodeMirror({
value,
onChange,
options,
parentRef,
placeholder,
preserveScrollPosition,
}: Props) {
const viewRef = useRef<EditorViewType>(null);
const lineWrappingCompartmentRef = useRef<Compartment>(new Compartment());

useEffect(() => {
const editorState: EditorStateType = EditorState.create({
doc: value,
extensions: [
basicSetup,
tsxLanguage,
preferDarkColorScheme() ? oneDark : false,
// We don't use compartment here since readonly can not be changed from UI
EditorView.editable.of(!options.readOnly),
placeholderExtension(placeholder),
lineWrappingCompartmentRef.current.of([]),
onChange &&
EditorView.updateListener.of((update: ViewUpdate) => {
if (update.docChanged) {
onChange(update.state.doc.toString());
}
}),
EditorView.theme({
"&": {
backgroundColor: "#fff",
height: "100%",
maxHeight: "100%",
},
}),
].filter(Boolean),
});
this._codeMirror.on("change", this._onChange);
this._codeMirror.setValue(this.props.value || "");
}

componentWillUnmount() {
// is there a lighter-weight way to remove the cm instance?
if (this._codeMirror) {
this._codeMirror.toTextArea();
}
}

UNSAFE_componentWillReceiveProps(nextProps: Props) {
if (
nextProps.value &&
nextProps.value !== this.props.value &&
this._codeMirror.getValue() !== nextProps.value
) {
if (nextProps.preserveScrollPosition) {
const prevScrollPosition = this._codeMirror.getScrollInfo();
this._codeMirror.setValue(nextProps.value);
this._codeMirror.scrollTo(
prevScrollPosition.left,
prevScrollPosition.top
);
} else {
this._codeMirror.setValue(nextProps.value);
}
} else if (!nextProps.value) {
this._codeMirror.setValue("");
}
viewRef.current ??= new EditorView({
state: editorState,
parent: parentRef.current,
});

if (typeof nextProps.options === "object") {
for (const optionName in nextProps.options) {
if (nextProps.options.hasOwnProperty(optionName)) {
this._updateOption(optionName, nextProps.options[optionName]);
}
return () => {
if (viewRef.current) {
viewRef.current.destroy();
viewRef.current = null;
}
}
}
};
}, []);

focus() {
if (this._codeMirror) {
this._codeMirror.focus();
// handle value prop updates
useEffect(() => {
if (value == null) {
return;
}
}

render() {
return (
<textarea
autoComplete="off"
autoFocus={this.props.autoFocus}
defaultValue={this.props.value}
ref={this._setTextAreaRef}
placeholder={this.props.placeholder}
/>
);
}

_updateOption(optionName: string, newValue: any) {
const oldValue = this._codeMirror.getOption(optionName);

if (oldValue !== newValue) {
this._codeMirror.setOption(optionName, newValue);
const currentValue = viewRef.current?.state.doc.toString();
if (viewRef.current && value !== currentValue) {
viewRef.current.dispatch({
changes: {
from: 0,
to: currentValue.length,
insert: value,
},
effects: [
preserveScrollPosition &&
EditorView.scrollIntoView(0, {
yMargin: -viewRef.current.scrollDOM.scrollTop,
}),
].filter(Boolean),
});
}
}

_onChange = (doc: any, change: any) => {
if (change.origin !== "setValue") {
this.props.onChange(doc.getValue());
}, [value]);

// handle lineWrapping updates
useEffect(() => {
if (viewRef.current) {
viewRef.current.dispatch({
effects: lineWrappingCompartmentRef.current.reconfigure(
options.lineWrapping ? EditorView.lineWrapping : []
),
});
}
};
}, [options.lineWrapping]);

_setTextAreaRef = (ref: HTMLTextAreaElement | null) => {
this._textAreaRef = ref;
};
return <></>;
}

injectGlobal({
".CodeMirror": {
height: "100% !important",
width: "100% !important",
WebkitOverflowScrolling: "touch",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This CSS property is long obsolete.

},
".CodeMirror pre.CodeMirror-placeholder.CodeMirror-line-like": css({
color: colors.foregroundLight,
}),
});
23 changes: 15 additions & 8 deletions js/repl/CodeMirrorPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { css, type Interpolation } from "@emotion/css";
import { css, type CSSInterpolation } from "@emotion/css";
import CodeMirror from "./CodeMirror";
import React from "react";
import React, { useRef } from "react";
import { colors } from "./styles";

type Props = {
Expand All @@ -9,33 +9,40 @@ type Props = {
errorMessage: string | undefined | null;
info?: string | null;
onChange?: (value: string) => void;
options: any;
options: {
fileSize: boolean;
lineWrapping: boolean;
};
placeholder?: string;
fileSize: string;
};

export default function CodeMirrorPanel(props: Props) {
const cmParentRef = useRef<HTMLDivElement>(null);
const {
className = "",
code,
errorMessage,
fileSize,
info,
onChange,
options,
placeholder,
} = props;

return (
<div className={`${styles.panel} ${className}`}>
<div className={styles.codeMirror}>
<div className={styles.codeMirror} ref={cmParentRef}>
<CodeMirror
onChange={onChange}
options={{
...props.options,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The fileSize option is not used by the codemirror component. So here we explicitly specify the passing-through options.

lineWrapping: options.lineWrapping,
readOnly: onChange == null,
}}
placeholder={props.placeholder}
parentRef={cmParentRef}
placeholder={placeholder}
preserveScrollPosition={onChange == null}
value={props.code}
value={code}
/>
{options.fileSize && <div className={styles.fileSize}>{fileSize}</div>}
</div>
Expand All @@ -45,7 +52,7 @@ export default function CodeMirrorPanel(props: Props) {
);
}

const sharedBoxStyles: Interpolation = {
const sharedBoxStyles: CSSInterpolation = {
flex: "0 0 auto",
maxHeight: "33%",
overflow: "auto",
Expand Down
20 changes: 0 additions & 20 deletions js/repl/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -571,29 +571,9 @@
</nav>
<div class="navPusher">
<div>
<link
rel="stylesheet"
type="text/css"
href="https://unpkg.com/[email protected]/lib/codemirror.css"
/>
<link
rel="stylesheet"
type="text/css"
href="https://unpkg.com/[email protected]/theme/darcula.css"
/>
<div id="root">
<noscript>You need to enable JavaScript to run this app.</noscript>
</div>
<script src="https://unpkg.com/[email protected]/lib/codemirror.js"></script>
<script src="https://unpkg.com/[email protected]/mode/javascript/javascript.js"></script>
<script src="https://unpkg.com/[email protected]/mode/xml/xml.js"></script>
<script src="https://unpkg.com/[email protected]/mode/jsx/jsx.js"></script>
<script src="https://unpkg.com/[email protected]/keymap/sublime.js"></script>
<script src="https://unpkg.com/[email protected]/addon/comment/comment.js"></script>
<script src="https://unpkg.com/[email protected]/addon/display/placeholder.js"></script>
<script src="https://unpkg.com/[email protected]/addon/edit/matchbrackets.js"></script>
<script src="https://unpkg.com/[email protected]/addon/search/searchcursor.js"></script>
<script src="https://unpkg.com/[email protected]/addon/selection/active-line.js"></script>
<script src="https://unpkg.com/[email protected]/libs/base64-string.js"></script>
<script src="https://unpkg.com/[email protected]/libs/lz-string.min.js"></script>
</div>
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,10 @@
"@babel/preset-env": "^8.0.0-alpha.12",
"@babel/preset-react": "^8.0.0-alpha.12",
"@babel/preset-typescript": "^8.0.0-alpha.12",
"@codemirror/lang-javascript": "6.2.1",
"@codemirror/lang-javascript": "6.2.2",
"@codemirror/state": "6.4.1",
"@codemirror/theme-one-dark": "6.1.2",
"@codemirror/view": "6.34.2",
"@emotion/babel-plugin": "^11.11.0",
"@rollup/plugin-node-resolve": "^15.1.0",
"@rollup/plugin-terser": "^0.4.3",
Expand Down
1 change: 0 additions & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ const config = {
}),
],
externals: {
codemirror: "CodeMirror",
"lz-string": "LZString",
},
performance: {
Expand Down
Loading