How to get folded source code inside foldWidget.toDOM() from @codemirror/fold

I am looking at @codemirror/fold as inspiration for an extension I want to write.
Instead of having a <span>...</span> element replacing the folded code, I want to have another codemirror editor instance containing the folded code.

Changing foldWidget.toDOM() to return an editor instance works. But I cannot figure out from where to get the folded code for that line, from within the toDOM function

The API used in element.onclick: let line = view.visualLineAt(view.posAtDOM(event.target)) does not work outside the event handler and fails with Uncaught RangeError: Trying to find position for a DOM position outside of the document.

I figured it out. I wrapped foldWidget in a function that receives the folded source code as a parameter.
And changed folded = folded.update({add: [foldWidget.range(e.value.from, e.value.to)]}) to:

let code = tr.state.doc.slice(e.value.from, e.value.to);
folded = folded.update({add: [foldWidget({code}).range(e.value.from, e.value.to)]})

Yes, that works. toDOM should just render the data that’s already in the widget object, not access anything external.