add Markdown surpport
This commit is contained in:
@@ -256,10 +256,7 @@ struct SentenceExplanationSheet: View {
|
||||
.font(.system(size: 15))
|
||||
.foregroundColor(Theme.textSubtle)
|
||||
} else {
|
||||
Text(explanation)
|
||||
.font(.system(size: 16))
|
||||
.foregroundColor(Theme.textDark)
|
||||
.lineSpacing(5)
|
||||
MarkdownExplanationText(text: explanation)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
@@ -320,3 +317,54 @@ struct SentenceExplanationSheet: View {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MarkdownExplanationText: View {
|
||||
let text: String
|
||||
|
||||
var body: some View {
|
||||
Text(Self.attributed(from: text))
|
||||
.font(.system(size: 16))
|
||||
.foregroundColor(Theme.textDark)
|
||||
.tint(Theme.buttonBlue)
|
||||
.lineSpacing(5)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
private static func attributed(from source: String) -> AttributedString {
|
||||
let options = AttributedString.MarkdownParsingOptions(
|
||||
interpretedSyntax: .full,
|
||||
failurePolicy: .returnPartiallyParsedIfPossible
|
||||
)
|
||||
if let parsed = try? AttributedString(
|
||||
markdown: preservingLineBreaks(source),
|
||||
options: options
|
||||
) {
|
||||
return parsed
|
||||
}
|
||||
return AttributedString(source)
|
||||
}
|
||||
|
||||
private static func preservingLineBreaks(_ source: String) -> String {
|
||||
let normalized = source
|
||||
.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
.replacingOccurrences(of: "\r", with: "\n")
|
||||
var result = ""
|
||||
var inFence = false
|
||||
let lines = normalized.split(separator: "\n", omittingEmptySubsequences: false)
|
||||
for (index, rawLine) in lines.enumerated() {
|
||||
let line = String(rawLine)
|
||||
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
if trimmed.hasPrefix("```") {
|
||||
inFence.toggle()
|
||||
}
|
||||
result += line
|
||||
guard index < lines.count - 1 else { continue }
|
||||
if inFence || trimmed.isEmpty {
|
||||
result += "\n"
|
||||
} else {
|
||||
result += "\n\n"
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user