// // TrendsPaneView.swift // Museion // // #32 (S5.2): the arc — per-metric trends across unaided first drafts // over time. The pane answers "am I getting better," never "is this // draft good": points are CAPTURES (pass-invocation moments on eligible // pieces, #31), not drafts-as-they-are-now, and only pieces whose // frontmatter carries the stats keys appear — the keys grow only at // capture time, so edited text can never feed the view. Rides // PostsModel's watched scan; no scan of its own. // import Charts import SwiftUI struct TrendsPaneView: View { var model: PostsModel /// The captured pieces, oldest capture first — the arc's x-axis. /// Same-second twins (cancel one pass, start another) tie-break on /// title so the verdict's first→last stays deterministic — `sorted` /// is not stable. private var series: [Post] { let captured = model.posts.compactMap { post in post.firstDraftStats.map { (post: post, at: $0.captured) } } let ordered = captured.sorted { lhs, rhs in if lhs.at != rhs.at { return lhs.at < rhs.at } return lhs.post.title.localizedStandardCompare(rhs.post.title) == .orderedAscending } return ordered.map(\.post) } var body: some View { VStack(spacing: 0) { PaneHeader(title: "Trends") { Text(series.count == 1 ? "1 capture" : "\(series.count) captures") .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) } if series.isEmpty { emptyState } else { // r5 (mercury#5/27/28, sol#10): the grid FILLS the pane's height // — charts take the leftover height (≥130 floor), killing the // bottom-third void; plots read ~3:1, not 5.3:1. The height // measurement must sit OUTSIDE the ScrollView (it proposes // unbounded height); scroll engages only when floors overflow. // ponytail: no aspect cap — cap at width/3 if lanky plots annoy. GeometryReader { geo in ScrollView { LazyVGrid( columns: [ GridItem(.flexible(), spacing: 12, alignment: .top), GridItem(.flexible(), spacing: 12, alignment: .top), ], spacing: 12, ) { ForEach(TrendMetric.allCases, id: \.self) { metric in MetricCard(metric: metric, series: series, chartHeight: filledChartHeight(geo.size.height)) } } .padding(14) .frame(minHeight: geo.size.height, alignment: .top) } } } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(DesignTokens.background) } /// The Learnings-posture empty state: name how the data arrives. private var emptyState: some View { VStack(spacing: 8) { Text("No measurements yet") .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) Text( "Stats capture the moment a Pass first meets an unaided draft — run Pass 1 or Pass 2 " + "on a writer piece still in First Draft, and the arc starts here.", ) .font(.callout) .foregroundStyle(DesignTokens.muted) .multilineTextAlignment(.center) } .padding(38) .frame(maxWidth: .infinity, maxHeight: .infinity) } } private extension TrendsPaneView { /// (paneHeight − grid padding 28 − row gap 12) / 2, minus each card's /// fixed chrome (~136: padding 28 + title + spacings + readout + /// explain); floored at 130 for short windows. r7 (argon#16/26/27, /// sol#35, mercury#53): the chrome estimate is deliberately GENEROUS — /// the r6 120 left the grid at the viewport's exact edge, where a /// hair of rounding tipped it into a scrollbar. Plot heights yield /// so all four cards + the symmetric 14pt top/bottom padding fit /// with slack. r8 (sol#4, mercury#14): ×0.87 — a modest ~13% plot /// reduction so the thin variance bands sit in less empty frame; /// y-domains stay FIXED (final). func filledChartHeight(_ paneHeight: CGFloat) -> CGFloat { max(130, ((paneHeight - 28 - 12) / 2 - 136) * 0.87) } } /// One metric's display facts: name, value rail, better-direction, and a /// fixed y-domain so single captures stay visible and scales read the /// same across sessions. Pure — pinned in TrendViewTests. nonisolated enum TrendMetric: CaseIterable { case burstiness case typeTokenRatio case sentenceVariation case trigramRepetition var title: String { switch self { case .burstiness: "Burstiness" case .typeTokenRatio: "Type-Token Ratio" case .sentenceVariation: "Sentence Variation" case .trigramRepetition: "Trigram Repetition" } } /// One plain-language line per term (#32 follow-up): the card's /// always-visible gloss, below the chart. Names the metric's grain /// and repeats which direction reads better. var explain: String { switch self { case .burstiness: "The swing between short and long sentences — higher means a livelier rhythm." case .typeTokenRatio: "Unique words ÷ total words — higher means a richer vocabulary." case .sentenceVariation: "How much sentence length changes from sentence to sentence — higher means more variety." case .trigramRepetition: "How often the same three-word runs repeat — lower means less recycled phrasing." } } /// The honest per-metric hint: repetition is the one metric where /// rising reads worse. var higherIsBetter: Bool { self != .trigramRepetition } func value(of stats: DraftStats) -> Double { switch self { case .burstiness: stats.burstiness case .typeTokenRatio: stats.typeTokenRatio case .sentenceVariation: stats.sentenceVariation case .trigramRepetition: stats.trigramRepetition } } /// Fixed where the metric has a natural range; sentence variation is /// unbounded, so it scales to 1.2× the observed peak (floor 1) — a /// single dot never flattens into an empty axis. func domain(peak: Double) -> ClosedRange { switch self { case .burstiness: -1 ... 1 case .typeTokenRatio, .trigramRepetition: 0 ... 1 case .sentenceVariation: 0 ... max(peak * 1.2, 1) } } /// One tick convention across all four cards (ui-polish r2): the /// domain's two bounds plus its midpoint — the zero line always /// reads on nonnegative domains (0…1 cards showed only 1.0/0.5), /// and the symmetric burstiness axis keeps its center. Exactly /// three labels per card. func ticks(peak: Double) -> [Double] { let domain = domain(peak: peak) return [ domain.lowerBound, (domain.lowerBound + domain.upperBound) / 2, domain.upperBound, ] } /// First capture vs last: the pane's whole judgment, one honest word /// (#32 AC — the arc, never a draft grade). Deltas inside the noise /// band read steady: ±0.01 at three-decimal grain. func verdict(first: Double, last: Double) -> TrendDirection { let tolerance = 0.01 let delta = (last - first) * (higherIsBetter ? 1 : -1) if delta > tolerance { return .improving } if delta < -tolerance { return .slipping } return .steady } } /// The first→last read on one metric. Not a grade — a direction. The /// rawValue IS the display word; polarity (which way reads better) /// rides the card-header badge alone (↑/↓ better) — never an arrow in /// the summary line (ui-polish r2: a value arrow there conflated /// rise/fall with better/worse on ↓-better metrics). nonisolated enum TrendDirection: String { case improving case steady case slipping } /// One metric's card: the chart plus the first→last readout that answers /// "am I getting better." One capture shows its point with no verdict — /// an arc needs two. private struct MetricCard: View { let metric: TrendMetric let series: [Post] /// r5: the pane hands each chart the height its grid row has left. let chartHeight: CGFloat private struct MetricPoint { let captured: Date let value: Double } /// Offset-keyed chart identity — two pieces can capture in the same /// second (cancel one pass, start another); `id: \.self` would drop /// the twin point silently. private var marks: some ChartContent { ForEach(Array(points.enumerated()), id: \.offset) { _, point in LineMark( x: .value("Captured", point.captured), y: .value(metric.title, point.value), ) .foregroundStyle(DesignTokens.accent) PointMark( x: .value("Captured", point.captured), y: .value(metric.title, point.value), ) .foregroundStyle(DesignTokens.accent) } } private var points: [MetricPoint] { series.compactMap { post in post.firstDraftStats.map { MetricPoint(captured: $0.captured, value: metric.value(of: $0.stats)) } } } /// The observed peak — feeds the sentence-variation domain + ticks. private var peak: Double { points.map(\.value).max() ?? 0 } /// Distinct capture dates, oldest first — the x-axis ticks. The /// captures ARE the data points; weekly grid ticks that miss them /// are noise (ui-polish r2). A same-day pair shares one label /// instead of overprinting. private var tickDates: [Date] { var seen = Set() return points.map(\.captured).filter { seen.insert($0).inserted } } var body: some View { // r7 (ALL SEATS regression): the '−1…1 divergent' caption is // DELETED — it rendered outside the card in the grid gutter (its // extra height is what made the row gap read ~2.5× the column // gap and tipped the grid into a scrollbar), and the burstiness // axis labels already carry the range (1.0 / 0.0 / −1.0). card } private var card: some View { VStack(alignment: .leading, spacing: 10) { HStack(alignment: .firstTextBaseline) { Text(metric.title) .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) .lineLimit(1) Spacer() // r6 (sol#38): the badge carries direction ONLY. r7: the // '−1…1 divergent' note is gone — the axis labels carry it. Text(metric.higherIsBetter ? "↑ better" : "↓ better") .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) } Chart { marks } .chartYScale(domain: metric.domain(peak: peak)) .chartXAxis { // One centered label under each actual capture date — // capture-aligned, "Oct 5" (month first, POSIX-locked so a // European locale never renders "5. Oct"). r4: collisionResolution // .disabled + centered — the default resolver both nudged labels // ~4px off their points and DROPPED the compressed // final-interval capture's date entirely (mercury#35/36); // every capture gets its date now. r6 (argon#47) VERIFIED: // AxisMarks(values:) places each mark at the capture instant // and `centered: true` centers the label on it — ticks sit // exactly under their capture dates (same-day twins share // one label by design, tickDates dedupes). // ponytail: tightly-spaced captures can overprint — day-only // labels or hairline leaders if a dense arc ever needs them. AxisMarks(values: tickDates) { value in AxisValueLabel(centered: true, collisionResolution: .disabled) { if let date = value.as(Date.self) { Text(Self.dateFmt(date)) // r8 (sol#4, mercury#14): axis/summary one // rung up — 11 → 12. .font(.system(size: 12, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) } } } } .chartYAxis { // Value labels live OUTSIDE the plot, in a dedicated // trailing axis gutter, vertically centered on their // gridlines — in-plot labels collided with the series and // end markers (Burstiness near 0.0, Sentence Variation // near 0.5). One tick convention: domain bounds + midpoint. AxisMarks(position: .trailing, values: metric.ticks(peak: peak)) { value in AxisGridLine() // r6 (sol#21, mercury#55): one contrast step up from // border — quiet, but readable against the surface. .foregroundStyle(DesignTokens.muted.opacity(0.35)) AxisValueLabel { if let axisValue = value.as(Double.self) { // FIXED-width gutter, r4 (sol#8, mercury#34/60). // r6 (sol#39): the text is RIGHT-aligned — mono // %.1f keeps the fractional width constant, so // '−1.0' / '0.0' / '1.0' share one decimal // column, and the glyphs move AWAY from the plot // (more marker daylight), not toward it. Text(Self.axisFmt(axisValue)) // r8 (sol#4, mercury#14): one rung up — // 11 → 12 (36pt gutter still fits '−1.0'). .font(.system(size: 12, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .frame(width: 36, alignment: .trailing) } } } } // r6 (mercury#28/55): 30pt trailing breathing room inside the // plot — the r5 shots still showed near-touches between the // last marker and the '0.5' label; one more touch of daylight. .chartPlotStyle { $0.padding(.trailing, 30) } .frame(height: chartHeight) .accessibilityLabel("\(metric.title) across \(points.count) captures") readout // #32 follow-up: the term's always-visible gloss — prose voice, // distinct from the mono data lines above it. Fixed two-line // frame so wrapping never grows the card. Text(metric.explain) .font(.system(size: 11)) .foregroundStyle(DesignTokens.muted) .lineLimit(2) .truncationMode(.tail) .frame(maxWidth: .infinity, minHeight: 28, alignment: .topLeading) } .padding(14) .background(DesignTokens.surface) .overlay( RoundedRectangle(cornerRadius: DesignTokens.radius) // r6 (sol#21, mercury#55): one contrast step up from // border — same step as the gridlines, quiet but present. .strokeBorder(DesignTokens.muted.opacity(0.35)), ) } /// mono-12 first→last line, typographically weighted (r5): numbers in /// primary ink, the verdict word one weight heavier. Polarity rides the /// card-header badge (↑/↓ better) alone — an arrow here conflated /// value direction with quality (ui-polish r2: "0.052 → 0.093 · ↓ /// slipping" on the one metric where rising reads worse). /// r8 (sol#4, mercury#14): one rung up — 11 → 12. @ViewBuilder private var readout: some View { let values = points.map(\.value) if values.count >= 2 { let verdict = metric.verdict(first: values.first!, last: values.last!) // r5 (argon#18): emphasis — numbers primary ink, verdict one // weight heavier; NO new hues (polarity stays on the badge). Group { Text("\(Self.fmt(values.first!)) → \(Self.fmt(values.last!))") .foregroundStyle(DesignTokens.foreground) + Text(" · ") .foregroundStyle(DesignTokens.muted) + Text(verdict.rawValue) .fontWeight(.medium) .foregroundStyle(DesignTokens.foreground) } .font(.system(size: 12, design: DesignTokens.mono)) .lineLimit(1) } else if let only = values.first { Text("\(Self.fmt(only)) · one capture") .font(.system(size: 12, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .lineLimit(1) } } /// The store's %.3f grain — a period, never a localized comma. private static func fmt(_ value: Double) -> String { String(format: "%.3f", value) } /// Axis labels at %.1f — the same period-only convention as the readout. private static func axisFmt(_ value: Double) -> String { String(format: "%.1f", value) } /// "Oct 5" — month first, day without a leading zero. POSIX-locked: /// the machine's European locale never swaps in "5. Oct" (per-access /// formatter, the repo's no-static convention). private static func dateFmt(_ date: Date) -> String { let fmt = DateFormatter() fmt.locale = Locale(identifier: "en_US_POSIX") fmt.dateFormat = "MMM d" return fmt.string(from: date) } }