2022-12-25 05:55:33 +00:00
|
|
|
import SwiftUI
|
|
|
|
import DesignSystem
|
2022-12-25 07:17:16 +00:00
|
|
|
import Models
|
|
|
|
import Network
|
2022-12-25 05:55:33 +00:00
|
|
|
|
|
|
|
@MainActor
|
|
|
|
class StatusEditorViewModel: ObservableObject {
|
|
|
|
@Published var statusText = NSAttributedString(string: "") {
|
|
|
|
didSet {
|
|
|
|
guard !internalUpdate else { return }
|
|
|
|
highlightMeta()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-25 07:17:16 +00:00
|
|
|
var client: Client?
|
2022-12-25 05:55:33 +00:00
|
|
|
private var internalUpdate: Bool = false
|
2022-12-25 07:17:16 +00:00
|
|
|
private var inReplyTo: Status?
|
|
|
|
|
|
|
|
init(inReplyTo: Status?) {
|
|
|
|
self.inReplyTo = inReplyTo
|
|
|
|
}
|
|
|
|
|
|
|
|
func postStatus() async -> Status? {
|
|
|
|
guard let client else { return nil }
|
|
|
|
do {
|
|
|
|
let status: Status = try await client.post(endpoint: Statuses.postStatus(status: statusText.string,
|
|
|
|
inReplyTo: inReplyTo?.id,
|
|
|
|
mediaIds: nil,
|
|
|
|
spoilerText: nil))
|
|
|
|
return status
|
|
|
|
} catch {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func insertReplyTo() {
|
|
|
|
if let inReplyTo {
|
|
|
|
statusText = .init(string: "@\(inReplyTo.account.acct) ")
|
|
|
|
}
|
|
|
|
}
|
2022-12-25 05:55:33 +00:00
|
|
|
|
|
|
|
func highlightMeta() {
|
|
|
|
let mutableString = NSMutableAttributedString(attributedString: statusText)
|
|
|
|
let hashtagPattern = "(#+[a-zA-Z0-9(_)]{1,})"
|
2022-12-25 07:17:16 +00:00
|
|
|
let mentionPattern = "(@+[a-zA-Z0-9(_).]{1,})"
|
2022-12-25 05:55:33 +00:00
|
|
|
var ranges: [NSRange] = [NSRange]()
|
|
|
|
|
2022-12-25 11:46:42 +00:00
|
|
|
do {
|
|
|
|
let hashtagRegex = try NSRegularExpression(pattern: hashtagPattern, options: [])
|
|
|
|
let mentionRegex = try NSRegularExpression(pattern: mentionPattern, options: [])
|
|
|
|
|
|
|
|
ranges = hashtagRegex.matches(in: mutableString.string,
|
|
|
|
options: [],
|
|
|
|
range: NSMakeRange(0, mutableString.string.utf16.count)).map { $0.range }
|
|
|
|
ranges.append(contentsOf: mentionRegex.matches(in: mutableString.string,
|
|
|
|
options: [],
|
|
|
|
range: NSMakeRange(0, mutableString.string.utf16.count)).map {$0.range})
|
2022-12-25 05:55:33 +00:00
|
|
|
|
2022-12-25 11:46:42 +00:00
|
|
|
for range in ranges {
|
|
|
|
mutableString.addAttributes([.foregroundColor: UIColor(Color.brand)],
|
|
|
|
range: NSRange(location: range.location, length: range.length))
|
|
|
|
}
|
|
|
|
internalUpdate = true
|
|
|
|
statusText = mutableString
|
|
|
|
internalUpdate = false
|
|
|
|
} catch {
|
|
|
|
|
2022-12-25 05:55:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|