← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Views/Settings/VocabularyView.swift (18300B)

1import OSLog
2import SwiftUI
3
4extension QuestionKind {
5    /// The kinds whose answers are tokens, in the order the Vocabulary
6    /// screen lists them.
7    static let vocabulary: [QuestionKind] = [.tokens, .people, .location]
8
9    /// Tokens of this kind, as the Vocabulary screen names them.
10    var vocabularyTitle: LocalizedStringKey {
11        switch self {
12        case .people: "People"
13        case .location: "Places"
14        default: "Activities"
15        }
16    }
17}
18
19/// Every activity, person and place that answers use, for renaming and for
20/// setting how each reads in narratives. Each change is saved as it's made.
21@MainActor
22@Observable
23final class VocabularyList {
24    struct Item: Identifiable, Equatable {
25        var token: Token
26        /// How often and how recently the token was used, for ordering.
27        var entry: VocabularyEntry
28
29        var id: String { token.id }
30    }
31
32    /// Tokens that are neither archived nor merged, by the kind of question
33    /// they answer, most used first.
34    private(set) var items: [QuestionKind: [Item]] = [:]
35    private(set) var isLoaded = false
36
37    private var store: ReportStore?
38    private var saving: Task<Void, Never>?
39    private let logger = Logger(subsystem: "net.inqk.reportage", category: "Vocabulary")
40
41    func load(from store: ReportStore?) async {
42        guard let store, let questions = try? await store.allQuestions() else { return }
43        let kinds = Dictionary(
44            uniqueKeysWithValues: questions.filter { QuestionKind.vocabulary.contains($0.kind) }.map { ($0.id, $0.kind) })
45        let questionIDs = Array(kinds.keys)
46        guard let entries = try? await store.vocabulary(for: questionIDs),
47            let tokens = try? await store.tokens(for: questionIDs)
48        else { return }
49
50        let byID = Dictionary(uniqueKeysWithValues: tokens.map { ($0.id, $0) })
51        var items: [QuestionKind: [Item]] = [:]
52        for (questionID, entries) in entries {
53            guard let kind = kinds[questionID] else { continue }
54            items[kind, default: []] += entries.compactMap { entry in
55                byID[entry.id].map { Item(token: $0, entry: entry) }
56            }
57        }
58        // Each kind can span several questions, such as one imported from
59        // Reporter and one added since.
60        for kind in items.keys {
61            items[kind]?.sort { Vocabulary.ranksBefore($0.entry, $1.entry) }
62        }
63        self.store = store
64        self.items = items
65        isLoaded = true
66    }
67
68    func item(id: String) -> Item? {
69        items.values.lazy.compactMap { $0.first { $0.id == id } }.first
70    }
71
72    /// Saves an edited token. A new text renames it in every report.
73    func update(_ token: Token) {
74        guard let kind = items.first(where: { $0.value.contains { $0.id == token.id } })?.key,
75            let index = items[kind]?.firstIndex(where: { $0.id == token.id }),
76            items[kind]?[index].token != token
77        else { return }
78        var token = token
79        token.modifiedAt = Date()
80        items[kind]?[index].token = token
81        enqueue { [token] in try await $0.save(token) }
82    }
83
84    /// Merges the token with `id` into the token with `target`, so reports
85    /// that use it read as using that token.
86    func merge(_ id: String, into target: String) {
87        enqueue(reloading: true) { try await $0.merge(id, into: target) }
88    }
89
90    /// Separates a token from the token it was merged into.
91    func separate(_ id: String) {
92        enqueue(reloading: true) { try await $0.merge(id, into: nil) }
93    }
94
95    /// Runs saves one after another, so a later edit can't be overwritten
96    /// by an earlier one finishing after it. A save that changes which tokens
97    /// are listed reloads the list.
98    private func enqueue(
99        reloading: Bool = false, _ save: @escaping @Sendable (ReportStore) async throws -> Void
100    ) {
101        guard let store else { return }
102        let previous = saving
103        saving = Task { [logger] in
104            await previous?.value
105            do {
106                try await save(store)
107                if reloading { await load(from: store) }
108                NotificationCenter.default.post(name: .summaryLookupChanged, object: nil)
109            } catch {
110                logger.error("Couldn't save vocabulary: \(error)")
111            }
112        }
113    }
114}
115
116/// The activities, people and places answers have used, each kind on a
117/// screen of its own.
118struct VocabularyView: View {
119    @Environment(\.reportStore) private var store
120    @State private var list = VocabularyList()
121
122    var body: some View {
123        List {
124            SettingsNote {
125                Text(
126                    "Rename the activities, people and places in your answers, and choose how each reads in the timeline."
127                )
128            }
129            Section {
130                ForEach(QuestionKind.vocabulary, id: \.self) { kind in
131                    NavigationLink {
132                        VocabularyKindView(kind: kind, list: list)
133                    } label: {
134                        LabeledContent(kind.vocabularyTitle) {
135                            if list.isLoaded {
136                                Text((list.items[kind]?.count ?? 0).formatted())
137                            }
138                        }
139                    }
140                    .settingsRow()
141                }
142            }
143        }
144        .listStyle(.plain)
145        .scrollContentBackground(.hidden)
146        .tabBarClearance()
147        .background(Theme.paper)
148        .foregroundStyle(Theme.ink)
149        .navigationTitle("Vocabulary")
150        .navigationBarTitleDisplayMode(.inline)
151        .toolbar(.visible, for: .navigationBar)
152        .task { await list.load(from: store) }
153    }
154}
155
156/// The tokens of one kind, most used first, filtered by search.
157private struct VocabularyKindView: View {
158    let kind: QuestionKind
159    let list: VocabularyList
160    @State private var search = ""
161
162    var body: some View {
163        List {
164            ForEach(items) { item in
165                NavigationLink {
166                    TokenDetailView(item: item, kind: kind, list: list)
167                } label: {
168                    VocabularyRow(item: item)
169                }
170                .settingsRow()
171            }
172            if list.isLoaded, items.isEmpty {
173                SettingsNote {
174                    if search.isEmpty {
175                        Text("None of your answers use these yet.")
176                    } else {
177                        Text("Nothing matches.")
178                    }
179                }
180            }
181        }
182        .listStyle(.plain)
183        .scrollContentBackground(.hidden)
184        .tabBarClearance()
185        .background(Theme.paper)
186        .foregroundStyle(Theme.ink)
187        .navigationTitle(Text(kind.vocabularyTitle))
188        .navigationBarTitleDisplayMode(.inline)
189        .searchable(text: $search)
190    }
191
192    private var items: [VocabularyList.Item] {
193        let all = list.items[kind] ?? []
194        let search = search.trimmingCharacters(in: .whitespaces)
195        guard !search.isEmpty else { return all }
196        return all.filter { item in
197            item.entry.matches(search)
198                || item.token.narrativeForm?.localizedStandardContains(search) ?? false
199        }
200    }
201}
202
203/// A token's name, with its narrative form and, for a place, where it was
204/// last used, and how many reports use it.
205private struct VocabularyRow: View {
206    let item: VocabularyList.Item
207
208    var body: some View {
209        HStack(alignment: .firstTextBaseline) {
210            VStack(alignment: .leading, spacing: Theme.lineGap) {
211                Text(item.token.text)
212                    .font(Theme.serif(.body))
213                if let subtitle {
214                    Text(subtitle)
215                        .font(.footnote)
216                        .foregroundStyle(Theme.muted)
217                }
218            }
219            Spacer()
220            Text(item.entry.useCount.formatted())
221                .font(.footnote)
222                .foregroundStyle(Theme.muted)
223                .accessibilityLabel(Text("Used in ^[\(item.entry.useCount) report](inflect: true)"))
224        }
225    }
226
227    private var subtitle: String? {
228        var parts: [String] = []
229        if let form = item.token.narrativeForm {
230            parts.append(String(localized: "Reads as '\(form)'", comment: "A token's narrative form, in a list"))
231        }
232        if let locality = item.entry.locality {
233            parts.append(locality)
234        }
235        return parts.isEmpty ? nil : parts.joined(separator: " · ")
236    }
237}
238
239/// One token, renamed and given a narrative form in place, and merged into
240/// another or separated from those merged into it. Each field is saved when
241/// it's finished.
242private struct TokenDetailView: View {
243    let kind: QuestionKind
244    let list: VocabularyList
245    @State private var text: String
246    @State private var form: String
247    @State private var isChoosingTarget = false
248    @FocusState private var focus: Field?
249    @Environment(\.dismiss) private var dismiss
250
251    private enum Field: Hashable {
252        case text
253        case form
254    }
255
256    init(item: VocabularyList.Item, kind: QuestionKind, list: VocabularyList) {
257        self.kind = kind
258        self.list = list
259        self.token = item.token
260        _text = State(initialValue: item.token.text)
261        _form = State(initialValue: item.token.narrativeForm ?? "")
262    }
263
264    /// The token as it was opened, for its ID and place.
265    private let token: Token
266
267    var body: some View {
268        List {
269            Section {
270                TextField("Name", text: $text)
271                    .font(Theme.serif(.title3, weight: .medium))
272                    .focused($focus, equals: .text)
273                    .submitLabel(.done)
274                    .filledField(focus: $focus, as: .text)
275                    .settingsRow()
276                    .listRowSeparator(.hidden)
277                SettingsNote { Text("Renaming changes the name in every report that uses it.") }
278            } header: {
279                SettingsHeading("Name")
280            }
281            Section {
282                TextField("In Narratives", text: $form, prompt: Text(verbatim: reading.automatic))
283                    .font(Theme.serif(.body))
284                    .focused($focus, equals: .form)
285                    .submitLabel(.done)
286                    .filledField(focus: $focus, as: .form)
287                    .settingsRow()
288                    .listRowSeparator(.hidden)
289                SettingsNote {
290                    if let sentence = reading.sentence {
291                        Text("Reads as '\(sentence)' \(Text(hint))")
292                    } else {
293                        Text(hint)
294                    }
295                }
296            } header: {
297                SettingsHeading("In Narratives")
298            }
299            if !merged.isEmpty {
300                Section {
301                    ForEach(merged) { token in
302                        LabeledContent {
303                            Text(token.useCount.formatted())
304                                .font(.footnote)
305                                .foregroundStyle(Theme.muted)
306                                .accessibilityLabel(Text("Used in ^[\(token.useCount) report](inflect: true)"))
307                        } label: {
308                            Text(token.text)
309                                .font(Theme.serif(.body))
310                        }
311                        .settingsRow()
312                        .swipeActions {
313                            Button("Separate") { list.separate(token.id) }
314                                .tint(Theme.accent)
315                        }
316                    }
317                    SettingsNote {
318                        Text("Reports that use these read as this one. Swipe one to separate it again.")
319                    }
320                } header: {
321                    SettingsHeading("Merged Into This")
322                }
323            }
324            if !targets.isEmpty {
325                Section {
326                    Button("Merge Into…") {
327                        commit()
328                        isChoosingTarget = true
329                    }
330                    .font(.body.weight(.semibold))
331                    .foregroundStyle(Theme.accent)
332                    .frame(maxWidth: .infinity, minHeight: 44)
333                    .listRowBackground(Theme.paper)
334                    .listRowSeparator(.hidden)
335                    SettingsNote { Text(mergeHint) }
336                }
337            }
338        }
339        .listStyle(.plain)
340        .scrollContentBackground(.hidden)
341        .tabBarClearance()
342        .scrollDismissesKeyboard(.interactively)
343        .background(Theme.paper)
344        .foregroundStyle(Theme.ink)
345        .navigationBarTitleDisplayMode(.inline)
346        .onChange(of: focus) { commit() }
347        .onDisappear { commit() }
348        .sheet(isPresented: $isChoosingTarget) {
349            MergeTargetView(kind: kind, source: name, targets: targets) { target in
350                isChoosingTarget = false
351                list.merge(token.id, into: target.id)
352                dismiss()
353            }
354        }
355    }
356
357    /// The token's saved name.
358    private var name: String {
359        list.item(id: token.id)?.token.text ?? token.text
360    }
361
362    /// The tokens merged into this one.
363    private var merged: [MergedToken] {
364        list.item(id: token.id)?.entry.merged ?? []
365    }
366
367    /// The other tokens of this kind, which this one can be merged into.
368    private var targets: [VocabularyList.Item] {
369        (list.items[kind] ?? []).filter { $0.id != token.id }
370    }
371
372    private var mergeHint: LocalizedStringKey {
373        switch kind {
374        case .people: "Merge a person entered twice, such as under a nickname, into the other."
375        case .location: "Merge a place entered twice into the other."
376        default: "Merge an activity entered twice, such as under another name, into the other."
377        }
378    }
379
380    private var hint: LocalizedStringKey {
381        switch kind {
382        case .people:
383            "Left blank, a name reads as the part before its first space, unless it's written in Chinese, Japanese or Korean."
384        case .location: "Write how the place reads after 'at', such as 'the park' or 'my desk'."
385        default: "Write how the activity reads in a sentence, such as 'going for a run'."
386        }
387    }
388
389    /// How the token reads with the rules alone, and the sentence it makes
390    /// with the drafted name and form.
391    private var reading: (automatic: String, sentence: String?) {
392        let rule = NarrativeRule.derived(for: kind) ?? .activities
393        var draft = token
394        draft.text = trimmed(text).isEmpty ? token.text : trimmed(text)
395        var lookup = SummaryLookup()
396        lookup.questionRules["Q"] = rule
397        lookup.tokenTexts["T"] = draft.text
398        if draft.isNamedByDirectory { lookup.directoryPlaces.insert("T") }
399        let automatic = NarrativeBuilder.form(of: "T", rule: rule, lookup: lookup) ?? draft.text
400        if !trimmed(form).isEmpty { lookup.narrativeForms["T"] = trimmed(form) }
401        let value: ResponseValue = kind == .location ? .place(PlaceAnswer(tokenID: "T")) : .tokens(["T"])
402        let sentence = NarrativeBuilder.build(
403            responses: [Response(questionID: "Q", prompt: "", value: value)], lookup: lookup
404        ).narrative
405        return (automatic, sentence)
406    }
407
408    private func trimmed(_ string: String) -> String {
409        string.trimmingCharacters(in: .whitespacesAndNewlines)
410    }
411
412    /// Saves the name and form. A name left blank goes back to what it was.
413    private func commit() {
414        guard var current = list.item(id: token.id)?.token else { return }
415        if trimmed(text).isEmpty {
416            text = current.text
417        } else {
418            current.text = trimmed(text)
419        }
420        current.narrativeForm = trimmed(form).isEmpty ? nil : trimmed(form)
421        list.update(current)
422    }
423}
424
425/// The tokens one can be merged into, searched by name. Choosing one asks
426/// for confirmation.
427private struct MergeTargetView: View {
428    let kind: QuestionKind
429    /// The name of the token being merged.
430    let source: String
431    let targets: [VocabularyList.Item]
432    let onMerge: (VocabularyList.Item) -> Void
433    @State private var search = ""
434    @State private var chosen: VocabularyList.Item?
435    @Environment(\.dismiss) private var dismiss
436
437    var body: some View {
438        NavigationStack {
439            List {
440                ForEach(matching) { item in
441                    Button {
442                        chosen = item
443                    } label: {
444                        VocabularyRow(item: item)
445                            .contentShape(Rectangle())
446                    }
447                    .buttonStyle(.plain)
448                    .settingsRow()
449                }
450                if matching.isEmpty {
451                    SettingsNote { Text("Nothing matches.") }
452                }
453            }
454            .listStyle(.plain)
455            .scrollContentBackground(.hidden)
456            .background(Theme.paper)
457            .foregroundStyle(Theme.ink)
458            .navigationTitle("Merge '\(source)' Into")
459            .navigationBarTitleDisplayMode(.inline)
460            .searchable(text: $search)
461            .toolbar {
462                ToolbarItem(placement: .cancellationAction) {
463                    Button("Cancel") { dismiss() }
464                }
465            }
466            .alert(
467                "Merge '\(source)' into '\(chosen?.token.text ?? "")'?",
468                isPresented: Binding(get: { chosen != nil }, set: { if !$0 { chosen = nil } }),
469                presenting: chosen
470            ) { target in
471                Button("Cancel", role: .cancel) {}
472                Button("Merge") { onMerge(target) }
473            } message: { target in
474                Text(
475                    "Reports that use '\(source)' will read as '\(target.token.text)'. You can separate them again from '\(target.token.text)'."
476                )
477            }
478        }
479    }
480
481    private var matching: [VocabularyList.Item] {
482        let search = search.trimmingCharacters(in: .whitespaces)
483        guard !search.isEmpty else { return targets }
484        return targets.filter { $0.entry.matches(search) }
485    }
486}