vue-codemirror

repository·main·Indexed 25 days ago

https://github.com/surmon-china/vue-codemirror

A Vue 3 component wrapper for CodeMirror 6 (version 6.1.1) that provides a reactive interface for integrating code editing capabilities into Vue applications. It supports local and global component registration, v-model binding, and modular extensions for languages and themes. The library includes utilities for managing EditorView and EditorState, as well as a set of editor tools for manipulating document content, focus, and styling.

Tokens
3.2K
Snippets
4
Records
17
Agent score
85%

What's inside vue-codemirror

  1. Install CodeMirror language and theme packages

    main

    CodeMirror 6 is modular. You must install additional packages for specific languages or themes. Examples include:

    • Languages: @codemirror/lang-html, @codemirror/lang-json, @codemirror/lang-javascript
    • Themes: @codemirror/theme-one-dark
    # Examples of additional packages
    yarn add @codemirror/lang-html
    yarn add @codemirror/lang-json
    yarn add @codemirror/lang-javascript
    yarn add @codemirror/theme-one-dark
  2. Use vue-codemirror as a global component

    main

    Register VueCodemirror globally in your Vue application to provide default options for all editor instances. Note that basicSetup is integrated by default; to override this and provide no default extensions, pass an empty array to the extensions option.

    import { createApp } from 'vue'
    import { basicSetup } from 'codemirror'
    import VueCodemirror from 'vue-codemirror'
    
    const app = createApp()
    
    app.use(VueCodemirror, {
      // optional default global options
      autofocus: true,
      disabled: false,
      indentWithTab: true,
      tabSize: 2,
      placeholder: 'Code goes here...',
      extensions: [basicSetup]
      // ...
    })
  3. Configure global defaults using injectGlobalConfig

    main

    You can set global configuration defaults for all vue-codemirror components by using injectGlobalConfig during your Vue application setup. This is useful for applying consistent settings like tabSize, indentWithTab, or extensions across your entire application.

    Note that the configuration provided will be merged or used as the base for components. The DEFAULT_CONFIG includes:

    • autofocus: boolean (default: false)
    • disabled: boolean (default: false)
    • indentWithTab: boolean (default: true)
    • tabSize: number (default: 2)
    • placeholder: string (default: '')
    • autoDestroy: boolean (default: true)
    • extensions: array (default: [basicSetup])

    Pass a partial ConfigProps object to the function.

  4. Use vue-codemirror as a local component

    main

    You can import and use the Codemirror component directly in your Vue components. This allows you to pass specific extensions (like languages and themes) and handle events like @ready to access the underlying CodeMirror EditorView instance.

    <template>
      <codemirror
        v-model="code"
        placeholder="Code goes here..."
        :style="{ height: '400px' }"
        :autofocus="true"
        :indent-with-tab="true"
        :tab-size="2"
        :extensions="extensions"
        @ready="handleReady"
        @change="log('change', $event)"
        @focus="log('focus', $event)"
        @blur="log('blur', $event)"
      />
    </template>
    
    <script>
      import { defineComponent, ref, shallowRef } from 'vue'
      import { Codemirror } from 'vue-codemirror'
      import { javascript } from '@codemirror/lang-javascript'
      import { oneDark } from '@codemirror/theme-one-dark'
    
      export default defineComponent({
        components: {
          Codemirror
        },
        setup() {
          const code = ref(`console.log('Hello, world!')`)
          const extensions = [javascript(), oneDark]
    
          // Codemirror EditorView instance ref
          const view = shallowRef()
          const handleReady = (payload) => {
            view.value = payload.view
          }
    
          // Status is available at all times via Codemirror EditorView
          const getCodemirrorStates = () => {
            const state = view.value.state
            const ranges = state.selection.ranges
            const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
            const cursor = ranges[0].anchor
            const length = state.doc.length
            const lines = state.doc.lines
            // more state info ...
            // return ...
          }
    
          return {
            code,
            extensions,
            handleReady,
            log: console.log
          }
        }
      })
    </script>
  5. Reference: Codemirror Component Events

    main

    The following events are emitted by the <codemirror /> component:

    EventDescriptionParams
    update:modelValueOnly when the CodeMirror content (doc) has changed.(value: string, viewUpdate: ViewUpdate)
    changeSame as update:modelValue.ditto
    updateWhen any state of CodeMirror changes.(viewUpdate: ViewUpdate)
    focusWhen CodeMirror focused.(viewUpdate: ViewUpdate)
    blurWhen CodeMirror blurred.(viewUpdate: ViewUpdate)
    readyWhen editor component mounted.(payload: { view: EditorView; state: EditorState; container: HTMLDivElement })
  6. Reference: Codemirror Component Props

    main

    The following props are available on the <codemirror /> component:

    PropDescriptionTypeDefault
    modelValueThe input values accepted by the component; supports two-way binding.String''
    autofocusFocus editor immediately after mounted.Booleanfalse
    disabledDisable input behavior and disable change state.Booleanfalse
    indentWithTabBind keyboard Tab key event.Booleantrue
    tabSizeSpecify the indent when the Tab key is pressed.Number2
    placeholderDisplay when empty.String''
    styleThe CSS style object that acts on the CodeMirror itself.Object{}
    phrasesCodemirror internationalization phrases.Object{}
    autoDestroyAuto destroy the CodeMirror instance before the component unmount.Booleantrue
    extensionsPassed to CodeMirror EditorState.create({ extensions })Extension[]
    selectionPassed to CodeMirror EditorState.create({ selection })EditorSelection-
    rootPassed to CodeMirror new EditorView({ root })ShadowRoot | Document-
  7. Handle editor lifecycle and interaction events

    main

    The component emits several events that allow you to react to editor changes, state updates, and lifecycle stages. The available event keys and their payload structures are:

    • change: Emitted when the content (doc) changes. Payload: (value: string, viewUpdate: ViewUpdate) => boolean.
    • update: Emitted when the CodeMirror state changes. Payload: (viewUpdate: ViewUpdate) => boolean.
    • focus: Emitted when the editor gains focus. Payload: (viewUpdate: ViewUpdate) => boolean.
    • blur: Emitted when the editor loses focus. Payload: (viewUpdate: ViewUpdate) => boolean.
    • ready: Emitted when the component is mounted. Payload: { view: EditorView; state: EditorState; container: HTMLDivElement }.
    • update:modelValue: An alias for the change event, typically used for v-model synchronization.
  8. Access Editor Utilities with getEditorTools

    main

    The getEditorTools function returns a set of utility methods to interact with an active EditorView without manually dispatching transactions.

    Available Tools:

    • getDoc(): Returns the current document as a string.
    • setDoc(newDoc: string): Replaces the entire document content.
    • focus(): Sets focus to the editor.
    • reExtensions(extensions: Extension[]): Reconfigures the editor extensions.
    • toggleDisabled(): Toggles the editor between editable and read-only modes.
    • toggleIndentWithTab(): Toggles the indentWithTab keymap.
    • setTabSize(tabSize: number): Sets the tab size and indentation unit.
    • setPhrases(phrases: Record<string, string>): Sets translation phrases.
    • setPlaceholder(value: string): Sets the editor's placeholder text.
    • setStyle(style: CSSProperties): Applies CSS styles to the editor element via EditorView.theme.
  9. Initialize Editor State with createEditorState

    main

    Use createEditorState to initialize the CodeMirror EditorState. This function wraps the standard EditorState.create and provides lifecycle hooks for updates, document changes, and focus changes.

    Options:

    • onUpdate: Called on every view update.
    • onChange: Called when the document content changes. Receives (doc: string, viewUpdate: ViewUpdate).
    • onFocus: Called when the editor gains focus.
    • onBlur: Called when the editor loses focus.
    • ...config: Any standard EditorStateConfig properties (e.g., doc, selection, extensions).