From 102d1f4186df20aacdf2b7841d6a0fad30a9ac8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Mon, 4 May 2026 16:02:15 +0200 Subject: [PATCH] restore folds when changing tab --- client/components/codeEditor/codeEditor.jsx | 22 ++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/client/components/codeEditor/codeEditor.jsx b/client/components/codeEditor/codeEditor.jsx index 43065462f..722301795 100644 --- a/client/components/codeEditor/codeEditor.jsx +++ b/client/components/codeEditor/codeEditor.jsx @@ -17,7 +17,7 @@ import { crosshairCursor, } from '@codemirror/view'; import { EditorState, Compartment, StateEffect, StateField } from '@codemirror/state'; -import { foldAll as foldAllCmd, unfoldAll as unfoldAllCmd, foldGutter, foldKeymap, foldEffect, syntaxHighlighting } from '@codemirror/language'; +import { foldAll as foldAllCmd, unfoldAll as unfoldAllCmd, foldGutter, foldKeymap, foldEffect, foldState, syntaxHighlighting } from '@codemirror/language'; import { defaultKeymap, history, undo, redo, undoDepth, redoDepth } from '@codemirror/commands'; import { languages } from '@codemirror/language-data'; import { css } from '@codemirror/lang-css'; @@ -151,6 +151,7 @@ const CodeEditor = forwardRef( const tabRef = useRef(tab); const prevTabRef = useRef(tab); const scrollRef = useRef({}); + const foldsRef = useRef({}); const pageMap = useRef([]); const recomputePages = (doc)=>{ @@ -180,6 +181,14 @@ const CodeEditor = forwardRef( return page; }; + const getFoldRanges = (state) => { + const folds = []; + state.field(foldState, false)?.between(0, state.doc.length, (from, to) => { + folds.push({ from, to }); + }); + return folds; + }; + const createExtensions = ({ onChange, language, editorTheme })=>{ const setEventListeners = EditorView.updateListener.of((update)=>{ if(update.docChanged) { @@ -284,6 +293,14 @@ const CodeEditor = forwardRef( }; }, []); + const restoreFolds = (view, folds) => { + if (!folds?.length) return; + + view.dispatch({ + effects: folds.map(f => foldEffect.of(f)) + }); + }; + useEffect(()=>{ const view = viewRef.current; if(!view) return; @@ -291,6 +308,8 @@ const CodeEditor = forwardRef( tabRef.current = tab; const prevTab = prevTabRef.current; + foldsRef.current[prevTab] = getFoldRanges(view.state); + if(prevTab !== tab) { docsRef.current[prevTab] = view.state; @@ -304,6 +323,7 @@ const CodeEditor = forwardRef( } view.setState(nextState); + restoreFolds(view, foldsRef.current[tab]); const savedScroll = scrollRef.current[tab];