Files
InvestmentTrackerApp/PortfolioJournal/Views/Charts/ComparisonChartView.swift
T
alexandrev-tibco 86c95a9e73 Feedback TestFlight build 58 (build 59): labels, needs-update, period selector, Home masonry
De 7 comentarios de TestFlight:
- Labels de línea ilegibles (puntos 5+7): ChartLabels.showsLabel thin-out
  (máx 5 iPhone / 8 iPad, siempre primero y último). Charts multi-serie
  (Compare, Period, Year vs Year) etiquetan solo el ENDPOINT de cada serie.
  Prediction etiqueta solo el forecast final. Aplicado a Evolution, Rolling,
  Drawdown, Volatility, Compare, Period, YoY, Prediction.
- 'Needs update' en meses pasados (punto 2): MonthlyCheckInView.snapshotForViewedMonth
  — el estado es por el MES QUE SE VE (effective month de referenceDate), no
  contra la última completion global. Diff usa el snapshot de ese mes.
- Selector de periodo Performance (punto 6): slider 1..60 → picker segmentado
  consistente con el resto, opciones capadas a los meses de datos disponibles
  (availableHistoryMonths). Ya no deja pedir ventanas sin datos.
- Home iPad/Mac (feedback previo): masonry con nº de columnas según ancho
  (2 iPad / 3 Mac ancho >=1250), reparto por peso, propio ScrollView.

Pendiente de este lote: Goals no sincronizan (verificado modelo Goal CloudKit-OK
→ es el subset del partial-failure, no filtro ni esquema; necesita códigos
internos del error), paste/OCR por campo (punto 3) y swipe entre charts (punto 4).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WoScpmHdVj1aUf4rAp6hbe
2026-07-10 20:36:15 +02:00

238 lines
8.9 KiB
Swift

import SwiftUI
import Charts
struct ComparisonChartView: View {
@Environment(\.chartImageExport) private var chartImageExport
@State private var selectedDate: Date?
private static let selectionDateFormatter: DateFormatter = {
let f = DateFormatter()
f.dateFormat = "MMM yyyy"
return f
}()
@ObservedObject var viewModel: ChartsViewModel
var body: some View {
VStack(alignment: .leading, spacing: 16) {
Text("Compare Sources")
.font(.headline)
sourceSelector
Picker("", selection: $viewModel.comparisonDisplayMode) {
ForEach(ChartsViewModel.ComparisonDisplayMode.allCases) { mode in
Text(mode.rawValue).tag(mode)
}
}
.pickerStyle(.segmented)
chartContent
}
.padding()
.background(Color(.systemBackground))
.cornerRadius(AppConstants.UI.cornerRadius)
.shadow(color: .black.opacity(0.05), radius: 8, y: 2)
}
// MARK: - Source Selector
private var sourceSelector: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(Array(viewModel.comparisonAvailableSources.enumerated()), id: \.element.id) { index, source in
let isSelected = viewModel.comparisonSelectedSourceIds.contains(source.id)
let chipColor = Color(hex: ChartsViewModel.sourceColorHexesPublic[index % ChartsViewModel.sourceColorHexesPublic.count]) ?? .appPrimary
Button {
if isSelected {
viewModel.comparisonSelectedSourceIds.remove(source.id)
} else {
viewModel.comparisonSelectedSourceIds.insert(source.id)
}
} label: {
HStack(spacing: 6) {
Circle()
.fill(chipColor)
.frame(width: 8, height: 8)
Text(source.name)
.font(.caption.weight(.medium))
.lineLimit(1)
}
.padding(.horizontal, 12)
.padding(.vertical, 7)
.background(isSelected ? chipColor.opacity(0.15) : Color.gray.opacity(0.1))
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(isSelected ? chipColor : Color.clear, lineWidth: 1.5)
)
.cornerRadius(16)
}
.buttonStyle(.plain)
}
}
.padding(.vertical, 2)
}
}
// MARK: - Chart Content
@ViewBuilder
private var chartContent: some View {
if viewModel.comparisonSelectedSourceIds.isEmpty {
emptySelectionView
} else if viewModel.comparisonData.isEmpty {
noDataView
} else {
lineChart
}
}
private var emptySelectionView: some View {
VStack(spacing: 12) {
Image(systemName: "chart.xyaxis.line")
.font(.system(size: 36))
.foregroundColor(.secondary)
Text("Select 2+ sources to compare")
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
}
.frame(maxWidth: .infinity)
.frame(height: 260)
}
private var noDataView: some View {
Text("No data available for selected sources in this period.")
.font(.subheadline)
.foregroundColor(.secondary)
.multilineTextAlignment(.center)
.frame(maxWidth: .infinity)
.frame(height: 260)
}
/// Multi-series comparison: labelling every point of every series overlaps
/// badly. Instead we label only each series' END point (where it landed),
/// which is the value the comparison is actually about.
private func selectionRows(for date: Date) -> [(label: String, value: String, color: Color)] {
viewModel.comparisonData.compactMap { series in
guard let point = series.points.min(by: {
abs($0.date.timeIntervalSince(date)) < abs($1.date.timeIntervalSince(date))
}) else { return nil }
return (series.name, yAxisLabel(for: point.value), Color(hex: series.colorHex) ?? .appPrimary)
}
}
private var lineChart: some View {
VStack(spacing: 12) {
Chart {
ForEach(viewModel.comparisonData, id: \.id) { series in
let seriesColor = Color(hex: series.colorHex) ?? .appPrimary
let lastDate = series.points.last?.date
ForEach(series.points, id: \.date) { point in
LineMark(
x: .value("Date", point.date),
y: .value("Value", point.value),
series: .value("Source", series.name)
)
.foregroundStyle(seriesColor)
.interpolationMethod(.catmullRom)
PointMark(
x: .value("Date", point.date),
y: .value("Value", point.value)
)
.foregroundStyle(seriesColor)
.symbolSize(point.date == lastDate ? 30 : 14)
.annotation(position: .trailing, spacing: 2) {
if point.date == lastDate {
ChartValueBubble(text: yAxisLabel(for: point.value), color: seriesColor)
}
}
}
}
if let selectedDate {
RuleMark(x: .value("Selected", selectedDate))
.foregroundStyle(Color.secondary.opacity(0.35))
.lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3]))
.annotation(position: .top, spacing: 4) {
ChartSelectionCard(
title: Self.selectionDateFormatter.string(from: selectedDate),
rows: selectionRows(for: selectedDate)
)
}
}
}
.chartXSelection(value: $selectedDate)
.chartXAxis {
AxisMarks(values: .stride(by: .month, count: xAxisStride)) { value in
AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: [3, 3]))
.foregroundStyle(Color.secondary.opacity(0.2))
AxisValueLabel(format: .dateTime.month(.abbreviated).year(.twoDigits))
.font(.caption2)
}
}
.chartYAxis {
AxisMarks(position: .leading) { value in
AxisValueLabel {
if let d = value.as(Double.self) {
Text(yAxisLabel(for: d))
.font(.caption2)
}
}
AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5, dash: [3, 3]))
.foregroundStyle(Color.secondary.opacity(0.15))
}
}
.frame(height: 260)
.chartDrawingGroup(disabledForExport: chartImageExport)
legend
}
}
private var legend: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 16) {
ForEach(viewModel.comparisonData, id: \.id) { series in
HStack(spacing: 6) {
RoundedRectangle(cornerRadius: 2)
.fill(Color(hex: series.colorHex) ?? .appPrimary)
.frame(width: 20, height: 3)
Text(series.name)
.font(.caption)
.foregroundColor(.secondary)
}
}
}
}
}
// MARK: - Helpers
private var xAxisStride: Int {
let maxPoints = viewModel.comparisonData.map { $0.points.count }.max() ?? 0
switch maxPoints {
case ...6: return 1
case ...12: return 2
case ...24: return 3
default: return 6
}
}
private func yAxisLabel(for value: Double) -> String {
switch viewModel.comparisonDisplayMode {
case .indexed:
return String(format: "%.0f", value)
case .returnPct:
return String(format: "%.1f%%", value)
case .absolute:
return Decimal(value).shortCurrencyString
case .monthlyReturn:
return String(format: "%.1f%%", value)
}
}
}