Store and restore folded ranges in the buffer file on save/load

This commit is contained in:
Jonatan Heyman 2025-06-13 12:58:17 +02:00
parent ef04ab9ba9
commit 448a26e758
2 changed files with 20 additions and 2 deletions

View File

@ -42,4 +42,11 @@ export class NoteFormat {
get cursors() { get cursors() {
return this.metadata.cursors return this.metadata.cursors
} }
set foldedRanges(foldState) {
this.metadata.foldedRanges = foldState
}
get foldedRanges() {
return this.metadata?.foldedRanges || []
}
} }

View File

@ -1,6 +1,6 @@
import { Annotation, EditorState, Compartment, Facet, EditorSelection, Transaction, Prec } from "@codemirror/state" import { Annotation, EditorState, Compartment, Facet, EditorSelection, Transaction, Prec, RangeSet } from "@codemirror/state"
import { EditorView, keymap as cmKeymap, drawSelection, ViewPlugin, lineNumbers } from "@codemirror/view" import { EditorView, keymap as cmKeymap, drawSelection, ViewPlugin, lineNumbers } from "@codemirror/view"
import { ensureSyntaxTree } from "@codemirror/language" import { ensureSyntaxTree, foldState, foldEffect } from "@codemirror/language"
import { markdown, markdownKeymap } from "@codemirror/lang-markdown" import { markdown, markdownKeymap } from "@codemirror/lang-markdown"
import { undo, redo } from "@codemirror/commands" import { undo, redo } from "@codemirror/commands"
@ -166,6 +166,13 @@ export class HeynoteEditor {
this.note.content = this.view.state.sliceDoc() this.note.content = this.view.state.sliceDoc()
this.note.cursors = this.view.state.selection.toJSON() this.note.cursors = this.view.state.selection.toJSON()
// fold state
const foldedRanges = []
this.view.state.field(foldState, false)?.between(0, this.view.state.doc.length, (from, to) => {
foldedRanges.push({from, to})
})
this.note.foldedRanges = foldedRanges
const ranges = this.note.cursors.ranges const ranges = this.note.cursors.ranges
if (ranges.length == 1 && ranges[0].anchor == 0 && ranges[0].head == 0) { if (ranges.length == 1 && ranges[0].anchor == 0 && ranges[0].head == 0) {
console.log("DEBUG!! Cursor is at 0,0") console.log("DEBUG!! Cursor is at 0,0")
@ -231,6 +238,10 @@ export class HeynoteEditor {
scrollIntoView: true, scrollIntoView: true,
}) })
} }
// set folded ranges
this.view.dispatch({
effects: this.note.foldedRanges.map(range => foldEffect.of(range)),
})
resolve() resolve()
}) })
}) })