I use snippet to add content throw exception

function insertText(text, isTemplate) {
  console.log('inserttext')
  const view = editor.value
  if (!view) return

  const { state } = view
  if (!state) return

  const [range] = state?.selection?.ranges || []

  view.focus()

  if (isTemplate) {
    snippet(text)(
      {
        state,
        dispatch: view.dispatch
      },
      {
        label: text,
        detail: text
      },
      range.from,
      range.to
    )
  } else {
    /*     view.dispatch({
      changes: {
        from: range.from,
        to: range.to,
        insert: text
      },
      selection: {
        anchor: range.from + text.length
      }
    }) */
    let aa = editor.value.state.selection.main.head
    view.dispatch({
      changes: {
        from: editor.value.state.selection.main.head,
        to: editor.value.state.selection.main.head,
        insert: text
      },
      // 光标位置
      selection: {
        anchor: editor.value.state.selection.main.head + text.length
      }
    })
  }
}

my program use vue3
“@codemirror/view”: “^6.7.1”,
“@codemirror/autocomplete”: “^6.18.0”,
“@codemirror/state”: “^0.19.0”,

when isTemplate is turee
throw exception info
Uncaught RangeError: Trying to update state with a transaction that doesn’t start from the previous state.
at _EditorView.update (chunk-R2OJLQUA.js?v=b404227b:10441:15)
at _EditorView.dispatchTransactions (chunk-R2OJLQUA.js?v=b404227b:10404:145)
at _EditorView.dispatch (chunk-R2OJLQUA.js?v=b404227b:10424:10)
at chunk-MZKI3HXW.js?v=b404227b:1512:12
at Proxy.insertText (editor.vue?t=1723625342144:60:22)
at Proxy.insertFunction (businessCodeEditor.vue?t=1723603235710:120:23)
at onDblclick (businessCodeEditor.vue?t=1723603235710:283:60)
at callWithErrorHandling (chunk-E7HXAGFX.js?v=b404227b:1750:18)
at callWithAsyncErrorHandling (chunk-E7HXAGFX.js?v=b404227b:1758:17)
at HTMLSpanElement.invoker (chunk-E7HXAGFX.js?v=b404227b:9694:5)
update @ chunk-R2OJLQUA.js?v=b404227b:10441
dispatchTransactions @ chunk-R2OJLQUA.js?v=b404227b:10404
dispatch @ chunk-R2OJLQUA.js?v=b404227b:10424
(anonymous) @ chunk-MZKI3HXW.js?v=b404227b:1512
insertText @ editor.vue?t=1723625342144:60
insertFunction @ businessCodeEditor.vue?t=1723603235710:120
onDblclick @ businessCodeEditor.vue?t=1723603235710:283
callWithErrorHandling @ chunk-E7HXAGFX.js?v=b404227b:1750
callWithAsyncErrorHandling @ chunk-E7HXAGFX.js?v=b404227b:1758
invoker @ chunk-E7HXAGFX.js?v=b404227b:9694
Show 7 more frames
Show less

Are you putting the EditorView in the Vue state? That will cause Vue to mess up the objects by inserting wrapper objects.

1 Like