IceCubesApp/IceCubesAppWidgetsExtension/AccountWidget/AccountWidget.swift

75 lines
2.1 KiB
Swift
Raw Permalink Normal View History

2024-05-17 12:22:00 +00:00
import DesignSystem
import Models
import Network
import SwiftUI
import Timeline
import WidgetKit
struct AccountWidgetProvider: AppIntentTimelineProvider {
func placeholder(in _: Context) -> AccountWidgetEntry {
.init(date: Date(), account: .placeholder(), avatar: nil)
}
2024-10-28 09:57:48 +00:00
func snapshot(for configuration: AccountWidgetConfiguration, in _: Context) async
-> AccountWidgetEntry
{
2024-05-17 12:22:00 +00:00
let account = await fetchAccount(configuration: configuration)
return .init(date: Date(), account: account, avatar: nil)
}
2024-10-28 09:57:48 +00:00
func timeline(for configuration: AccountWidgetConfiguration, in _: Context) async -> Timeline<
AccountWidgetEntry
> {
2024-05-17 12:22:00 +00:00
let account = await fetchAccount(configuration: configuration)
let images = try? await loadImages(urls: [account.avatar])
2024-10-28 09:57:48 +00:00
return .init(
entries: [.init(date: Date(), account: account, avatar: images?.first?.value)],
policy: .atEnd)
2024-05-17 12:22:00 +00:00
}
2024-08-01 06:58:54 +00:00
2024-05-17 12:22:00 +00:00
private func fetchAccount(configuration: AccountWidgetConfiguration) async -> Account {
guard let account = configuration.account else {
return .placeholder()
}
2024-10-28 09:57:48 +00:00
let client = Client(
server: account.account.server,
oauthToken: account.account.oauthToken)
2024-05-17 12:22:00 +00:00
do {
let account: Account = try await client.get(endpoint: Accounts.verifyCredentials)
return account
} catch {
return .placeholder()
}
}
}
struct AccountWidgetEntry: TimelineEntry {
let date: Date
let account: Account
let avatar: UIImage?
}
struct AccountWidget: Widget {
let kind: String = "AccountWidget"
var body: some WidgetConfiguration {
2024-10-28 09:57:48 +00:00
AppIntentConfiguration(
kind: kind,
intent: AccountWidgetConfiguration.self,
provider: AccountWidgetProvider()
) { entry in
2024-05-17 12:22:00 +00:00
AccountWidgetView(entry: entry)
.containerBackground(Color("WidgetBackground").gradient, for: .widget)
}
.configurationDisplayName("Account")
.description("Show information about your Mastodon account")
.supportedFamilies([.systemSmall])
}
}
#Preview(as: .systemSmall) {
AccountWidget()
} timeline: {
AccountWidgetEntry(date: Date(), account: .placeholder(), avatar: nil)
}