27 lines
840 B
Swift
27 lines
840 B
Swift
import Foundation
|
|
|
|
#if canImport(UIKit)
|
|
import UIKit
|
|
#elseif canImport(AppKit)
|
|
import AppKit
|
|
#endif
|
|
|
|
public struct PlainTextParser {
|
|
public static func parse(text: String, title: String, author: String? = nil) -> Book {
|
|
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else {
|
|
return Book(title: title, author: author, chapters: [])
|
|
}
|
|
|
|
let attributedText = AttributedStringBuilder.buildPlain(text: trimmed)
|
|
let chapter = Chapter(index: 0, title: title, text: trimmed, attributedText: attributedText)
|
|
return Book(title: title, author: author, chapters: [chapter])
|
|
}
|
|
|
|
public static func parse(url: URL) throws -> Book {
|
|
let text = try String(contentsOf: url, encoding: .utf8)
|
|
let title = url.deletingPathExtension().lastPathComponent
|
|
return parse(text: text, title: title)
|
|
}
|
|
}
|