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