Gathering detailed insights and metrics for @uiw/react-codemirror
Gathering detailed insights and metrics for @uiw/react-codemirror
Gathering detailed insights and metrics for @uiw/react-codemirror
Gathering detailed insights and metrics for @uiw/react-codemirror
CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
npm install @uiw/react-codemirror
Typescript
Module System
Node Version
NPM Version
TypeScript (93.5%)
HTML (4.18%)
JavaScript (2.17%)
CSS (0.15%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
1,715 Stars
932 Commits
135 Forks
8 Watching
14 Branches
49 Contributors
Minified
Minified + Gzipped
Latest Version
4.23.7
Package Id
@uiw/react-codemirror@4.23.7
Unpacked Size
751.16 kB
Size
182.92 kB
File Count
30
NPM Version
10.8.2
Node Version
20.18.1
Publised On
16 Dec 2024
Cumulative downloads
Total Downloads
Last day
0%
0
Compared to previous day
Last week
0%
0
Compared to previous week
Last month
0%
0
Compared to previous month
Last year
0%
0
Compared to previous year
CodeMirror component for React. Demo Preview: @uiwjs.github.io/react-codemirror
Features:
🚀 Quickly and easily configure the API.
🌱 Versions after @uiw/react-codemirror@v4
use codemirror 6. #88.
⚛️ Support the features of React Hook(requires React 16.8+).
📚 Use Typescript to write, better code hints.
🌐 The bundled version supports use directly in the browser #267.
🌎 There are better sample previews.
🎨 Support theme customization, provide theme editor.
Not dependent on uiw.
1npm install @uiw/react-codemirror --save
All Packages
1import React from 'react'; 2import CodeMirror from '@uiw/react-codemirror'; 3import { javascript } from '@codemirror/lang-javascript'; 4 5function App() { 6 const [value, setValue] = React.useState("console.log('hello world!');"); 7 const onChange = React.useCallback((val, viewUpdate) => { 8 console.log('val:', val); 9 setValue(val); 10 }, []); 11 return <CodeMirror value={value} height="200px" extensions={[javascript({ jsx: true })]} onChange={onChange} />; 12} 13export default App;
1import CodeMirror from '@uiw/react-codemirror'; 2import { StreamLanguage } from '@codemirror/language'; 3import { go } from '@codemirror/legacy-modes/mode/go'; 4 5const goLang = `package main 6import "fmt" 7 8func main() { 9 fmt.Println("Hello, 世界") 10}`; 11 12export default function App() { 13 return <CodeMirror value={goLang} height="200px" extensions={[StreamLanguage.define(go)]} />; 14}
@codemirror/legacy-modes/mode/cpp
@codemirror/lang-cpp
@codemirror/legacy-modes/mode/html
@codemirror/lang-html
@codemirror/legacy-modes/mode/java
@codemirror/lang-java
@codemirror/legacy-modes/mode/javascript
@codemirror/lang-javascript
@codemirror/legacy-modes/mode/json
@codemirror/lang-json
@codemirror/legacy-modes/mode/lezer
@codemirror/lang-lezer
@codemirror/legacy-modes/mode/markdown
@codemirror/lang-markdown
@codemirror/legacy-modes/mode/php
@codemirror/lang-php
@codemirror/legacy-modes/mode/python
@codemirror/lang-python
@codemirror/legacy-modes/mode/rust
@codemirror/lang-rust
@codemirror/legacy-modes/mode/sql
@codemirror/lang-sql
@codemirror/legacy-modes/mode/xml
@codemirror/lang-xml
@codemirror/legacy-modes/mode/css
@codemirror/lang-less
@codemirror/legacy-modes/mode/sass
@codemirror/lang-sass
@codemirror/legacy-modes/mode/clojure
@nextjournal/lang-clojure
@codemirror/legacy-modes/mode/clike
@replit/codemirror-lang-csharp
Markdown language code is automatically highlighted.
1import CodeMirror from '@uiw/react-codemirror'; 2import { markdown, markdownLanguage } from '@codemirror/lang-markdown'; 3import { languages } from '@codemirror/language-data'; 4 5const code = `## Title 6 7\`\`\`jsx 8function Demo() { 9 return <div>demo</div> 10} 11\`\`\` 12 13\`\`\`bash 14# Not dependent on uiw. 15npm install @codemirror/lang-markdown --save 16npm install @codemirror/language-data --save 17\`\`\` 18 19[weisit ulr](https://uiwjs.github.io/react-codemirror/) 20 21\`\`\`go 22package main 23import "fmt" 24func main() { 25 fmt.Println("Hello, 世界") 26} 27\`\`\` 28`; 29 30export default function App() { 31 return <CodeMirror value={code} extensions={[markdown({ base: markdownLanguage, codeLanguages: languages })]} />; 32}
A component that highlights the changes between two versions of a file in a side-by-side view, highlighting added, modified, or deleted lines of code.
1npm install react-codemirror-merge --save
1import CodeMirrorMerge from 'react-codemirror-merge'; 2import { EditorView } from 'codemirror'; 3import { EditorState } from '@codemirror/state'; 4 5const Original = CodeMirrorMerge.Original; 6const Modified = CodeMirrorMerge.Modified; 7let doc = `one 8two 9three 10four 11five`; 12 13export const Example = () => { 14 return ( 15 <CodeMirrorMerge> 16 <Original value={doc} /> 17 <Modified 18 value={doc.replace(/t/g, 'T') + 'Six'} 19 extensions={[EditorView.editable.of(false), EditorState.readOnly.of(true)]} 20 /> 21 </CodeMirrorMerge> 22 ); 23};
1import { useEffect, useMemo, useRef } from 'react'; 2import { useCodeMirror } from '@uiw/react-codemirror'; 3import { javascript } from '@codemirror/lang-javascript'; 4 5const code = "console.log('hello world!');\n\n\n"; 6// Define the extensions outside the component for the best performance. 7// If you need dynamic extensions, use React.useMemo to minimize reference changes 8// which cause costly re-renders. 9const extensions = [javascript()]; 10 11export default function App() { 12 const editor = useRef(); 13 const { setContainer } = useCodeMirror({ 14 container: editor.current, 15 extensions, 16 value: code, 17 }); 18 19 useEffect(() => { 20 if (editor.current) { 21 setContainer(editor.current); 22 } 23 }, [editor.current]); 24 25 return <div ref={editor} />; 26}
We have created a theme editor
where you can define your own theme. We have also defined some themes ourselves, which can be installed and used directly. Below is a usage example:
1import CodeMirror from '@uiw/react-codemirror'; 2import { javascript } from '@codemirror/lang-javascript'; 3import { okaidia } from '@uiw/codemirror-theme-okaidia'; 4 5const extensions = [javascript({ jsx: true })]; 6 7export default function App() { 8 return <CodeMirror value="console.log('hello world!');" height="200px" theme={okaidia} extensions={extensions} />; 9}
1import CodeMirror from '@uiw/react-codemirror'; 2import { createTheme } from '@uiw/codemirror-themes'; 3import { javascript } from '@codemirror/lang-javascript'; 4import { tags as t } from '@lezer/highlight'; 5 6const myTheme = createTheme({ 7 theme: 'light', 8 settings: { 9 background: '#ffffff', 10 backgroundImage: '', 11 foreground: '#75baff', 12 caret: '#5d00ff', 13 selection: '#036dd626', 14 selectionMatch: '#036dd626', 15 lineHighlight: '#8a91991a', 16 gutterBackground: '#fff', 17 gutterForeground: '#8a919966', 18 }, 19 styles: [ 20 { tag: t.comment, color: '#787b8099' }, 21 { tag: t.variableName, color: '#0080ff' }, 22 { tag: [t.string, t.special(t.brace)], color: '#5c6166' }, 23 { tag: t.number, color: '#5c6166' }, 24 { tag: t.bool, color: '#5c6166' }, 25 { tag: t.null, color: '#5c6166' }, 26 { tag: t.keyword, color: '#5c6166' }, 27 { tag: t.operator, color: '#5c6166' }, 28 { tag: t.className, color: '#5c6166' }, 29 { tag: t.definition(t.typeName), color: '#5c6166' }, 30 { tag: t.typeName, color: '#5c6166' }, 31 { tag: t.angleBracket, color: '#5c6166' }, 32 { tag: t.tagName, color: '#5c6166' }, 33 { tag: t.attributeName, color: '#5c6166' }, 34 ], 35}); 36const extensions = [javascript({ jsx: true })]; 37 38export default function App() { 39 const onChange = React.useCallback((value, viewUpdate) => { 40 console.log('value:', value); 41 }, []); 42 return ( 43 <CodeMirror 44 value="console.log('hello world!');" 45 height="200px" 46 theme={myTheme} 47 extensions={extensions} 48 onChange={onChange} 49 /> 50 ); 51}
initialState
to restore state from JSON-serialized representationCodeMirror allows to serialize editor state to JSON representation with toJSON function for persistency or other needs. This JSON representation can be later used to recreate ReactCodeMirror component with the same internal state.
For example, this is how undo history can be saved in the local storage, so that it remains after the page reloads
1import CodeMirror from '@uiw/react-codemirror'; 2import { historyField } from '@codemirror/commands'; 3 4// When custom fields should be serialized, you can pass them in as an object mapping property names to fields. 5// See [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) documentation for more details 6const stateFields = { history: historyField }; 7 8export function EditorWithInitialState() { 9 const serializedState = localStorage.getItem('myEditorState'); 10 const value = localStorage.getItem('myValue') || ''; 11 12 return ( 13 <CodeMirror 14 value={value} 15 initialState={ 16 serializedState 17 ? { 18 json: JSON.parse(serializedState || ''), 19 fields: stateFields, 20 } 21 : undefined 22 } 23 onChange={(value, viewUpdate) => { 24 localStorage.setItem('myValue', value); 25 26 const state = viewUpdate.state.toJSON(stateFields); 27 localStorage.setItem('myEditorState', JSON.stringify(state)); 28 }} 29 /> 30 ); 31}
value?: string
value of the auto created model in the editor.width?: string
width of editor. Defaults to auto
.height?: string
height of editor. Defaults to auto
.theme?
: 'light'
/ 'dark'
/ Extension
Defaults to 'light'
.1import React from 'react'; 2import { EditorState, EditorStateConfig, Extension } from '@codemirror/state'; 3import { EditorView, ViewUpdate } from '@codemirror/view'; 4export * from '@codemirror/view'; 5export * from '@codemirror/basic-setup'; 6export * from '@codemirror/state'; 7export interface UseCodeMirror extends ReactCodeMirrorProps { 8 container?: HTMLDivElement | null; 9} 10export declare function useCodeMirror(props: UseCodeMirror): { 11 state: EditorState | undefined; 12 setState: import('react').Dispatch<import('react').SetStateAction<EditorState | undefined>>; 13 view: EditorView | undefined; 14 setView: import('react').Dispatch<import('react').SetStateAction<EditorView | undefined>>; 15 container: HTMLDivElement | null | undefined; 16 setContainer: import('react').Dispatch<import('react').SetStateAction<HTMLDivElement | null | undefined>>; 17}; 18export interface ReactCodeMirrorProps 19 extends Omit<EditorStateConfig, 'doc' | 'extensions'>, 20 Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'placeholder'> { 21 /** value of the auto created model in the editor. */ 22 value?: string; 23 height?: string; 24 minHeight?: string; 25 maxHeight?: string; 26 width?: string; 27 minWidth?: string; 28 maxWidth?: string; 29 /** focus on the editor. */ 30 autoFocus?: boolean; 31 /** Enables a placeholder—a piece of example content to show when the editor is empty. */ 32 placeholder?: string | HTMLElement; 33 /** 34 * `light` / `dark` / `Extension` Defaults to `light`. 35 * @default light 36 */ 37 theme?: 'light' | 'dark' | Extension; 38 /** 39 * Whether to optional basicSetup by default 40 * @default true 41 */ 42 basicSetup?: boolean | BasicSetupOptions; 43 /** 44 * This disables editing of the editor content by the user. 45 * @default true 46 */ 47 editable?: boolean; 48 /** 49 * This disables editing of the editor content by the user. 50 * @default false 51 */ 52 readOnly?: boolean; 53 /** 54 * Controls whether pressing the `Tab` key inserts a tab character and indents the text (`true`) 55 * or behaves according to the browser's default behavior (`false`). 56 * @default true 57 */ 58 indentWithTab?: boolean; 59 /** Fired whenever a change occurs to the document. */ 60 onChange?(value: string, viewUpdate: ViewUpdate): void; 61 /** Some data on the statistics editor. */ 62 onStatistics?(data: Statistics): void; 63 /** The first time the editor executes the event. */ 64 onCreateEditor?(view: EditorView, state: EditorState): void; 65 /** Fired whenever any state change occurs within the editor, including non-document changes like lint results. */ 66 onUpdate?(viewUpdate: ViewUpdate): void; 67 /** 68 * Extension values can be [provided](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions) when creating a state to attach various kinds of configuration and behavior information. 69 * They can either be built-in extension-providing objects, 70 * such as [state fields](https://codemirror.net/6/docs/ref/#state.StateField) or [facet providers](https://codemirror.net/6/docs/ref/#state.Facet.of), 71 * or objects with an extension in its `extension` property. Extensions can be nested in arrays arbitrarily deep—they will be flattened when processed. 72 */ 73 extensions?: Extension[]; 74 /** 75 * If the view is going to be mounted in a shadow root or document other than the one held by the global variable document (the default), you should pass it here. 76 * Originally from the [config of EditorView](https://codemirror.net/6/docs/ref/#view.EditorView.constructor%5Econfig.root) 77 */ 78 root?: ShadowRoot | Document; 79 /** 80 * Create a state from its JSON representation serialized with [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) function 81 */ 82 initialState?: { 83 json: any; 84 fields?: Record<'string', StateField<any>>; 85 }; 86} 87export interface ReactCodeMirrorRef { 88 editor?: HTMLDivElement | null; 89 state?: EditorState; 90 view?: EditorView; 91} 92declare const ReactCodeMirror: React.ForwardRefExoticComponent< 93 ReactCodeMirrorProps & React.RefAttributes<ReactCodeMirrorRef> 94>; 95export default ReactCodeMirror; 96export interface BasicSetupOptions { 97 lineNumbers?: boolean; 98 highlightActiveLineGutter?: boolean; 99 highlightSpecialChars?: boolean; 100 history?: boolean; 101 foldGutter?: boolean; 102 drawSelection?: boolean; 103 dropCursor?: boolean; 104 allowMultipleSelections?: boolean; 105 indentOnInput?: boolean; 106 syntaxHighlighting?: boolean; 107 bracketMatching?: boolean; 108 closeBrackets?: boolean; 109 autocompletion?: boolean; 110 rectangularSelection?: boolean; 111 crosshairCursor?: boolean; 112 highlightActiveLine?: boolean; 113 highlightSelectionMatches?: boolean; 114 closeBracketsKeymap?: boolean; 115 defaultKeymap?: boolean; 116 searchKeymap?: boolean; 117 historyKeymap?: boolean; 118 foldKeymap?: boolean; 119 completionKeymap?: boolean; 120 lintKeymap?: boolean; 121}
1import { EditorSelection, SelectionRange } from '@codemirror/state'; 2import { ViewUpdate } from '@codemirror/view'; 3export interface Statistics { 4 /** Get the number of lines in the editor. */ 5 lineCount: number; 6 /** total length of the document */ 7 length: number; 8 /** Get the proper [line-break](https://codemirror.net/docs/ref/#state.EditorState^lineSeparator) string for this state. */ 9 lineBreak: string; 10 /** Returns true when the editor is [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. */ 11 readOnly: boolean; 12 /** The size (in columns) of a tab in the document, determined by the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. */ 13 tabSize: number; 14 /** Cursor Position */ 15 selection: EditorSelection; 16 /** Make sure the selection only has one range. */ 17 selectionAsSingle: SelectionRange; 18 /** Retrieves a list of all current selections. */ 19 ranges: readonly SelectionRange[]; 20 /** Get the currently selected code. */ 21 selectionCode: string; 22 /** 23 * The length of the given array should be the same as the number of active selections. 24 * Replaces the content of the selections with the strings in the array. 25 */ 26 selections: string[]; 27 /** Return true if any text is selected. */ 28 selectedText: boolean; 29} 30export declare const getStatistics: (view: ViewUpdate) => Statistics;
1$ npm install # Installation dependencies 2$ npm run build # Compile all package
@uiw/react-codemirror
package:1$ cd core 2# listen to the component compile and output the .js file 3# listen for compilation output type .d.ts file 4$ npm run watch # Monitor the compiled package `@uiw/react-codemirror`
1npm run start
As always, thanks to our amazing contributors!
Made with contributors.
Licensed under the MIT License.
No vulnerabilities found.
Reason
11 commit(s) and 10 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
packaging workflow detected
Details
Reason
Found 5/30 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More