commit 0967017c0e17308663a34fb7a71737dc5e6f15b0
parent 3053b7f8f359f6bbf35a2cde42beff0af4aa0d8f
Author: Michael Camilleri <[email protected]>
Date: Mon, 19 Oct 2026 19:41:40 +0900
Add a Questions screen and read entries in question order
This commit adds a Questions screen to Settings. It lists the questions
under the Prompted, Wake and Bedtime surveys. A question which is not
asked is under 'Not Asked'. Dragging a question moves it among the
questions of that survey and leaves the rest of the order alone, since
every survey shares one order. Opening a question sets the surveys it's
asked in and whether it shows in the timeline; asking an archived
question brings it back in that survey alone. Each change is saved as
it's made.
Entries now read in the questions' current order rather than the order
a report was made in, so reordering a question changes every entry,
imported ones included, and the special case that put sleep first is
gone. Answers to a question with 'Show in Timeline' turned off are
left out of the timeline but still listed in the report's details.
The setting is stored on each question and written to exports; an
export without it is read as showing every question.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
18 files changed, 490 insertions(+), 52 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -150,7 +150,8 @@ the app. A change that needs data rewritten would need a migration of its own.
| `options` | For `choice`: the fixed answer list. |
| `placeholder` | Optional. |
| `askOn` | Set of report kinds the question appears in: `random`, `wake`, `bedtime`. |
-| `order` | Sort order within a survey. |
+| `order` | Sort order within a survey, one order across all surveys. Entries read in the current order, so reordering a question changes past entries too. |
+| `showsInTimeline` | Whether answers appear in the timeline's entries. Hidden answers are still shown in a report's details. |
| `archivedAt` | Questions are archived, never deleted, so history keeps its meaning. |
Reporter's `questionType` values map as: 0 → `tokens`, 1 → `choice`,
@@ -175,6 +176,13 @@ devices that both seed them end up with the same questions after syncing.
Their prompts are written in the user's language at seeding time and are
ordinary data after that.
+**The Questions screen.** Settings lists the questions by survey (prompted,
+wake, bedtime), plus those not asked in any. Dragging reorders a question
+among those in the same survey, leaving the rest of the order alone. Opening
+a question sets the surveys it's asked in and whether it shows in the
+timeline. Asking an archived question brings it back in that survey alone.
+Adding, removing and rewording questions come later.
+
**Built-in and custom questions (planned).** Each question needs a
[display rule](#drafts) for its answers to read well in an entry. The plan is
a fixed set of built-in questions whose prompts, options and display rules are
@@ -398,12 +406,13 @@ Each question has a `DisplayRule` saying how its answer reads:
| Count | number | '1 coffee', '2 coffees' |
| Quote | note | "Learned: 'The neighbours are nice people.'" |
-Activities, place and people join one clause. How the night went comes
-first ('Slept well.'), then the clause, since it's what was happening, then
-the other answers in survey order, one sentence each. So 'Are you working?'
-being asked before 'What are you doing?' doesn't make the entry open with
-'Working.'. An answer to a question with no rule is shown beneath the entry
-as its prompt and answer, so nothing is hidden.
+Answers read in the questions' current order, so the user decides how
+entries read by reordering questions, and every entry follows, including
+imported ones. Activities, place and people join one clause, placed where
+the first of those answers comes. Other answers are one sentence each. An
+answer to a question with no rule is shown beneath the entry as its prompt
+and answer. Answers to a question not shown in the timeline are left out of
+both.
Notes are quoted exactly as written and never rewritten: free writing breaks
templates in ways casing can't fix (several sentences, first person, lists).
diff --git a/Notes/ExportFormat.md b/Notes/ExportFormat.md
@@ -51,7 +51,8 @@ Fractional seconds appear only when a date has them, to millisecond precision: | `options` | [string]? | The fixed answer list of a `choice` question. | | `placeholder` | string? | | | `askOn` | [string] | Surveys the question appears in: `random`, `wake`, `bedtime`. Manual reports use the `random` survey. | -| `order` | integer | Sort order within a survey. | +| `order` | integer | Sort order within a survey, and the order answers read in an entry. | +| `showsInTimeline` | boolean | Whether answers appear in the timeline's entries. Missing in older exports, where it means `true`. | | `archivedAt` | date? | Questions are archived, never deleted. | | `modifiedAt` | date | |
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -49,6 +49,8 @@
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */; };
97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28AD66BC8ED4AEABF6640108 /* ReportStore.swift */; };
9EF3CB3707CD6B5AFFD3B767 /* ReporterArchive.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC1C5F0F722477CDA949F018 /* ReporterArchive.swift */; };
+ 9FD499B8FACD1BA034804590 /* QuestionListTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0E6B536B922A8468136815CD /* QuestionListTests.swift */; };
+ 9FEE3B78B770C6A3CF9C6610 /* QuestionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */; };
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */; };
A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F498961A14F24AE6CC37453C /* ReportDetailView.swift */; };
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */; };
@@ -97,6 +99,7 @@
/* Begin PBXFileReference section */
0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummaryTests.swift; sourceTree = "<group>"; };
0B35602A218BE4EE399835FD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 0E6B536B922A8468136815CD /* QuestionListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionListTests.swift; sourceTree = "<group>"; };
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePickerTests.swift; sourceTree = "<group>"; };
1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummary.swift; sourceTree = "<group>"; };
1C4665B55B0307E899595C1D /* PromptScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduler.swift; sourceTree = "<group>"; };
@@ -132,6 +135,7 @@
7CE5E7D863F9BD3DF363AA9A /* AppBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppBadge.swift; sourceTree = "<group>"; };
7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirstLaunch.swift; sourceTree = "<group>"; };
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExportTests.swift; sourceTree = "<group>"; };
+ 7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionsView.swift; sourceTree = "<group>"; };
7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlanTests.swift; sourceTree = "<group>"; };
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
844ABAD88442C143BA239374 /* SurveyModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModel.swift; sourceTree = "<group>"; };
@@ -318,6 +322,7 @@
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */,
2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */,
BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */,
+ 0E6B536B922A8468136815CD /* QuestionListTests.swift */,
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */,
BEB5080BDA34F703DDC08ADB /* ReportDetailsTests.swift */,
@@ -379,6 +384,7 @@
children = (
CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */,
87545A7909A370C668314DFF /* DiagnosticsSection.swift */,
+ 7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */,
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */,
);
path = Settings;
@@ -543,6 +549,7 @@
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */,
35D02EAE3D95DB5CCEE8A82E /* PromptScheduleTests.swift in Sources */,
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */,
+ 9FD499B8FACD1BA034804590 /* QuestionListTests.swift in Sources */,
4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */,
FBE598AB29E0297BC232ED75 /* ReportDetailsTests.swift in Sources */,
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */,
@@ -592,6 +599,7 @@
C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */,
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */,
85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */,
+ 9FEE3B78B770C6A3CF9C6610 /* QuestionsView.swift in Sources */,
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */,
A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */,
34C3A453ABC838F73DC3E294 /* ReportDetails.swift in Sources */,
diff --git a/Reportage/Services/Export/ReportageExport.swift b/Reportage/Services/Export/ReportageExport.swift
@@ -101,6 +101,9 @@ struct ExportedQuestion: Codable, Hashable, Sendable {
/// Survey names: `random`, `wake` and `bedtime`.
var askOn: [String]
var order: Int
+ /// Missing from exports made before it existed, when every question was
+ /// shown.
+ var showsInTimeline: Bool?
var archivedAt: Date?
var modifiedAt: Date
@@ -116,6 +119,7 @@ struct ExportedQuestion: Codable, Hashable, Sendable {
placeholder = question.placeholder
askOn = Self.surveys.filter { question.askOn.contains($0.kind) }.map(\.name)
order = question.order
+ showsInTimeline = question.showsInTimeline
archivedAt = question.archivedAt
modifiedAt = question.modifiedAt
}
@@ -136,6 +140,7 @@ struct ExportedQuestion: Codable, Hashable, Sendable {
placeholder: placeholder,
askOn: surveys,
order: order,
+ showsInTimeline: showsInTimeline ?? true,
archivedAt: archivedAt,
modifiedAt: modifiedAt
)
diff --git a/Reportage/Services/Narrative/DisplayRule.swift b/Reportage/Services/Narrative/DisplayRule.swift
@@ -58,15 +58,6 @@ enum DisplayRule: Equatable, Sendable {
return rules
}()
- /// Questions whose answers open the entry, before the main clause: the
- /// night comes before what's happening now. Includes Reporter's
- /// questions that ask the same things.
- static let leading: Set<String> = {
- let names: Set<String> = ["sleep-quality"]
- let reporterIDs = reporterQuestions.filter { names.contains($0.value) }.keys
- return Set(names.map { DefaultQuestions.idPrefix + $0 }).union(reporterIDs)
- }()
-
/// Reporter's built-in questions, by the default question that asks the
/// same thing.
private static let reporterQuestions = [
diff --git a/Reportage/Services/Narrative/EntryBuilder.swift b/Reportage/Services/Narrative/EntryBuilder.swift
@@ -8,40 +8,44 @@ struct AnswerDetail: Equatable, Identifiable, Sendable {
var answer: String
}
-/// Builds entries from answers using each question's `DisplayRule`.
+/// Builds entries from answers using each question's `DisplayRule`, in the
+/// questions' current order.
@MainActor
enum EntryBuilder {
static func build(
responses: [Response],
lookup: SummaryLookup
) -> (entry: String?, details: [AnswerDetail]) {
- // Sentences that open the entry, then the rest in survey order.
- var leading: [Sentence] = []
var sentences: [Sentence] = []
var details: [AnswerDetail] = []
var activities: [String] = []
var people: [String] = []
var place: String?
+ // The main clause goes where its first answer would have.
+ var clauseIndex: Int?
- for response in responses {
- guard let value = response.value else { continue }
- let start = sentences.count
- defer {
- if DisplayRule.leading.contains(response.questionID) {
- leading += sentences[start...]
- sentences.removeSubrange(start...)
- }
- }
+ // Stable, so answers to the same or unknown questions keep their order.
+ let ordered = responses.enumerated().sorted { a, b in
+ let orders = (lookup.questionOrder[a.element.questionID], lookup.questionOrder[b.element.questionID])
+ return (orders.0 ?? .max, a.offset) < (orders.1 ?? .max, b.offset)
+ }.map(\.element)
+
+ for response in ordered {
+ guard let value = response.value, !lookup.hiddenQuestions.contains(response.questionID)
+ else { continue }
let rule = DisplayRule.rule(
for: response.questionID, kind: lookup.questionKinds[response.questionID])
switch (rule, value) {
case (.activities, .tokens(let ids)):
activities += ids.compactMap { lookup.tokenTexts[$0] }
+ clauseIndex = clauseIndex ?? sentences.count
case (.people, .tokens(let ids)):
people += ids.compactMap { lookup.tokenTexts[$0] }
+ clauseIndex = clauseIndex ?? sentences.count
case (.place, .place(let answer)):
place = place ?? placePhrase(for: answer.tokenID, lookup: lookup)
+ clauseIndex = clauseIndex ?? sentences.count
case (.phrases(let phrases), .options(let options)):
if let phrase = options.lazy.compactMap({ phrases[$0] }).first {
sentences.append(Sentence(phrase))
@@ -63,11 +67,9 @@ enum EntryBuilder {
}
}
- // What's happening comes before the answers about it.
if let clause = mainClause(activities: activities, place: place, people: people) {
- sentences.insert(clause, at: 0)
+ sentences.insert(clause, at: min(clauseIndex ?? 0, sentences.count))
}
- sentences = leading + sentences
guard !sentences.isEmpty else { return (nil, details) }
let entry = sentences.map { sentence in
diff --git a/Reportage/Views/Home/ReportSummary.swift b/Reportage/Views/Home/ReportSummary.swift
@@ -11,6 +11,11 @@ struct SummaryLookup: Equatable, Sendable {
/// gave them. A merged token's ID is here if its token's is.
var directoryPlaces: Set<String> = []
var questionKinds: [String: QuestionKind] = [:]
+ /// Each question's place in the current order, so entries follow it
+ /// rather than the order the report was made in.
+ var questionOrder: [String: Int] = [:]
+ /// Questions whose answers are left out of the timeline.
+ var hiddenQuestions: Set<String> = []
}
/// A report described for the home screen: its entry, built from the answers
@@ -82,6 +87,8 @@ extension ReportStore {
for entity in try context.fetch(QuestionEntity.fetchRequest()) {
let question = try entity.question()
lookup.questionKinds[question.id] = question.kind
+ lookup.questionOrder[question.id] = question.order
+ if !question.showsInTimeline { lookup.hiddenQuestions.insert(question.id) }
}
return lookup
}
diff --git a/Reportage/Views/Settings/QuestionsView.swift b/Reportage/Views/Settings/QuestionsView.swift
@@ -0,0 +1,281 @@
+import OSLog
+import SwiftUI
+
+/// The surveys a question can be asked in, as the Questions screen names
+/// them. Manual reports ask the prompted survey's questions.
+enum Survey: CaseIterable, Hashable {
+ case prompted
+ case wake
+ case bedtime
+
+ var kinds: SurveyKinds {
+ switch self {
+ case .prompted: .random
+ case .wake: .wake
+ case .bedtime: .bedtime
+ }
+ }
+
+ var title: LocalizedStringKey {
+ switch self {
+ case .prompted: "Prompted"
+ case .wake: "Wake"
+ case .bedtime: "Bedtime"
+ }
+ }
+}
+
+extension Question {
+ /// Whether the question is asked in `survey`. An archived question isn't
+ /// asked anywhere, whatever surveys it was last in.
+ func isAsked(in survey: Survey) -> Bool {
+ archivedAt == nil && askOn.contains(survey.kinds)
+ }
+
+ /// Asks or stops asking the question in `survey`. Asking an archived
+ /// question brings it back in that survey alone.
+ mutating func setAsked(_ isAsked: Bool, in survey: Survey) {
+ if isAsked {
+ if archivedAt != nil {
+ archivedAt = nil
+ askOn = []
+ }
+ askOn.insert(survey.kinds)
+ } else {
+ askOn.remove(survey.kinds)
+ }
+ }
+}
+
+/// Every question in order, for reordering and editing on the Questions
+/// screen. Each change is saved as it's made.
+@MainActor
+@Observable
+final class QuestionList {
+ /// Every question, archived or not, in survey order.
+ private(set) var questions: [Question] = [] {
+ didSet { group() }
+ }
+ private(set) var bySurvey: [Survey: [Question]] = [:]
+ /// Questions not asked in any survey.
+ private(set) var notAsked: [Question] = []
+ private(set) var isLoaded = false
+
+ private var store: ReportStore?
+ private let logger = Logger(subsystem: "net.inqk.reportage", category: "Questions")
+
+ func load(from store: ReportStore?) async {
+ guard let store, let questions = try? await store.allQuestions() else { return }
+ self.store = store
+ self.questions = questions
+ isLoaded = true
+ }
+
+ func question(id: String) -> Question? {
+ questions.first { $0.id == id }
+ }
+
+ func update(_ question: Question) {
+ guard let index = questions.firstIndex(where: { $0.id == question.id }),
+ questions[index] != question
+ else { return }
+ var question = question
+ question.modifiedAt = Date()
+ questions[index] = question
+ save([question])
+ }
+
+ /// Moves questions within `survey`, keeping every other question where
+ /// it was in the order.
+ func move(in survey: Survey, from offsets: IndexSet, to destination: Int) {
+ let orders = Dictionary(uniqueKeysWithValues: questions.map { ($0.id, $0.order) })
+ var moved = Self.reordered(questions, in: survey, from: offsets, to: destination)
+ let now = Date()
+ var changed: [Question] = []
+ for index in moved.indices where moved[index].order != orders[moved[index].id] {
+ moved[index].modifiedAt = now
+ changed.append(moved[index])
+ }
+ questions = moved
+ save(changed)
+ }
+
+ /// `questions` with those asked in `survey` moved among themselves into
+ /// the places they held, then numbered in order.
+ static func reordered(
+ _ questions: [Question], in survey: Survey, from offsets: IndexSet, to destination: Int
+ ) -> [Question] {
+ let places = questions.indices.filter { questions[$0].isAsked(in: survey) }
+ var group = places.map { questions[$0] }
+ group.move(fromOffsets: offsets, toOffset: destination)
+ var result = questions
+ for (place, question) in zip(places, group) {
+ result[place] = question
+ }
+ for index in result.indices {
+ result[index].order = index
+ }
+ return result
+ }
+
+ private func group() {
+ bySurvey = Dictionary(
+ uniqueKeysWithValues: Survey.allCases.map { survey in
+ (survey, questions.filter { $0.isAsked(in: survey) })
+ })
+ notAsked = questions.filter { question in
+ !Survey.allCases.contains { question.isAsked(in: $0) }
+ }
+ }
+
+ private func save(_ questions: [Question]) {
+ guard let store, !questions.isEmpty else { return }
+ Task {
+ do {
+ try await store.save(questions)
+ } catch {
+ logger.error("Couldn't save questions: \(error)")
+ }
+ }
+ }
+}
+
+/// The questions in each survey, in the order they're asked and read in the
+/// timeline. Questions are moved by dragging, and opened to choose their
+/// surveys and whether they show in the timeline.
+struct QuestionsView: View {
+ @Environment(\.reportStore) private var store
+ @State private var list = QuestionList()
+
+ var body: some View {
+ List {
+ SettingsNote {
+ Text(
+ "Questions are asked in this order, and their answers read in this order in the timeline. Manual reports ask the prompted questions."
+ )
+ }
+ ForEach(Survey.allCases, id: \.self) { survey in
+ Section {
+ ForEach(list.bySurvey[survey] ?? [], id: \.id) { question in
+ QuestionRow(question: question, list: list)
+ }
+ .onMove { offsets, destination in
+ list.move(in: survey, from: offsets, to: destination)
+ }
+ if list.isLoaded, list.bySurvey[survey]?.isEmpty ?? true {
+ SettingsNote { Text("No questions are asked.") }
+ }
+ } header: {
+ SettingsHeading(survey.title)
+ }
+ }
+ if !list.notAsked.isEmpty {
+ Section {
+ ForEach(list.notAsked, id: \.id) { question in
+ QuestionRow(question: question, list: list)
+ }
+ } header: {
+ SettingsHeading("Not Asked")
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationTitle("Questions")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar(.visible, for: .navigationBar)
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ EditButton()
+ }
+ }
+ .task { await list.load(from: store) }
+ }
+}
+
+/// A question's prompt, noting when its answers are left out of the
+/// timeline.
+private struct QuestionRow: View {
+ let question: Question
+ let list: QuestionList
+
+ var body: some View {
+ NavigationLink {
+ QuestionDetailView(id: question.id, list: list)
+ } label: {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(question.prompt)
+ .font(Theme.serif(.body))
+ if !question.showsInTimeline {
+ Text("Not shown in timeline")
+ .font(.footnote)
+ .foregroundStyle(Theme.muted)
+ }
+ }
+ }
+ .settingsRow()
+ }
+}
+
+/// One question's surveys and whether its answers show in the timeline.
+private struct QuestionDetailView: View {
+ let id: String
+ let list: QuestionList
+
+ var body: some View {
+ List {
+ if let question = list.question(id: id) {
+ Text(question.prompt)
+ .font(Theme.serif(.title3, weight: .medium))
+ .settingsRow()
+ .listRowSeparator(.hidden, edges: .top)
+ Section {
+ ForEach(Survey.allCases, id: \.self) { survey in
+ Toggle(survey.title, isOn: asked(in: survey, question))
+ .settingsRow()
+ }
+ } header: {
+ SettingsHeading("Asked In")
+ }
+ Section {
+ Toggle("Show in Timeline", isOn: showsInTimeline(question))
+ .settingsRow()
+ SettingsNote {
+ Text(
+ "When this is off, answers to this question are left out of the timeline. They're still shown in each report's details."
+ )
+ }
+ } header: {
+ SettingsHeading("Timeline")
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private func asked(in survey: Survey, _ question: Question) -> Binding<Bool> {
+ Binding(
+ get: { question.isAsked(in: survey) },
+ set: { isAsked in
+ var question = question
+ question.setAsked(isAsked, in: survey)
+ list.update(question)
+ })
+ }
+
+ private func showsInTimeline(_ question: Question) -> Binding<Bool> {
+ Binding(
+ get: { question.showsInTimeline },
+ set: { shows in
+ var question = question
+ question.showsInTimeline = shows
+ list.update(question)
+ })
+ }
+}
diff --git a/Reportage/Views/Settings/SettingsView.swift b/Reportage/Views/Settings/SettingsView.swift
@@ -23,6 +23,12 @@ struct SettingsView: View {
NavigationStack {
List {
SettingsTitle()
+ Section {
+ NavigationLink("Questions") { QuestionsView() }
+ .settingsRow()
+ } header: {
+ SettingsHeading("Surveys")
+ }
Section {
Toggle("Random Prompts", isOn: promptsEnabled)
.settingsRow()
diff --git a/Shared/Models/DefaultQuestions.swift b/Shared/Models/DefaultQuestions.swift
@@ -41,12 +41,6 @@ enum DefaultQuestions {
],
askOn: .wake
),
- question(
- "working",
- String(localized: "Are you working?", comment: "Default question"),
- .yesNo,
- askOn: .random
- ),
question(
"activity",
String(localized: "What are you doing?", comment: "Default question"),
@@ -65,6 +59,12 @@ enum DefaultQuestions {
.people,
askOn: .random
),
+ question(
+ "working",
+ String(localized: "Are you working?", comment: "Default question"),
+ .yesNo,
+ askOn: .random
+ ),
question(
"mood",
String(localized: "How do you feel?", comment: "Default question"),
diff --git a/Shared/Models/Question.swift b/Shared/Models/Question.swift
@@ -13,8 +13,12 @@ struct Question: Hashable, Sendable {
var placeholder: String?
/// The surveys the question appears in.
var askOn: SurveyKinds
- /// Sort order within a survey.
+ /// Sort order within a survey, and the order its answers read in an
+ /// entry.
var order: Int
+ /// Whether the question's answers appear in the timeline. Hidden answers
+ /// are still shown in the report's details.
+ var showsInTimeline = true
var archivedAt: Date?
var modifiedAt: Date
}
diff --git a/Shared/Persistence/EntityMapping.swift b/Shared/Persistence/EntityMapping.swift
@@ -29,6 +29,7 @@ extension QuestionEntity {
placeholder = question.placeholder
askOn = question.askOn.rawValue
order = Int32(question.order)
+ showsInTimeline = question.showsInTimeline
archivedAt = question.archivedAt
modifiedAt = question.modifiedAt
}
@@ -49,6 +50,7 @@ extension QuestionEntity {
placeholder: placeholder,
askOn: SurveyKinds(rawValue: askOn),
order: Int(order),
+ showsInTimeline: showsInTimeline,
archivedAt: archivedAt,
modifiedAt: modifiedAt
)
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -41,6 +41,36 @@ struct ReportStore: Sendable {
}
}
+ /// Every question, archived or not, in survey order.
+ func allQuestions() async throws -> [Question] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = QuestionEntity.fetchRequest()
+ request.sortDescriptors = [
+ NSSortDescriptor(key: "order", ascending: true),
+ NSSortDescriptor(key: "id", ascending: true),
+ ]
+ return try context.fetch(request).map { try $0.question() }
+ }
+ }
+
+ /// Saves edits to existing questions. Questions not in the store are
+ /// left out, since questions are only added by seeding or importing.
+ func save(_ questions: [Question]) async throws {
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ let request = QuestionEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", questions.map(\.id))
+ let entities = Dictionary(
+ try context.fetch(request).compactMap { entity in entity.id.map { ($0, entity) } },
+ uniquingKeysWith: { first, _ in first })
+ for question in questions {
+ try entities[question.id]?.update(from: question)
+ }
+ try context.save()
+ }
+ }
+
/// The questions with `ids`, archived or not, in the order given. IDs
/// with no question are left out.
func questions(ids: [String]) async throws -> [Question] {
diff --git a/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents b/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents
@@ -10,6 +10,7 @@
<attribute name="order" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="placeholder" optional="YES" attributeType="String"/>
<attribute name="prompt" attributeType="String"/>
+ <attribute name="showsInTimeline" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES"/>
<uniquenessConstraints>
<uniquenessConstraint>
<constraint value="id"/>
diff --git a/Tests/Unit/QuestionListTests.swift b/Tests/Unit/QuestionListTests.swift
@@ -0,0 +1,42 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@MainActor
+@Suite("QuestionList")
+struct QuestionListTests {
+
+ private static func question(_ id: String, _ askOn: SurveyKinds, archived: Bool = false) -> Question {
+ Question(
+ id: id, prompt: id, kind: .yesNo, askOn: askOn, order: 0,
+ archivedAt: archived ? Date(timeIntervalSince1970: 0) : nil,
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ @Test("Moving within a survey leaves other questions where they were")
+ func reordered() {
+ let questions = [
+ Self.question("sleep", .wake),
+ Self.question("doing", .random),
+ Self.question("note", .bedtime),
+ Self.question("work", .random),
+ Self.question("mood", [.random, .bedtime]),
+ ]
+ // Prompted holds doing, work and mood; move mood to the front.
+ let moved = QuestionList.reordered(questions, in: .prompted, from: [2], to: 0)
+ #expect(moved.map(\.id) == ["sleep", "mood", "note", "doing", "work"])
+ #expect(moved.map(\.order) == [0, 1, 2, 3, 4])
+ }
+
+ @Test("Archived questions aren't asked, and asking one brings it back in that survey alone")
+ func asking() {
+ var question = Self.question("Q", [.random, .wake], archived: true)
+ #expect(!question.isAsked(in: .prompted))
+ question.setAsked(true, in: .bedtime)
+ #expect(question.archivedAt == nil)
+ #expect(question.askOn == .bedtime)
+ question.setAsked(false, in: .bedtime)
+ #expect(question.askOn.isEmpty)
+ }
+}
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -268,7 +268,7 @@ struct ReportStoreTests {
var archived = try #require(try await store.surveyQuestions(for: .wake).first)
archived.archivedAt = Date()
let context = persistence.newBackgroundContext()
- try await context.perform {
+ try await context.perform { [archived] in
let request = QuestionEntity.fetchRequest()
request.predicate = NSPredicate(format: "id == %@", archived.id)
try #require(try context.fetch(request).first).update(from: archived)
@@ -367,3 +367,19 @@ struct ReportStoreTests {
#expect(try persistence.viewContext.count(for: QuestionEntity.fetchRequest()) == 0)
}
}
+
+extension ReportStoreTests {
+ @Test("Edited questions are saved, and every question is listed in order")
+ func saveQuestions() async throws {
+ try await store.seedDefaultQuestionsIfNeeded(now: Date(timeIntervalSince1970: 0))
+ var questions = try await store.allQuestions()
+ #expect(questions.map(\.order) == Array(questions.indices))
+ questions[0].showsInTimeline = false
+ questions[0].archivedAt = Date(timeIntervalSince1970: 1)
+ try await store.save([questions[0]])
+
+ let saved = try await store.allQuestions()
+ #expect(saved.first == questions[0])
+ #expect(try await store.surveyQuestions(for: .wake).contains { $0.id == questions[0].id } == false)
+ }
+}
diff --git a/Tests/Unit/ReportSummaryTests.swift b/Tests/Unit/ReportSummaryTests.swift
@@ -55,7 +55,7 @@ struct EntryBuilderTests {
#expect(bottle == "Reading at Blue bottle.")
}
- @Test("Built-in rules phrase each kind of answer")
+ @Test("Built-in rules phrase each kind of answer, in survey order")
func builtInRules() {
let (entry, _) = Self.build([
Self.response("reportage-default-working", .options([ResponseValue.noOption])),
@@ -66,19 +66,38 @@ struct EntryBuilderTests {
])
#expect(
entry
- == "Reading. Not working. Feeling great. 1 coffee. Learned: 'The neighbours are nice people.'")
+ == "Not working. Reading. Feeling great. 1 coffee. Learned: 'The neighbours are nice people.'")
}
- @Test("Sleep opens the entry, then the main clause, then the rest in survey order")
- func order() {
- let (entry, _) = Self.build([
- Self.response("reportage-default-working", .options([ResponseValue.yesOption])),
- Self.response("activity", .tokens(["read"])),
- Self.response("place", .place(PlaceAnswer(tokenID: "library"))),
- Self.response("reportage-default-mood", .options(["Good"])),
- Self.response("reportage-default-sleep-quality", .options(["Well"])),
- ])
- #expect(entry == "Slept well. Reading at the library. Working. Feeling good.")
+ @Test("Answers follow the questions' current order, not the order they were given in")
+ func currentOrder() {
+ var lookup = Self.lookup
+ lookup.questionOrder = ["activity": 0, "place": 1, "reportage-default-working": 2]
+ let (entry, _) = EntryBuilder.build(
+ responses: [
+ Self.response("reportage-default-working", .options([ResponseValue.yesOption])),
+ Self.response("activity", .tokens(["read"])),
+ Self.response("place", .place(PlaceAnswer(tokenID: "library"))),
+ Self.response("reportage-default-mood", .options(["Good"])),
+ ],
+ lookup: lookup)
+ // Mood has no order, so it comes last.
+ #expect(entry == "Reading at the library. Working. Feeling good.")
+ }
+
+ @Test("Answers to questions hidden from the timeline are left out")
+ func hidden() {
+ var lookup = Self.lookup
+ lookup.hiddenQuestions = ["reportage-default-working", "custom"]
+ let (entry, details) = EntryBuilder.build(
+ responses: [
+ Self.response("reportage-default-working", .options([ResponseValue.yesOption])),
+ Self.response("activity", .tokens(["read"])),
+ Self.response("custom", .options([ResponseValue.yesOption])),
+ ],
+ lookup: lookup)
+ #expect(entry == "Reading.")
+ #expect(details.isEmpty)
}
@Test("Reporter's built-in questions read like the defaults that ask the same things")
diff --git a/Tests/Unit/ReportageExportTests.swift b/Tests/Unit/ReportageExportTests.swift
@@ -152,6 +152,20 @@ struct ReportageExportTests {
#expect(try exported.question() == question)
}
+ @Test("Whether a question shows in the timeline is exported, and shown when missing")
+ func showsInTimeline() throws {
+ var question = Question(
+ id: "Q", prompt: "P", kind: .yesNo, askOn: [.random], order: 0,
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ question.showsInTimeline = false
+ let exported = ExportedQuestion(question)
+ #expect(try exported.question() == question)
+
+ var older = exported
+ older.showsInTimeline = nil
+ #expect(try older.question().showsInTimeline)
+ }
+
@Test("An empty store exports empty arrays")
func empty() async throws {
let (summary, data) = try await exportData()