Skip to content

onBeforeChange returns wrong third parameter when previous change is canceled #279

Open

Description

@simpsonphile

My intention is to block some lines from the edition.
When I try to edit code specified in linesReadOnly it works fine but when the next action is correct for example some changes in line 10 then nValue returns the wrong string (with changes that were blocked by changeObj.cancel()

const linesReadOnly = [0,1,2,3];
const onBeforeChange ({}, changeObj, nValue: string) => {
          if (~linesReadOnly.indexOf(changeObj.from.line)) {
            changeObj.cancel();
          } else {
            setValue(nValue);
          }
        }

Activity

  1. Sruli-RD commented on May 26, 2022

    @Sruli-RD

    Hey, just had the same issue. Whipped up a solution if you're still having this issue.
    For reference, cm is the first value that is passed in from onBeforeChange which you are destructuring to an empty object.

    // onBeforeChange will get triggered again with the origin of "setValue".
    // This prevents an infinite loop
    if (action.origin !== "setValue") {
        // Getting the first selection in the array (If you are dealing with multiple cursors you would want to get all the ranges)
        const oldSelection = cm.doc.sel.ranges[0];
        // Getting the old scroll info from CodeMirror
        const scrollInfo = cm.getScrollInfo();
        const oldScrollTop = scrollInfo.top;
        const oldScrollLeft = scrollInfo.left;
        // Setting the data back to your old value
        cm.setValue(INSERT_OLD_CODE_VALUE_HERE);
        // Setting the old selections in place (If you are dealing with multiple cursors you would want to use cm.setSelections and 
        pass them all in)
        cm.setSelection(oldSelection.anchor, oldSelection.head);
        // Scrolling back to where we were
        cm.scrollTo(oldScrollLeft, oldScrollTop);
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions