2020-07-13 03:09:22 +00:00
|
|
|
//
|
|
|
|
// Document.swift
|
|
|
|
// GeminiFormat
|
|
|
|
//
|
|
|
|
// Created by Shadowfacts on 7/12/20.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
2020-07-13 03:25:20 +00:00
|
|
|
public struct Document {
|
|
|
|
public let url: URL
|
|
|
|
public var lines: [Line]
|
2020-07-13 03:09:22 +00:00
|
|
|
|
2020-07-13 03:52:38 +00:00
|
|
|
public init(url: URL, lines: [Line] = []) {
|
2020-07-13 03:09:22 +00:00
|
|
|
self.url = url
|
|
|
|
self.lines = lines
|
|
|
|
}
|
2020-07-13 04:02:53 +00:00
|
|
|
|
|
|
|
/// Renders this Document to Gemini formatted text. This is not guaranteed to be the original input text.
|
|
|
|
public func toGeminiText() -> String {
|
|
|
|
// todo: should this be \r\n
|
|
|
|
return lines.map { $0.geminiText() }.joined(separator: "\n")
|
|
|
|
}
|
2020-12-17 04:01:44 +00:00
|
|
|
|
|
|
|
public var title: String? {
|
|
|
|
for case let .heading(text, level: _) in lines {
|
|
|
|
return text
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2020-07-13 03:09:22 +00:00
|
|
|
}
|
|
|
|
|
2020-07-13 03:25:20 +00:00
|
|
|
public extension Document {
|
2020-07-13 03:09:22 +00:00
|
|
|
enum Line: Equatable {
|
|
|
|
case text(String)
|
|
|
|
case link(URL, text: String?)
|
2020-07-13 03:52:38 +00:00
|
|
|
case preformattedToggle(alt: String?)
|
|
|
|
case preformattedText(String)
|
2020-07-13 03:09:22 +00:00
|
|
|
case heading(String, level: HeadingLevel)
|
|
|
|
case unorderedListItem(String)
|
|
|
|
case quote(String)
|
2020-07-13 04:02:53 +00:00
|
|
|
|
|
|
|
func geminiText() -> String {
|
|
|
|
switch self {
|
|
|
|
case let .text(text):
|
|
|
|
return text
|
|
|
|
case let .link(url, text: text):
|
|
|
|
if let text = text {
|
|
|
|
return "=> \(url.absoluteString) \(text)"
|
|
|
|
} else {
|
|
|
|
return "=> \(url.absoluteString)"
|
|
|
|
}
|
|
|
|
case let .preformattedToggle(alt: alt):
|
|
|
|
if let alt = alt {
|
|
|
|
return "```\(alt)"
|
|
|
|
} else {
|
|
|
|
return "```"
|
|
|
|
}
|
|
|
|
case let .preformattedText(text):
|
|
|
|
return text
|
|
|
|
case let .heading(text, level: level):
|
|
|
|
return "\(level.geminiText) \(text)"
|
|
|
|
case let .unorderedListItem(text):
|
|
|
|
return "* \(text)"
|
|
|
|
case let .quote(text):
|
|
|
|
return "> \(text)"
|
|
|
|
}
|
|
|
|
}
|
2020-07-13 03:09:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-13 03:25:20 +00:00
|
|
|
public extension Document {
|
2020-07-13 03:09:22 +00:00
|
|
|
enum HeadingLevel: Int {
|
|
|
|
case h1 = 1, h2 = 2, h3 = 3
|
2020-07-13 04:02:53 +00:00
|
|
|
|
|
|
|
var geminiText: String {
|
|
|
|
switch self {
|
|
|
|
case .h1:
|
|
|
|
return "#"
|
|
|
|
case .h2:
|
|
|
|
return "##"
|
|
|
|
case .h3:
|
|
|
|
return "###"
|
|
|
|
}
|
|
|
|
}
|
2020-07-13 03:09:22 +00:00
|
|
|
}
|
|
|
|
}
|