63 lines
2.6 KiB
Swift
63 lines
2.6 KiB
Swift
import Foundation
|
|
|
|
public enum MarkdownSpeech {
|
|
/// The prose of a document for a voice to read: one sentence per line, markup, URLs, code blocks and rules left out.
|
|
/// A line without closing punctuation gets a full stop, so the voice pauses between blocks.
|
|
public static func plainText(_ blocks: [MarkdownBlock]) -> String {
|
|
lines(blocks).joined(separator: "\n")
|
|
}
|
|
|
|
/// The text with each `$` that is not before a digit written as "dollar", so the voice does not say "dollar sign".
|
|
/// A `$` before a digit stays: the voice reads `$5` as "five dollars".
|
|
public static func spoken(_ text: String) -> String {
|
|
let characters = Array(text)
|
|
var result = ""
|
|
for (index, character) in characters.enumerated() {
|
|
let next = index + 1 < characters.count ? characters[index + 1] : nil
|
|
guard character == "$", !(next?.isNumber ?? false) else {
|
|
result.append(character)
|
|
continue
|
|
}
|
|
if let last = result.last, !last.isWhitespace { result.append(" ") }
|
|
result.append("dollar")
|
|
if let next, !next.isWhitespace { result.append(" ") }
|
|
}
|
|
return result
|
|
}
|
|
|
|
private static func lines(_ blocks: [MarkdownBlock]) -> [String] {
|
|
blocks.flatMap { block -> [String] in
|
|
switch block {
|
|
case let .heading(_, content), let .paragraph(content): [sentence(content)]
|
|
case let .quote(inner): lines(inner)
|
|
case let .list(_, items): items.map(sentence)
|
|
case let .table(header, _, rows):
|
|
([header] + rows).map { cells in sentence(cells.map(text).filter { !$0.isEmpty }.joined(separator: ", ")) }
|
|
case .code, .rule: []
|
|
}
|
|
}
|
|
.filter { !$0.isEmpty }
|
|
}
|
|
|
|
private static func sentence(_ inlines: [MarkdownInline]) -> String {
|
|
sentence(text(inlines))
|
|
}
|
|
|
|
private static func sentence(_ text: String) -> String {
|
|
let trimmed = text.split(whereSeparator: \.isWhitespace).joined(separator: " ")
|
|
guard let last = trimmed.last else { return "" }
|
|
return ".!?:;".contains(last) ? trimmed : trimmed + "."
|
|
}
|
|
|
|
private static func text(_ inlines: [MarkdownInline]) -> String {
|
|
inlines.map { inline in
|
|
switch inline {
|
|
case let .text(text), let .code(text): text
|
|
case let .strong(inner), let .emphasis(inner), let .strikethrough(inner), let .link(inner, _, _): text(inner)
|
|
case let .image(alt, _, _): alt
|
|
}
|
|
}
|
|
.joined()
|
|
}
|
|
}
|