forked from viktorstrate/mactrix
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrixImageView.swift
More file actions
70 lines (62 loc) · 2.34 KB
/
MatrixImageView.swift
File metadata and controls
70 lines (62 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import MatrixRustSDK
import SwiftUI
import UniformTypeIdentifiers
struct MatrixImageView: View {
let mediaSource: MediaSource?
let mimeType: String?
@Environment(AppState.self) private var appState
@State private var image: Image? = nil
@State private var errorMessage: String? = nil
init(mediaSource: MediaSource?, mimeType: String?) {
self.mediaSource = mediaSource
self.mimeType = mimeType
if let url = mediaSource?.url(),
let cached = MatrixClient.imageCache.object(forKey: NSString(string: url)) {
self._image = State(initialValue: Image(nsImage: cached))
}
}
@ViewBuilder
var content: some View {
if let image {
image
} else if let errorMessage {
VStack {
ContentUnavailableView("Error loading image", image: "photo.badge.exclamationmark")
Text(errorMessage)
}
} else if mediaSource == nil {
Rectangle()
.fill(Color.gray.opacity(0.3))
} else {
ProgressView {
Text("Fetching image")
}
}
}
var body: some View {
content
.task(id: mediaSource?.url(), priority: .utility) {
guard image == nil else { return }
guard let matrixClient = appState.matrixClient else {
errorMessage = "Matrix client not available"
return
}
guard let mediaSource else { return }
let cacheKey = NSString(string: mediaSource.url())
if let cached = MatrixClient.imageCache.object(forKey: cacheKey) {
image = Image(nsImage: cached)
return
}
do {
let data = try await matrixClient.client.getMediaContent(mediaSource: mediaSource)
let contentType = mimeType.flatMap { UTType(mimeType: $0) }
image = try await Image(importing: data, contentType: contentType)
if let nsImage = NSImage(data: data) {
MatrixClient.imageCache.setObject(nsImage, forKey: cacheKey)
}
} catch {
errorMessage = error.localizedDescription
}
}
}
}