react-codemirror icon indicating copy to clipboard operation
react-codemirror copied to clipboard

Add a way to clear history

Open afska opened this issue 3 years ago • 7 comments

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.

afska avatar Nov 13 '22 20:11 afska

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

@rodri042

jaywcjlove avatar Nov 14 '22 02:11 jaywcjlove

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 avatar Dec 29 '22 08:12 BenStorey

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...

BenStorey avatar Dec 29 '22 09:12 BenStorey

I think this problem needs to be resolved

Leessonomy avatar Nov 14 '23 06:11 Leessonomy

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

Leessonomy avatar Nov 14 '23 06:11 Leessonomy

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

chenzhutian avatar Jan 16 '24 03:01 chenzhutian