IceCubesApp/Packages/Models/Sources/Models/Alias/HTMLString.swift

60 lines
1.5 KiB
Swift
Raw Normal View History

2022-12-17 12:37:46 +00:00
import Foundation
import HTML2Markdown
2022-12-26 07:24:55 +00:00
import SwiftSoup
2022-12-17 12:37:46 +00:00
import SwiftUI
public typealias HTMLString = String
extension HTMLString {
public var asMarkdown: String {
do {
let dom = try HTMLParser().parse(html: self)
return dom.toMarkdown()
} catch {
return self
}
}
2022-12-26 07:24:55 +00:00
public var asRawText: String {
do {
let document: Document = try SwiftSoup.parse(self)
return try document.text()
} catch {
return self
}
}
2022-12-27 06:51:44 +00:00
public func findStatusesIds(instance: String) -> [Int]? {
do {
let document: Document = try SwiftSoup.parse(self)
let links: Elements = try document.select("a")
var ids: [Int] = []
for link in links {
let href = try link.attr("href")
if href.contains(instance.lowercased()),
2022-12-27 06:51:44 +00:00
let url = URL(string: href),
let statusId = Int(url.lastPathComponent) {
ids.append(statusId)
}
}
return ids
} catch {
return nil
}
}
2022-12-17 12:37:46 +00:00
public var asSafeAttributedString: AttributedString {
do {
2022-12-22 06:00:22 +00:00
// Add space between hashtags and mentions that follow each other
let markdown = asMarkdown
.replacingOccurrences(of: ")[", with: ") [")
2022-12-20 13:35:47 +00:00
let options = AttributedString.MarkdownParsingOptions(allowsExtendedAttributes: true,
interpretedSyntax: .inlineOnlyPreservingWhitespace)
2022-12-21 16:39:48 +00:00
return try AttributedString(markdown: markdown, options: options)
2022-12-17 12:37:46 +00:00
} catch {
return AttributedString(stringLiteral: self)
}
}
}