struct MarkdownRenderer: View { let text: String let role: String let streaming: Bool…
- User
struct MarkdownRenderer: View { let text: String let role: String let streaming: Bool let defaultFontSize: CGFloat
code - Assistant
struct MarkdownRenderer: View { let text: String let role: String let streaming: Bool let defaultFontSize: CGFloat
@State private var parsedContent: [ParsedContent] = []
@State private var lastParsedText: String = ""
init(text: String, role: String, streaming: Bool, defaultFontSize: CGFloat? = nil) {
self.text = text
self.role = role
self.streaming = streaming
self.defaultFontSize = defaultFontSize ?? 16
}
enum ParsedContent: Identifiable {
case text(NSAttributedString)
case code(CodeBlock)
var id: UUID {
switch self {
case .text:
return UUID()
case .code(let codeBlock):
return codeBlock.id
}
}
}
struct CodeBlock: Identifiable {
let id = UUID()
let code: String
let language: String?
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
ForEach(parsedContent, id: \.id) { content in
switch content {
case .text(let attributedString):
Text(AttributedString(attributedString))
.lineSpacing(4)
.textSelection(.enabled)
case .code(let codeBlock):
CodeBlockView(code: codeBlock.code, language: codeBlock.language, defaultFontSize: defaultFontSize)
}
}
}
}
.scrollContentBackground(.hidden)
.padding(4)
.onAppear {
parseMarkdown()
}
.onChange(of: text) {
parseMarkdown()
}
}
private func parseMarkdown() {
let paragraphs = text.components(separatedBy: .newlines)
var currentCodeBlock: String?
var currentCodeLanguage: String?
var parsedContent: [ParsedContent] = []
var currentTextBlock = NSMutableAttributedString()
let codeBlockRegex = try? NSRegularExpression(pattern: "^\\s*```\\s*(.*)$", options: [])
func appendCurrentTextBlock() {
if currentTextBlock.length > 0 {
parsedContent.append(.text(currentTextBlock))
currentTextBlock = NSMutableAttributedString()
}
}
func isCodeBlockStart(_ line: String) -> Bool {
if let backtickIndex = line.firstIndex(of: "`") {
let prefix = line[..<backtickIndex]
return prefix.allSatisfy({ $0.isWhitespace }) && line[backtickIndex...].hasPrefix("```")
}
return false
}
for (index, paragraph) in paragraphs.enumerated() {
if isCodeBlockStart(paragraph) {
if currentCodeBlock == nil {
appendCurrentTextBlock()
currentCodeBlock = ""
if let match = codeBlockRegex?.firstMatch(in: paragraph, options: [], range: NSRange(location: 0, length: paragraph.utf16.count)),
let languageRange = Range(match.range(at: 1), in: paragraph) {
currentCodeLanguage = String(paragraph[languageRange]).trimmingCharacters(in: .whitespaces)
}
} else {
parsedContent.append(.code(CodeBlock(code: currentCodeBlock!, language: currentCodeLanguage)))
currentCodeBlock = nil
currentCodeLanguage = nil
}
} else if currentCodeBlock != nil {
currentCodeBlock!.append(paragraph + "\n")
} else {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 10
let attributes: [NSAttributedString.Key: Any] = [
.font: NSFont.systemFont(ofSize: defaultFontSize),
.foregroundColor: role == "assistant" ? NSColor.textColor : NSColor.secondaryLabelColor,
.paragraphStyle: paragraphStyle
]
let attributedParagraph = NSMutableAttributedString(string: paragraph, attributes: attributes)
let attributedParagraphCopy = attributedParagraph
do {
try applyMarkdownFormatting(to: attributedParagraph)
currentTextBlock.append(attributedParagraph)
} catch {
print("Error applying Markdown formatting: \(error)")
currentTextBlock.append(attributedParagraphCopy)
}
// Add a newline with custom size after each paragraph, except for the last one
if index < paragraphs.count - 1 {
let newlineStyle = NSMutableParagraphStyle()
newlineStyle.paragraphSpacing = 0
let newlineAttributes: [NSAttributedString.Key: Any] = [
.font: NSFont.systemFont(ofSize: 1), // Adjust this size to control spacing
.paragraphStyle: newlineStyle
]
// Determine the appropriate newline string
let newlineString: String
if paragraph.hasSuffix("\n") {
newlineString = ""
} else {
newlineString = "\n"
}
let attributedNewline = NSAttributedString(string: newlineString, attributes: newlineAttributes)
currentTextBlock.append(attributedNewline)
}
}
}
appendCurrentTextBlock()
self.parsedContent = parsedContent
}
private func applyMarkdownFormatting(to attributedString: NSMutableAttributedString) throws {
do {
try applyTitleFormatting(to: attributedString)
try applyBoldItalicFormatting(to: attributedString)
try applyBoldFormatting(to: attributedString)
try applyItalicFormatting(to: attributedString)
try applyStrikethroughFormatting(to: attributedString)
try applyLinkFormatting(to: attributedString)
try applyListFormatting(to: attributedString)
try applyQuoteFormatting(to: attributedString)
try applyInlineCodeFormatting(to: attributedString)
} catch {
throw error
}
}
}
struct CodeBlockView: View { let code: String let language: String? let defaultFontSize: CGFloat @State private var copied = false var body: some View { VStack(alignment: .leading, spacing: 0) { HStack { Text(language ?? "plain text") .font(.system(.caption, design: .monospaced)) .fontWeight(.semibold) Spacer() Button(action: { NSPasteboard.general.clearContents() NSPasteboard.general.setString(code, forType: .string) copied = true DispatchQueue.main.asyncAfter(deadline: .now() + 2) { copied = false } }) { HStack { Text(copied ? "Copied" : "Copy") .font(.system(.caption, design: .monospaced)) .fontWeight(.semibold) Image(systemName: copied ? "checkmark" : "doc.on.doc") .font(.system(size: copied ? 14 : 12)) } } .buttonStyle(PlainButtonStyle()) .frame(height: 16) } .padding(.horizontal) .padding(.vertical, 8) Divider() ScrollView(.horizontal, showsIndicators: false) { CodeText(code) .textSelection(.enabled) .font(.system(size: defaultFontSize-1)) } } .background(Color(NSColor.textBackgroundColor)) .cornerRadius(8) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(Color(NSColor.separatorColor), lineWidth: 1) ) .padding(0) } }So I have this code, what I want to do is actually to modify this as you see when there will be a long draw a long block of code streaming you will not show anything and then all of a sudden when it sees the second triple back quote it will end and generate the code block what I want to do is actually add the code block as soon as possible and then add content to that so you probably need to change the codeblock view so that its content can be editable. Make sure that there are multiple, there can be multiple rounds of multiple number of code blocks there and then also you probably need to update the parse markdown function to make sure you add the code block at the first instance, something like that. So figure this out. First, think, plan out, then reflect on your thinking multiple times if you need. Then you come up with the Sulu algorithm without coding it and then finally give the code. So that's the drill you have to go through.
To achieve your goal of displaying code blocks as soon as they start and updating them incrementally as more code comes in, you need to modify both the MarkdownRenderer and CodeBlockView as you've outlined. Here's how you can do it:
Overview:
Modify CodeBlock to be a class that conforms to ObservableObject:
CodeBlock instances to be observed for changes.@Published to observe changes to the code property.Modify CodeBlockView to accept an @ObservedObject CodeBlock:
code property changes.Update parseMarkdown() function:
CodeBlock immediately.code property of the CodeBlock as new lines are parsed.CodeBlock instances are reused across parses.Handle multiple code blocks:
Ensure parsedContent maintains references to the same CodeBlock instances:
Step-by-Step Implementation:
CodeBlock:class CodeBlock: ObservableObject, Identifiable {
let id = UUID()
@Published var code: String
var language: String?
init(code: String, language: String?) {
self.code = code
self.language = language
}
}
CodeBlockView:struct CodeBlockView: View {
@ObservedObject var codeBlock: CodeBlock
let defaultFontSize: CGFloat
@State private var copied = false
var body: some View {
VStack(alignment: .leading, spacing: 0) {
// Header with language and copy button
HStack {
Text(codeBlock.language ?? "plain text")
.font(.system(.caption, design: .monospaced))
.fontWeight(.semibold)
Spacer()
Button(action: {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(codeBlock.code, forType: .string)
copied = true
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
copied = false
}
}) {
HStack {
Text(copied ? "Copied" : "Copy")
.font(.system(.caption, design: .monospaced))
.fontWeight(.semibold)
Image(systemName: copied ? "checkmark" : "doc.on.doc")
.font(.system(size: copied ? 14 : 12))
}
}
.buttonStyle(PlainButtonStyle())
.frame(height: 16)
}
.padding(.horizontal)
.padding(.vertical, 8)
Divider()
// Code content
ScrollView(.horizontal, showsIndicators: false) {
Text(codeBlock.code)
.textSelection(.enabled)
.font(.system(size: defaultFontSize - 1, design: .monospaced))
.padding()
}
}
.background(Color(NSColor.textBackgroundColor))
.cornerRadius(8)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color(NSColor.separatorColor), lineWidth: 1)
)
.padding(0)
}
}
MarkdownRenderer:Explanation:
CodeBlock Modifications:
CodeBlock from a struct to a class conforming to ObservableObject.@Published to the code property to observe changes.language a variable to allow updates if the language changes.CodeBlockView Modifications:
code from a String to an @ObservedObject var codeBlock: CodeBlock.codeBlock for any changes and updates accordingly.MarkdownRenderer Modifications:
codeBlocks dictionary to keep track of code blocks using an index.parseMarkdown(), when an opening triple backtick is encountered:
CodeBlock is created (or retrieved if it already exists) and added to parsedContent immediately.currentCodeBlock is set, and subsequent lines are appended to its code.currentCodeBlock is set to nil.Handling Multiple Code Blocks:
codeBlockIndex is incremented each time a new code block starts.codeBlocks.Note: The applyMarkdownFormatting function is left for you to implement as per your existing logic.
Conclusion:
With these modifications, your MarkdownRenderer will display code blocks as soon as they are started and update them incrementally as more code comes in. This solution maintains the ability to handle multiple code blocks and ensures that the UI remains responsive and reflects the current state of the streaming content.
This approach provides a balance between efficiency and simplicity, ensuring that code blocks are only created once and updated as needed, without the overhead of complex diffing algorithms.
Feel free to adjust the code further to fit the specifics of your application, especially the markdown formatting and any additional features you might have.
Not yet included in a published release.
struct MarkdownRenderer: View {
let text: String
let role: String
let streaming: Bool
let defaultFontSize: CGFloat
@State private var parsedContent: [ParsedContent] = []
@State private var lastParsedText: String = ""
@State private var codeBlocks: [Int: CodeBlock] = [:]
init(text: String, role: String, streaming: Bool, defaultFontSize: CGFloat? = nil) {
self.text = text
self.role = role
self.streaming = streaming
self.defaultFontSize = defaultFontSize ?? 16
}
enum ParsedContent: Identifiable {
case text(NSAttributedString)
case code(CodeBlock)
var id: UUID {
switch self {
case .text:
return UUID()
case .code(let codeBlock):
return codeBlock.id
}
}
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
ForEach(parsedContent, id: \.id) { content in
switch content {
case .text(let attributedString):
Text(AttributedString(attributedString))
.lineSpacing(4)
.textSelection(.enabled)
case .code(let codeBlock):
CodeBlockView(codeBlock: codeBlock, defaultFontSize: defaultFontSize)
}
}
}
}
.scrollContentBackground(.hidden)
.padding(4)
.onAppear {
parseMarkdown()
}
.onChange(of: text) { _ in
parseMarkdown()
}
}
private func parseMarkdown() {
var codeBlockIndex = 0
var currentCodeBlock: CodeBlock? = nil
var currentCodeLanguage: String? = nil
var currentTextBlock = NSMutableAttributedString()
parsedContent = []
let paragraphs = text.components(separatedBy: .newlines)
let codeBlockRegex = try? NSRegularExpression(pattern: "^\\s*```\\s*(.*)$", options: [])
func appendCurrentTextBlock() {
if currentTextBlock.length > 0 {
parsedContent.append(.text(currentTextBlock))
currentTextBlock = NSMutableAttributedString()
}
}
func isCodeBlockStart(_ line: String) -> Bool {
if let backtickIndex = line.firstIndex(of: "`") {
let prefix = line[..<backtickIndex]
return prefix.allSatisfy { $0.isWhitespace } && line[backtickIndex...].hasPrefix("```")
}
return false
}
for (index, paragraph) in paragraphs.enumerated() {
if isCodeBlockStart(paragraph) {
if currentCodeBlock == nil {
// Start of code block
appendCurrentTextBlock()
// Extract language
if let match = codeBlockRegex?.firstMatch(in: paragraph, options: [], range: NSRange(location: 0, length: paragraph.utf16.count)),
let languageRange = Range(match.range(at: 1), in: paragraph) {
currentCodeLanguage = String(paragraph[languageRange]).trimmingCharacters(in: .whitespaces)
}
codeBlockIndex += 1
if let existingCodeBlock = codeBlocks[codeBlockIndex] {
currentCodeBlock = existingCodeBlock
// Optionally reset code if starting fresh
currentCodeBlock?.code = ""
currentCodeBlock?.language = currentCodeLanguage
} else {
currentCodeBlock = CodeBlock(code: "", language: currentCodeLanguage)
codeBlocks[codeBlockIndex] = currentCodeBlock
}
parsedContent.append(.code(currentCodeBlock!))
} else {
// End of code block
currentCodeBlock = nil
currentCodeLanguage = nil
}
} else if currentCodeBlock != nil {
// Inside code block; append line to code
currentCodeBlock!.code.append(paragraph + "\n")
} else {
// Regular text
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.paragraphSpacing = 10
let attributes: [NSAttributedString.Key: Any] = [
.font: NSFont.systemFont(ofSize: defaultFontSize),
.foregroundColor: role == "assistant" ? NSColor.textColor : NSColor.secondaryLabelColor,
.paragraphStyle: paragraphStyle
]
let attributedParagraph = NSMutableAttributedString(string: paragraph, attributes: attributes)
let attributedParagraphCopy = attributedParagraph
do {
try applyMarkdownFormatting(to: attributedParagraph)
currentTextBlock.append(attributedParagraph)
} catch {
print("Error applying Markdown formatting: \(error)")
currentTextBlock.append(attributedParagraphCopy)
}
// Add a newline with custom size after each paragraph, except for the last one
if index < paragraphs.count - 1 {
let newlineStyle = NSMutableParagraphStyle()
newlineStyle.paragraphSpacing = 0
let newlineAttributes: [NSAttributedString.Key: Any] = [
.font: NSFont.systemFont(ofSize: 1),
.paragraphStyle: newlineStyle
]
let attributedNewline = NSAttributedString(string: "\n", attributes: newlineAttributes)
currentTextBlock.append(attributedNewline)
}
}
}
appendCurrentTextBlock()
}
private func applyMarkdownFormatting(to attributedString: NSMutableAttributedString) throws {
// Implement your markdown formatting logic here
}
}