Sources/OrgstarMobile/EntrySheet.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/EntrySheet.swift history · blame · raw

315 lines · 14019 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import OrgDocument
  5import OrgPresentation
  6import SwiftUI
  7
  8/// An agenda entry's title, state, priority, dates, tags and notes, changed by the editor's
  9/// commands on a copy of its file and written back as one edit on Done.
 10struct EntrySheet: View {
 11    let item: AgendaItem
 12    let workspace: WorkspaceModel
 13    let session: DocumentSession
 14    /// Whether anything was written, and the entry to show in its file.
 15    let done: (_ saved: Bool, _ open: (path: String, offset: Int)?) -> Void
 16    @Environment(MobileModel.self) private var model
 17    @Environment(\.colorScheme) private var colorScheme
 18    @State private var draft: DocumentState?
 19    @State private var original = ""
 20    @State private var offset = 0
 21    @State private var title = ""
 22    @State private var notes = ""
 23    /// Changes on the copy that undo may take back, and those redo may bring back: the copy of
 24    /// an open file has the editor's history too.
 25    @State private var steps = 0
 26    @State private var undone = 0
 27    @State private var problem: String?
 28    @State private var prompt: PendingPrompt?
 29    @State private var planning: Planning?
 30    @State private var choosingTags = false
 31    @State private var confirmingDiscard = false
 32
 33    private enum Planning: String, Identifiable {
 34        case scheduled = "Scheduled", deadline = "Deadline"
 35        var id: String { rawValue }
 36    }
 37
 38    private struct PendingPrompt: Identifiable {
 39        let id = UUID()
 40        let prompt: Prompt
 41        let reply: (String?) -> Void
 42    }
 43
 44    private var fields: EntryFields? {
 45        draft.flatMap { EntryFields.read($0.text, at: offset, settings: $0.tree.settings) }
 46    }
 47
 48    private var hasChanges: Bool {
 49        guard let draft, let fields else { return false }
 50        return draft.text != original || title != fields.title || trimmed(notes) != fields.notes
 51    }
 52
 53    private var isDark: Bool { colorScheme == .dark }
 54
 55    var body: some View {
 56        NavigationStack {
 57            Group {
 58                if let fields, let draft {
 59                    form(fields, settings: draft.tree.settings)
 60                } else if let problem {
 61                    ContentUnavailableView("Can't open the entry", systemImage: "exclamationmark.triangle", description: Text(problem))
 62                } else {
 63                    ProgressView()
 64                }
 65            }
 66            .navigationBarTitleDisplayMode(.inline)
 67            .toolbar {
 68                ToolbarItemGroup(placement: .topBarLeading) {
 69                    Button("Cancel", systemImage: "xmark") {
 70                        if hasChanges { confirmingDiscard = true } else { done(false, nil) }
 71                    }
 72                    Button("Undo", systemImage: "arrow.uturn.backward", action: undo).disabled(steps == 0)
 73                    Button("Redo", systemImage: "arrow.uturn.forward", action: redo).disabled(undone == 0)
 74                }
 75                ToolbarItem(placement: .primaryAction) {
 76                    Menu("More", systemImage: "ellipsis") {
 77                        Button("Open in File", systemImage: "doc.text") { save(open: true) }
 78                    }
 79                    .disabled(draft == nil)
 80                }
 81                ToolbarItem(placement: .confirmationAction) {
 82                    Button("Done", systemImage: "checkmark") { save() }.disabled(draft == nil)
 83                }
 84            }
 85            .confirmationDialog("Discard your changes?", isPresented: $confirmingDiscard, titleVisibility: .visible) {
 86                Button("Discard Changes", role: .destructive) { done(false, nil) }
 87            }
 88        }
 89        .presentationDragIndicator(.visible)
 90        .interactiveDismissDisabled(hasChanges)
 91        .task { load() }
 92        .sheet(item: $prompt) { pending in
 93            PromptSheet(prompt: pending.prompt) { answer in
 94                prompt = nil
 95                pending.reply(answer)
 96            }
 97        }
 98        .sheet(item: $planning) { which in
 99            let stamp = which == .scheduled ? fields?.scheduled : fields?.deadline
100            DateTimeSheet(title: which.rawValue, initial: stamp.flatMap(Self.timestamp).map(Self.date) ?? Calendar.current.startOfDay(for: Date())) { answer in
101                planning = nil
102                if let answer { run(SetPlanning(deadline: which == .deadline), ["date": answer]) }
103            }
104        }
105        .sheet(isPresented: $choosingTags) {
106            TagsSheet(selected: fields?.tags ?? [], choices: (try? workspace.index.tags()) ?? []) { tags in
107                choosingTags = false
108                guard let tags, let old = fields?.tags else { return }
109                for tag in old where !tags.contains(tag) { run(ToggleTag(tag: tag, on: false)) }
110                for tag in tags where !old.contains(tag) { run(ToggleTag(tag: tag, on: true)) }
111            }
112        }
113    }
114
115    private func form(_ fields: EntryFields, settings: OrgSettings) -> some View {
116        ScrollView {
117            VStack(alignment: .leading, spacing: 12) {
118                TextField("Title", text: $title, axis: .vertical)
119                    .font(.title3.weight(.semibold))
120                ScrollView(.horizontal, showsIndicators: false) {
121                    HStack(spacing: 8) {
122                        stateChip(fields, settings: settings)
123                        priorityChip(fields, settings: settings)
124                        dateChip(.scheduled, fields.scheduled)
125                        dateChip(.deadline, fields.deadline)
126                    }
127                }
128                Button {
129                    choosingTags = true
130                } label: {
131                    chip(fields.tags.isEmpty ? String(localized: "Tags") : fields.tags.joined(separator: " "), systemImage: "tag", color: fields.tags.isEmpty ? .secondary : .accentColor)
132                }
133                if let problem {
134                    Text(problem).font(.footnote).foregroundStyle(.red)
135                }
136            }
137            .padding()
138            .frame(maxWidth: .infinity, alignment: .leading)
139            .background(Color.accentColor.opacity(0.08))
140            Divider()
141            TextEditor(text: $notes)
142                .font(.body)
143                .scrollDisabled(true)
144                .scrollContentBackground(.hidden)
145                .frame(minHeight: 240)
146                .overlay(alignment: .topLeading) {
147                    if notes.isEmpty {
148                        Text("Add notes").foregroundStyle(.tertiary).padding(.top, 8).padding(.leading, 5).allowsHitTesting(false)
149                    }
150                }
151                .padding(.horizontal)
152        }
153        .scrollDismissesKeyboard(.interactively)
154    }
155
156    private func stateChip(_ fields: EntryFields, settings: OrgSettings) -> some View {
157        let keywords = settings.todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
158        let color = fields.todo.flatMap { todo in
159            model.theme.todoColor(todo, isDone: settings.todoSequences.contains { $0.done.contains { $0.name == todo } }, dark: isDark)?.swiftUI
160        } ?? .secondary
161        return Menu {
162            ForEach(keywords, id: \.self) { keyword in
163                Button(keyword) { run(SetTodo(keyword: keyword)) }
164            }
165            Button(String(localized: "none.state", defaultValue: "None", comment: "No TODO state")) { run(SetTodo(keyword: nil)) }
166        } label: {
167            chip(fields.todo ?? String(localized: "No State"), color: color)
168        }
169    }
170
171    @ViewBuilder
172    private func priorityChip(_ fields: EntryFields, settings: OrgSettings) -> some View {
173        let priorities = CaptureEntry.priorities(settings.priorities)
174        if !priorities.isEmpty {
175            let color = fields.priority.flatMap { model.theme.priorityColor($0, dark: isDark)?.swiftUI } ?? .secondary
176            Menu {
177                ForEach(priorities, id: \.self) { priority in
178                    Button("Priority \(priority)") { run(SetPriority(), ["priority": priority]) }
179                }
180                Button(String(localized: "none.priority", defaultValue: "None", comment: "No priority")) { run(SetPriority(), ["priority": " "]) }
181            } label: {
182                chip(fields.priority.map { "#" + $0 } ?? "#", color: color)
183            }
184            .accessibilityLabel(fields.priority.map { "Priority \($0)" } ?? "No priority")
185        }
186    }
187
188    private func dateChip(_ which: Planning, _ value: String?) -> some View {
189        let stamp = value.flatMap(Self.timestamp)
190        return Menu {
191            Button("Today") { set(which, days: 0, keeping: stamp) }
192            Button("Tomorrow") { set(which, days: 1, keeping: stamp) }
193            Button("In a Week") { set(which, days: 7, keeping: stamp) }
194            Button("Pick Date…") { planning = which }
195            if value != nil {
196                Button("Remove", role: .destructive) { run(RemovePlanning(deadline: which == .deadline)) }
197            }
198        } label: {
199            chip(stamp.map { which == .scheduled ? String(localized: "S: \(Self.text($0))") : String(localized: "D: \(Self.text($0))") }
200                    ?? (which == .scheduled ? String(localized: "Schedule") : String(localized: "Deadline")),
201                 systemImage: which == .scheduled ? "calendar" : "flag", color: stamp == nil ? .secondary : .accentColor)
202        }
203    }
204
205    private func chip(_ text: String, systemImage: String? = nil, color: Color) -> some View {
206        HStack(spacing: 4) {
207            if let systemImage { Image(systemName: systemImage) }
208            Text(text).lineLimit(1)
209        }
210        .font(.subheadline.weight(.medium))
211        .foregroundStyle(color)
212        .padding(.horizontal, 12)
213        .padding(.vertical, 7)
214        .background(color.opacity(0.14), in: Capsule())
215    }
216
217    // MARK: - Changes
218
219    private func load() {
220        guard draft == nil else { return }
221        guard let path = item.path, let line = item.headingLine, let near = item.headingOffset,
222              let at = session.locateHeading(path: path, line: line, near: near), let copy = session.copy(of: path),
223              let fields = EntryFields.read(copy.text, at: at, settings: copy.tree.settings) else {
224            problem = "The entry changed or its file can't be read."
225            return
226        }
227        (draft, original, offset, title, notes) = (copy, copy.text, at, fields.title, fields.notes)
228    }
229
230    /// Runs `command` at the heading on the copy, asking what it asks.
231    private func run(_ command: any OrgCommand, _ answers: [String: String] = [:]) {
232        guard var copy = draft else { return }
233        do {
234            switch try copy.run(command, selection: [offset..<offset], answers: answers, options: session.options) {
235            case .commit:
236                problem = nil
237                guard copy.text != draft?.text else { return }
238                draft = copy
239                steps += 1
240                undone = 0
241            case .prompt(let request):
242                prompt = PendingPrompt(prompt: request) { answer in
243                    if let answer { run(command, answers.merging([request.key: answer]) { $1 }) }
244                }
245            case .failed(let text):
246                problem = text
247            case .external(let request):
248                problem = MobileEditor.unavailable(request, title: command.title)
249            }
250        } catch {
251            problem = "\(error)"
252        }
253    }
254
255    private func undo() {
256        guard steps > 0, var copy = draft, copy.undo() != nil else { return }
257        draft = copy
258        steps -= 1
259        undone += 1
260    }
261
262    private func redo() {
263        guard undone > 0, var copy = draft, copy.redo() != nil else { return }
264        draft = copy
265        undone -= 1
266        steps += 1
267    }
268
269    /// `days` from today, at the time `stamp` has.
270    private func set(_ which: Planning, days: Int, keeping stamp: Timestamp?) {
271        var day = Calendar.current.date(byAdding: .day, value: days, to: Calendar.current.startOfDay(for: Date())) ?? Date()
272        if let hour = stamp?.start.hour {
273            day = Calendar.current.date(bySettingHour: hour, minute: stamp?.start.minute ?? 0, second: 0, of: day) ?? day
274        }
275        run(SetPlanning(deadline: which == .deadline), ["date": QuestionField.stamp(day, withTime: stamp?.start.hour != nil)])
276    }
277
278    /// The title and notes onto the copy, and the copy written back to the file.
279    private func save(open: Bool = false) {
280        guard let path = item.path, let fields else { return }
281        if title != fields.title { run(SetHeadingTitle(title: title)) }
282        if trimmed(notes) != fields.notes { run(SetEntryNotes(notes: notes)) }
283        guard let draft else { return }
284        var saved = false
285        if let command = ReplaceChangedText(from: original, to: draft.text) {
286            if case .failed(let text) = session.perform(command, path: path, at: offset, expect: nil) {
287                problem = text
288                return
289            }
290            saved = true
291        }
292        done(saved, open ? (path, offset) : nil)
293    }
294
295    private func trimmed(_ text: String) -> String {
296        var text = text
297        while text.last?.isWhitespace == true { text.removeLast() }
298        return text
299    }
300
301    private static func timestamp(_ value: String) -> Timestamp? { Timestamp.parse("<" + value + ">") }
302
303    private static func date(_ stamp: Timestamp) -> Date {
304        let p = stamp.start
305        return Calendar.current.date(from: DateComponents(year: p.year, month: p.month, day: p.day, hour: p.hour, minute: p.minute)) ?? Date()
306    }
307
308    /// `Sat 17 Oct`, with the time when it has one.
309    private static func text(_ stamp: Timestamp) -> String {
310        let day = date(stamp).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
311        guard let hour = stamp.start.hour else { return day }
312        return day + String(format: " %02d:%02d", hour, stamp.start.minute ?? 0)
313    }
314}
315#endif