Skip to content

Commit

Permalink
fix(codeeditor): ensure selections are inside of the document length (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
danilowoz authored Apr 27, 2022
1 parent b700e70 commit 7391c6e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
16 changes: 11 additions & 5 deletions sandpack-react/src/components/CodeEditor/CodeMirror.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { lineNumbers } from "@codemirror/gutter";
import { defaultHighlightStyle } from "@codemirror/highlight";
import { history, historyKeymap } from "@codemirror/history";
import { bracketMatching } from "@codemirror/matchbrackets";
import { EditorState } from "@codemirror/state";
import { EditorState, EditorSelection } from "@codemirror/state";
import type { Annotation, Extension } from "@codemirror/state";
import {
highlightSpecialChars,
Expand Down Expand Up @@ -311,10 +311,16 @@ export const CodeMirror = React.forwardRef<CodeMirrorRef, CodeMirrorProps>(
React.useEffect(() => {
if (cmView.current && code !== internalCode) {
const view = cmView.current;
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: code },
selection: view.state.selection,
});

const selection = view.state.selection.ranges.some(
({ to, from }) => to > code.length || from > code.length
)
? EditorSelection.cursor(code.length)
: view.state.selection;

const changes = { from: 0, to: view.state.doc.length, insert: code };

view.dispatch({ changes, selection });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [code]);
Expand Down
7 changes: 5 additions & 2 deletions website/docs/docs/advanced-usage/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,8 @@ import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
If you want to interact directly with CodeMirror, use the component ref to access the `getCodemirror` function, which will return the CodeMirror instance. Check out how to use it:
```jsx
import { EditorSelection } from "@codemirror/state";

const App = () => {
const codemirrorInstance = useRef();

Expand All @@ -272,17 +274,18 @@ const App = () => {
if(!cmInstance) return

// Current position
const currentPosition = cmInstance.state.selection;
const currentPosition = cmInstance.state.selection.ranges[0].to;

// Setting a new position
const trans = cmInstance.state.update({
selection: currentPosition + 1,
selection: EditorSelection.cursor(currentPosition + 1),
changes: {
from: 0,
to: cmInstance.state.doc.length,
insert: code
}
});

cmInstance.update([trans]);
}, []);

Expand Down

0 comments on commit 7391c6e

Please sign in to comment.