uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.61k stars 128 forks source link

Add a way to clear history #405

Open afska opened 1 year ago

afska commented 1 year ago

I cannot find any method to clear history (to prevent Ctrl+Z in some cases) It seems that CodeMirror 6 suggests doing editor.setState(...) with a new state, but in this library states are created internally and there's no easy way to do it.

jaywcjlove commented 1 year ago

https://discuss.codemirror.net/t/codemirror-6-cm-clearhistory-equivalent/2851/7

@rodri042

BenStorey commented 1 year ago

I don't understand how to re-use that code when we are using react-codemirror. If somewhere in my code I'm using react-codemirror like this:

<CodeMirror
    ref={codeRef}
    style={{ whatever }}
    className={{ whatever }}
    value={ code }
    theme={mytheme}
    placeholder={mytext}
    extensions={[StreamLanguage.define(q)]}
    onChange={(e) => console.log(e) }
/>

Then how am I supposed to recreate the Editor to keep absolutely everything the same, but only removing History? If I create a new instance without all the options set then it's just broken. But if I need to carefully craft the arguments to exactly match whatever react-codemirror is generating, then why use codemirror in the first place? It seems like I shouldn't....?

Just FYI, my attempt that is broken, is inside useEffect() I set state like this:

codeRef.current.view.setState(EditorState.create({ doc: newcode, extensions: [StreamLanguage.define(q)] };

I end up with a white box with zero formatting (no line numbers, highlighting etc). How can I call EditorState.create() with the same values that react-codemirror would have used?

BenStorey commented 1 year ago

Actually one hacky workaround that seems to work is by setting the history state to false then back to true again right after. So code like this appears to work fine:

const [ codeMirrorUseHistory, setCodeMirrorUseHistory ] = useState(true);

useEffect(() =>
{
    // unset history
    setCodeMirrorUseHistory(false);
    setTimeout(() => setCodeMirrorUseHistory(true), 1);
}, [deps]);

<CodeMirror
    basicSetup={{ history: codeMirrorUseHistory}}
/>

Dirty but somehow seems better than the other alternative...

Leessonomy commented 9 months ago

I think this problem needs to be resolved

Leessonomy commented 9 months ago

https://discuss.codemirror.net/t/codemirror-6-cm-clearhistory-equivalent/2851/7

@rodri042

it seems as view.setState will break functionality like this https://github.com/uiwjs/react-codemirror/blob/c68d27d789346a87dcb157b33772e0522f653ad7/merge/src/Modified.tsx#L18

chenzhutian commented 7 months ago

+1, if I reset state, all the internal extensions of react-codemirror will be lost