Sources/OrgstarMobile/BoardScreen.swift
257 lines · 10903 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgPresentation
5import SwiftUI
6
7/// The agenda files' entries as a list, or as a kanban board by TODO keyword, as on the Mac.
8/// Dragging a card to another column, or Move To in its menu, sets its keyword.
9struct BoardScreen: View {
10 let workspace: WorkspaceModel
11 let session: DocumentSession
12 let done: () -> Void
13 @Environment(MobileModel.self) private var model
14 @State private var agenda: AgendaModel
15 @State private var entries: [BoardEntry] = []
16 @State private var keywords: [String] = []
17 @State private var message: String?
18 @State private var tick = 0
19 @State private var prompt: EditorScreen.PromptRequest?
20 @State private var matchText = ""
21 @AppStorage("boardKanban") private var kanban = false
22 @AppStorage("boardMatch") private var match = ""
23
24 init(workspace: WorkspaceModel, session: DocumentSession, done: @escaping () -> Void) {
25 self.workspace = workspace
26 self.session = session
27 self.done = done
28 _agenda = State(initialValue: AgendaModel(workspace: workspace))
29 }
30
31 private var theme: MobileTheme { MobileTheme(model.theme) }
32
33 private struct RefreshKey: Hashable {
34 var match: String
35 var files: Int
36 var changed: Int?
37 var edits: Int
38 var tick: Int
39 var settings: Int
40 }
41
42 /// Entries by keyword order, then title.
43 private var sorted: [BoardEntry] {
44 entries.enumerated().sorted { a, b in
45 let ka = a.element.todo.flatMap { keywords.firstIndex(of: $0) } ?? Int.max
46 let kb = b.element.todo.flatMap { keywords.firstIndex(of: $0) } ?? Int.max
47 if ka != kb { return ka < kb }
48 if a.element.title != b.element.title { return a.element.title.localizedStandardCompare(b.element.title) == .orderedAscending }
49 return a.offset < b.offset
50 }.map(\.element)
51 }
52
53 var body: some View {
54 NavigationStack {
55 VStack(spacing: 0) {
56 TextField("Match: +work/!TODO", text: $matchText)
57 .textInputAutocapitalization(.never)
58 .autocorrectionDisabled()
59 .submitLabel(.search)
60 .onSubmit { match = matchText }
61 .padding(.horizontal, 12)
62 .padding(.vertical, 8)
63 .background(.bar)
64 if kanban { board } else { list }
65 }
66 .safeAreaInset(edge: .bottom) {
67 if let message {
68 Text(message).font(.footnote).padding(.horizontal, 12).padding(.vertical, 6)
69 .glassEffect(.regular, in: Capsule())
70 .onTapGesture { self.message = nil }
71 }
72 }
73 .navigationTitle(kanban ? "Kanban" : "Entries")
74 .navigationBarTitleDisplayMode(.inline)
75 .toolbar {
76 ToolbarItem(placement: .cancellationAction) { Button("Done", action: done) }
77 ToolbarItem(placement: .principal) {
78 Picker("View", selection: $kanban) {
79 Label("List", systemImage: "list.bullet").tag(false)
80 Label("Kanban", systemImage: "rectangle.split.3x1").tag(true)
81 }
82 .pickerStyle(.segmented)
83 .frame(width: 180)
84 }
85 }
86 .sheet(item: $prompt) { request in
87 PromptSheet(prompt: request.prompt) { answer in
88 prompt = nil
89 request.reply(answer)
90 }
91 }
92 }
93 .onAppear { matchText = match }
94 .task(id: RefreshKey(match: match, files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion,
95 tick: tick, settings: model.settingsVersion)) {
96 agenda.includeSubfolders = OrgPreferences.agendaSubfolders()
97 agenda.excludeArchives = OrgPreferences.agendaExcludeArchives()
98 agenda.agendaFiles = OrgPreferences.agendaFiles()
99 let result = await agenda.board(open: session.openTexts, match: match)
100 entries = result.entries
101 keywords = result.keywords
102 }
103 }
104
105 // MARK: - List
106
107 private var list: some View {
108 List {
109 if entries.isEmpty { Text("No entries").foregroundStyle(.secondary) }
110 ForEach(sorted) { entry in
111 Button { open(entry) } label: {
112 HStack(alignment: .firstTextBaseline, spacing: 8) {
113 if let todo = entry.todo {
114 Text(todo).font(.caption.weight(.bold)).foregroundStyle(keywordColor(todo, done: entry.isDone))
115 }
116 VStack(alignment: .leading, spacing: 2) {
117 Text((entry.priority.map { "[#\($0)] " } ?? "") + entry.title).foregroundStyle(.primary)
118 details(entry)
119 }
120 }
121 }
122 .tint(.primary)
123 .contextMenu { menu(entry) }
124 }
125 }
126 }
127
128 // MARK: - Kanban
129
130 private var board: some View {
131 ScrollView(.horizontal) {
132 HStack(alignment: .top, spacing: 12) {
133 ForEach(keywords, id: \.self) { keyword in column(keyword) }
134 }
135 .padding(12)
136 .frame(maxHeight: .infinity, alignment: .top)
137 }
138 .background(Color(.systemGroupedBackground))
139 }
140
141 private func column(_ keyword: String) -> some View {
142 let cards = entries.filter { $0.todo == keyword }
143 return VStack(alignment: .leading, spacing: 8) {
144 HStack {
145 Text(keyword).font(.headline).foregroundStyle(keywordColor(keyword, done: cards.first?.isDone ?? false))
146 Text("\(cards.count)").foregroundStyle(.secondary)
147 }
148 ScrollView {
149 VStack(alignment: .leading, spacing: 6) {
150 ForEach(cards) { entry in
151 card(entry)
152 .onTapGesture { open(entry) }
153 .draggable(entry.id)
154 .contextMenu { menu(entry) }
155 .accessibilityElement(children: .combine)
156 .accessibilityAddTraits(.isButton)
157 .accessibilityAction { open(entry) }
158 .accessibilityActions {
159 ForEach(keywords.filter { $0 != keyword }, id: \.self) { other in
160 Button("Move to \(other)") { setTodo(entry, other) }
161 }
162 }
163 }
164 }
165 }
166 }
167 .frame(width: 260, alignment: .topLeading)
168 .frame(maxHeight: .infinity, alignment: .top)
169 .padding(8)
170 .background(RoundedRectangle(cornerRadius: 10).fill(Color(.secondarySystemFill)))
171 .dropDestination(for: String.self) { ids, _ in
172 for id in ids {
173 if let entry = entries.first(where: { $0.id == id }), entry.todo != keyword { setTodo(entry, keyword) }
174 }
175 return true
176 }
177 }
178
179 private func card(_ entry: BoardEntry) -> some View {
180 VStack(alignment: .leading, spacing: 4) {
181 Text((entry.priority.map { "[#\($0)] " } ?? "") + entry.title).lineLimit(3)
182 details(entry)
183 }
184 .padding(10)
185 .frame(maxWidth: .infinity, alignment: .leading)
186 .background(RoundedRectangle(cornerRadius: 8).fill(Color(.systemBackground)))
187 .contentShape(RoundedRectangle(cornerRadius: 8))
188 }
189
190 @ViewBuilder
191 private func details(_ entry: BoardEntry) -> some View {
192 HStack(spacing: 6) {
193 Text(entry.category).font(.caption).foregroundStyle(.secondary)
194 if !entry.tags.isEmpty {
195 Text(entry.tags.joined(separator: " ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)
196 }
197 }
198 if let deadline = entry.deadline {
199 Text("Deadline \(deadline)").font(.caption).foregroundStyle(.red)
200 } else if let scheduled = entry.scheduled {
201 Text("Scheduled \(scheduled)").font(.caption).foregroundStyle(.secondary)
202 }
203 }
204
205 @ViewBuilder
206 private func menu(_ entry: BoardEntry) -> some View {
207 Menu("Move To", systemImage: "arrow.right.circle") {
208 ForEach(keywords.filter { $0 != entry.todo }, id: \.self) { keyword in Button(keyword) { setTodo(entry, keyword) } }
209 if entry.todo != nil {
210 Divider()
211 Button(String(localized: "none.state", defaultValue: "None", comment: "No TODO state")) { setTodo(entry, nil) }
212 }
213 }
214 Button("Set Property…", systemImage: "list.bullet.rectangle") { askProperty(entry) }
215 Button("Open", systemImage: "doc.text") { open(entry) }
216 }
217
218 private func keywordColor(_ keyword: String, done: Bool) -> Color {
219 theme.keywordColor(keyword, done: done).map(Color.init(uiColor:)) ?? (done ? .green : .red)
220 }
221
222 // MARK: - Editing
223
224 private func perform(_ command: any OrgCommand, on entry: BoardEntry, answers: [String: String] = [:]) {
225 switch session.perform(command, path: entry.path, at: entry.headingOffset, expect: (entry.headingOffset, entry.headingLine), answers: answers) {
226 case .failed(let text): message = text
227 case .prompt(let request):
228 // A state note, or what else the change asks.
229 prompt = EditorScreen.PromptRequest(prompt: request) { answer in
230 guard let answer else { return }
231 perform(command, on: entry, answers: answers.merging([request.key: answer]) { $1 })
232 }
233 case .external(let request): message = MobileEditor.unavailable(request, title: command.title)
234 case .commit: message = nil
235 }
236 tick += 1
237 }
238
239 private func setTodo(_ entry: BoardEntry, _ keyword: String?) {
240 perform(SetTodo(keyword: keyword), on: entry)
241 }
242
243 private func askProperty(_ entry: BoardEntry) {
244 prompt = EditorScreen.PromptRequest(prompt: Prompt(key: "property", message: "Property (NAME value):")) { answer in
245 guard let answer, let space = answer.firstIndex(of: " ") else { return }
246 let key = String(answer[..<space])
247 let value = String(answer[answer.index(after: space)...]).trimmingCharacters(in: .whitespaces)
248 perform(SetProperty(key: key, value: value), on: entry)
249 }
250 }
251
252 private func open(_ entry: BoardEntry) {
253 done()
254 model.openRequest = .offset(entry.path, entry.headingOffset)
255 }
256}
257#endif