-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPriceWidget.swift
More file actions
208 lines (181 loc) · 6.88 KB
/
PriceWidget.swift
File metadata and controls
208 lines (181 loc) · 6.88 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import Charts
import SwiftUI
/// A widget that displays cryptocurrency price information with chart
struct PriceWidget: View {
/// Configuration options for the widget
var options: PriceWidgetOptions = .init()
/// Flag indicating if the widget is in editing mode
var isEditing: Bool = false
/// Callback to signal when editing should end
var onEditingEnd: (() -> Void)?
/// Price view model singleton
@StateObject private var viewModel = PriceViewModel.shared
/// Initialize the widget
init(
options: PriceWidgetOptions = PriceWidgetOptions(),
isEditing: Bool = false,
onEditingEnd: (() -> Void)? = nil
) {
self.options = options
self.isEditing = isEditing
self.onEditingEnd = onEditingEnd
}
var body: some View {
BaseWidget(
type: .price,
isEditing: isEditing,
onEditingEnd: onEditingEnd
) {
VStack(spacing: 0) {
if viewModel.isLoading && filteredPriceData.isEmpty {
WidgetContentBuilder.loadingView()
} else if viewModel.error != nil {
WidgetContentBuilder.errorView(t("widgets__price__error"))
} else {
ForEach(filteredPriceData, id: \.name) { priceData in
PriceRow(data: priceData)
.accessibilityIdentifier("PriceWidgetRow-\(priceData.name)")
}
}
if let firstPair = filteredPriceData.first {
PriceChart(
values: firstPair.pastValues,
isPositive: firstPair.change.isPositive,
period: options.selectedPeriod.rawValue
)
.frame(height: 96)
.padding(.top, 8)
}
if options.showSource {
WidgetContentBuilder.sourceRow(source: "Bitfinex.com")
.accessibilityIdentifier("PriceWidgetSource")
}
}
}
.onAppear {
fetchPriceData()
}
.onChange(of: options.selectedPairs) {
fetchPriceData()
}
.onChange(of: options.selectedPeriod) {
fetchPriceData()
}
}
private var filteredPriceData: [PriceData] {
let currentPeriodData = viewModel.getCurrentData(for: options.selectedPeriod)
let dataByPair = Dictionary(uniqueKeysWithValues: currentPeriodData.map { ($0.name, $0) })
return options.selectedPairs.compactMap { pair in
dataByPair[pair]
}
}
/// Fetch price data from view model
private func fetchPriceData() {
viewModel.fetchPriceData(pairs: options.selectedPairs, period: options.selectedPeriod)
}
}
// MARK: - Price Row Component
struct PriceRow: View {
let data: PriceData
var body: some View {
HStack {
BodySSBText(data.name, textColor: .textSecondary)
Spacer()
BodySSBText(data.change.formatted, textColor: data.change.isPositive ? .greenAccent : .redAccent)
.padding(.trailing, 8)
BodySSBText(data.price, textColor: .textPrimary)
}
.frame(minHeight: 28)
}
}
// MARK: - Price Chart Component
struct PriceChart: View {
let values: [Double]
let isPositive: Bool
let period: String
// Chart styling constants
private let lineWidth: CGFloat = 1.3
private let chartPadding: CGFloat = 4
private let cornerRadius: CGFloat = 8
private let gradientOpacityTop: CGFloat = 0.64
private let gradientOpacityBottom: CGFloat = 0.08
private var normalizedValues: [Double] {
guard values.count > 1 else { return values }
let minValue = values.min() ?? 0
let maxValue = values.max() ?? 0
let range = maxValue - minValue
guard range > 0 else { return values.map { _ in 0.5 } }
// Map to 0.15...0.85 range for more generous margins
// This prevents chart content from reaching the very edges where clipping occurs
return values.map { value in
let normalized = (value - minValue) / range
return 0.15 + (normalized * 0.7) // Maps 0-1 to 0.15-0.85
}
}
private var chartColors: (gradient: [Color], line: Color) {
if isPositive {
return (
gradient: [.greenAccent.opacity(gradientOpacityTop), .greenAccent.opacity(gradientOpacityBottom)],
line: .greenAccent
)
} else {
return (
gradient: [.redAccent.opacity(gradientOpacityTop), .redAccent.opacity(gradientOpacityBottom)],
line: .redAccent
)
}
}
var body: some View {
ZStack(alignment: .bottomLeading) {
Chart {
ForEach(Array(normalizedValues.enumerated()), id: \.offset) { index, value in
// Area fill with gradient
AreaMark(
x: .value("Index", index),
y: .value("Price", value)
)
.foregroundStyle(
LinearGradient(
colors: chartColors.gradient,
startPoint: .top,
endPoint: .bottom
)
)
.interpolationMethod(.catmullRom)
// Line on top
LineMark(
x: .value("Index", index),
y: .value("Price", value)
)
.foregroundStyle(chartColors.line)
.lineStyle(StrokeStyle(lineWidth: lineWidth))
.interpolationMethod(.catmullRom)
}
}
.chartXAxis(.hidden)
.chartYAxis(.hidden)
// Y scale domain provides buffer zone beyond data range (0.15...0.85)
// This ensures chart elements (lines, curves) don't get clipped at edges
.chartYScale(domain: 0.1 ... 0.9) // Domain slightly larger than data range for extra buffer
// Apply rounded corners only to bottom - chart content extends to edges for visible clipping
// The internal margins above prevent any actual data from being cut off
.clipShape(
.rect(
topLeadingRadius: 0,
bottomLeadingRadius: cornerRadius,
bottomTrailingRadius: cornerRadius,
topTrailingRadius: 0
)
)
// Period label
CaptionBText(period, textColor: isPositive ? .green50 : .red50)
.padding(7)
}
}
}
#Preview {
PriceWidget()
.padding()
.background(.black)
.preferredColorScheme(.dark)
}