RichText(markdown) live editor using TextEditor

hi everyone, any thought on how to implement a RichText(markdown) live editor using the new TextEditor(text: AttributedString, selection: AttributedTextSelection)?

Having issues like:

  1. how to get the location of the selected text relatived to the TextEditor bounds, which is used to show and position a floating toolbar.
  2. how to detect the cursor point is a new line and the content is "# ", (of couse now the user enter a space after the "#"), and if so, how to apply a H1 heading format to that line

much more issues like this, but these two are how to get me started, thanks

struct TextEditor8: View {
    @State var text: AttributedString
    @State var selection = AttributedTextSelection()
    @State var isShowFloatingToolbar = false
    @State var toolbarPosition: CGPoint = .zero

    init() {
        var text = AttributedString("Hello ✋🏻,Who is ready for Cooking?")
        let range = text.characters.indices(where: \.isUppercase)
        text[range].foregroundColor = .blue
        _text = State(initialValue: text)
    }

    var body: some View {
        ZStack(alignment: .topLeading) {
            GeometryReader { geo in
                TextEditor(text: $text, selection: $selection)
                    .onChange(of: selection, perform: { newV in
                        let v = text[newV]
                        if v.characters.isEmpty {
                            isShowFloatingToolbar = false
                        } else {
                            isShowFloatingToolbar = true
                            toolbarPosition = CGPoint(x: 20, y: 20) // how to get CGPoint relatived to TextEditor from selection
                        }
                        print("vvvv", v.characters.isEmpty)
                    })
            }
            if isShowFloatingToolbar {
                FloatingToolbarAtSelection()
                    .position(toolbarPosition)
            }
        }
    }
}

Frankly, I have no idea. I've tried the same thing on MacOS. I have an app which allows for basic editing of XML files, and I wanted to highlight the tags and comments as I type. Turns out it works, but it is really slow. It maybe my fault, though, since I refresh the whole highlighting at each keystroke, but I don’t see how to it differently (so far). Probably I should limit the highlighting to the current line, but I’m not certain how to do that.

I think the new TextEditor is still a barely discovered country.

RichText(markdown) live editor using TextEditor
 
 
Q