Get the content from the caret back to nearest HR, or document start

Right now I am getting the text from the caret back to the start of the doc, like so:

let { $from, $to } = editor.state.selection
if ($from.pos === $to.pos) fm = 0
let selectedText: string = editor.state.doc.textBetween(fm, $to.pos, '\n')

I imagine it would be some sort of loop backwards through the blocks, gathering text as it goes back, either until it hits an HR or the top of the document.

Not quite sure how to achieve this though. I’d also need to maintain line breaks (from paragraph to paragraph).

Thanks in advance.