commit 95c9d308f863293efe7b5fb29f310be925afc089
parent 6d03d6aa4b72fecf494be8ab676aa16ab8a68a80
Author: Michael Camilleri <[email protected]>
Date: Tue, 20 Oct 2026 17:22:56 +0900
Edit and add questions on the Questions screen
Questions could be reordered and moved between surveys, but their
wording, a choice question's answers and how they read in the narrative
were fixed, and there was no way to ask anything new.
This commit makes opening a question edit it in place. The prompt is a
field, a choice question's answers can be renamed, added, moved and
removed, and a Narrative section holds the fields for the question's
kind — a phrase for each of yes and no, a template with %@ for a
choice, the nouns for a count, a lead-in for a note — beneath an
example of how answers read, or a note that blank fields show them as
question and answer. A new add button asks for a kind first, since
existing answers wouldn't fit a different one, then takes the same
fields. A new question goes to the end of the order, asked in the
Prompted survey.
Edits are kept as drafts and saved when a field is finished, so an
answer renamed in its field is renamed once rather than per keystroke.
Renaming a choice answer rewrites past answers given with it in the
same save, as renaming a token does, and marks their reports modified;
removing one leaves past answers alone. Saves run one after another so
an earlier edit can't land after a later one. Saving a question not in
the store now adds it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 20 | +++++++++++++++++--- |
| M | Reportage.xcodeproj/project.pbxproj | | | 8 | ++++++++ |
| A | Reportage/Views/Settings/QuestionEditor.swift | | | 412 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Settings/QuestionsView.swift | | | 131 | +++++++++++++++++++++++++++++++++++++++++++++---------------------------------- |
| M | Shared/Persistence/ReportStore.swift | | | 37 | ++++++++++++++++++++++++++++++++++--- |
| A | Tests/Unit/QuestionEditorTests.swift | | | 84 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportStoreTests.swift | | | 33 | +++++++++++++++++++++++++++++++++ |
7 files changed, 663 insertions(+), 62 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -191,9 +191,23 @@ 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 are next. +a question edits it in place: its prompt, a choice question's answers, +whether it shows in the timeline and how it reads there, and the surveys it's +asked in. Each field is saved when it's finished, not on every keystroke. +Rewording a question leaves past reports with the prompt they were answered +under. Renaming a choice answer renames it in past reports too, as renaming a +token does, and those reports count as modified; removing one leaves past +answers as they were. + +The screen avoids the word 'narrative', which means nothing to someone using +the app: a question's type is shown with a sentence on how its answers appear +in the timeline, and the narrative rule's fields sit in the Timeline section +under Show in Timeline, with an example of how answers read. The type is +chosen when a question is added, in the same form, and is shown but can't be +changed after that, since answers already given wouldn't fit another type. A +new question goes to the end of the order, asked in the prompted survey. +Asking an archived question brings it back in that survey alone. Removing +questions is next. **Editable questions.** Every question is the user's to edit, the defaults included: there is no fixed built-in set. Each question stores its own
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -18,6 +18,7 @@
19FD732027A16A84552DFD0E /* HealthContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86069F79CD8FA24FC6C26650 /* HealthContext.swift */; };
1BB257513FDA7541960B294C /* HealthCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1F55B30D0B5E711A28CD0B1 /* HealthCache.swift */; };
226A38BE6D7171D892EA35B3 /* FirstLaunch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */; };
+ 227F8E03F77DE5704797CC28 /* QuestionEditorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48ACB0E76C4E2271EA59B8E9 /* QuestionEditorTests.swift */; };
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */; };
25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3BE62142CCC4A791F05163A /* Token.swift */; };
275A9497C40065F5C77AE473 /* InstantReportLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 729C291798F29C69029E7DB7 /* InstantReportLogger.swift */; };
@@ -54,6 +55,7 @@
8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */; };
8AF60BB296144ED9D11EA053 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6024EA06BE24A189D4F7D0E4 /* Response.swift */; };
905D1185CF8B3426ECB91AFD /* HealthTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 695CB01E79016592A3823541 /* HealthTests.swift */; };
+ 93B2DAAF451BBE42A539CB94 /* QuestionEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1458729667512D1B7E04D92F /* QuestionEditor.swift */; };
961848A8D899BC67FA43F475 /* ReportageApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */; };
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */; };
97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28AD66BC8ED4AEABF6640108 /* ReportStore.swift */; };
@@ -136,6 +138,7 @@
0A246867F8FAC9D3FFABD61D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; 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>"; };
+ 1458729667512D1B7E04D92F /* QuestionEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionEditor.swift; sourceTree = "<group>"; };
1AD7CB7E9FF6D01BF4CE8617 /* AboutView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AboutView.swift; sourceTree = "<group>"; };
1B5C26C38B8B25086810CAB1 /* HealthReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthReader.swift; sourceTree = "<group>"; };
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePickerTests.swift; sourceTree = "<group>"; };
@@ -153,6 +156,7 @@
3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportVerifier.swift; sourceTree = "<group>"; };
46FB42E5DB43201A13D6D141 /* PassiveLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassiveLog.swift; sourceTree = "<group>"; };
487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchiveTests.swift; sourceTree = "<group>"; };
+ 48ACB0E76C4E2271EA59B8E9 /* QuestionEditorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionEditorTests.swift; sourceTree = "<group>"; };
48D44876FDE4293FA0460595 /* ReporterImporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporter.swift; sourceTree = "<group>"; };
4C40E7F6C3A90E317C8CB5B1 /* PlacePicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePicker.swift; sourceTree = "<group>"; };
5591E042089D038B59B26E9F /* ReportKind+Title.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ReportKind+Title.swift"; sourceTree = "<group>"; };
@@ -405,6 +409,7 @@
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */,
2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */,
BC27A2AF600780976CFA295C /* PromptScheduleTests.swift */,
+ 48ACB0E76C4E2271EA59B8E9 /* QuestionEditorTests.swift */,
0E6B536B922A8468136815CD /* QuestionListTests.swift */,
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */,
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */,
@@ -470,6 +475,7 @@
CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */,
87545A7909A370C668314DFF /* DiagnosticsSection.swift */,
F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */,
+ 1458729667512D1B7E04D92F /* QuestionEditor.swift */,
7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */,
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */,
);
@@ -679,6 +685,7 @@
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */,
35D02EAE3D95DB5CCEE8A82E /* PromptScheduleTests.swift in Sources */,
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */,
+ 227F8E03F77DE5704797CC28 /* QuestionEditorTests.swift in Sources */,
9FD499B8FACD1BA034804590 /* QuestionListTests.swift in Sources */,
4A0DEFB7E69A9FC5EAAD99D4 /* RealExportVerificationTests.swift in Sources */,
FBE598AB29E0297BC232ED75 /* ReportDetailsTests.swift in Sources */,
@@ -736,6 +743,7 @@
690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */,
C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */,
F38A1CCFAF016AB982EAB791 /* Question.swift in Sources */,
+ 93B2DAAF451BBE42A539CB94 /* QuestionEditor.swift in Sources */,
85A36A88AB170F0EAC0DAC03 /* QuestionPage.swift in Sources */,
9FEE3B78B770C6A3CF9C6610 /* QuestionsView.swift in Sources */,
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */,
diff --git a/Reportage/Views/Settings/QuestionEditor.swift b/Reportage/Views/Settings/QuestionEditor.swift
@@ -0,0 +1,412 @@
+import SwiftUI
+
+extension QuestionKind {
+ /// The kind as the question editor names it.
+ var title: LocalizedStringKey {
+ switch self {
+ case .yesNo: "Yes or No"
+ case .choice: "Choice"
+ case .tokens: "Activities"
+ case .people: "People"
+ case .location: "Place"
+ case .number: "Number"
+ case .note: "Note"
+ }
+ }
+
+ /// How answers of this kind show in the timeline.
+ var timelineSummary: LocalizedStringKey {
+ switch self {
+ case .yesNo: "In the timeline, each answer reads as the phrase given for it below."
+ case .choice: "In the timeline, answers read as the phrase below, with the answer in it."
+ case .tokens:
+ "In the timeline, answers start the report's opening sentence, as in 'Reading and drinking coffee at the library, with Sam.'"
+ case .location:
+ "In the timeline, answers join the report's opening sentence after 'at', as in 'Reading at the library.'"
+ case .people:
+ "In the timeline, answers join the report's opening sentence after 'with', as in 'Reading at the library, with Sam.'"
+ case .number: "In the timeline, answers read as a count of the thing named below."
+ case .note: "In the timeline, answers are quoted as written, after the words below."
+ }
+ }
+
+ /// The order kinds are offered in when adding a question.
+ static let offered: [QuestionKind] = [.tokens, .location, .people, .yesNo, .choice, .number, .note]
+}
+
+/// A question being edited: its prompt, answers and narrative rule as
+/// drafts, so that edits are saved when a field is finished rather than on
+/// every keystroke, and an answer renamed in the field renames past answers
+/// once.
+@MainActor
+@Observable
+final class QuestionEditor {
+ /// A choice answer being edited, with the text it was last saved with.
+ struct Option: Identifiable, Equatable {
+ let id = UUID()
+ var text: String
+ /// `nil` for an answer added since the last save.
+ var saved: String?
+ }
+
+ /// The question as last saved, or as it will be added.
+ private(set) var question: Question
+ /// Whether the question is still to be added. Only a new question's
+ /// kind can be chosen: answers already given wouldn't fit another.
+ let isNew: Bool
+ var kind: QuestionKind
+ var prompt: String
+ var options: [Option]
+ private(set) var askOn: SurveyKinds
+ private(set) var archivedAt: Date?
+ var showsInTimeline: Bool
+ var yesPhrase = ""
+ var noPhrase = ""
+ var template = ""
+ var singular = ""
+ var plural = ""
+ var lead = ""
+
+ init(question: Question, isNew: Bool = false) {
+ self.question = question
+ self.isNew = isNew
+ kind = question.kind
+ prompt = question.prompt
+ options = question.options.map { Option(text: $0, saved: $0) }
+ askOn = question.askOn
+ archivedAt = question.archivedAt
+ showsInTimeline = question.showsInTimeline
+ switch question.narrativeRule {
+ case .phrases(let yes, let no): (yesPhrase, noPhrase) = (yes, no)
+ case .template(let format): template = format
+ case .count(let singular, let plural): (self.singular, self.plural) = (singular, plural)
+ case .quote(let lead): self.lead = lead
+ case .activities, .place, .people, nil: break
+ }
+ }
+
+ /// A new question of `kind`, asked in the prompted survey.
+ convenience init(adding kind: QuestionKind) {
+ self.init(
+ question: Question(
+ id: UUID().uuidString, prompt: "", kind: kind, askOn: .random, order: 0,
+ modifiedAt: Date()),
+ isNew: true)
+ }
+
+ /// The rule the fields describe. Kinds whose rule comes from the kind
+ /// have none of their own.
+ var narrativeRule: NarrativeRule? {
+ switch kind {
+ case .yesNo: .phrases(yes: yesPhrase.trimmed, no: noPhrase.trimmed)
+ case .choice: .template(format: template.trimmed)
+ case .number: .count(singular: singular.trimmed, plural: plural.trimmed)
+ case .note: .quote(lead: lead.trimmed)
+ case .tokens, .location, .people: nil
+ }
+ }
+
+ /// Whether the draft can be added as a new question.
+ var isComplete: Bool {
+ !prompt.trimmed.isEmpty && (kind != .choice || options.contains { !$0.text.trimmed.isEmpty })
+ }
+
+ /// The question with the drafts applied, and the saved answers renamed
+ /// since, by old text. Blank and repeated answers are dropped; past
+ /// answers given with a dropped answer keep it.
+ func drafted() -> (question: Question, renames: [String: String]) {
+ var drafted = question
+ drafted.kind = kind
+ if !prompt.trimmed.isEmpty {
+ drafted.prompt = prompt.trimmed
+ }
+ var texts: [String] = []
+ var renames: [String: String] = [:]
+ for option in options {
+ let text = option.text.trimmed
+ guard !text.isEmpty else { continue }
+ if !texts.contains(text) { texts.append(text) }
+ if let saved = option.saved, saved != text { renames[saved] = text }
+ }
+ drafted.options = kind == .choice ? texts : []
+ drafted.askOn = askOn
+ drafted.archivedAt = archivedAt
+ drafted.showsInTimeline = showsInTimeline
+ // A question that never had a rule keeps none until one is written,
+ // so a rule the kind implies isn't replaced with a blank one.
+ let fields: [String] =
+ switch kind {
+ case .yesNo: [yesPhrase, noPhrase]
+ case .choice: [template]
+ case .number: [singular, plural]
+ case .note: [lead]
+ case .tokens, .location, .people: []
+ }
+ if question.narrativeRule != nil || fields.contains(where: { !$0.trimmed.isEmpty }) {
+ drafted.narrativeRule = narrativeRule
+ }
+ return (drafted, renames)
+ }
+
+ func isAsked(in survey: Survey) -> Bool {
+ var question = question
+ (question.askOn, question.archivedAt) = (askOn, archivedAt)
+ return question.isAsked(in: survey)
+ }
+
+ /// Asks or stops asking the question in `survey`, as
+ /// `Question.setAsked(_:in:)` does.
+ func setAsked(_ isAsked: Bool, in survey: Survey) {
+ var question = question
+ (question.askOn, question.archivedAt) = (askOn, archivedAt)
+ question.setAsked(isAsked, in: survey)
+ (askOn, archivedAt) = (question.askOn, question.archivedAt)
+ }
+
+ /// Takes `question` as saved, tidying the answers to match it.
+ func saved(_ question: Question) {
+ self.question = question
+ prompt = question.prompt
+ options = options.compactMap { option in
+ let text = option.text.trimmed
+ guard !text.isEmpty else { return nil }
+ var option = option
+ option.text = text
+ option.saved = text
+ return option
+ }
+ // Repeated answers were dropped from the question; drop their rows.
+ var seen: Set<String> = []
+ options.removeAll { !seen.insert($0.text).inserted }
+ }
+}
+
+extension String {
+ fileprivate var trimmed: String {
+ trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+}
+
+/// The fields of a question being edited or added: its prompt, its type,
+/// its answers for a choice, how it shows in the timeline and the surveys
+/// it's asked in. `onCommit` runs when a field is finished, a toggle changes
+/// or an answer is moved or removed.
+struct QuestionForm: View {
+ @Bindable var editor: QuestionEditor
+ var onCommit: () -> Void = {}
+
+ @FocusState private var focus: Field?
+
+ enum Field: Hashable {
+ case prompt
+ case option(UUID)
+ case rule(Int)
+ }
+
+ var body: some View {
+ List {
+ TextField("Question", text: $editor.prompt, axis: .vertical)
+ .font(Theme.serif(.title3, weight: .medium))
+ .focused($focus, equals: .prompt)
+ .submitLabel(.done)
+ .onChange(of: editor.prompt) { _, prompt in
+ // Return finishes the prompt rather than starting a line.
+ if prompt.contains("\n") {
+ editor.prompt = prompt.replacingOccurrences(of: "\n", with: "")
+ focus = nil
+ }
+ }
+ .settingsRow()
+ .listRowSeparator(.hidden, edges: .top)
+ Section {
+ if editor.isNew {
+ Picker("Type", selection: $editor.kind) {
+ ForEach(QuestionKind.offered, id: \.self) { kind in
+ Text(kind.title).tag(kind)
+ }
+ }
+ .tint(Theme.muted)
+ .settingsRow()
+ } else {
+ LabeledContent("Type") {
+ Text(editor.kind.title)
+ }
+ .settingsRow()
+ }
+ SettingsNote { Text(editor.kind.timelineSummary) }
+ }
+ if editor.kind == .choice {
+ OptionsSection(editor: editor, focus: $focus, onCommit: onCommit)
+ }
+ TimelineSection(editor: editor, focus: $focus)
+ Section {
+ ForEach(Survey.allCases, id: \.self) { survey in
+ Toggle(survey.title, isOn: asked(in: survey))
+ .settingsRow()
+ }
+ } header: {
+ SettingsHeading("Asked In")
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .scrollDismissesKeyboard(.interactively)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .onChange(of: focus) { onCommit() }
+ .onChange(of: editor.showsInTimeline) { onCommit() }
+ .onDisappear { onCommit() }
+ }
+
+ private func asked(in survey: Survey) -> Binding<Bool> {
+ Binding(
+ get: { editor.isAsked(in: survey) },
+ set: { isAsked in
+ editor.setAsked(isAsked, in: survey)
+ onCommit()
+ })
+ }
+}
+
+/// A choice question's answers, which can be renamed, moved, removed and
+/// added to.
+private struct OptionsSection: View {
+ @Bindable var editor: QuestionEditor
+ var focus: FocusState<QuestionForm.Field?>.Binding
+ let onCommit: () -> Void
+
+ var body: some View {
+ Section {
+ ForEach($editor.options) { $option in
+ TextField("Answer", text: $option.text)
+ .font(Theme.serif(.body))
+ .focused(focus, equals: .option(option.id))
+ .submitLabel(.done)
+ .settingsRow()
+ }
+ .onMove { offsets, destination in
+ editor.options.move(fromOffsets: offsets, toOffset: destination)
+ onCommit()
+ }
+ .onDelete { offsets in
+ editor.options.remove(atOffsets: offsets)
+ onCommit()
+ }
+ Button("Add Answer", systemImage: "plus") {
+ let option = QuestionEditor.Option(text: "")
+ editor.options.append(option)
+ focus.wrappedValue = .option(option.id)
+ }
+ .foregroundStyle(Theme.accent)
+ .settingsRow()
+ if !editor.isNew {
+ SettingsNote {
+ Text(
+ "Renaming an answer renames it in past reports too. Removing one leaves past reports as they were."
+ )
+ }
+ }
+ } header: {
+ SettingsHeading("Answers")
+ }
+ }
+}
+
+/// Whether the question shows in the timeline and, for kinds with phrasing
+/// of their own, how its answers read there, with an example.
+private struct TimelineSection: View {
+ @Bindable var editor: QuestionEditor
+ var focus: FocusState<QuestionForm.Field?>.Binding
+
+ var body: some View {
+ Section {
+ Toggle("Show in Timeline", isOn: $editor.showsInTimeline)
+ .settingsRow()
+ if editor.showsInTimeline {
+ switch editor.kind {
+ case .yesNo:
+ field("Yes", "Working", text: $editor.yesPhrase, index: 0)
+ field("No", "Not working", text: $editor.noPhrase, index: 1)
+ case .choice:
+ field("Phrase", "Feeling %@", text: $editor.template, index: 0)
+ case .number:
+ field("One", "coffee", text: $editor.singular, index: 0)
+ field("More", "coffees", text: $editor.plural, index: 1)
+ case .note:
+ field("Before", "Learned", text: $editor.lead, index: 0)
+ case .tokens, .location, .people:
+ EmptyView()
+ }
+ if let example {
+ SettingsNote { Text(example) }
+ }
+ } else {
+ SettingsNote {
+ Text("Answers to this question are left out of the timeline. They're still shown in each report's details.")
+ }
+ }
+ } header: {
+ SettingsHeading("Timeline")
+ }
+ }
+
+ private func field(
+ _ label: LocalizedStringKey, _ prompt: String, text: Binding<String>, index: Int
+ ) -> some View {
+ LabeledContent(label) {
+ TextField(label, text: text, prompt: Text(verbatim: prompt))
+ .font(Theme.serif(.body))
+ .multilineTextAlignment(.trailing)
+ .focused(focus, equals: .rule(index))
+ .submitLabel(.done)
+ }
+ .settingsRow()
+ }
+
+ /// What the question's answers read as now, and what happens to those
+ /// whose phrasing is left blank. `nil` for kinds without phrasing.
+ private var example: String? {
+ let samples = NarrativeExample.samples(for: editor.kind, options: editor.options.map(\.text))
+ guard editor.narrativeRule != nil else { return nil }
+ let narratives = samples.compactMap { NarrativeExample.narrative(of: $0, rule: editor.narrativeRule) }
+ let blank = String(localized: "Left blank, answers are shown beneath the report's sentence with their question.")
+ guard !narratives.isEmpty else {
+ return editor.kind == .choice && samples.isEmpty
+ ? String(localized: "Put %@ where the answer goes.") : blank
+ }
+ let quoted = narratives.map { "'\($0)'" }.formatted(.list(type: .or))
+ var example = String(localized: "Reads as \(quoted)")
+ if editor.kind == .choice {
+ example = String(localized: "Put %@ where the answer goes. \(example)")
+ }
+ if narratives.count < samples.count {
+ example += " " + String(localized: "An answer left blank is shown with its question.")
+ }
+ return example
+ }
+}
+
+/// Sample answers for showing how a rule reads.
+@MainActor
+enum NarrativeExample {
+ static func samples(for kind: QuestionKind, options: [String]) -> [ResponseValue] {
+ switch kind {
+ case .yesNo: [.options([ResponseValue.yesOption]), .options([ResponseValue.noOption])]
+ case .choice:
+ options.lazy.map { $0.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty }
+ .map { [.options([$0])] } ?? []
+ case .number: [.number(1), .number(2)]
+ case .note: [.text("…")]
+ case .tokens, .location, .people: []
+ }
+ }
+
+ /// The narrative `value` reads as under `rule`, or `nil` when it would
+ /// be shown as question and answer instead.
+ static func narrative(of value: ResponseValue, rule: NarrativeRule?) -> String? {
+ var lookup = SummaryLookup()
+ lookup.questionRules["Q"] = rule
+ let response = Response(questionID: "Q", prompt: "", value: value)
+ return NarrativeBuilder.build(responses: [response], lookup: lookup).narrative
+ }
+}
diff --git a/Reportage/Views/Settings/QuestionsView.swift b/Reportage/Views/Settings/QuestionsView.swift
@@ -62,6 +62,7 @@ final class QuestionList {
private(set) var isLoaded = false
private var store: ReportStore?
+ private var saving: Task<Void, Never>?
private let logger = Logger(subsystem: "net.inqk.reportage", category: "Questions")
func load(from store: ReportStore?) async {
@@ -75,13 +76,24 @@ final class QuestionList {
questions.first { $0.id == id }
}
- func update(_ question: Question) {
+ /// Saves an edited question. Renamed answers, by old text, are renamed
+ /// in past reports too.
+ func update(_ question: Question, renamingOptions renames: [String: String] = [:]) {
guard let index = questions.firstIndex(where: { $0.id == question.id }),
- questions[index] != question
+ questions[index] != question || !renames.isEmpty
else { return }
var question = question
question.modifiedAt = Date()
questions[index] = question
+ enqueue { [question] in try await $0.save(question, renamingOptions: renames) }
+ }
+
+ /// Adds a question at the end of the order.
+ func add(_ question: Question) {
+ var question = question
+ question.order = (questions.map(\.order).max() ?? -1) + 1
+ question.modifiedAt = Date()
+ questions.append(question)
save([question])
}
@@ -129,10 +141,19 @@ final class QuestionList {
}
private func save(_ questions: [Question]) {
- guard let store, !questions.isEmpty else { return }
- Task {
+ guard !questions.isEmpty else { return }
+ enqueue { try await $0.save(questions) }
+ }
+
+ /// Runs saves one after another, so a later edit can't be overwritten
+ /// by an earlier one finishing after it.
+ private func enqueue(_ save: @escaping @Sendable (ReportStore) async throws -> Void) {
+ guard let store else { return }
+ let previous = saving
+ saving = Task { [logger] in
+ await previous?.value
do {
- try await store.save(questions)
+ try await save(store)
} catch {
logger.error("Couldn't save questions: \(error)")
}
@@ -141,11 +162,12 @@ final class QuestionList {
}
/// 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.
+/// timeline. Questions are moved by dragging, opened to edit, and added
+/// with the add button.
struct QuestionsView: View {
@Environment(\.reportStore) private var store
@State private var list = QuestionList()
+ @State private var isAdding = false
var body: some View {
List {
@@ -190,6 +212,13 @@ struct QuestionsView: View {
ToolbarItem(placement: .primaryAction) {
EditButton()
}
+ ToolbarItem(placement: .primaryAction) {
+ Button("Add Question", systemImage: "plus") { isAdding = true }
+ .disabled(!list.isLoaded)
+ }
+ }
+ .sheet(isPresented: $isAdding) {
+ AddQuestionView(list: list)
}
.task { await list.load(from: store) }
}
@@ -203,7 +232,7 @@ private struct QuestionRow: View {
var body: some View {
NavigationLink {
- QuestionDetailView(id: question.id, list: list)
+ QuestionDetailView(question: question, list: list)
} label: {
VStack(alignment: .leading, spacing: Theme.lineGap) {
Text(question.prompt)
@@ -219,63 +248,53 @@ private struct QuestionRow: View {
}
}
-/// One question's surveys and whether its answers show in the timeline.
+/// One question, edited in place. Each field is saved when it's finished.
private struct QuestionDetailView: View {
- let id: String
let list: QuestionList
+ @State private var editor: QuestionEditor
+
+ init(question: Question, list: QuestionList) {
+ self.list = list
+ _editor = State(initialValue: QuestionEditor(question: question))
+ }
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")
- }
+ QuestionForm(editor: editor) {
+ let (question, renames) = editor.drafted()
+ guard question != editor.question || !renames.isEmpty else { return }
+ list.update(question, renamingOptions: renames)
+ if let saved = list.question(id: question.id) {
+ editor.saved(saved)
}
}
- .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)
- })
- }
+/// A new question's fields, its type among them, added to the end of the
+/// order.
+private struct AddQuestionView: View {
+ let list: QuestionList
+ @State private var editor = QuestionEditor(adding: .tokens)
+ @Environment(\.dismiss) private var dismiss
- private func showsInTimeline(_ question: Question) -> Binding<Bool> {
- Binding(
- get: { question.showsInTimeline },
- set: { shows in
- var question = question
- question.showsInTimeline = shows
- list.update(question)
- })
+ var body: some View {
+ NavigationStack {
+ QuestionForm(editor: editor)
+ .navigationTitle("New Question")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Cancel") { dismiss() }
+ }
+ ToolbarItem(placement: .confirmationAction) {
+ Button("Add") {
+ list.add(editor.drafted().question)
+ dismiss()
+ }
+ .disabled(!editor.isComplete)
+ }
+ }
+ }
}
}
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -76,9 +76,20 @@ struct ReportStore: Sendable {
}
}
- /// Saves edits to existing questions. Questions not in the store are
- /// left out, since questions are only added by seeding or importing.
+ /// Saves questions, adding those not yet in the store.
func save(_ questions: [Question]) async throws {
+ try await save(questions, renaming: [:])
+ }
+
+ /// Saves a choice question along with renamed options, by old text.
+ /// Past answers given with an old option are rewritten to the new one,
+ /// as renaming a token renames it throughout history, and their reports
+ /// count as modified.
+ func save(_ question: Question, renamingOptions renames: [String: String]) async throws {
+ try await save([question], renaming: [question.id: renames])
+ }
+
+ private func save(_ questions: [Question], renaming: [String: [String: String]]) async throws {
let context = persistence.newBackgroundContext()
try await context.perform {
let request = QuestionEntity.fetchRequest()
@@ -87,12 +98,32 @@ struct ReportStore: Sendable {
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 (entities[question.id] ?? QuestionEntity(context: context)).update(from: question)
+ }
+ for question in questions {
+ guard let renames = renaming[question.id], !renames.isEmpty else { continue }
+ try Self.renameOptions(renames, of: question.id, at: question.modifiedAt, in: context)
}
try context.save()
}
}
+ private static func renameOptions(
+ _ renames: [String: String], of questionID: String, at now: Date, in context: NSManagedObjectContext
+ ) throws {
+ let request = ResponseEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "questionID == %@", questionID)
+ for entity in try context.fetch(request) {
+ guard let data = entity.value,
+ case .options(let options) = try ModelCoding.decode(ResponseValue.self, from: data)
+ else { continue }
+ let renamed = options.map { renames[$0] ?? $0 }
+ guard renamed != options else { continue }
+ entity.value = try ModelCoding.encode(ResponseValue.options(renamed))
+ entity.report?.modifiedAt = now
+ }
+ }
+
/// 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/Tests/Unit/QuestionEditorTests.swift b/Tests/Unit/QuestionEditorTests.swift
@@ -0,0 +1,84 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@MainActor
+@Suite("QuestionEditor")
+struct QuestionEditorTests {
+
+ private static func question(
+ _ kind: QuestionKind, options: [String] = [], rule: NarrativeRule? = nil
+ ) -> Question {
+ Question(
+ id: "Q", prompt: "Prompt?", kind: kind, options: options, narrativeRule: rule, askOn: .random,
+ order: 0, modifiedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ @Test("Answers renamed in their field are renamed by old text; blank and repeated answers are dropped")
+ func renames() {
+ let editor = QuestionEditor(question: Self.question(.choice, options: ["Great", "Okay", "Bad"]))
+ editor.options[1].text = " Fine "
+ editor.options[2].text = ""
+ editor.options.append(.init(text: "Great"))
+ editor.options.append(.init(text: "Awful"))
+
+ let (question, renames) = editor.drafted()
+ #expect(question.options == ["Great", "Fine", "Awful"])
+ #expect(renames == ["Okay": "Fine"])
+
+ editor.saved(question)
+ #expect(editor.options.map(\.text) == ["Great", "Fine", "Awful"])
+ #expect(editor.drafted().renames.isEmpty)
+ }
+
+ @Test("A question with no rule keeps none until one is written, and a written rule can be cleared")
+ func rules() {
+ let editor = QuestionEditor(question: Self.question(.yesNo))
+ editor.prompt = "Raining?"
+ #expect(editor.drafted().question.narrativeRule == nil)
+
+ editor.yesPhrase = "Raining"
+ #expect(editor.drafted().question.narrativeRule == .phrases(yes: "Raining", no: ""))
+
+ let cleared = QuestionEditor(question: Self.question(.number, rule: .count(singular: "cup", plural: "cups")))
+ (cleared.singular, cleared.plural) = ("", "")
+ #expect(cleared.drafted().question.narrativeRule == .count(singular: "", plural: ""))
+ }
+
+ @Test("A blank prompt keeps the saved one, and a choice needs an answer to be added")
+ func completeness() {
+ let editor = QuestionEditor(adding: .choice)
+ editor.prompt = "Weather?"
+ #expect(!editor.isComplete)
+ editor.options.append(.init(text: "Sunny"))
+ #expect(editor.isComplete)
+
+ let existing = QuestionEditor(question: Self.question(.note))
+ existing.prompt = " "
+ #expect(existing.drafted().question.prompt == "Prompt?")
+ }
+
+ @Test("Examples read as the rule writes, or not at all when it's blank")
+ func examples() {
+ let rule = NarrativeRule.count(singular: "cup", plural: "cups")
+ let samples = NarrativeExample.samples(for: .number, options: [])
+ #expect(samples.compactMap { NarrativeExample.narrative(of: $0, rule: rule) } == ["1 cup.", "2 cups."])
+ #expect(NarrativeExample.narrative(of: .number(1), rule: .count(singular: "", plural: "")) == nil)
+ }
+
+ @Test("A new question's type can be chosen, and only a choice keeps answers")
+ func newKind() {
+ let editor = QuestionEditor(adding: .tokens)
+ #expect(editor.isNew)
+ editor.prompt = "Weather?"
+ editor.kind = .choice
+ editor.options.append(.init(text: "Sunny"))
+ #expect(editor.drafted().question.kind == .choice)
+ #expect(editor.drafted().question.options == ["Sunny"])
+ editor.kind = .yesNo
+ #expect(editor.drafted().question.options.isEmpty)
+ #expect(editor.drafted().question.narrativeRule == nil)
+ #expect(!QuestionEditor(question: editor.drafted().question).isNew)
+ }
+}
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -401,4 +401,37 @@ extension ReportStoreTests {
#expect(filled[mood].narrativeRule == .template(format: "Feeling %@"))
#expect(filled[working].narrativeRule == .phrases(yes: "", no: ""))
}
+
+ @Test("A new question is added by saving it")
+ func addQuestion() async throws {
+ let question = Question(
+ id: "new", prompt: "Raining?", kind: .yesNo, askOn: .random, order: 0,
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ try await store.save([question])
+ #expect(try await store.allQuestions() == [question])
+ }
+
+ @Test("Renaming a choice answer renames it in past reports, which count as modified")
+ func renameOptions() async throws {
+ var question = Question(
+ id: "mood", prompt: "Mood?", kind: .choice, options: ["Okay", "Good"], askOn: .random, order: 0,
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ try await store.save([question])
+ let okay = Self.report(1, responses: [Response(questionID: "mood", prompt: "Mood?", value: .options(["Okay"]))])
+ let good = Self.report(2, responses: [Response(questionID: "mood", prompt: "Mood?", value: .options(["Good"]))])
+ try await store.insert(okay)
+ try await store.insert(good)
+
+ question.options = ["Fine", "Good"]
+ question.modifiedAt = Date(timeIntervalSince1970: 100)
+ try await store.save(question, renamingOptions: ["Okay": "Fine"])
+
+ let renamed = try #require(try await store.report(id: okay.id))
+ #expect(renamed.responses.first?.value == .options(["Fine"]))
+ #expect(renamed.modifiedAt == question.modifiedAt)
+ let kept = try #require(try await store.report(id: good.id))
+ #expect(kept.responses.first?.value == .options(["Good"]))
+ #expect(kept.modifiedAt == good.modifiedAt)
+ #expect(try await store.allQuestions().first?.options == ["Fine", "Good"])
+ }
}