commit cb3abf3be5c65b69cb57dbccbc2dc126b1f4d6c0
parent 87e87e5f6d854c9efe58e67908f05a189f41aa0c
Author: Michael Camilleri <[email protected]>
Date: Sat, 17 Oct 2026 06:13:57 +0900
Support editing a report's answers from the timeline
Once a survey was submitted, its answers were fixed and could not be
corrected.
This commit opens any report in the survey when it is tapped, with its
answers filled in. The survey shows the questions the report answered,
in its order and as they were asked, including archived ones. An instant
report, which has no answers yet, is filled in with the current survey
as before.
Editing changes only what the user changes. An answer left alone is
saved back exactly, with the prompt it was given under and where a
place answer was given, and responses to questions that no longer exist
are kept. A changed answer keeps its original prompt. Answers that use
archived or merged tokens still show as chosen, so saving cannot drop
them; a merged token shows the name of the token it was merged into but
keeps its own ID, so the merge can still be undone. The report keeps
when it was completed, and its entry is rewritten because its draft
changes.
Cancelling asks for confirmation only when something has changed, and
says that the report stays as it was.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 10 | ++++++++++ |
| M | Reportage/Views/Home/HomeView.swift | | | 18 | +++++++++++------- |
| M | Reportage/Views/Survey/PlacePicker.swift | | | 21 | +++++++++++++++++++++ |
| M | Reportage/Views/Survey/SurveyModel.swift | | | 84 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------- |
| M | Reportage/Views/Survey/SurveyView.swift | | | 37 | ++++++++++++++++++++++++------------- |
| M | Shared/Models/Response.swift | | | 11 | +++++++++++ |
| M | Shared/Persistence/ReportStore.swift | | | 61 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- |
| M | Tests/Unit/ReportStoreTests.swift | | | 43 | +++++++++++++++++++++++++++++++++++++++---- |
| M | Tests/Unit/SurveyModelTests.swift | | | 58 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++- |
9 files changed, 303 insertions(+), 40 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -521,6 +521,16 @@ opening the survey. The badge counts passive reports; it shows only once notifications are allowed, which Phase 3 asks for, and could become a setting. +Any finished report can be edited the same way, by tapping it. The survey +shows the questions the report answered, in its order and as they were asked, +including archived ones, rather than today's survey: adding new questions to +an old report would rewrite history. Answers using archived or merged tokens +still show as chosen. An answer left as it was keeps its response exactly, +with the prompt it was given under and where a place answer was given, and +responses to questions that no longer exist are kept. A changed answer keeps +its original prompt. The report keeps when it was completed; its entry is +rewritten because its draft changes. + There's one App Intent, `LogPassiveReportIntent`, in `Shared/`. It drives every quick-log surface:
diff --git a/Reportage/Views/Home/HomeView.swift b/Reportage/Views/Home/HomeView.swift
@@ -17,7 +17,7 @@ struct HomeView: View {
describer: describer,
onStart: { kind in survey = SurveyRequest(kind: kind) },
onQuickLog: quickLog,
- onFillIn: { id, kind in survey = .fillIn(id, kind: kind) }
+ onEdit: { id, kind in survey = .edit(id, kind: kind) }
)
.toolbar(.hidden, for: .navigationBar)
}
@@ -95,8 +95,8 @@ struct ReportList: View {
let describer: ReportDescriber
let onStart: (ReportKind) -> Void
let onQuickLog: () -> Void
- /// Opens the survey for a report logged for later.
- let onFillIn: (UUID, ReportKind) -> Void
+ /// Opens the survey for an existing report, to fill it in or edit it.
+ let onEdit: (UUID, ReportKind) -> Void
@SectionedFetchRequest(fetchRequest: ReportList.request, sectionIdentifier: \ReportEntity.dayKey)
private var days: SectionedFetchResults<String, ReportEntity>
@@ -140,18 +140,22 @@ struct ReportList: View {
.background(Theme.paper)
}
- /// A report logged for later can be tapped to fill it in.
+ /// A report can be tapped to fill it in, if it's an instant report, or
+ /// to edit its answers.
@ViewBuilder
private func row(for report: ReportEntity) -> some View {
- if report.state == ReportState.passive.rawValue, let id = report.id {
+ if let id = report.id {
Button {
- onFillIn(id, report.kind.flatMap(ReportKind.init) ?? .manual)
+ onEdit(id, report.kind.flatMap(ReportKind.init) ?? .manual)
} label: {
ReportRow(report: report, describer: describer)
.contentShape(.rect)
}
.buttonStyle(.plain)
- .accessibilityHint(Text("Answers the survey for this moment"))
+ .accessibilityHint(
+ report.state == ReportState.passive.rawValue
+ ? Text("Answers the survey for this moment")
+ : Text("Edits this report's answers"))
} else {
ReportRow(report: report, describer: describer)
}
diff --git a/Reportage/Views/Survey/PlacePicker.swift b/Reportage/Views/Survey/PlacePicker.swift
@@ -164,6 +164,27 @@ final class PlacePicker {
query = ""
}
+ /// Chooses the place with token `id`, as an existing answer does, adding
+ /// `entry` if the suggestions leave it out.
+ func preselect(_ id: String, entry: VocabularyEntry?) {
+ if let entry, !entries.contains(where: { $0.id == entry.id }) {
+ entries.append(entry)
+ update()
+ }
+ let known = entries.first { $0.id == id }
+ selection =
+ candidate(id: id)
+ ?? PlaceCandidate(
+ id: id,
+ source: .own,
+ name: known?.text ?? "",
+ coordinate: known?.coordinate,
+ distance: location.flatMap { location in
+ known?.coordinate?.distance(to: location.coordinate)
+ }
+ )
+ }
+
/// The place added in this survey, if it's the one chosen.
func usedNewTokens(now: Date) -> [Token] {
guard let id = selectedTokenID, var token = newTokens[id] else { return [] }
diff --git a/Reportage/Views/Survey/SurveyModel.swift b/Reportage/Views/Survey/SurveyModel.swift
@@ -8,12 +8,13 @@ import Observation
final class SurveyModel {
let kind: ReportKind
/// The moment the report describes: when the survey was started, or
- /// when the report being filled in was logged.
+ /// when the report being edited was made.
let date: Date
let timeZone: String
let questions: [Question]
- /// The report logged for later that this survey fills in, if any. Its
- /// context was captured when it was logged, so none is captured now.
+ /// The report this survey edits, if any: an instant report being filled
+ /// in, or a finished one being changed. Its context was captured when it
+ /// was made, so none is captured now.
let existing: Report?
/// Pickers for `tokens` and `people` questions, and for `location`
/// questions, by question ID. They're created once so each page keeps its
@@ -23,6 +24,8 @@ final class SurveyModel {
private(set) var index = 0
private var answers: [String: ResponseValue] = [:]
+ /// The existing report's responses, by question ID.
+ private let originalResponses: [String: Response]
/// Live context, captured from when the survey opens.
private var contextTask: Task<Context, Never>?
@@ -39,11 +42,15 @@ final class SurveyModel {
questions: questions, vocabulary: vocabulary, directory: directory)
}
- /// A survey that fills in `report`, as of the moment it was logged.
+ /// A survey that edits `report`, as of the moment it describes, starting
+ /// from its answers. `tokens` are entries for the tokens its answers use
+ /// that suggestions leave out, such as archived ones, so every answer
+ /// shows.
convenience init(
- fillingIn report: Report,
+ editing report: Report,
questions: [Question],
vocabulary: [String: [VocabularyEntry]],
+ tokens: [String: VocabularyEntry] = [:],
directory: any PlaceDirectory = MapKitPlaceDirectory()
) {
self.init(
@@ -52,6 +59,17 @@ final class SurveyModel {
for picker in placePickers.values {
picker.setLocation(report.context.location)
}
+ for question in questions {
+ guard let value = originalResponses[question.id]?.value else { continue }
+ switch value {
+ case .options, .number, .text:
+ answers[question.id] = value
+ case .tokens(let ids):
+ pickers[question.id]?.preselect(ids, entries: ids.compactMap { tokens[$0] })
+ case .place(let place):
+ placePickers[question.id]?.preselect(place.tokenID, entry: tokens[place.tokenID])
+ }
+ }
}
private init(
@@ -68,6 +86,9 @@ final class SurveyModel {
self.timeZone = timeZone
self.existing = existing
self.questions = questions
+ self.originalResponses = Dictionary(
+ (existing?.responses ?? []).map { ($0.questionID, $0) },
+ uniquingKeysWith: { first, _ in first })
var pickers: [String: TokenPicker] = [:]
var placePickers: [String: PlacePicker] = [:]
for question in questions {
@@ -103,6 +124,24 @@ final class SurveyModel {
questions.contains { value(for: $0) != nil }
}
+ /// Whether cancelling would lose work: anything answered in a new
+ /// report, or any answer changed in an existing one.
+ var hasChanges: Bool {
+ guard existing != nil else { return hasAnswers }
+ return questions.contains { question in
+ !Self.isSameAnswer(originalResponses[question.id]?.value, value(for: question))
+ }
+ }
+
+ /// Whether two answers are the same. A place answer is the same place
+ /// whatever coordinate it records.
+ private static func isSameAnswer(_ lhs: ResponseValue?, _ rhs: ResponseValue?) -> Bool {
+ if case .place(let lhs) = lhs, case .place(let rhs) = rhs {
+ return lhs.tokenID == rhs.tokenID
+ }
+ return lhs == rhs
+ }
+
// MARK: Answers
/// The chosen option of a `yesNo` or `choice` question.
@@ -218,14 +257,19 @@ final class SurveyModel {
/// The finished report, with a response for every question in the
/// survey (skipped questions have no value), and the tokens created
- /// while answering that the report uses. A report being filled in keeps
- /// its ID, trigger and context, and gains the answers.
+ /// while answering that the report uses.
+ ///
+ /// An existing report keeps its ID, trigger and context. An answer left
+ /// as it was keeps its response exactly, with the prompt it was given
+ /// under and where a place answer was given; responses to questions not
+ /// shown are kept too. An instant report becomes complete now; a
+ /// finished one keeps when it was completed.
func makeReport(
id: UUID = UUID(),
now: Date,
context: Context = Context()
) -> (report: Report, newTokens: [Token]) {
- let responses = questions.map { question in
+ var responses = questions.map { question in
var value = value(for: question)
// A place answer records where it was given.
if case .place(var answer) = value, let location = context.location {
@@ -233,15 +277,27 @@ final class SurveyModel {
answer.accuracy = location.horizontalAccuracy
value = .place(answer)
}
+ if let original = originalResponses[question.id] {
+ return Self.isSameAnswer(original.value, value)
+ ? original
+ : Response(questionID: question.id, prompt: original.prompt, value: value)
+ }
return Response(questionID: question.id, prompt: question.prompt, value: value)
}
+ if let existing, !existing.responses.isEmpty {
+ let edited = Dictionary(
+ responses.map { ($0.questionID, $0) }, uniquingKeysWith: { first, _ in first })
+ responses = existing.responses.map { edited[$0.questionID] ?? $0 }
+ }
let newTokens = questions.flatMap { question in
pickers[question.id]?.usedNewTokens(now: now)
?? placePickers[question.id]?.usedNewTokens(now: now) ?? []
}
if var report = existing {
- report.state = .complete
- report.completedAt = now
+ if report.state == .passive {
+ report.state = .complete
+ report.completedAt = now
+ }
report.responses = responses
report.modifiedAt = now
return (report, newTokens)
@@ -333,6 +389,14 @@ final class TokenPicker {
query = ""
}
+ /// Selects `ids`, as an existing answer does, adding `entries` for any
+ /// the suggestions leave out so each selected token shows.
+ func preselect(_ ids: [String], entries extra: [VocabularyEntry]) {
+ let known = Set(entries.map(\.id))
+ entries += extra.filter { !known.contains($0.id) }
+ selection = ids
+ }
+
/// Tokens added in this survey that are still selected.
func usedNewTokens(now: Date) -> [Token] {
selection.compactMap { id in
diff --git a/Reportage/Views/Survey/SurveyView.swift b/Reportage/Views/Survey/SurveyView.swift
@@ -1,16 +1,17 @@
import SwiftUI
-/// What to survey: a new report of `kind` describing `date`, or answers for
-/// a report that was logged for later.
+/// What to survey: a new report of `kind` describing `date`, or an existing
+/// report to fill in or edit.
struct SurveyRequest: Identifiable {
let id = UUID()
var kind: ReportKind
var date = Date()
- /// The report logged for later to fill in.
+ /// The existing report to edit.
var reportID: UUID?
- /// Fills in the report logged for later with `id`.
- static func fillIn(_ id: UUID, kind: ReportKind) -> SurveyRequest {
+ /// Edits the report with `id`: an instant report to fill in, or a
+ /// finished one to change.
+ static func edit(_ id: UUID, kind: ReportKind) -> SurveyRequest {
SurveyRequest(kind: kind, reportID: id)
}
}
@@ -53,14 +54,24 @@ struct SurveySheet: View {
}
existing = report
}
- let questions = try await store.surveyQuestions(for: existing?.kind ?? request.kind)
+ // A report with answers is edited with the questions it answered,
+ // as they were asked; an instant report is filled in with its
+ // survey as it is now.
+ let questions =
+ if let existing, !existing.responses.isEmpty {
+ try await store.questions(ids: existing.responses.map(\.questionID))
+ } else {
+ try await store.surveyQuestions(for: existing?.kind ?? request.kind)
+ }
let tokenQuestions = questions.filter {
[QuestionKind.tokens, .people, .location].contains($0.kind)
}
let vocabulary = try await store.vocabulary(for: tokenQuestions.map(\.id))
let model: SurveyModel
if let existing {
- model = SurveyModel(fillingIn: existing, questions: questions, vocabulary: vocabulary)
+ let tokens = try await store.tokenEntries(ids: existing.responses.flatMap(\.tokenIDs))
+ model = SurveyModel(
+ editing: existing, questions: questions, vocabulary: vocabulary, tokens: tokens)
} else {
model = SurveyModel(
kind: request.kind,
@@ -106,18 +117,18 @@ struct SurveyView: View {
onCancel: cancel
)
.confirmationDialog(
- model.existing == nil ? "Discard this report?" : "Discard these answers?",
+ model.existing == nil ? "Discard this report?" : "Discard your changes?",
isPresented: $isConfirmingCancel,
titleVisibility: .visible
) {
if model.existing == nil {
Button("Discard Report", role: .destructive) { dismiss() }
} else {
- Button("Discard Answers", role: .destructive) { dismiss() }
+ Button("Discard Changes", role: .destructive) { dismiss() }
}
} message: {
if model.existing != nil {
- Text("The report stays logged, and can be filled in later.")
+ Text("The report stays as it was.")
}
}
}
@@ -137,11 +148,11 @@ struct SurveyView: View {
} message: {
if let saveError { Text(saveError) }
}
- .interactiveDismissDisabled(model.hasAnswers)
+ .interactiveDismissDisabled(model.hasChanges)
}
private func cancel() {
- if model.hasAnswers {
+ if model.hasChanges {
isConfirmingCancel = true
} else {
dismiss()
@@ -177,7 +188,7 @@ struct SurveyView: View {
if model.existing == nil {
try await store.insert(report, newTokens: newTokens)
} else {
- try await store.fillIn(report, newTokens: newTokens)
+ try await store.saveAnswers(report, newTokens: newTokens)
}
dismiss()
} catch {
diff --git a/Shared/Models/Response.swift b/Shared/Models/Response.swift
@@ -22,6 +22,17 @@ enum ResponseValue: Hashable, Sendable {
case place(PlaceAnswer)
}
+extension Response {
+ /// The tokens the answer uses: its tokens, or its place.
+ var tokenIDs: [String] {
+ switch value {
+ case .tokens(let ids): ids
+ case .place(let place): [place.tokenID]
+ case .options, .number, .text, nil: []
+ }
+ }
+}
+
extension ResponseValue {
/// The options `yesNo` answers are stored with. These are fixed values
/// rather than display text, as they were in Reporter.
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -41,6 +41,56 @@ struct ReportStore: Sendable {
}
}
+ /// 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] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = QuestionEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", ids)
+ let byID = Dictionary(
+ try context.fetch(request).map { try $0.question() }.map { ($0.id, $0) },
+ uniquingKeysWith: { first, _ in first })
+ return ids.compactMap { byID[$0] }
+ }
+ }
+
+ /// Entries for the tokens with `ids`, archived or not, by ID. A token
+ /// merged into another shows that token's name and place, but keeps its
+ /// own ID, so an answer that uses it is unchanged.
+ func tokenEntries(ids: [String]) async throws -> [String: VocabularyEntry] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ var tokens: [String: Token] = [:]
+ var wanted = Set(ids)
+ // Fetch the tokens, then the tokens they were merged into, and so
+ // on along each chain.
+ while !wanted.isEmpty {
+ let request = TokenEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id IN %@", Array(wanted))
+ let found = try context.fetch(request).map { try $0.token() }
+ for token in found { tokens[token.id] = token }
+ wanted = Set(found.compactMap(\.mergedInto)).subtracting(tokens.keys)
+ }
+ var entries: [String: VocabularyEntry] = [:]
+ for id in ids {
+ guard var token = tokens[id] else { continue }
+ var seen: Set<String> = [id]
+ while let next = token.mergedInto.flatMap({ tokens[$0] }), seen.insert(next.id).inserted {
+ token = next
+ }
+ entries[id] = VocabularyEntry(
+ id: id,
+ text: token.text,
+ useCount: 0,
+ coordinate: token.place?.coordinate,
+ externalID: token.place?.externalID
+ )
+ }
+ return entries
+ }
+ }
+
/// Ranked suggestions for each of `questionIDs`. See `Vocabulary`.
func vocabulary(for questionIDs: [String]) async throws -> [String: [VocabularyEntry]] {
let context = persistence.newBackgroundContext()
@@ -77,11 +127,12 @@ struct ReportStore: Sendable {
}
}
- /// Saves the answers to a report that was logged for later, together
- /// with the tokens created while answering. Only the answers and what
- /// marks the report complete are taken from `report`, so a context
- /// captured meanwhile isn't overwritten.
- func fillIn(_ report: Report, newTokens: [Token] = []) async throws {
+ /// Saves new answers to an existing report, whether filling in an instant
+ /// report or editing a finished one, together with the tokens created
+ /// while answering. Only the answers and what marks the report complete
+ /// are taken from `report`, so a context captured meanwhile isn't
+ /// overwritten.
+ func saveAnswers(_ report: Report, newTokens: [Token] = []) async throws {
let context = persistence.newBackgroundContext()
try await context.perform {
guard let entity = try Self.entity(id: report.id, in: context) else {
diff --git a/Tests/Unit/ReportStoreTests.swift b/Tests/Unit/ReportStoreTests.swift
@@ -212,8 +212,8 @@ struct ReportStoreTests {
#expect(report.context == captured)
}
- @Test("Filling in a report saves its answers and keeps its context")
- func fillIn() async throws {
+ @Test("Saving answers to a logged report keeps its context")
+ func saveAnswers() async throws {
var logged = Self.report(1, responses: [])
logged.state = .passive
try await store.insert(logged)
@@ -228,7 +228,7 @@ struct ReportStoreTests {
var captured = Context()
captured.device = DeviceContext(connectivity: .wifi)
try await store.setContext(captured, for: logged.id)
- try await store.fillIn(answered, newTokens: [Self.token("N", "New")])
+ try await store.saveAnswers(answered, newTokens: [Self.token("N", "New")])
let report = try #require(try await store.report(id: logged.id))
#expect(report.state == .complete)
@@ -240,10 +240,45 @@ struct ReportStoreTests {
#expect(try await store.vocabulary(for: ["Q"])["Q"]?.map(\.id) == ["N"])
await #expect(throws: ReportStoreError.self) {
- try await store.fillIn(Self.report(2, responses: []))
+ try await store.saveAnswers(Self.report(2, responses: []))
}
}
+ @Test("Questions are found by ID in the order given, archived or not")
+ func questionsByID() async throws {
+ try await store.seedDefaultQuestionsIfNeeded()
+ var archived = try #require(try await store.surveyQuestions(for: .wake).first)
+ archived.archivedAt = Date()
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ let request = QuestionEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id == %@", archived.id)
+ try #require(try context.fetch(request).first).update(from: archived)
+ try context.save()
+ }
+ let ids = ["reportage-default-location", "missing", archived.id]
+ let found = try await store.questions(ids: ids)
+ #expect(found.map(\.id) == ["reportage-default-location", archived.id])
+ }
+
+ @Test("Token entries follow merges but keep their own IDs")
+ func tokenEntries() async throws {
+ var archived = Self.token("A", "Archived")
+ archived.archivedAt = Date()
+ let tokens = [
+ archived,
+ Self.token("B", "Before", mergedInto: "C"),
+ Self.token("C", "Middle", mergedInto: "D"),
+ Self.token("D", "Final"),
+ ]
+ try await store.insert(Self.report(1, responses: []), newTokens: tokens)
+ let entries = try await store.tokenEntries(ids: ["A", "B", "missing"])
+ #expect(entries.keys.sorted() == ["A", "B"])
+ #expect(entries["A"]?.text == "Archived")
+ #expect(entries["B"]?.id == "B")
+ #expect(entries["B"]?.text == "Final")
+ }
+
@Test("A report and its new tokens are saved together")
func insert() async throws {
let token = Self.token("N", "New")
diff --git a/Tests/Unit/SurveyModelTests.swift b/Tests/Unit/SurveyModelTests.swift
@@ -163,7 +163,7 @@ struct SurveyModelTests {
modifiedAt: Date(timeIntervalSince1970: 50)
)
let model = SurveyModel(
- fillingIn: logged, questions: Self.questions,
+ editing: logged, questions: Self.questions,
vocabulary: [
"place": [
VocabularyEntry(
@@ -197,6 +197,62 @@ struct SurveyModelTests {
== .place(PlaceAnswer(tokenID: "P1", coordinate: context.location?.coordinate, accuracy: 20)))
}
+ @Test("Editing starts from the report's answers and keeps those left alone")
+ func editing() throws {
+ let given = PlaceAnswer(
+ tokenID: "P1", coordinate: Coordinate(latitude: 9, longitude: 9), accuracy: 5)
+ let original = Report(
+ id: Fixtures.reportID(8),
+ date: Date(timeIntervalSince1970: 50),
+ timeZone: "Asia/Tokyo",
+ kind: .manual,
+ trigger: .app,
+ state: .complete,
+ completedAt: Date(timeIntervalSince1970: 60),
+ responses: [
+ Response(questionID: "yes", prompt: "Old wording?", value: .options(["Yes"])),
+ Response(questionID: "tokens", prompt: "Doing?", value: .tokens(["T1", "OLD"])),
+ Response(questionID: "place", prompt: "Where?", value: .place(given)),
+ Response(questionID: "note", prompt: "Note?", value: .text("Before")),
+ // A response to a question the survey doesn't show.
+ Response(questionID: "gone", prompt: "Gone?", value: .number(1)),
+ ],
+ modifiedAt: Date(timeIntervalSince1970: 60)
+ )
+ let questions = Self.questions.filter { ["yes", "tokens", "place", "note"].contains($0.id) }
+ let model = SurveyModel(
+ editing: original, questions: questions,
+ vocabulary: [
+ "tokens": [Self.entry("T1", "Reading")],
+ "place": [Self.entry("P1", "Home")],
+ ],
+ // An archived token the suggestions leave out.
+ tokens: ["OLD": Self.entry("OLD", "Knitting")]
+ )
+
+ #expect(model[optionFor: "yes"] == "Yes")
+ #expect(model.pickers["tokens"]?.selectedEntries.map(\.text) == ["Reading", "Knitting"])
+ #expect(model.placePickers["place"]?.selectedTokenID == "P1")
+ #expect(model.placePickers["place"]?.selection?.name == "Home")
+ #expect(model[textFor: "note"] == "Before")
+ #expect(!model.hasChanges)
+
+ // Saving without changes keeps every response exactly.
+ let unchanged = model.makeReport(now: Date(timeIntervalSince1970: 300)).report
+ #expect(unchanged.responses == original.responses)
+ #expect(unchanged.completedAt == original.completedAt)
+ #expect(unchanged.modifiedAt == Date(timeIntervalSince1970: 300))
+
+ model[textFor: "note"] = "After"
+ #expect(model.hasChanges)
+ let changed = model.makeReport(now: Date(timeIntervalSince1970: 300)).report
+ #expect(changed.responses.map(\.questionID) == original.responses.map(\.questionID))
+ // The changed answer keeps the prompt it was first given under.
+ #expect(changed.responses[3] == Response(questionID: "note", prompt: "Note?", value: .text("After")))
+ #expect(Array(changed.responses[0..<3]) == Array(original.responses[0..<3]))
+ #expect(changed.responses[4] == original.responses[4])
+ }
+
@Test("New place tokens carry place details")
func newPlace() throws {
let model = makeModel()