Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
simpsonphile opened this issue Mar 22, 2022 · 1 comment

Comments

@simpsonphile
Copy link

simpsonphile commented Mar 22, 2022

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);
          }
        }
@Sruli-RD
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants