← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Views/Home/HomeView.swift (21697B)

1import CoreData
2import OSLog
3import SwiftUI
4import UserNotifications
5
6/// The app's main screen: reports by day, newest first, and the button that
7/// starts one.
8struct HomeView: View {
9    @Environment(\.reportStore) private var store
10    @Environment(PromptInbox.self) private var inbox: PromptInbox?
11    @State private var survey: SurveyRequest?
12    @State private var describer = ReportDescriber()
13    /// The reports opened from the timeline.
14    @State private var path: [ReportRoute] =
15        DemoSeed.screen == .detail ? [ReportRoute(id: DemoSeed.detailReportID)] : []
16
17    private let logger = Logger(subsystem: "net.inqk.reportage", category: "Home")
18
19    var body: some View {
20        NavigationStack(path: $path) {
21            ReportList(
22                describer: describer,
23                onStart: { kind in survey = SurveyRequest(kind: kind) },
24                onQuickLog: quickLog,
25                onOpen: { id in path.append(ReportRoute(id: id)) }
26            )
27            .toolbar(.hidden, for: .navigationBar)
28            .navigationDestination(for: ReportRoute.self) { route in
29                ReportDetailView(id: route.id, describer: describer) { id, kind in
30                    survey = .edit(id, kind: kind)
31                }
32            }
33        }
34        .sheet(item: $survey, onDismiss: reload) { request in
35            SurveySheet(request: request)
36        }
37        .task {
38            await describer.load(from: store)
39            // Earlier builds badged the icon with the number of instant
40            // reports; Reportage no longer badges, so clear what's left.
41            try? await UNUserNotificationCenter.current().setBadgeCount(0)
42        }
43        .onChange(of: inbox?.survey?.id, initial: true) { openPrompt() }
44        // Questions and vocabulary edited in Settings change how reports read.
45        .task {
46            for await _ in NotificationCenter.default.notifications(named: .summaryLookupChanged) {
47                await describer.load(from: store)
48                // The demo's survey opens once its reports are seeded, so
49                // their answers are suggested, at 9:41 to match the status
50                // bar.
51                if DemoSeed.screen == .survey, survey == nil {
52                    let date = Calendar.current.date(bySettingHour: 9, minute: 41, second: 0, of: Date()) ?? Date()
53                    survey = SurveyRequest(kind: .manual, date: date)
54                }
55            }
56        }
57    }
58
59    private func reload() {
60        openPrompt()
61        Task {
62            await describer.load(from: store)
63            await PromptScheduler().refresh()
64        }
65    }
66
67    /// Opens the survey for a tapped prompt, once nothing else is open, so
68    /// a survey in progress isn't lost.
69    private func openPrompt() {
70        guard survey == nil, let request = inbox?.take() else { return }
71        survey = request
72    }
73
74    /// Logs this moment with its context and no answers. It goes straight
75    /// into the timeline, where it can be filled in or left as it is.
76    private func quickLog() {
77        guard let store else { return }
78        Task {
79            do {
80                try await PassiveLog(store: store).log(trigger: .app)
81            } catch {
82                logger.error("Couldn't file an instant report: \(error)")
83            }
84            await PromptScheduler().refresh()
85        }
86    }
87}
88
89/// Describes reports for the list, using token names and question kinds
90/// loaded once rather than per row.
91@MainActor
92@Observable
93final class ReportDescriber {
94    private(set) var lookup = SummaryLookup()
95
96    func load(from store: ReportStore?) async {
97        guard let store, let lookup = try? await store.summaryLookup() else { return }
98        self.lookup = lookup
99    }
100
101    func summary(of report: ReportEntity) -> ReportSummary {
102        let responses = (report.responses as? Set<ResponseEntity> ?? [])
103            .sorted { $0.order < $1.order }
104            .compactMap { try? $0.response() }
105        let context = report.context.flatMap { try? ModelCoding.decode(Context.self, from: $0) }
106        return ReportSummary(
107            responses: responses, context: context ?? Context(),
108            health: try? report.health?.record().health,
109            kind: report.kind.flatMap(ReportKind.init), lookup: lookup)
110    }
111}
112
113extension ReportEntity {
114    /// The calendar day of the report in the device's time zone, for grouping
115    /// the list. Grouping by each report's own zone would put reports out of
116    /// order around midnight when the user changes zones, which a sectioned
117    /// fetch can't show.
118    @objc var dayKey: String {
119        guard let date else { return "" }
120        let components = Calendar.current.dateComponents([.year, .month, .day], from: date)
121        return String(
122            format: "%04d-%02d-%02d", components.year ?? 0, components.month ?? 0,
123            components.day ?? 0)
124    }
125}
126
127/// Works out how far back the timeline reaches, and reaches further as it's
128/// scrolled to its end.
129struct ReportList: View {
130    let describer: ReportDescriber
131    let onStart: (ReportKind) -> Void
132    let onQuickLog: () -> Void
133    /// Opens a report's details.
134    let onOpen: (UUID) -> Void
135
136    @Environment(\.reportStore) private var store
137    /// How many of the newest reports the list covers. Grouping into days
138    /// loads every report the fetch covers, and regroups them all whenever
139    /// one changes, so the list starts with the newest and reaches further
140    /// back as it's scrolled to its end.
141    @State private var reach = Self.page
142    @State private var start = ListStart.unknown
143
144    private static let page = 300
145    private static let morePage = 500
146
147    var body: some View {
148        ReportDays(
149            start: start,
150            describer: describer,
151            onStart: onStart,
152            onQuickLog: onQuickLog,
153            onOpen: onOpen,
154            onReachEnd: { reach += Self.morePage }
155        )
156        .task(id: reach) { await widen() }
157    }
158
159    private func widen() async {
160        guard let store, let date = try? await store.listStart(covering: reach) else {
161            start = .all
162            return
163        }
164        start = .date(date)
165    }
166}
167
168private enum ListStart: Hashable {
169    /// Not worked out yet: the list is empty until it is.
170    case unknown
171    /// Reports from this date on, with older ones beyond.
172    case date(Date)
173    /// Every report.
174    case all
175
176    var predicate: NSPredicate? {
177        switch self {
178        case .unknown: NSPredicate(value: false)
179        case .date(let date): NSPredicate(format: "date >= %@", date as NSDate)
180        case .all: nil
181        }
182    }
183}
184
185/// The timeline's reports, grouped by day. The fetch is built from `start`
186/// each time the view is, rather than changed after the fact, so a new
187/// copy of the view never brings back an empty fetch.
188private struct ReportDays: View {
189    let start: ListStart
190    let describer: ReportDescriber
191    let onStart: (ReportKind) -> Void
192    let onQuickLog: () -> Void
193    let onOpen: (UUID) -> Void
194    /// Reaches further back once the list is scrolled to its end.
195    let onReachEnd: () -> Void
196
197    @SectionedFetchRequest private var days: SectionedFetchResults<String, ReportEntity>
198    /// The current day, for marking its header. A list left open overnight
199    /// isn't redrawn on its own, so this moves on at midnight, or when the
200    /// app returns after one.
201    @State private var today = Date()
202
203    init(
204        start: ListStart, describer: ReportDescriber,
205        onStart: @escaping (ReportKind) -> Void, onQuickLog: @escaping () -> Void,
206        onOpen: @escaping (UUID) -> Void, onReachEnd: @escaping () -> Void
207    ) {
208        self.start = start
209        self.describer = describer
210        self.onStart = onStart
211        self.onQuickLog = onQuickLog
212        self.onOpen = onOpen
213        self.onReachEnd = onReachEnd
214        _days = SectionedFetchRequest(
215            fetchRequest: Self.request(predicate: start.predicate),
216            sectionIdentifier: \ReportEntity.dayKey)
217    }
218
219    private static func request(predicate: NSPredicate?) -> NSFetchRequest<ReportEntity> {
220        let request = ReportEntity.fetchRequest()
221        request.predicate = predicate
222        request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
223        request.fetchBatchSize = 40
224        request.relationshipKeyPathsForPrefetching = ["responses", "health"]
225        return request
226    }
227
228    var body: some View {
229        List {
230            HomeHeader(onStart: onStart, onQuickLog: onQuickLog)
231                .listRowInsets(EdgeInsets(top: 8, leading: Theme.margin, bottom: 20, trailing: Theme.margin))
232                .listRowBackground(Theme.paper)
233                .listRowSeparatorTint(Theme.ink)
234                .listRowSeparator(.hidden, edges: .top)
235            if days.isEmpty && start == .all {
236                EmptyReports()
237                    .listRowInsets(EdgeInsets(top: 0, leading: Theme.margin, bottom: 0, trailing: Theme.margin))
238                    .listRowBackground(Theme.paper)
239                    .listRowSeparator(.hidden)
240            }
241            ForEach(days) { day in
242                Section {
243                    ForEach(day) { report in
244                        row(for: report)
245                            .listRowInsets(EdgeInsets(top: Theme.rowPadding, leading: Theme.margin, bottom: Theme.rowPadding, trailing: Theme.margin))
246                            .listRowBackground(Theme.paper)
247                            .listRowSeparatorTint(Theme.rule)
248                    }
249                } header: {
250                    DayHeader(date: day.first?.date, today: today)
251                }
252            }
253            if case .date = start {
254                // Drawn only once the list is scrolled near its end.
255                ProgressView()
256                    .frame(maxWidth: .infinity)
257                    .listRowBackground(Theme.paper)
258                    .listRowSeparator(.hidden)
259                    // A new row each time the list reaches further, so it
260                    // keeps reaching while its end is still in view.
261                    .id(start)
262                    .onAppear(perform: onReachEnd)
263            }
264        }
265        .listStyle(.plain)
266        .scrollContentBackground(.hidden)
267        .tabBarClearance()
268        .background(Theme.paper)
269        .task {
270            for await _ in NotificationCenter.default.notifications(named: UIApplication.significantTimeChangeNotification) {
271                today = Date()
272            }
273        }
274    }
275
276    /// A report is tapped to see it in full, where it can be edited or
277    /// answered.
278    @ViewBuilder
279    private func row(for report: ReportEntity) -> some View {
280        if let id = report.id {
281            Button {
282                onOpen(id)
283            } label: {
284                ReportRow(report: report, describer: describer)
285                    .contentShape(.rect)
286            }
287            .buttonStyle(.plain)
288            .accessibilityHint(Text("Shows this report in full"))
289        } else {
290            ReportRow(report: report, describer: describer)
291        }
292    }
293}
294
295struct HomeHeader: View {
296    let onStart: (ReportKind) -> Void
297    let onQuickLog: () -> Void
298
299    var body: some View {
300        HStack(alignment: .center) {
301            // The app's name is a wordmark: italic, with a full stop in the
302            // mark colour, where other screen titles are upright. VoiceOver
303            // reads the name without the stop.
304            Text("Reportage\(Text(".").foregroundStyle(Theme.mark))", comment: "The app's name in the timeline's title, with a coloured full stop")
305                .screenTitle()
306                .accessibilityLabel(Text("Reportage"))
307            Spacer()
308            HStack(spacing: Theme.itemGap) {
309                QuickLogButton(action: onQuickLog)
310                NewReportMenu(onStart: onStart)
311            }
312        }
313    }
314}
315
316/// Logs the moment without a survey: a bolt, ink-outlined beside the filled
317/// + so the two read as a pair. Nothing opens, so a tap is confirmed
318/// with a haptic as the report slides into the timeline.
319struct QuickLogButton: View {
320    let action: () -> Void
321
322    @State private var taps = 0
323
324    var body: some View {
325        Button {
326            taps += 1
327            action()
328        } label: {
329            Image(systemName: "bolt.fill")
330                .font(.title3.weight(.semibold))
331                .foregroundStyle(Theme.ink)
332                .frame(width: 44, height: 44)
333                .overlay(Circle().strokeBorder(Theme.ink, lineWidth: 1.5))
334                .contentShape(.circle)
335        }
336        .buttonStyle(.plain)
337        .accessibilityLabel(Text("Instant Report"))
338        .accessibilityHint(Text("Files this report without a survey"))
339        .sensoryFeedback(.success, trigger: taps)
340    }
341}
342
343struct NewReportMenu: View {
344    let onStart: (ReportKind) -> Void
345
346    var body: some View {
347        Menu {
348            Button("Manual", systemImage: "square.and.pencil") { onStart(.manual) }
349            Button("Wake Up", systemImage: "sunrise") { onStart(.wake) }
350            Button("Bedtime", systemImage: "moon") { onStart(.bedtime) }
351        } label: {
352            Image(systemName: "plus")
353                .font(.title3.weight(.semibold))
354                .foregroundStyle(Theme.paper)
355                .frame(width: 44, height: 44)
356                .background(Theme.ink, in: .circle)
357                .accessibilityLabel(Text("New Report"))
358        }
359    }
360}
361
362struct DayHeader: View {
363    let date: Date?
364    let today: Date
365
366    var body: some View {
367        if let date {
368            Text(date, format: Self.format(for: date, now: today))
369                .eyebrow(Calendar.current.isDate(date, inSameDayAs: today) ? Theme.accent : Theme.muted)
370                .frame(maxWidth: .infinity, alignment: .leading)
371                .padding(.horizontal, Theme.margin)
372                .padding(.top, Theme.headingTop)
373                .padding(.bottom, 4)
374                .background(Theme.paper)
375                .listRowInsets(EdgeInsets())
376        }
377    }
378}
379
380extension DayHeader {
381    /// The year is only shown for days in another year.
382    static func format(for date: Date, now: Date = Date()) -> Date.FormatStyle {
383        let style = Date.FormatStyle().weekday(.wide).day().month(.wide)
384        let calendar = Calendar.current
385        return calendar.isDate(date, equalTo: now, toGranularity: .year) ? style : style.year()
386    }
387}
388
389struct EmptyReports: View {
390    var body: some View {
391        VStack(alignment: .leading, spacing: 8) {
392            Text("Nothing recorded yet.")
393                .font(Theme.serif(.title2))
394                .foregroundStyle(Theme.ink)
395            Text("Tap + to make your first report.")
396                .font(.subheadline)
397                .foregroundStyle(Theme.muted)
398        }
399        .padding(.vertical, 40)
400    }
401}
402
403/// One report: its local time, kind, its narrative, its other answers and
404/// where it was.
405struct ReportRow: View {
406    @ObservedObject var report: ReportEntity
407    let describer: ReportDescriber
408
409    /// Wide enough for '10:20' in the time's font, and scaled with it, so
410    /// the time never wraps and every row's column lines up.
411    @ScaledMetric(relativeTo: .title3) private var timeWidth: CGFloat = 60
412
413    var body: some View {
414        if let health = report.health {
415            // Reading Health again changes the narrative but not the report,
416            // so the row watches the narrative as well.
417            HealthObserver(health: health) { content }
418        } else {
419            content
420        }
421    }
422
423    @ViewBuilder private var content: some View {
424        let summary = describer.summary(of: report)
425        let kind = report.kind.flatMap(ReportKind.init)
426        // The tops of the time's digits and of the kind label line up,
427        // rather than their baselines, so the small label heads the
428        // narrative instead of sitting at the foot of the large digits.
429        HStack(alignment: .capTop, spacing: Theme.itemGap) {
430            ReportTime(date: report.date, timeZone: report.timeZone)
431                .frame(width: timeWidth, alignment: .leading)
432            VStack(alignment: .leading, spacing: 6) {
433                ReportKindLabel(kind: kind, isLogged: isLogged)
434                ReportSummaryText(
435                    narrative: summary.narrative,
436                    details: summary.details,
437                    context: summary.context,
438                    isLogged: isLogged
439                )
440            }
441        }
442    }
443
444    /// Whether the report was logged for later and has no answers yet.
445    private var isLogged: Bool { report.state == ReportState.passive.rawValue }
446}
447
448/// Redraws its content when a report's Health entry changes.
449private struct HealthObserver<Content: View>: View {
450    @ObservedObject var health: HealthEntity
451    @ViewBuilder let content: () -> Content
452
453    var body: some View { content() }
454}
455
456/// A report's local time. On a 12-hour clock the period goes beneath the
457/// digits, so every time fits the same narrow column.
458struct ReportTime: View {
459    let date: Date?
460    let timeZone: String?
461
462    @ScaledMetric(relativeTo: .title3) private var timeCapHeight = Theme.capHeight(.title3, weight: .medium, design: .serif)
463
464    var body: some View {
465        if let date {
466            let zone = timeZone.flatMap(TimeZone.init(identifier:)) ?? .current
467            let capHeight = timeCapHeight
468            VStack(alignment: .leading, spacing: Theme.lineGap) {
469                Text(date, format: Self.format(in: zone))
470                    .font(Theme.serif(.title3, weight: .medium))
471                    .monospacedDigit()
472                    .foregroundStyle(Theme.ink)
473                    .alignmentGuide(.capTop) { $0[.firstTextBaseline] - capHeight }
474                if let period = Self.period(of: date, in: zone) {
475                    Text(period)
476                        .eyebrow()
477                }
478            }
479        }
480    }
481
482    private static func format(in zone: TimeZone) -> Date.FormatStyle {
483        Date.FormatStyle(timeZone: zone).hour(.defaultDigits(amPM: .omitted)).minute()
484    }
485
486    /// 'am' or 'pm' when the user's locale uses a 12-hour clock.
487    private static func period(of date: Date, in zone: TimeZone) -> String? {
488        switch Locale.current.hourCycle {
489        case .zeroToEleven, .oneToTwelve:
490            var calendar = Calendar.current
491            calendar.timeZone = zone
492            return calendar.component(.hour, from: date) < 12
493                ? calendar.amSymbol : calendar.pmSymbol
494        case .zeroToTwentyThree, .oneToTwentyFour:
495            return nil
496        @unknown default:
497            return nil
498        }
499    }
500}
501
502struct ReportKindLabel: View {
503    let kind: ReportKind?
504    /// A report logged without answers is labelled as an instant rather than
505    /// as unfinished: leaving it as it is is fine.
506    let isLogged: Bool
507
508    @ScaledMetric(relativeTo: .caption) private var capHeight = Theme.capHeight(.caption1, weight: .semibold)
509
510    var body: some View {
511        let capHeight = capHeight
512        Group {
513            if isLogged {
514                Text("Instant", comment: "Label for a report filed without answers, such as from the quick file button")
515                    .eyebrow()
516                    .italic()
517            } else {
518                Text((kind ?? .manual).shortTitle)
519                    .eyebrow(kind == .wake || kind == .bedtime ? Theme.accent : Theme.muted)
520            }
521        }
522        .alignmentGuide(.capTop) { $0[.firstTextBaseline] - capHeight }
523    }
524}
525
526struct ReportSummaryText: View {
527    let narrative: String?
528    let details: [AnswerDetail]
529    let context: String?
530    /// A report logged for later has no answers, and doesn't say so.
531    let isLogged: Bool
532
533    /// Answers shown beneath the narrative before the rest are counted.
534    private static let detailLimit = 2
535
536    var body: some View {
537        VStack(alignment: .leading, spacing: 4) {
538            if let narrative {
539                Text(narrative)
540                    .font(Theme.serif(.body))
541                    .foregroundStyle(Theme.ink)
542            } else if details.isEmpty, !isLogged {
543                Text("No answers", comment: "Shown for a report whose questions were all skipped")
544                    .font(Theme.serif(.body).italic())
545                    .foregroundStyle(Theme.muted)
546            }
547            ForEach(details.prefix(Self.detailLimit)) { detail in
548                Text("\(detail.prompt) \(Text(detail.answer).foregroundStyle(Theme.ink))")
549                    .font(.subheadline)
550                    .foregroundStyle(Theme.muted)
551                    .lineLimit(2)
552            }
553            if details.count > Self.detailLimit {
554                Text(
555                    "and \(details.count - Self.detailLimit) more",
556                    comment: "Count of a report's answers not shown in the list")
557                    .font(.subheadline)
558                    .foregroundStyle(Theme.muted)
559            }
560            if let context {
561                Text(context)
562                    .font(.footnote)
563                    .foregroundStyle(Theme.muted)
564                    .padding(.top, 2)
565            }
566        }
567    }
568}
569
570#Preview {
571    let persistence = PersistenceController(inMemory: true)
572    let store = ReportStore(persistence: persistence)
573    HomeView()
574        .environment(\.managedObjectContext, persistence.viewContext)
575        .environment(\.reportStore, store)
576        .tint(Theme.accent)
577        .task { _ = try? await store.seedDefaultQuestionsIfNeeded() }
578}