Skip to content
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
16 changes: 14 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,28 @@
"react-hook-form": "^7.16.2"
},
"dependencies": {
"codemirror": "^5.62.2",
"@codemirror/closebrackets": "^0.19.0",
"@codemirror/comment": "^0.19.0",
"@codemirror/gutter": "^0.19.5",
"@codemirror/highlight": "^0.19.6",
"@codemirror/lang-java": "^0.19.1",
"@codemirror/lang-javascript": "^0.19.3",
"@codemirror/lang-markdown": "^0.19.2",
"@codemirror/lang-python": "^0.19.2",
"@codemirror/lang-sql": "^0.19.4",
"@codemirror/language": "^0.19.5",
"@codemirror/matchbrackets": "^0.19.3",
"@codemirror/state": "^0.19.5",
"@codemirror/view": "^0.19.19",
"lodash": "^4.17.21",
"polished": "^4.1.1",
"react-codemirror2": "^7.2.1",
"react-markdown": "^5.0.3",
"react-modal": "^3.12.1",
"react-syntax-highlighter": "^15.4.4",
"react-tabs": "^3.2.1",
"react-toastify": "^8.0.3",
"remark-gfm": "^1.0.0",
"rodemirror": "^1.6.5",
"styled-system": "^5.1.5"
},
"scripts": {
Expand Down
51 changes: 42 additions & 9 deletions src/CodeEditor.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Transaction } from "@codemirror/state";
import { Story, Meta } from "@storybook/react/types-6-0";
import { useState } from "react";

import { CodeEditor, CodeEditorProps } from "./CodeEditor";
import { useRef } from "react";
import { Box } from "./Box";
import { ButtonPrimary } from "./ButtonPrimary";
import { CodeEditor, CodeEditorProps, CodeEditorRef } from "./CodeEditor";

export default {
title: "Components/CodeEditor",
Expand All @@ -17,10 +19,7 @@ export default {
} as Meta;

const Template: Story<CodeEditorProps> = (args) => {
const [value, setValue] = useState(args.value || "");
return (
<CodeEditor {...args} value={value} onChange={(_, v) => setValue(v)} />
);
return <CodeEditor {...args} />;
};

export const Python = Template.bind({});
Expand All @@ -38,9 +37,43 @@ TypeScript.args = {
language: "typescript",
};

export const SelectionEvent = Template.bind({});
SelectionEvent.args = {
export const FixedHeight = Template.bind({});
FixedHeight.args = {
height: "200px",
value: `let test: number = 20;
`,
language: "typescript",
};

export const Record: Story = () => {
const editor = useRef<CodeEditorRef>();
const transactions = useRef<Transaction[]>([]);

const playback = () => {
if (editor.current) {
function apply(ts: Transaction[]) {
if (ts.length > 0 && editor.current) {
const [t, ...rest] = ts;
if (editor.current.state !== t.startState) {
editor.current.setState(t.startState);
}
editor.current.dispatch(t);
setTimeout(() => apply(rest), 200);
} else {
transactions.current = [];
}
}
apply(transactions.current);
}
};

return (
<Box>
<CodeEditor
ref={editor}
onChange={(_, t) => transactions.current.push(...t)}
/>
<ButtonPrimary onClick={playback}>Playback</ButtonPrimary>
</Box>
);
};
274 changes: 145 additions & 129 deletions src/CodeEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,143 +1,159 @@
import { Controlled as CodeMirror } from "react-codemirror2";
import CodeMirror, { CodeMirrorProps } from "rodemirror";
import { closeBrackets } from "@codemirror/closebrackets";
import { sql } from "@codemirror/lang-sql";
import { java } from "@codemirror/lang-java";
import { javascript } from "@codemirror/lang-javascript";
import { markdown } from "@codemirror/lang-markdown";
import { css } from "@emotion/react";
import { Box } from "./Box";
import { CodeEditorStyles } from "./CodeEditorStyles";

import { Box, BoxProps } from "./Box";
import { CodeEditorStyles, CodeEditorStylesProps } from "./CodeEditorStyles";
import { forwardRef, useImperativeHandle, useMemo, useState } from "react";
import { Extension, Transaction } from "@codemirror/state";
import { python } from "@codemirror/lang-python";
import {
Editor,
EditorChange,
EditorConfiguration,
EditorSelectionChange,
} from "codemirror";
import { CSSObject } from "@emotion/react";

const languages = {
markdown: "markdown",
java: "text/x-java",
c: "clike",
python: "python",
sql: "sql",
javascript: "javascript",
typescript: "text/typescript",
} as const;

let modeLoaded = false;
if (typeof window !== "undefined" && typeof window.navigator !== "undefined") {
require("codemirror/addon/edit/closebrackets.js");
// require("codemirror/keymap/emacs.js");
// require("codemirror/keymap/vim.js");

require("codemirror/mode/markdown/markdown.js");
require("codemirror/mode/clike/clike.js");
require("codemirror/mode/sql/sql.js");
require("codemirror/mode/python/python.js");
require("codemirror/mode/javascript/javascript.js");
modeLoaded = true;
}
drawSelection,
EditorView,
highlightActiveLine,
highlightSpecialChars,
} from "@codemirror/view";
import {
highlightActiveLineGutter,
lineNumbers as lineNumbersEx,
} from "@codemirror/gutter";
import { indentOnInput } from "@codemirror/language";
import { defaultHighlightStyle } from "@codemirror/highlight";

export type CodeEditorProps = {
language?: keyof typeof languages;
language?:
| "sql"
| "java"
| "python"
| "javascript"
| "markdown"
| "typescript";
height?: BoxProps["height"];
value?: string;
height?: CSSObject["height"];
disabled?: boolean;
config?: EditorConfiguration;
autoCloseBrackets?: boolean;
lineNumbers?: boolean;
keyMap?: "default";
theme?: "light" | "dark";
disabled?: boolean;
fontFamily?: CodeEditorStylesProps["fontFamily"];
selection?: CodeMirrorProps["selection"];
variant?: "outlined" | "normal" | "input";
selection?: {
ranges: Array<{ anchor: CodeMirror.Position; head: CodeMirror.Position }>;
};
onChange?: (change: EditorChange, value: string) => void;
onBlur?: () => void;
onSelection?: (selection: EditorSelectionChange) => void;
onGutterClick?: (lineNumber: number, gutter: string) => void;
editorDidMount?: (editor: Editor, value: string, cb: () => void) => void;
onChange?: (value: string, changes: readonly Transaction[]) => void;
};

export const CodeEditor = ({
language = "markdown",
value = "",
config = {},
height,
theme = "light",
disabled = false,
keyMap = "default",
autoCloseBrackets = true,
lineNumbers = true,
onChange = () => {},
onSelection = () => {},
onGutterClick = () => {},
onBlur = () => {},
editorDidMount,
selection,
variant = "normal",
}: CodeEditorProps) => {
let options = {};
if (modeLoaded) {
options = {
...config,
theme: theme === "light" ? "default" : "vscode-dark",
autoCloseBrackets,
readOnly: disabled ? "nocursor" : false,
keyMap,
lineNumbers,
mode: languages[language],
} as any;
}
return (
<Box
css={(theme) => [
css`
.CodeMirror {
height: ${height};
min-height: 60px;
}
`,
variant === "outlined" &&
css`
border-style: solid;
border-radius: ${theme.radii.small};
border-width: ${theme.borderWidths.standard};
border-color: ${theme.colors.neutral["200"]};
export type CodeEditorRef = EditorView | null;

export const CodeEditor = forwardRef<unknown, CodeEditorProps>(
(
{
language = "markdown",
value = "",
onChange = () => {},
selection,
disabled,
height = "auto",
fontFamily,
lineNumbers = false,
variant = "normal",
},
ref
) => {
const [editorView, setEditorView] = useState<EditorView | null>(null);

useImperativeHandle(ref, () => editorView);

const extensions = useMemo<Extension[]>(() => {
const e: Extension[] = [
highlightActiveLineGutter(),
highlightSpecialChars(),
defaultHighlightStyle.fallback,
drawSelection(),
closeBrackets(),
indentOnInput(),
highlightActiveLine(),
];

> div,
> div > div {
if (lineNumbers) {
e.push(lineNumbersEx());
}

if (disabled) {
e.push(
EditorView.contentAttributes.of({ contenteditable: false } as any)
);
}
switch (language) {
case "typescript":
case "javascript": {
e.push(javascript());
break;
}
case "python": {
e.push(python());
break;
}
case "java": {
e.push(java());
break;
}
case "sql": {
e.push(sql());
break;
}
default: {
e.push(markdown());
}
}
return e;
}, [lineNumbers, disabled, language]);

return (
<Box
height={height}
onClick={() => {
editorView?.focus();
}}
overflowY="auto"
css={(theme) => [
variant === "outlined" &&
css`
border-style: solid;
border-radius: ${theme.radii.small};
}
`,
variant === "input" &&
css`
border-radius: ${theme.radii.small};
border-color: ${theme.colors.neutral["100"]};
border-style: solid;
border-width: ${theme.borderWidths.standard};
border-width: ${theme.borderWidths.standard};
border-color: ${theme.colors.neutral["200"]};

> div,
> div > div {
> div,
> div > div {
border-radius: ${theme.radii.small};
}
`,
variant === "input" &&
css`
border-radius: ${theme.radii.small};
border-color: ${theme.colors.neutral["100"]};
border-style: solid;
border-width: ${theme.borderWidths.standard};

> div,
> div > div {
border-radius: ${theme.radii.small};
}
`,
]}
>
<CodeEditorStyles fontFamily={fontFamily} />
<CodeMirror
value={value}
extensions={extensions}
selection={selection}
onEditorViewChange={setEditorView}
onUpdate={(v) => {
if (v.docChanged) {
onChange(v.state.doc.toString(), v.transactions);
}
`,
]}
>
<CodeEditorStyles />
<CodeMirror
value={value}
selection={selection}
editorDidMount={editorDidMount}
options={options}
onGutterClick={(_, lineNumber, gutter) => {
onGutterClick(lineNumber, gutter);
}}
onBlur={onBlur}
onSelection={(_, data) => {
onSelection(data);
}}
onBeforeChange={(_, data, value) => {
onChange(data, value);
}}
/>
</Box>
);
};
}}
/>
</Box>
);
}
);
Loading