gonzalezreal / swift-markdown-ui

Display and customize Markdown text in SwiftUI
MIT License
2.39k stars 287 forks source link

Issues with Code Highlighting when Highlighting needs Async #338

Open erik-aie opened 1 month ago

erik-aie commented 1 month ago

Description I am trying to use a from-source version of HighlightSwift to perform my code highlighting as I want a macOS / iOS / visionOS unified solution for highlighting, which this library seems closest to providing. It's based in HighlightJS though, and the calls to the JS Core are done via async, which means it's root level call to get attributed text for given code is async. CodeSyntaxHighlighter from MarkdownUI only provides a synchronous highlightCode method.

I was able to make this kind of work, it works on macOS, but it freezes on iOS and visionOS. I ripped this down to a sample project (See SyntaxHighlightFreezeDemo ) and I think I've narrowed it down to the code that interfaces with MarkdownUI, not the underlying highlighting code, which seems to work cross platform as expected.

The offending code seems to be my highlightCode function, which I had to finagle to work with the async call inside the synchronous function. Maybe there's a much better way to do this? I am getting a lot of warnings regarding Swift 6 Concurrency but I don't know of a better way to do this without getting an async call from MarkdownUI's protocol.

func highlightCode(_ content: String, language: String?) -> Text {
        guard language != nil else {
            return Text(content)
        }

        let semaphore = DispatchSemaphore(value: 0)
        var result: AttributedString?

        var detectedLanguage: HighlightLanguage? = nil
        if language == "swift" {
            detectedLanguage = .swift
        } else if language == "csharp" {
            detectedLanguage = .cSharp
        }

        Task {
            do {
                if detectedLanguage != nil {
                        result = try await syntaxHighlighter.attributedText(content, language: detectedLanguage!, colors: isDarkMode ? .dark(.github) : .light(.github))
                } else {
                    result = try await syntaxHighlighter.attributedText(content, colors: isDarkMode ? .dark(.github) : .light(.github))
                }
                print("finished")
            } catch {
                // Handle error
                print(error)
            }
            semaphore.signal()
        }
        semaphore.wait()

        return Text(result ?? AttributedString(""))
    }

What's weirder is that the function executes, and it gets to the Highlight.swift function call to create NSMutableAttributedString from the HTML data generated by HighlightJS, but my debug execution stops after that call:

        let mutableString = try NSMutableAttributedString(
            data: data,
            options: [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ],
            documentAttributes: nil
        )

Checklist

Steps to reproduce See SyntaxHighlightFreezeDemo

Expected behavior MarkdownUI performing syntax highlighting cross platform

Resulting Behavior Syntax highlighting on macOS, but a freeze on iOS and visionOS

Version information

malicious commented 1 month ago

Does the UI freeze, or does it simply not update?

When you call the code from a Task (in the freeze demo), you're updating the @State var asyncLoadedAttributedText, but SwiftUI is built to handle updates from the main thread only. You can't directly update a @State variable from a background thread (well you can, but SwiftUI gets out of sync, and updates aren't pushed correctly).

Try something like:

.task {
    let attributedText = try? await…
    DispatchQueue.main.async {
        asyncLoadedAttributedText = attributedText
    }
}

This transfers execution of that block back to the main thread, where SwiftUI can see that it happened.

Also, instead of the semaphore, try withCheckedThrowingContinuation or its siblings.

erik-aie commented 1 month ago

edit - The UI just froze, like the navigation page would freeze when trying to navigate to a sub-page containing code-blocks, and not respond to touch on other elements until the app was force closed, which was strange behavior to me, at least, and only on iOS / visionOS. macOS was fine.

Appreciate the feedback! I ended up forking the repository and changing the protocol to be async myself which fixed my issue. It also let me adjust the code block behavior on macOS to not use scroll views since the nested ScrollViews kept messing up my vertical scrolling of my implementation on macOS, but it worked fine on other targets.

Here's the commit from the fork: https://github.com/erik-aie/aie-swift-markdown-ui/commit/60c5ef7f0e741fb48d10986b86b33cfa3bcf5a8a

This issue can be closed if ultimately there isn't value to an async code styling adjustment to this protocol in the main repository

erik-aie commented 1 month ago

Does the UI freeze, or does it simply not update?

When you call the code from a Task (in the freeze demo), you're updating the @State var asyncLoadedAttributedText, but SwiftUI is built to handle updates from the main thread only. You can't directly update a @State variable from a background thread (well you can, but SwiftUI gets out of sync, and updates aren't pushed correctly).

Try something like:

.task {
    let attributedText = try? await…
    DispatchQueue.main.async {
        asyncLoadedAttributedText = attributedText
    }
}

This transfers execution of that block back to the main thread, where SwiftUI can see that it happened.

Also, instead of the semaphore, try withCheckedThrowingContinuation or its siblings.

I tried the solutions in this comment and wanted to report back on what I found:

var body: some View { VStack { //fails on iOS Markdown(demoMarkdown) .markdownCodeSyntaxHighlighter(HighlightSyntaxHighligher(isDarkMode: true)) //works cross platform Text(asyncLoadedAttributedText ?? AttributedString()) //Static Test Text("Hello World") } .padding() .task { let loadedAttributedText = try? await highlighter.syntaxHighlighter.attributedText(demoSwift, language: .swift) DispatchQueue.main.async { asyncLoadedAttributedText = loadedAttributedText } } }

- I tried to adjust my `highlightCode` implementation to use `withCheckedThrowingContinuation` but it's an async method too, so I don't think I can call it from my synchronous `highlightCode` method. At least, Xcode is giving me an error on usage of it in this adjustment of `highlightCode` from earlier:
```swift
func highlightCode(_ content: String, language: String?) -> Text {
    guard let language = language else {
        return Text(content)
    }

    let result: AttributedString

    do {
        //xcode error here
        result = try withCheckedThrowingContinuation { continuation in
            Task {
                var detectedLanguage: HighlightLanguage? = nil

                switch language {
                    case "swift": detectedLanguage = .swift
                    case "csharp": detectedLanguage = .cSharp
                    default: break
                }

                do {
                    let attributedText: AttributedString
                    if let detectedLanguage = detectedLanguage {
                        attributedText = try await syntaxHighlighter.attributedText(content, language: detectedLanguage, colors: isDarkMode ? .dark(.github) : .light(.github))
                    } else {
                        attributedText = try await syntaxHighlighter.attributedText(content, colors: isDarkMode ? .dark(.github) : .light(.github))
                    }

                    continuation.resume(returning: attributedText)
                } catch {
                    continuation.resume(throwing: error)
                }
            }
        }
    } catch {
        print(error)
        return Text(content)
    }

    return Text(result)
}