CodeMirror Merge - Calling a Function on Chunk Approval/Reject

I am using CodeMirror 6, and the @codemirror/merge package. So far I’ve gotten everything UI related working. However, I can not figure out how to trigger a function when the user has either approved or rejected a code chunk.

Here is what my (JS/React) code looks like:

const editorState = EditorState.create({
  doc: modifiedCode,
  extensions: [
    ...extensions,
    showMergeView ? unifiedMergeView({ original: originalCode }) : [],
  ],
});

const view = new EditorView({
  state: editorState,
  parent: editorRef.current,
});

For reference, I want to run a function to know when to turn off merge view. I am doing this by counting the number of chunks returned by getChunks. However, I can not for the life of me figure out how to run a function when the user has interacted with the merge control buttons.

The extension will fire transactions tagged with a user event of "accept" or "revert". You could listen to those and, if necessary reconstruct which chunk was reverted by comparing the change’s location to the chunks that existed in the state at the start of the transaction.

2 Likes

Thanks @marijn. Here’s the final code for future reference:

const editorState = EditorState.create({
  doc: "// my code",
  extensions: [
    ...extensions,
    EditorView.updateListener.of((update) => {
      if (update.transactions) {
        update.transactions.forEach((tr) => {
          if (tr.isUserEvent("accept")) {
            // handle accept
          } else if (tr.isUserEvent("revert")) {
            // handle revert
          }
        });
      }
    }),
  ],
});
1 Like