Sources/OrgstarMobile/AgendaScreen.swift
1193 lines · 55240 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import OrgPresentation
6import SwiftUI
7
8/// The agenda over the workspace's agenda files: the day/week view, the TODO list, tag and
9/// property matches, text search and the views in `views.toml`, with Org's filters and the
10/// agenda's actions on each entry.
11struct AgendaScreen: View, Equatable {
12 let workspace: WorkspaceModel
13 let session: DocumentSession
14 @Bindable var agenda: AgendaModel
15 let scheduler: ReminderScheduler
16 @State private var message: String?
17 @Environment(ClockModel.self) private var clock
18 @Environment(MobileModel.self) private var model
19 @Environment(\.colorScheme) private var colorScheme
20 @Environment(\.openURL) private var openURL
21 @State private var tick = 0
22 /// The time the now line shows, kept to the minute while the agenda is open.
23 @State private var now = Date()
24 @State private var views = AgendaViewLoader.builtIn
25 @State private var viewName = "Agenda"
26 @State private var filter = AgendaFilter()
27 @State private var showingFilter = false
28 @State private var asking: Asking?
29 @State private var prompt: EditorScreen.PromptRequest?
30 @State private var refiling: AgendaItem?
31 @State private var archiving: AgendaItem?
32 @State private var deleting: AgendaItem?
33 /// The day, week or month shown; nil for `org-agenda-span` and `org-agenda-start-day`.
34 @State private var range: SpanRange?
35 /// The mode `range` set, to notice when something else changes the view.
36 @State private var rangeMode: AgendaMode?
37 @State private var jumping = false
38 @State private var rescheduling: AgendaRow?
39 @AppStorage("agendaOverdueExpanded") private var overdueExpanded = true
40 @State private var done = 0
41 @State private var moved = 0
42 /// `org-agenda-log-mode`: closed entries and clocked time on each day.
43 @State private var logMode = false
44 /// Selecting entries for bulk actions, as `m` marks them in Org's agenda, and those marked.
45 @State private var selecting = false
46 @State private var marked: [Mark] = []
47 @State private var bulkRefiling = false
48 @State private var bulkArchiving = false
49 @State private var bulkPlanning: BulkPlanning?
50 @State private var showingBoard = false
51
52 /// A marked entry: its heading line, to find it again.
53 private struct Mark: Hashable {
54 let path: String
55 let line: String
56 let offset: Int
57
58 init?(_ item: AgendaItem?) {
59 guard let item, let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
60 (self.path, self.line, self.offset) = (path, line, offset)
61 }
62 }
63
64 private enum BulkPlanning: String, Identifiable {
65 case schedule, deadline
66 var id: String { rawValue }
67 }
68
69 /// A match typed for the tag and property view, or a search string.
70 private enum Asking: Identifiable {
71 case match, search
72 var id: Self { self }
73 }
74
75 enum SpanRange: String, CaseIterable, Identifiable {
76 case day, week, month
77 var id: String { rawValue }
78 var title: String { rawValue.capitalized }
79 }
80
81 private struct Key: Equatable {
82 var files: Int
83 var changed: Int?
84 var edits: Int
85 var tick: Int
86 var mode: AgendaMode
87 var start: Int?
88 var span: Int
89 var startOffset: Int
90 var subfolders: Bool
91 var settings: Int
92 var logMode: Bool
93 }
94
95 /// The same models: the root redrawing for navigation leaves the list alone.
96 nonisolated static func == (a: Self, b: Self) -> Bool {
97 a.workspace === b.workspace && a.session === b.session && a.agenda === b.agenda && a.scheduler === b.scheduler
98 }
99
100 private var isDark: Bool { colorScheme == .dark }
101 private var theme: ThemeSpec { model.theme }
102
103 var body: some View {
104 List {
105 // With no folders the empty state stands alone, not over a column of empty days.
106 if workspace.rootPaths.isEmpty {
107 } else if case .agenda = agenda.mode {
108 let _ = model.settingsVersion
109 ForEach(Perf.measure("agenda.groups") { agenda.groups(showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter) }) { group in
110 Section {
111 day(group)
112 } header: {
113 header(group)
114 }
115 }
116 } else if case .blocks = agenda.mode {
117 // A block's title over its days, or over its entries.
118 ForEach(Array(agenda.blocks.enumerated()), id: \.offset) { _, block in
119 if block.isAgenda {
120 Section { } header: { Text(block.header).font(.headline) }
121 ForEach(agenda.groups(block, showAllDates: OrgPreferences.agendaShowAllDates(), filter: filter)) { group in
122 Section {
123 day(group)
124 } header: {
125 header(group)
126 }
127 }
128 } else {
129 Section {
130 let rows = block.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
131 if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) }
132 ForEach(rows) { item in Deferred { row(item, day: agenda.today) } }
133 } header: {
134 Text(block.header).font(.headline)
135 }
136 }
137 }
138 } else {
139 let rows = agenda.list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
140 if rows.isEmpty, !agenda.isComputing { Text("No entries").foregroundStyle(.secondary) }
141 ForEach(rows) { item in Deferred { row(item, day: agenda.today) } }
142 }
143 if let reminderStatus {
144 Section { } footer: { Text(reminderStatus) }
145 }
146 }
147 .listStyle(.insetGrouped)
148 .listSectionSpacing(.compact)
149 // The now line is shorter than a row.
150 .environment(\.defaultMinListRowHeight, 16)
151 .navigationTitle(title)
152 .navigationBarTitleDisplayMode(.inline)
153 .sensoryFeedback(.success, trigger: done)
154 .sensoryFeedback(.impact(weight: .light), trigger: moved)
155 .onChange(of: agenda.start) {
156 // Days a followed timestamp asked for.
157 if agenda.start != nil, case .agenda = agenda.mode { viewName = "Agenda" }
158 }
159 .onChange(of: agenda.mode) {
160 if agenda.mode != rangeMode { range = nil }
161 }
162 .overlay {
163 if workspace.rootPaths.isEmpty {
164 ContentUnavailableView("No folders", systemImage: "folder", description: Text("Add a folder of org files under Folders."))
165 }
166 }
167 .safeAreaInset(edge: .bottom) {
168 if !workspace.rootPaths.isEmpty {
169 if selecting { bulkBar } else { bottomBar }
170 }
171 }
172 .sheet(isPresented: $bulkRefiling) {
173 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
174 bulkRefiling = false
175 guard let target else { return }
176 bulk { path, offset in
177 // Targets in the entry's own file from its text now, as earlier moves shift them.
178 let document = session.openDocuments.first { $0.path == path }?.document
179 ?? FileManager.default.contents(atPath: path).map { DocumentState(bytes: [UInt8]($0)) }
180 guard let current = workspace.refileTargets(openPath: path, document: document).first(where: { $0.label == target.label }) else {
181 return "Can't find \(target.label) any more."
182 }
183 return session.refile(to: current, from: (path, offset))
184 }
185 }
186 }
187 .sheet(item: $bulkPlanning) { kind in
188 DateSheet(title: kind == .deadline ? "Deadline" : "Schedule", action: "Set", initial: date(agenda.today)) { picked in
189 bulkPlanning = nil
190 guard let picked else { return }
191 let d = Days.date(Days.absolute(picked, calendar: .current))
192 let answer = String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
193 bulk { perform(SetPlanning(deadline: kind == .deadline), $0, $1, answers: ["date": answer]) }
194 }
195 }
196 .confirmationDialog("Archive \(marked.count) \(marked.count == 1 ? "entry" : "entries")?", isPresented: $bulkArchiving, titleVisibility: .visible) {
197 Button("Archive", role: .destructive) { bulk { session.archive(from: ($0, $1)) } }
198 }
199 .toolbar {
200 ToolbarItem(placement: .topBarLeading) {
201 Menu {
202 ForEach(views) { definition in
203 Button(definition.name) { show(definition) }
204 }
205 Button("Tags and Properties…") { asking = .match }
206 Button("Search…") { asking = .search }
207 Divider()
208 Button("Board", systemImage: "rectangle.split.3x1") { showingBoard = true }
209 } label: {
210 Label("Views", systemImage: "list.bullet.rectangle")
211 }
212 }
213 }
214 .fullScreenCover(isPresented: $showingBoard) {
215 BoardScreen(workspace: workspace, session: session) { showingBoard = false }
216 }
217 .sheet(isPresented: $showingFilter) {
218 FilterSheet(filter: $filter, items: shownItems)
219 }
220 .sheet(isPresented: $jumping) {
221 DateSheet(title: "Go to Date", action: "Go", initial: date(firstDay)) { picked in
222 jumping = false
223 if let picked { jump(to: Days.absolute(picked, calendar: .current)) }
224 }
225 }
226 .sheet(item: $rescheduling) { row in
227 DateSheet(title: row.icon == .deadline ? "Deadline" : "Schedule", action: "Set", initial: date(row.planningDay ?? agenda.today)) { picked in
228 rescheduling = nil
229 if let picked, let item = row.item { reschedule(row, item, to: Days.absolute(picked, calendar: .current)) }
230 }
231 }
232 .sheet(item: $asking) { kind in
233 if kind == .search {
234 PromptSheet(prompt: Prompt(key: "search", message: "Search: a phrase, or +word -word {regexp}; * for headlines, ! for TODO entries")) { answer in
235 asking = nil
236 guard let answer, answer.contains(where: { !$0.isWhitespace }) else { return }
237 agenda.mode = .search(answer, todoOnly: false)
238 viewName = answer
239 }
240 } else {
241 PromptSheet(prompt: Prompt(key: "match", message: "Match: tags and properties, as +work-home or TODO=\"WAIT\"")) { answer in
242 asking = nil
243 guard let answer, !answer.isEmpty else { return }
244 agenda.mode = .match(answer, todoOnly: false)
245 viewName = answer
246 }
247 }
248 }
249 .sheet(item: $prompt) { request in
250 PromptSheet(prompt: request.prompt) { answer in
251 prompt = nil
252 request.reply(answer)
253 }
254 }
255 .sheet(item: $refiling) { item in
256 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document)) { target in
257 refiling = nil
258 if let target { refile(item, to: target) }
259 }
260 }
261 .confirmationDialog("Archive this entry?", isPresented: Binding { archiving != nil } set: { if !$0 { archiving = nil } }, titleVisibility: .visible) {
262 Button("Archive", role: .destructive) {
263 if let item = archiving { archive(item) }
264 archiving = nil
265 }
266 } message: {
267 Text(archiving?.text ?? "")
268 }
269 .confirmationDialog("Delete this entry?", isPresented: Binding { deleting != nil } set: { if !$0 { deleting = nil } }, titleVisibility: .visible) {
270 Button("Delete", role: .destructive) {
271 // `org-cut-subtree`: the heading and everything under it.
272 if let item = deleting { run(CopySubtree(cut: true), on: item) }
273 deleting = nil
274 }
275 } message: {
276 Text("\(deleting?.text ?? "")\n\nThe heading and every line under it are removed from the file.")
277 }
278 .refreshable {
279 await workspace.refresh()
280 await agenda.refresh(open: session.openTexts)
281 }
282 .task {
283 let loaded = AgendaViewLoader.load()
284 views = loaded.views
285 agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
286 if let problem = loaded.problems.first { message = problem }
287 }
288 // The now line moves each minute; a new day refreshes the statuses.
289 .task {
290 while !Task.isCancelled {
291 let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
292 try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
293 now = Date()
294 if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
295 }
296 }
297 // Calendar and Reminders access are asked for when calendar-events and
298 // agenda-reminders are turned on.
299 .task(id: model.settingsVersion) {
300 if OrgPreferences.calendarEvents(), !CalendarEvents.isAuthorized, await model.calendarEvents.requestAccess() { tick += 1 }
301 if OrgPreferences.agendaReminders(), !ReminderLists.isAuthorized, await model.reminderLists.requestAccess() { tick += 1 }
302 }
303 .background { Refresher(workspace: workspace, session: session, agenda: agenda, model: model, tick: tick, logMode: logMode) }
304 }
305
306 /// Refreshes the agenda when files, edits or settings change. Its own view, so that what it
307 /// watches redraws only it, not the whole list.
308 private struct Refresher: View {
309 let workspace: WorkspaceModel
310 let session: DocumentSession
311 let agenda: AgendaModel
312 let model: MobileModel
313 let tick: Int
314 let logMode: Bool
315
316 var body: some View {
317 Color.clear
318 .task(id: Key(files: workspace.files.count, changed: workspace.changedFile?.version, edits: session.editVersion, tick: tick,
319 mode: agenda.mode, start: agenda.start, span: agenda.span, startOffset: agenda.startOffset,
320 subfolders: agenda.includeSubfolders, settings: model.settingsVersion, logMode: logMode)) {
321 // Changes come in bursts (a folder scan, typing); a newer one cancels this wait.
322 try? await Task.sleep(for: .milliseconds(150))
323 guard !Task.isCancelled else { return }
324 agenda.options.logMode = logMode
325 await agenda.refresh(open: session.openTexts)
326 }
327 }
328 }
329
330 private var shownItems: [AgendaItem] {
331 if case .agenda = agenda.mode { return agenda.days.flatMap(\.items).filter(\.isEntry) }
332 if case .blocks = agenda.mode { return agenda.blocks.flatMap { $0.days.flatMap(\.items).filter(\.isEntry) + $0.list } }
333 return agenda.list
334 }
335
336 private func show(_ definition: AgendaViewDefinition) {
337 viewName = definition.name
338 agenda.mode = definition.mode
339 }
340
341 /// How far ahead notifications are set, as the design asks the agenda to show: iOS keeps
342 /// at most 64, and sets no more while the app isn't opened.
343 private var reminderStatus: String? {
344 guard OrgPreferences.reminders() else { return nil }
345 if !scheduler.isAuthorized { return "Notifications are off for orgstar in Settings." }
346 guard let through = scheduler.scheduledThrough else { return nil }
347 return "Reminders are set through " + through.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated).hour().minute())
348 + ". Open orgstar to set later ones."
349 }
350
351 // MARK: - Days
352
353 private func day(_ group: AgendaDayGroup) -> some View {
354 Group {
355 if group.isToday, !group.overdue.isEmpty {
356 Button {
357 withAnimation { overdueExpanded.toggle() }
358 } label: {
359 HStack(spacing: 6) {
360 Image(systemName: "chevron.right")
361 .font(.caption.weight(.semibold))
362 .rotationEffect(.degrees(overdueExpanded ? 90 : 0))
363 Text("Overdue").font(.subheadline.weight(.semibold))
364 Text("\(group.overdue.count)").font(.subheadline.monospacedDigit())
365 Spacer()
366 }
367 .foregroundStyle(themed(theme.statusColor(.overdue, dark: isDark), .red))
368 .contentShape(Rectangle())
369 }
370 .buttonStyle(.plain)
371 if overdueExpanded {
372 ForEach(group.overdue) { item in Deferred { row(item, day: group.day) } }
373 }
374 }
375 if group.isEmpty {
376 Text("Nothing scheduled").font(.subheadline).foregroundStyle(.secondary)
377 }
378 // One view per element, so the list counts its rows without building them.
379 ForEach(lines(group)) { line in
380 switch line {
381 case .now: NowLine(time: now, color: todayColor)
382 case .grid(let time): GridLineRow(time: time)
383 case .row(let item): Deferred { row(item, day: group.day) }
384 }
385 }
386 }
387 }
388
389 /// A day's rows, with the grid and now lines among them as lines of their own.
390 private enum DayLine: Identifiable {
391 case now
392 case grid(Int)
393 case row(AgendaRow)
394
395 var id: String {
396 switch self {
397 case .row(let row): row.id
398 case .grid(let time): "grid \(time)"
399 case .now: "now"
400 }
401 }
402 }
403
404 private func lines(_ group: AgendaDayGroup) -> [DayLine] {
405 let c = Calendar.current.dateComponents([.hour, .minute], from: now)
406 return group.lines(now: (c.hour ?? 0) * 100 + (c.minute ?? 0)).map { line in
407 switch line {
408 case .row(let index): .row(group.rows[index])
409 case .grid(let time): .grid(time)
410 case .now: .now
411 }
412 }
413 }
414
415 private var todayColor: Color { themed(theme.color("agenda-today", dark: isDark), .accentColor) }
416
417 private func header(_ group: AgendaDayGroup) -> some View {
418 let day = date(group.day).formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))
419 let color = group.isToday ? todayColor : group.day < agenda.today ? Color.secondary : themed(theme.color("agenda-date", dark: isDark), .primary)
420 return HStack(alignment: .firstTextBaseline) {
421 Text(group.relativeName(today: agenda.today).map { $0 + " · " + day } ?? day)
422 .font(.subheadline.weight(group.isToday ? .bold : .semibold))
423 .foregroundStyle(color)
424 Spacer()
425 Button("Add to \(day)", systemImage: "plus.circle") { model.captureRequest = CaptureRequest(day: group.day) }
426 .labelStyle(.iconOnly)
427 .font(.body)
428 .foregroundStyle(group.isToday ? todayColor : .secondary)
429 }
430 .textCase(nil)
431 }
432
433 // MARK: - Span
434
435 /// The first day shown, as `Days` numbers it, and how many.
436 private var shown: (first: Int, span: Int) { agenda.shown(today: agenda.today) }
437
438 private var firstDay: Int { shown.first }
439
440 private var todayShown: Bool { (shown.first..<(shown.first + shown.span)).contains(agenda.today) }
441
442 /// The span: `Thu 8 Oct`, `Week of 5 Oct`, `October 2026`, or the days, `5 – 14 Oct`.
443 private var title: String {
444 guard case .agenda = agenda.mode else { return viewName }
445 if viewName != "Agenda", range == nil, agenda.start == nil { return viewName }
446 let (first, span) = shown
447 let start = date(first)
448 if span == 1 { return start.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated)) }
449 if span == 7, first == weekStart(first) { return "Week of " + start.formatted(.dateTime.day().month(.abbreviated)) }
450 let d = Days.date(first)
451 if d.day == 1, span == Days.absolute(year: d.year, month: d.month + 1, day: 1) - first {
452 return start.formatted(.dateTime.month(.wide).year())
453 }
454 return start.formatted(.dateTime.day().month(.abbreviated)) + " – " + date(first + span - 1).formatted(.dateTime.day().month(.abbreviated))
455 }
456
457 private func weekStart(_ day: Int) -> Int {
458 Days.weekStart(day, on: agenda.startOnWeekday)
459 }
460
461 /// Shows `range` around `day`; nil returns to the configured span.
462 private func show(_ range: SpanRange?, around day: Int) {
463 self.range = range
464 let mode: AgendaMode
465 let start: Int?
466 switch range {
467 case .day:
468 (mode, start) = (.agenda(span: 1, startOffset: 0), day)
469 case .week:
470 (mode, start) = (.agenda(span: 7, startOffset: 0), weekStart(day))
471 case .month:
472 let d = Days.date(day)
473 let first = Days.absolute(year: d.year, month: d.month, day: 1)
474 (mode, start) = (.agenda(span: Days.absolute(year: d.year, month: d.month + 1, day: 1) - first, startOffset: 0), first)
475 case nil:
476 (mode, start) = (.agenda(span: nil, startOffset: nil), day == agenda.today ? nil : day)
477 }
478 rangeMode = mode
479 viewName = "Agenda"
480 agenda.mode = mode
481 agenda.start = start
482 }
483
484 private func step(forward: Bool) {
485 if range == nil, case .agenda = agenda.mode {
486 agenda.shift(forward: forward)
487 } else {
488 let (first, span) = shown
489 show(range, around: forward ? first + span : first - 1)
490 }
491 }
492
493 private func jump(to day: Int) {
494 show(range, around: day)
495 }
496
497 private func goToday() {
498 if range == nil { show(nil, around: agenda.today) } else { show(range, around: agenda.today) }
499 }
500
501 /// The bar while selecting: the count, the bulk actions (`B` in Org's agenda) and Done.
502 private var bulkBar: some View {
503 VStack(spacing: 8) {
504 if let message {
505 Text(message).font(.footnote).padding(.horizontal, 12).padding(.vertical, 6)
506 .glassEffect(.regular, in: Capsule())
507 .onTapGesture { self.message = nil }
508 }
509 HStack(spacing: 12) {
510 Text("\(marked.count) selected").font(.footnote.weight(.semibold).monospacedDigit()).padding(.leading, 12)
511 Menu {
512 Button("TODO State…", systemImage: "checkmark.circle") { askBulkTodo() }
513 Button("Add Tag…", systemImage: "tag") { askBulkTag(on: true) }
514 Button("Remove Tag…", systemImage: "tag.slash") { askBulkTag(on: false) }
515 Button("Schedule…", systemImage: "calendar") { bulkPlanning = .schedule }
516 Button("Deadline…", systemImage: "calendar.badge.exclamationmark") { bulkPlanning = .deadline }
517 Divider()
518 Button("Refile…", systemImage: "arrow.turn.down.right") { bulkRefiling = true }
519 Button("Archive…", systemImage: "archivebox", role: .destructive) { bulkArchiving = true }
520 } label: {
521 Text("Actions").font(.body.weight(.semibold)).frame(minHeight: 44)
522 }
523 .disabled(marked.isEmpty)
524 Button("Done") {
525 selecting = false
526 marked = []
527 }
528 .font(.body.weight(.semibold))
529 .frame(minHeight: 44)
530 .padding(.trailing, 12)
531 }
532 .glassEffect(.regular.interactive(), in: Capsule())
533 }
534 .padding(.bottom, 8)
535 .frame(maxWidth: .infinity)
536 }
537
538 private var bottomBar: some View {
539 VStack(spacing: 8) {
540 if let status = message ?? (filter.isEmpty ? nil : "Filter: " + filter.description) {
541 Text(status).font(.footnote).padding(.horizontal, 12).padding(.vertical, 6)
542 .glassEffect(.regular, in: Capsule())
543 .onTapGesture { message = nil }
544 }
545 HStack(spacing: 2) {
546 let isAgenda = if case .agenda = agenda.mode { true } else { false }
547 if isAgenda {
548 barButton("Earlier", "chevron.left") { step(forward: false) }
549 }
550 barButton("Filter", filter.isEmpty ? "line.3.horizontal.decrease" : "line.3.horizontal.decrease.circle.fill") { showingFilter = true }
551 barButton("Select", "checkmark.circle") { selecting = true }
552 if isAgenda {
553 barButton("Today", "smallcircle.filled.circle") { goToday() }
554 barButton("Go to Date", "calendar") { jumping = true }
555 Menu {
556 Picker("Span", selection: Binding { range } set: { show($0, around: $0 == nil || todayShown ? agenda.today : firstDay) }) {
557 ForEach(SpanRange.allCases) { Text($0.title).tag(Optional($0)) }
558 Text("\(agenda.span) Days").tag(SpanRange?.none)
559 }
560 Toggle("Log Mode", systemImage: "clock.arrow.circlepath", isOn: $logMode)
561 } label: {
562 Text(range?.title ?? "\(agenda.span) Days")
563 .font(.footnote.weight(.semibold).monospacedDigit())
564 .lineLimit(1)
565 .frame(minWidth: 52, minHeight: 44)
566 .contentShape(Rectangle())
567 }
568 .accessibilityLabel("Span")
569 barButton("Later", "chevron.right") { step(forward: true) }
570 } else {
571 barButton("Agenda", "calendar") { show(nil, around: agenda.today) }
572 }
573 }
574 .padding(.horizontal, 6)
575 .glassEffect(.regular.interactive(), in: Capsule())
576 }
577 .padding(.bottom, 8)
578 .frame(maxWidth: .infinity)
579 }
580
581 private func barButton(_ title: String, _ image: String, action: @escaping () -> Void) -> some View {
582 Button(title, systemImage: image, action: action)
583 .labelStyle(.iconOnly)
584 .font(.body.weight(.medium))
585 .frame(width: 44, height: 44)
586 .contentShape(Rectangle())
587 }
588
589 // MARK: - Rows
590
591 private func row(_ row: AgendaRow, day: Int) -> some View {
592 Group {
593 if selecting {
594 if let mark = Mark(row.item) {
595 Button {
596 if let index = marked.firstIndex(of: mark) { marked.remove(at: index) } else { marked.append(mark) }
597 } label: {
598 HStack(spacing: 10) {
599 Image(systemName: marked.contains(mark) ? "checkmark.circle.fill" : "circle")
600 .foregroundStyle(marked.contains(mark) ? Color.accentColor : .secondary)
601 .font(.title3)
602 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
603 }
604 }
605 .tint(.primary)
606 .accessibilityAddTraits(marked.contains(mark) ? .isSelected : [])
607 } else {
608 AgendaRowView(row: row, day: day, theme: theme, dark: isDark).opacity(0.5)
609 }
610 } else if let item = row.item, let path = item.path, let offset = item.headingOffset ?? item.markerOffset {
611 NavigationLink(value: ReaderRoute.offset(path, offset)) { AgendaRowView(row: row, day: day, theme: theme, dark: isDark) }
612 } else if let event = row.event {
613 // Calendar can't be asked for one event by URL; it opens on the event's day.
614 Button {
615 let link = event.isReminder ? "x-apple-reminderkit://REMCDReminder/\(event.id)" : "calshow:\(event.start.timeIntervalSinceReferenceDate)"
616 if let url = URL(string: link) { openURL(url) }
617 } label: {
618 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
619 }
620 .tint(.primary)
621 } else {
622 AgendaRowView(row: row, day: day, theme: theme, dark: isDark)
623 }
624 }
625 .swipeActions(edge: .trailing) {
626 if let item = row.item, item.todo != nil, !item.isDone, item.doneKeyword != nil {
627 Button("Done", systemImage: "checkmark") { markDone(item) }.tint(.green)
628 Button("Next State", systemImage: "arrow.right.circle") { run("org.todo.next", on: item) }.tint(.blue)
629 }
630 // Last, so a full swipe doesn't reach it; it asks first.
631 if let item = row.item, item.path != nil, item.headingLine != nil {
632 Button("Delete", systemImage: "trash") { deleting = item }.tint(.red)
633 }
634 }
635 .swipeActions(edge: .leading) {
636 if canReschedule(row), let item = row.item {
637 Button("Tomorrow", systemImage: "sunrise") { reschedule(row, item, to: agenda.today + 1) }.tint(.orange)
638 Button("Next Week", systemImage: "calendar.badge.plus") { reschedule(row, item, to: weekStart(agenda.today) + 7) }.tint(.indigo)
639 Button("Pick Date", systemImage: "calendar") { rescheduling = row }.tint(.gray)
640 }
641 }
642 .contextMenu {
643 if let item = row.item, item.path != nil {
644 if let mark = Mark(item) {
645 Button("Select", systemImage: "checkmark.circle") {
646 selecting = true
647 if !marked.contains(mark) { marked.append(mark) }
648 }
649 }
650 Button("TODO State…", systemImage: "checkmark.circle") { run("org.todo.cycle", on: item) }
651 if canReschedule(row) {
652 Menu("Reschedule", systemImage: "calendar.badge.clock") {
653 Button("Tomorrow") { reschedule(row, item, to: agenda.today + 1) }
654 Button("Next Week") { reschedule(row, item, to: weekStart(agenda.today) + 7) }
655 Button("Pick Date…") { rescheduling = row }
656 }
657 }
658 Button("Schedule…", systemImage: "calendar") { run("org.schedule", on: item) }
659 Button("Deadline…", systemImage: "calendar.badge.exclamationmark") { run("org.deadline", on: item) }
660 Button("Tags…", systemImage: "tag") { run("org.tags.set", on: item) }
661 Button("Priority…", systemImage: "exclamationmark.circle") { run("org.priority.set", on: item) }
662 Button("Clock In", systemImage: "stopwatch") {
663 if let (path, offset) = locate(item) { clockIn(path, offset) }
664 }
665 Divider()
666 Button("Refile…", systemImage: "arrow.turn.down.right") { refiling = item }
667 Button("Archive…", systemImage: "archivebox") { archiving = item }
668 if item.headingLine != nil {
669 Button("Delete…", systemImage: "trash", role: .destructive) { deleting = item }
670 }
671 }
672 }
673 }
674
675 // MARK: - Actions
676
677 /// Entries with a heading, not done, that a schedule or deadline can move.
678 private func canReschedule(_ row: AgendaRow) -> Bool {
679 guard let item = row.item, item.path != nil, item.headingLine != nil, !row.isDone else { return false }
680 return item.todo != nil || row.icon == .scheduled || row.icon == .deadline || row.icon == .habit
681 }
682
683 /// Moves the row's deadline (on a deadline row) or schedule to `day`, keeping its times,
684 /// as `org-agenda-schedule` and `org-agenda-deadline` with a date typed.
685 private func reschedule(_ row: AgendaRow, _ item: AgendaItem, to day: Int) {
686 let d = Days.date(day)
687 var answer = String(format: "%04d-%02d-%02d", d.year, d.month, d.day)
688 if let start = row.start {
689 answer += String(format: " %02d:%02d", start / 100 % 24, start % 100)
690 if let end = row.end { answer += String(format: "-%02d:%02d", end / 100 % 24, end % 100) }
691 }
692 run(row.icon == .deadline ? "org.deadline" : "org.schedule", on: item, answers: ["date": answer])
693 moved += 1
694 }
695
696 /// The heading of `item` now, found again by its line in case the file changed.
697 private func locate(_ item: AgendaItem) -> (path: String, offset: Int)? {
698 guard let path = item.path, let line = item.headingLine, let near = item.headingOffset,
699 let offset = session.locateHeading(path: path, line: line, near: near) else {
700 message = "The entry changed; the agenda has been refreshed."
701 tick += 1
702 return nil
703 }
704 return (path, offset)
705 }
706
707 /// `org-agenda-clock-in`: `org-clock-in` at the entry, dangling clocks resolved first.
708 private func clockIn(_ path: String, _ offset: Int) {
709 let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
710 Task {
711 let outcome = await clock.clockIn(session, target: .entry(path: path, offset: offset), paths: paths, ask: model.clockPrompts.ask)
712 if let jump = outcome.jump { model.openRequest = .offset(jump.path, jump.offset) }
713 message = outcome.messages.last { !$0.isEmpty }
714 }
715 }
716
717 /// Runs a command at the entry's heading, asking what it asks.
718 private func run(_ id: String, on item: AgendaItem, answers: [String: String] = [:]) {
719 guard let command = Commands.command(id) else { return }
720 run(command, on: item, answers: answers)
721 }
722
723 private func run(_ command: any OrgCommand, on item: AgendaItem, answers: [String: String] = [:]) {
724 guard let (path, offset) = locate(item), let line = item.headingLine else { return }
725 switch session.perform(command, path: path, at: offset, expect: (offset, line), answers: answers) {
726 case .prompt(let request):
727 prompt = EditorScreen.PromptRequest(prompt: request) { answer in
728 guard let answer else { return }
729 run(command, on: item, answers: answers.merging([request.key: answer]) { $1 })
730 }
731 case .failed(let text):
732 message = text
733 case .external(let request):
734 message = MobileEditor.unavailable(request, title: command.title)
735 case .commit:
736 message = nil
737 }
738 tick += 1
739 }
740
741 // MARK: - Bulk actions
742
743 /// Runs `action` on each marked entry, found again first; later entries in a file first,
744 /// so earlier ones keep their place. Selection ends; the last message shows.
745 private func bulk(_ action: (String, Int) -> String?) {
746 var last: String?
747 var failed = 0
748 for mark in marked.sorted(by: { ($0.path, $1.offset) < ($1.path, $0.offset) }) {
749 guard let offset = session.locateHeading(path: mark.path, line: mark.line, near: mark.offset) else {
750 failed += 1
751 continue
752 }
753 last = action(mark.path, offset)
754 }
755 message = failed > 0 ? "\(failed) selected \(failed == 1 ? "entry" : "entries") changed and \(failed == 1 ? "was" : "were") skipped" : last
756 marked = []
757 selecting = false
758 tick += 1
759 }
760
761 /// `command` at the heading at `offset` in `path`; a message when it doesn't apply.
762 private func perform(_ command: any OrgCommand, _ path: String, _ offset: Int, answers: [String: String] = [:]) -> String? {
763 switch session.perform(command, path: path, at: offset, expect: nil, answers: answers) {
764 case .failed(let text): text
765 case .prompt: "\(command.title) needs an answer; run it on the entry itself"
766 case .external(let request): MobileEditor.unavailable(request, title: command.title)
767 case .commit: nil
768 }
769 }
770
771 private func askBulkTodo() {
772 let keywords = OrgPreferences.orgSettings().todoSequences.flatMap { $0.active.map(\.name) + $0.done.map(\.name) }
773 prompt = EditorScreen.PromptRequest(prompt: Prompt(key: "todo", message: "TODO state (empty for none):", choices: keywords)) { answer in
774 guard let answer else { return }
775 let word = answer.trimmingCharacters(in: .whitespaces)
776 bulk { perform(SetTodo(keyword: word.isEmpty ? nil : word), $0, $1) }
777 }
778 }
779
780 private func askBulkTag(on: Bool) {
781 prompt = EditorScreen.PromptRequest(prompt: Prompt(key: "tag", message: on ? "Tag to add:" : "Tag to remove:")) { answer in
782 guard let tag = answer?.trimmingCharacters(in: .whitespaces), !tag.isEmpty else { return }
783 bulk { perform(ToggleTag(tag: tag, on: on), $0, $1) }
784 }
785 }
786
787 private func markDone(_ item: AgendaItem) {
788 guard let keyword = item.doneKeyword else { return }
789 run(SetTodo(keyword: keyword), on: item)
790 done += 1
791 }
792
793 private func refile(_ item: AgendaItem, to target: RefileTarget) {
794 guard let (path, offset) = locate(item) else { return }
795 // Targets in the entry's own file come from its text now.
796 let document = session.openDocuments.first { $0.path == path }?.document
797 ?? FileManager.default.contents(atPath: path).map { DocumentState(bytes: [UInt8]($0)) }
798 guard let current = workspace.refileTargets(openPath: path, document: document).first(where: { $0.label == target.label }) else {
799 message = "Can't find \(target.label) any more."
800 return
801 }
802 message = session.refile(to: current, from: (path, offset))
803 tick += 1
804 }
805
806 private func archive(_ item: AgendaItem) {
807 guard let (path, offset) = locate(item) else { return }
808 message = session.archive(from: (path, offset))
809 tick += 1
810 }
811
812 private func date(_ day: Int) -> Date {
813 let d = Days.date(day)
814 return Calendar.current.date(from: DateComponents(year: d.year, month: d.month, day: d.day)) ?? Date()
815 }
816
817 private func themed(_ color: RGBA?, _ fallback: Color) -> Color { color?.swiftUI ?? fallback }
818}
819
820extension RGBA {
821 var swiftUI: Color { Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha) }
822}
823
824/// One agenda line: the time or status with an icon in the gutter; the category, title,
825/// progress and tags; the TODO keyword and priority on the right.
826struct AgendaRowView: View {
827 let row: AgendaRow
828 /// The day the row is on, for habit graphs.
829 let day: Int
830 let theme: ThemeSpec
831 let dark: Bool
832
833 var body: some View {
834 HStack(alignment: .top, spacing: 10) {
835 // TODO and match lists have no times or statuses.
836 if !row.gutter.isEmpty || row.icon != nil { gutter.frame(width: 82, alignment: .leading) }
837 VStack(alignment: .leading, spacing: 2) {
838 HStack(spacing: 5) {
839 if !row.category.isEmpty {
840 Circle().fill(categoryColor).frame(width: 7, height: 7)
841 Text(row.category).lineLimit(1).layoutPriority(1)
842 }
843 if let detail = row.prefixDetail { Text(detail).lineLimit(1).truncationMode(.middle) }
844 ForEach([row.progress, row.detail].compactMap { $0 }, id: \.self) { progress in
845 Text(progress).monospacedDigit()
846 .padding(.horizontal, 5)
847 .background(.quaternary.opacity(0.7), in: Capsule())
848 }
849 ForEach(row.tags.prefix(3), id: \.self) { tag in
850 Text(tag).lineLimit(1)
851 .padding(.horizontal, 5)
852 .background(.quaternary.opacity(0.7), in: Capsule())
853 }
854 Spacer(minLength: 4)
855 marks
856 }
857 .font(.caption)
858 .foregroundStyle(.secondary)
859 Text(row.title.isEmpty ? " " : row.title)
860 .font(.body)
861 .strikethrough(row.isDone)
862 .foregroundStyle(row.isDone ? .secondary : .primary)
863 if let habit = row.item?.habit {
864 HabitStrip(cells: habit.graph(today: day), theme: theme, dark: dark).padding(.top, 3)
865 }
866 }
867 }
868 .padding(.vertical, 2)
869 // Blocked entries dim, as `org-agenda-dim-blocked-tasks`.
870 .opacity(row.isBlocked ? 0.5 : row.isDone ? 0.75 : 1)
871 }
872
873 /// The TODO keyword and the priority, on the category's line.
874 private var marks: some View {
875 HStack(spacing: 5) {
876 if let todo = row.todo {
877 let color = theme.todoColor(todo, isDone: row.isDone, dark: dark)?.swiftUI ?? .secondary
878 Text(todo)
879 .font(.caption2.weight(.semibold))
880 .foregroundStyle(color)
881 .padding(.horizontal, 6).padding(.vertical, 2)
882 .background(color.opacity(0.14), in: Capsule())
883 }
884 if let priority = row.priority {
885 let color = theme.priorityColor(priority, dark: dark)?.swiftUI ?? .orange
886 Text(priority)
887 .font(.caption2.weight(.bold))
888 .foregroundStyle(color)
889 .frame(width: 18, height: 18)
890 .background(color.opacity(0.14), in: Circle())
891 .overlay(Circle().strokeBorder(color, lineWidth: 1.2))
892 .accessibilityLabel("Priority \(priority)")
893 }
894 }
895 .fixedSize()
896 }
897
898 private var statusColor: Color {
899 theme.statusColor(row.status, dark: dark)?.swiftUI ?? .secondary
900 }
901
902 private var categoryColor: Color {
903 if let event = row.event { return theme.eventColor(event, dark: dark)?.swiftUI ?? .purple }
904 return theme.categoryColor(row.category, dark: dark).swiftUI
905 }
906
907 /// The start over the end for timed rows, else the status; the icon under them.
908 private var gutter: some View {
909 HStack(alignment: .firstTextBaseline, spacing: 4) {
910 Image(systemName: icon ?? "circle").font(.caption2.weight(.semibold)).foregroundStyle(iconColor)
911 .frame(width: 14)
912 .opacity(icon == nil ? 0 : 1)
913 VStack(alignment: .leading, spacing: 1) {
914 if row.start != nil {
915 let parts = row.gutter.split(separator: "–", maxSplits: 1)
916 Text(parts.first.map(String.init) ?? row.gutter)
917 .font(.subheadline.monospacedDigit().weight(.semibold))
918 .foregroundStyle(row.status == .normal ? Color.primary : row.status == .done ? Color.secondary : statusColor)
919 if parts.count > 1 {
920 Text(parts[1]).font(.caption.monospacedDigit()).foregroundStyle(.secondary)
921 }
922 } else if !row.gutter.isEmpty {
923 Text(row.gutter)
924 .font(.caption.weight(.medium).monospacedDigit())
925 .foregroundStyle(statusColor)
926 .lineLimit(1)
927 .allowsTightening(true)
928 .minimumScaleFactor(0.8)
929 }
930 }
931 }
932 }
933
934 private var icon: String? {
935 switch row.icon {
936 case .scheduled: row.status == .overdue ? "exclamationmark.circle.fill" : "calendar"
937 case .deadline: row.status == .overdue ? "exclamationmark.triangle.fill" : "flag.fill"
938 case .habit: "repeat"
939 case .event: "calendar"
940 case .reminder: "circle"
941 case .timestamp: "clock"
942 case nil: nil
943 }
944 }
945
946 private var iconColor: Color {
947 if row.isEvent { return categoryColor }
948 return row.status == .normal ? Color(.tertiaryLabel) : statusColor
949 }
950}
951
952/// An `org-agenda-time-grid` line.
953struct GridLineRow: View {
954 let time: Int
955
956 var body: some View {
957 HStack(spacing: 6) {
958 Text(String(format: "%02d:%02d", time / 100, time % 100))
959 .font(.caption2.monospacedDigit())
960 Rectangle().fill(Color(.separator)).frame(height: 0.5)
961 }
962 .foregroundStyle(.tertiary)
963 .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
964 .listRowSeparator(.hidden)
965 .frame(height: 14)
966 .accessibilityHidden(true)
967 }
968}
969
970/// The current time between timed rows, as Org's `now - - -` line.
971struct NowLine: View {
972 let time: Date
973 let color: Color
974
975 var body: some View {
976 HStack(spacing: 6) {
977 Text(time.formatted(date: .omitted, time: .shortened))
978 .font(.caption2.weight(.semibold).monospacedDigit())
979 .foregroundStyle(color)
980 Circle().fill(color).frame(width: 6, height: 6)
981 Rectangle().fill(color).frame(height: 1.5)
982 }
983 .listRowInsets(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
984 .listRowSeparator(.hidden)
985 .frame(height: 16)
986 .accessibilityLabel("Now")
987 }
988}
989
990/// org-habit's consistency graph, compact: a bar per day, a dot where the habit was done,
991/// today outlined.
992struct HabitStrip: View {
993 let cells: [Habit.Cell]
994 let theme: ThemeSpec
995 let dark: Bool
996
997 var body: some View {
998 HStack(spacing: 1) {
999 ForEach(cells, id: \.day) { cell in
1000 RoundedRectangle(cornerRadius: 1.5)
1001 .fill(color(cell.face))
1002 .frame(width: 4, height: 12)
1003 .overlay {
1004 if cell.glyph == "*" { Circle().fill(.white.opacity(0.9)).frame(width: 3, height: 3) }
1005 }
1006 .overlay {
1007 if cell.glyph == "!" { RoundedRectangle(cornerRadius: 1.5).strokeBorder(Color.primary, lineWidth: 1) }
1008 }
1009 }
1010 }
1011 .accessibilityElement(children: .ignore)
1012 .accessibilityLabel("Done \(cells.filter { $0.glyph == "*" }.count) of the last \(Habit.precedingDays) days")
1013 }
1014
1015 /// Due-state colors, lighter for days to come, as org-habit's faces.
1016 private func color(_ face: Habit.Face) -> Color {
1017 func themed(_ key: String, _ fallback: Color) -> Color { theme.color(key, dark: dark)?.swiftUI ?? fallback }
1018 switch face {
1019 case .clear: return themed("habit-clear", .blue).opacity(0.7)
1020 case .clearFuture: return themed("habit-clear", .blue).opacity(0.3)
1021 case .ready: return themed("habit-ready", .green).opacity(0.8)
1022 case .readyFuture: return themed("habit-ready", .green).opacity(0.3)
1023 case .alert: return themed("habit-alert", .yellow).opacity(0.85)
1024 case .alertFuture: return themed("habit-alert", .yellow).opacity(0.35)
1025 case .overdue: return themed("habit-overdue", .red).opacity(0.8)
1026 case .overdueFuture: return themed("habit-overdue", .red).opacity(0.3)
1027 }
1028 }
1029}
1030
1031/// A date to go to or to schedule on.
1032struct DateSheet: View {
1033 let title: String
1034 let action: String
1035 let initial: Date
1036 let done: (Date?) -> Void
1037 @State private var date = Date()
1038
1039 var body: some View {
1040 NavigationStack {
1041 DatePicker(title, selection: $date, displayedComponents: .date)
1042 .datePickerStyle(.graphical)
1043 .padding(.horizontal)
1044 .navigationTitle(title)
1045 .navigationBarTitleDisplayMode(.inline)
1046 .toolbar {
1047 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { done(nil) } }
1048 ToolbarItem(placement: .confirmationAction) { Button(action) { done(date) } }
1049 }
1050 Spacer()
1051 }
1052 .presentationDetents([.medium, .large])
1053 .onAppear { date = initial }
1054 }
1055}
1056
1057extension AgendaItem: Identifiable {
1058 public var id: String { "\(path ?? "")|\(headingOffset ?? -1)|\(kind.rawValue)|\(text)" }
1059
1060 /// An entry, not a time-grid line.
1061 var isEntry: Bool { kind != .timeGrid && kind != .currentTime }
1062}
1063
1064/// Org's agenda filter: tags and categories of the entries shown, kept or left out, or the
1065/// filter typed as `/` takes it.
1066struct FilterSheet: View {
1067 @Binding var filter: AgendaFilter
1068 let items: [AgendaItem]
1069 @State private var typed = ""
1070 @Environment(\.dismiss) private var dismiss
1071
1072 var body: some View {
1073 let tags = Set(items.flatMap(\.tags)).sorted()
1074 let categories = Set(items.filter { $0.path != nil }.map(\.category)).sorted()
1075 NavigationStack {
1076 Form {
1077 Section {
1078 TextField("+work-home", text: $typed)
1079 .autocorrectionDisabled()
1080 .textInputAutocapitalization(.never)
1081 .onSubmit(apply)
1082 } footer: {
1083 Text("As Org's / filter: +keep and -drop tags or categories, <0:30 for effort, /regexp/.")
1084 }
1085 if !tags.isEmpty {
1086 Section("Tags") { ForEach(tags, id: \.self) { term($0, in: \.tags) } }
1087 }
1088 if !categories.isEmpty {
1089 Section("Categories") { ForEach(categories, id: \.self) { term($0, in: \.categories) } }
1090 }
1091 }
1092 .navigationTitle("Filter")
1093 .navigationBarTitleDisplayMode(.inline)
1094 .toolbar {
1095 ToolbarItem(placement: .cancellationAction) { Button("Clear") { filter = AgendaFilter(); dismiss() } }
1096 ToolbarItem(placement: .confirmationAction) { Button("Done") { apply(); dismiss() } }
1097 }
1098 }
1099 .onAppear { typed = filter.description }
1100 }
1101
1102 /// Keep, leave out, or no filter on `name`.
1103 private func term(_ name: String, in list: WritableKeyPath<AgendaFilter, [String]>) -> some View {
1104 let state = filter[keyPath: list].contains("+" + name) ? 1 : filter[keyPath: list].contains("-" + name) ? -1 : 0
1105 return Button {
1106 var terms = filter[keyPath: list].filter { $0.dropFirst() != Substring(name) }
1107 if state == 0 { terms.append("+" + name) } else if state == 1 { terms.append("-" + name) }
1108 filter[keyPath: list] = terms
1109 typed = filter.description
1110 } label: {
1111 HStack {
1112 Text(name).foregroundStyle(.primary)
1113 Spacer()
1114 Text(state == 1 ? "Keep" : state == -1 ? "Leave out" : "").foregroundStyle(.secondary)
1115 }
1116 }
1117 }
1118
1119 private func apply() {
1120 guard typed != filter.description else { return }
1121 let tags = Set(items.flatMap(\.tags))
1122 let categories = Set(items.map(\.category))
1123 filter = AgendaFilter().parse(typed, tags: tags, categories: categories).filter
1124 }
1125}
1126
1127/// Where to refile an entry: each file, at its end, and the headings in it down to level 3,
1128/// as the Mac's prompt offers them, searchable by their path.
1129struct RefileSheet: View {
1130 let targets: [RefileTarget]
1131 /// `org-refile-allow-creating-parent-nodes`: `parent/new` in the search field offers to
1132 /// add the heading.
1133 var create: ((RefileTarget, String) -> Void)?
1134 var title = "Refile to"
1135 let choose: (RefileTarget?) -> Void
1136 @State private var query = ""
1137
1138 /// Targets by file, in the order given, each file's own row first.
1139 private var files: [(path: String, targets: [RefileTarget])] {
1140 var order: [String] = []
1141 var byPath: [String: [RefileTarget]] = [:]
1142 for target in targets where query.isEmpty || target.label.localizedCaseInsensitiveContains(query) {
1143 if byPath[target.path] == nil { order.append(target.path) }
1144 byPath[target.path, default: []].append(target)
1145 }
1146 return order.map { ($0, byPath[$0] ?? []) }
1147 }
1148
1149 var body: some View {
1150 NavigationStack {
1151 List {
1152 if let create, let (parent, child) = RefileSettings.newNode(query, in: targets) {
1153 Button {
1154 create(parent, child)
1155 } label: {
1156 Label("New heading “\(child)” under \(parent.label)", systemImage: "plus")
1157 }
1158 }
1159 ForEach(files, id: \.path) { file in
1160 Section {
1161 ForEach(file.targets, id: \.self) { target in
1162 Button {
1163 choose(target)
1164 } label: {
1165 HStack(spacing: 6) {
1166 if target.start == nil {
1167 Image(systemName: "doc.text").foregroundStyle(.secondary)
1168 Text(target.label)
1169 } else {
1170 Text(String(repeating: " ", count: max(0, target.level - 1)) + target.title)
1171 }
1172 }
1173 }
1174 .foregroundStyle(.primary)
1175 }
1176 }
1177 }
1178 }
1179 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
1180 .navigationTitle(title)
1181 .navigationBarTitleDisplayMode(.inline)
1182 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { choose(nil) } } }
1183 }
1184 }
1185}
1186/// A view built when the list draws it: a list makes every row's view up front, and a row's
1187/// actions and menus cost more than the row.
1188private struct Deferred<Content: View>: View {
1189 @ViewBuilder let content: () -> Content
1190
1191 var body: some View { content() }
1192}
1193#endif