Skip to content

Commit

Permalink
fix(read only): use codemirror instance with decorators (#1186)
Browse files Browse the repository at this point in the history
  • Loading branch information
danilowoz authored Aug 27, 2024
1 parent 5e9d607 commit 623a346
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import { storiesOf } from "@storybook/react";
import * as React from "react";

import { SandpackProvider } from "../../contexts/sandpackContext";
import { useSandpack } from "../../hooks";

import * as mocks from "./languages-mocks";

import { CodeEditor, SandpackCodeEditor } from "./index";
import { useSandpack } from "../../hooks";

const stories = storiesOf("components/CodeMirror", module);

Object.entries(mocks).forEach(([languageName, mockFile]) =>
Expand Down Expand Up @@ -147,6 +148,7 @@ export default function List() {
);
return <ul>{listItems}</ul>;
}`}
readOnly
decorators={[
{ className: "highlight", line: 1 },
{ className: "highlight", line: 9 },
Expand Down
17 changes: 13 additions & 4 deletions sandpack-react/src/components/CodeEditor/CodeMirror.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,12 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(
[decorators]
);

const useStaticReadOnly = readOnly && decorators?.length === 0;

React.useEffect(() => {
if (!wrapper.current || !shouldInitEditor || readOnly) return;
if (!wrapper.current || !shouldInitEditor || useStaticReadOnly) {
return;
}

const parentDiv = wrapper.current;
const existingPlaceholder = parentDiv.querySelector(
Expand Down Expand Up @@ -214,10 +218,14 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(
cmView.current?.destroy();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shouldInitEditor, readOnly]);
}, [shouldInitEditor, readOnly, useStaticReadOnly]);

React.useEffect(() => {
if (cmView.current && !readOnly) {
if (useStaticReadOnly) {
return;
}

if (cmView.current) {
const customCommandsKeymap: KeyBinding[] = [
{
key: "Tab",
Expand Down Expand Up @@ -327,6 +335,7 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(
wrapContent,
themeId,
readOnly,
useStaticReadOnly,
autoReload,
]);

Expand Down Expand Up @@ -441,7 +450,7 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(
return `var(--${THEME_PREFIX}-space-${offset})`;
};

if (readOnly) {
if (useStaticReadOnly) {
return (
<>
<pre
Expand Down

0 comments on commit 623a346

Please sign in to comment.