Sources/Orgstar/AgendaView.swift
594 lines · 26220 bytes
1import AppKit
2import OrgApp
3import OrgDocument
4import OrgCore
5import OrgPresentation
6import SwiftUI
7
8/// The days an agenda shows, as Org's `v d`, `v w` and `v m`.
9enum AgendaSpan: String, CaseIterable {
10 case day, week, month
11}
12
13/// The app's one reader of Calendar events, for the agenda and Settings.
14@MainActor
15enum CalendarAccess {
16 static let events = CalendarEvents()
17}
18
19/// The agenda window: the day/week agenda, the TODO list, tag matches, text search and saved views.
20/// Return or a double click jumps to the entry in the main window. Keys as in Emacs's agenda:
21/// n/p (or the arrows) move between lines, f/b/. move the span, j picks a date, v d/v w/v m (or
22/// d/w) show a day, week or month, g refreshes, l shows the log (closed and clocked), / filters
23/// (`+cat-tag<0:10-/regexp/`), \ by tag, < by the line's category, = by regexp, _ by effort,
24/// | clears filters, I/O/X clock in, out and cancel, C-c C-w refiles, $ archives, m/u/U mark
25/// and unmark, B acts on the marked entries, t cycles the TODO state, +/- change the priority and
26/// , sets it, : or C-c C-q sets tags, C-c C-s / C-c C-d schedule and set a deadline, S-→/S-← move
27/// the date, k captures on the line's day, s saves all files, TAB and SPC show the entry.
28struct AgendaView: View {
29 let workspace: WorkspaceModel
30 let session: DocumentSession
31 let commands: AppCommands
32 let scheduler: ReminderScheduler?
33 let clock: ClockModel
34 @State var agenda: AgendaModel
35 @State var views = AgendaViewLoader.builtIn
36 @State var viewName = AgendaViewLoader.builtIn[0].name
37 @State var matchText = ""
38 /// The selected line: `day:index` (`day:o` + index in the overdue group), or `list:index`.
39 @State var selection: String?
40 @State var tick = 0
41 /// The time the now line shows, kept to the minute while the agenda is open.
42 @State var now = Date()
43 /// The view picker moved to the agenda for a followed timestamp, which sets its own days.
44 @State var keepRequestedDays = false
45 @State var message: String?
46 @State var prompt: PendingPrompt?
47 @State var promptText = ""
48 @State var prefix: String?
49 /// Entries marked for a bulk action.
50 @State var marked: [EntryRef] = []
51 @State var logMode = false
52 @State var filter = AgendaFilter()
53 /// A filter question: its title and which filter it sets.
54 @State var filterPrompt: (title: String, kind: Character)?
55 @State var filterText = ""
56 /// A one-line question for an agenda action, and what to do with the answer.
57 struct TextPrompt {
58 let title: String
59 let apply: (String) -> Void
60 }
61 @State var textPrompt: TextPrompt?
62 @State private var textAnswer = ""
63 /// Day, week or month chosen with `v`; nil shows the span the settings or the view give.
64 @State var spanKind: AgendaSpan?
65 @State var showingDatePicker = false
66 @State var pickedDate = Date()
67 @AppStorage("agendaOverdueExpanded") private var overdueShown = true
68 @State private var hovered: String?
69 @FocusState private var focused: Bool
70 @AppStorage("agendaSpan") var span = 10
71 @AppStorage("agendaStartOffset") var startOffset = 0
72 @AppStorage("agendaStartOnWeekday") private var startOnWeekday = "1"
73 @AppStorage("agendaSubfolders") private var includeSubfolders = false
74 @AppStorage("agendaShowAllDates") private var showAllDates = false
75 @AppStorage("calendarEvents") private var calendarEventsOn = false
76 @AppStorage("calendarEventCalendars") private var calendarNames = ""
77 @AppStorage("agendaPrefixAgenda") private var prefixAgenda = PrefixFormat.defaults["agenda"]!
78 @AppStorage("agendaPrefixTodo") private var prefixTodo = PrefixFormat.defaults["todo"]!
79 @AppStorage("agendaPrefixTags") private var prefixTags = PrefixFormat.defaults["tags"]!
80 @AppStorage("agendaSortAgenda") private var sortAgenda = ""
81 @AppStorage("agendaSortTodo") private var sortTodo = ""
82 @AppStorage("agendaSortTags") private var sortTags = ""
83 @AppStorage("agendaSortSearch") private var sortSearch = ""
84 @AppStorage("agendaUseTimeGrid") private var useTimeGrid = true
85 @AppStorage("agendaShowCurrentTime") private var showCurrentTime = true
86 @AppStorage("agendaTimeGridWhen") private var gridWhen = ""
87 @AppStorage("agendaTimeGridTimes") private var gridTimes = ""
88 @AppStorage("stuckProjectsMatch") private var stuckMatch = ""
89 @AppStorage("stuckProjectsTodo") private var stuckTodo = ""
90 @AppStorage("stuckProjectsTags") private var stuckTags = ""
91 @AppStorage("stuckProjectsRegexp") private var stuckRegexp = ""
92 @Environment(\.openWindow) var openWindow
93
94 static let match = "Match…"
95 static let todoMatch = "TODO Match…"
96 static let search = "Search…"
97 static let todoSearch = "TODO Search…"
98
99 init(workspace: WorkspaceModel, session: DocumentSession, commands: AppCommands, scheduler: ReminderScheduler?, clock: ClockModel) {
100 self.workspace = workspace
101 self.session = session
102 self.commands = commands
103 self.scheduler = scheduler
104 self.clock = clock
105 _agenda = State(initialValue: AgendaModel(workspace: workspace))
106 }
107
108 /// An agenda entry by its file, heading line and where that line was.
109 struct EntryRef: Hashable {
110 let path: String
111 let line: String
112 let offset: Int
113
114 init?(_ item: AgendaItem) {
115 guard let path = item.path, let line = item.headingLine, let offset = item.headingOffset else { return nil }
116 self.path = path
117 self.line = line
118 self.offset = offset
119 }
120 }
121
122 struct PendingPrompt: Identifiable {
123 let id = UUID()
124 let prompt: Prompt
125 let command: any OrgCommand
126 let atMarker: Bool
127 let answers: [String: String]
128 let itemID: String
129 }
130
131 private struct RefreshKey: Hashable {
132 var mode: AgendaMode
133 var start: Int?
134 var span: Int
135 var startOffset: Int
136 var startOnWeekday: String
137 var includeSubfolders: Bool
138 var prefix: [String]
139 var settings: [String]
140 var logMode: Bool
141 var calendars: [String]
142 var files: Int
143 var changed: Int?
144 var edits: Int
145 var path: String?
146 var tick: Int
147 }
148
149 /// The settings part of the refresh key; `Refresher` adds the files and edits, so that
150 /// they redraw only it.
151 private var refreshKey: RefreshKey {
152 RefreshKey(
153 mode: agenda.mode, start: agenda.start, span: span, startOffset: startOffset, startOnWeekday: startOnWeekday, includeSubfolders: includeSubfolders, prefix: [prefixAgenda, prefixTodo, prefixTags],
154 settings: [sortAgenda, sortTodo, sortTags, sortSearch, gridWhen, gridTimes, "\(useTimeGrid) \(showCurrentTime)", stuckMatch, stuckTodo, stuckTags, stuckRegexp],
155 logMode: logMode,
156 calendars: calendarEventsOn ? [calendarNames] : [], files: 0, changed: nil, edits: 0, path: nil, tick: tick
157 )
158 }
159
160 private func refresh() async {
161 agenda.span = span
162 agenda.startOffset = startOffset
163 agenda.startOnWeekday = Int(startOnWeekday)
164 agenda.includeSubfolders = includeSubfolders
165 agenda.options.prefixFormat = ["agenda": prefixAgenda, "todo": prefixTodo, "tags": prefixTags]
166 agenda.options.logMode = logMode
167 agenda.options = OrgPreferences.agendaOptions(agenda.options)
168 agenda.calendarNames = OrgPreferences.calendarEventCalendars()
169 if calendarEventsOn, isAgenda || isBlocks {
170 agenda.calendarEvents = await CalendarAccess.events.requestAccess() ? CalendarAccess.events : nil
171 } else {
172 agenda.calendarEvents = nil
173 }
174 await agenda.refresh(open: session.openTexts)
175 }
176
177 /// Refreshes the agenda when the settings, files or edits change, once a burst of them ends.
178 private struct Refresher: View {
179 let base: RefreshKey
180 let session: DocumentSession
181 let workspace: WorkspaceModel
182 let refresh: () async -> Void
183
184 var key: RefreshKey {
185 var key = base
186 key.files = workspace.files.count
187 key.changed = workspace.changedFile?.version
188 key.edits = session.editVersion
189 key.path = session.path
190 return key
191 }
192
193 var body: some View {
194 Color.clear.task(id: key) {
195 try? await Task.sleep(for: .milliseconds(150))
196 guard !Task.isCancelled else { return }
197 await refresh()
198 }
199 }
200 }
201
202 var isAgenda: Bool {
203 if case .agenda = agenda.mode { return true }
204 return false
205 }
206
207 var isBlocks: Bool {
208 if case .blocks = agenda.mode { return true }
209 return false
210 }
211
212 var isMatch: Bool { viewName == Self.match || viewName == Self.todoMatch }
213 var isSearch: Bool { viewName == Self.search || viewName == Self.todoSearch }
214
215 @Environment(\.orgTheme) private var theme
216
217 // MARK: - Lines
218
219 /// A selectable line: its selection id, the row, and the day it is on.
220 struct Line {
221 let id: String
222 let row: AgendaRow
223 let day: Int
224 }
225
226 private var groups: [AgendaDayGroup] {
227 isAgenda ? agenda.groups(showAllDates: showAllDates, filter: filter) : []
228 }
229
230 private var listRows: [AgendaRow] { rows(agenda.list) }
231
232 private func rows(_ list: [AgendaItem]) -> [AgendaRow] {
233 list.filter(filter.keeps).compactMap { AgendaRow(item: $0, day: agenda.today, today: agenda.today) }
234 }
235
236 /// The lines in order, as up and down move through them.
237 func lines(_ groups: [AgendaDayGroup]) -> [Line] {
238 if isBlocks {
239 return agenda.blocks.enumerated().flatMap { k, block in
240 block.isAgenda ? dayLines(agenda.groups(block, showAllDates: showAllDates, filter: filter), prefix: "b\(k):")
241 : rows(block.list).enumerated().map { Line(id: "b\(k):list:\($0.offset)", row: $0.element, day: agenda.today) }
242 }
243 }
244 guard isAgenda else { return listRows.enumerated().map { Line(id: "list:\($0.offset)", row: $0.element, day: agenda.today) } }
245 return dayLines(groups, prefix: "")
246 }
247
248 private func dayLines(_ groups: [AgendaDayGroup], prefix: String) -> [Line] {
249 groups.flatMap { group in
250 (overdueShown ? group.overdue.enumerated().map { Line(id: "\(prefix)\(group.day):o\($0.offset)", row: $0.element, day: group.day) } : [])
251 + group.rows.enumerated().map { Line(id: "\(prefix)\(group.day):\($0.offset)", row: $0.element, day: group.day) }
252 }
253 }
254
255 func line(_ id: String) -> Line? { lines(groups).first { $0.id == id } }
256
257 var body: some View {
258 let groups = self.groups
259 _ = tick
260 return ScrollViewReader { proxy in
261 ScrollView {
262 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
263 if isBlocks {
264 ForEach(Array(agenda.blocks.enumerated()), id: \.offset) { k, block in
265 Section {
266 if block.isAgenda {
267 ForEach(agenda.groups(block, showAllDates: showAllDates, filter: filter)) { group in
268 dayHeader(group)
269 dayRows(group, prefix: "b\(k):")
270 }
271 } else {
272 ForEach(Array(rows(block.list).enumerated()), id: \.offset) { index, row in
273 rowView(Line(id: "b\(k):list:\(index)", row: row, day: agenda.today), showsGutter: false)
274 }
275 }
276 } header: {
277 header { Text(block.header).font(.system(size: 13, weight: .semibold)) }
278 }
279 }
280 } else if isAgenda {
281 ForEach(groups) { group in
282 Section {
283 dayRows(group)
284 } header: {
285 dayHeader(group).id("day\(group.day)")
286 }
287 }
288 } else {
289 Section {
290 ForEach(Array(listRows.enumerated()), id: \.offset) { index, row in
291 rowView(Line(id: "list:\(index)", row: row, day: agenda.today), showsGutter: false)
292 }
293 } header: {
294 header { Text(listTitle).font(.system(size: 13, weight: .semibold)) }
295 }
296 }
297 }
298 .padding(.bottom, 12)
299 }
300 .onChange(of: selection) {
301 if let selection { proxy.scrollTo(selection) }
302 }
303 .onChange(of: agenda.days.first?.day) {
304 if groups.contains(where: \.isToday) { proxy.scrollTo("day\(agenda.today)", anchor: .top) }
305 }
306 }
307 .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
308 .focusable()
309 .focusEffectDisabled()
310 .focused($focused)
311 .onAppear { focused = true }
312 .onKeyPress(phases: .down) { press in handle(press) }
313 .safeAreaInset(edge: .bottom, spacing: 0) {
314 if let message = message ?? (filter.isEmpty ? reminderStatus : "Filter: " + filter.description) {
315 Text(message)
316 .font(.callout)
317 .frame(maxWidth: .infinity, alignment: .leading)
318 .padding(.horizontal, 12)
319 .padding(.vertical, 6)
320 .background(.bar)
321 }
322 }
323 .toolbar { toolbar }
324 .overlay {
325 if agenda.files.isEmpty {
326 ContentUnavailableView("No agenda files", systemImage: "calendar", description: Text("The agenda reads the org files at the top of each folder you add."))
327 }
328 }
329 .sheet(item: Binding(get: { prompt?.prompt.fast == nil ? nil : prompt }, set: { if $0 == nil { prompt = nil } })) { pending in
330 if let fast = pending.prompt.fast {
331 FastSelectionView(selection: fast, message: pending.prompt.message) { answer in
332 prompt = nil
333 guard let answer else { return }
334 promptText = answer
335 prompt = pending
336 answerPrompt()
337 }
338 .frame(minWidth: 420)
339 }
340 }
341 .alert(prompt?.prompt.message ?? "", isPresented: Binding(get: { prompt != nil && prompt?.prompt.fast == nil }, set: { if !$0 { prompt = nil } })) {
342 TextField("", text: $promptText)
343 Button("OK") { answerPrompt() }
344 Button("Cancel", role: .cancel) { prompt = nil }
345 } message: {
346 if let choices = prompt?.prompt.choices, !choices.isEmpty {
347 Text(choices.prefix(12).joined(separator: " "))
348 }
349 }
350 .alert(filterPrompt?.title ?? "", isPresented: Binding(get: { filterPrompt != nil }, set: { if !$0 { filterPrompt = nil } })) {
351 TextField("", text: $filterText)
352 Button("Filter") { applyFilter() }
353 Button("Cancel", role: .cancel) { filterPrompt = nil }
354 } message: {
355 if filterPrompt?.kind == "/" || filterPrompt?.kind == "\\" {
356 Text(shown.tags.sorted().prefix(20).joined(separator: " "))
357 }
358 }
359 .alert(textPrompt?.title ?? "", isPresented: Binding(get: { textPrompt != nil }, set: { if !$0 { textPrompt = nil } })) {
360 TextField("", text: $textAnswer)
361 Button("OK") {
362 let pending = textPrompt
363 let answer = textAnswer
364 textPrompt = nil
365 textAnswer = ""
366 // A follow-up question opens after this alert closes.
367 DispatchQueue.main.async { pending?.apply(answer) }
368 }
369 Button("Cancel", role: .cancel) {
370 textPrompt = nil
371 textAnswer = ""
372 }
373 }
374 .navigationTitle(title)
375 .navigationSubtitle(isAgenda && viewName != AgendaViewLoader.builtIn[0].name ? viewName : "")
376 .onChange(of: viewName) { applyView() }
377 .onChange(of: commands.agendaRequest?.start, initial: true) { showRequestedDays() }
378 .onChange(of: commands.agendaRequest?.days) { showRequestedDays() }
379 .background { Refresher(base: refreshKey, session: session, workspace: workspace, refresh: refresh) }
380 .task {
381 loadViews()
382 // The now line moves each minute; a new day refreshes the statuses.
383 while !Task.isCancelled {
384 let next = Calendar.current.nextDate(after: Date(), matching: DateComponents(second: 0), matchingPolicy: .nextTime) ?? Date().addingTimeInterval(60)
385 try? await Task.sleep(for: .seconds(next.timeIntervalSinceNow))
386 now = Date()
387 if Days.absolute(now, calendar: .current) != agenda.today { tick += 1 }
388 }
389 }
390 }
391
392 // MARK: - Days
393
394 private var todayColor: Color { theme.color("agenda-today") ?? .accentColor }
395
396 @ViewBuilder
397 private func dayRows(_ group: AgendaDayGroup, prefix: String = "") -> some View {
398 if group.isToday, !group.overdue.isEmpty {
399 overdueHeader(count: group.overdue.count)
400 if overdueShown {
401 ForEach(Array(group.overdue.enumerated()), id: \.element.id) { index, row in
402 rowView(Line(id: "\(prefix)\(group.day):o\(index)", row: row, day: group.day))
403 }
404 Divider().padding(.leading, 16).padding(.vertical, 4)
405 }
406 }
407 if group.isEmpty {
408 Text("Nothing scheduled")
409 .font(.callout)
410 .foregroundStyle(.secondary)
411 .padding(.horizontal, 16)
412 .padding(.vertical, 10)
413 }
414 ForEach(Array(group.lines(now: Self.hhmm(now)).enumerated()), id: \.offset) { _, line in
415 switch line {
416 case .row(let index): rowView(Line(id: "\(prefix)\(group.day):\(index)", row: group.rows[index], day: group.day))
417 case .grid(let time): gridLine(time)
418 case .now: nowLine
419 }
420 }
421 }
422
423 /// An `org-agenda-time-grid` line.
424 private func gridLine(_ time: Int) -> some View {
425 HStack(spacing: 6) {
426 Text(String(format: "%02d:%02d", time / 100, time % 100))
427 .font(.system(size: 10).monospacedDigit())
428 .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
429 GridRule().stroke(style: StrokeStyle(lineWidth: 0.5, dash: [2, 3])).frame(height: 1)
430 }
431 .foregroundStyle(.tertiary)
432 .padding(.horizontal, 16)
433 .frame(height: 10)
434 .accessibilityHidden(true)
435 }
436
437 private func header(@ViewBuilder _ content: () -> some View) -> some View {
438 HStack(spacing: 6) { content() }
439 .padding(.horizontal, 16)
440 .frame(height: 30)
441 .frame(maxWidth: .infinity, alignment: .leading)
442 .background(theme.color("agenda-background") ?? Color(nsColor: .textBackgroundColor))
443 .overlay(alignment: .bottom) { Divider() }
444 }
445
446 private func dayHeader(_ group: AgendaDayGroup) -> some View {
447 let past = group.day < agenda.today
448 let color = group.isToday ? todayColor : past ? Color.secondary : theme.color("agenda-date") ?? .primary
449 return header {
450 if let relative = group.relativeName(today: agenda.today) {
451 Text(relative)
452 .font(.system(size: 13, weight: .bold))
453 .foregroundStyle(color)
454 Text("·").foregroundStyle(.tertiary)
455 }
456 Text(Self.format(group.day, Days.date(group.day).year == Days.date(agenda.today).year ? "EEEE d MMMM" : "EEEE d MMMM yyyy"))
457 .font(.system(size: 13, weight: group.isToday ? .bold : .semibold))
458 .foregroundStyle(color)
459 Spacer()
460 Button {
461 capture(on: group.day)
462 } label: {
463 Image(systemName: "plus")
464 .font(.system(size: 12, weight: .semibold))
465 .frame(width: 22, height: 22)
466 .contentShape(Rectangle())
467 }
468 .buttonStyle(.borderless)
469 .foregroundStyle(group.isToday ? todayColor : .secondary)
470 .help("Capture an entry scheduled on this day (k)")
471 }
472 }
473
474 private func overdueHeader(count: Int) -> some View {
475 let color = theme.dynamic(.systemRed) { [theme] in theme.statusColor(.overdue, dark: $0) }
476 return Button {
477 withAnimation(.snappy(duration: 0.2)) { overdueShown.toggle() }
478 if !overdueShown, selection?.contains(":o") == true { selection = nil }
479 } label: {
480 HStack(spacing: 6) {
481 Image(systemName: "chevron.right")
482 .font(.system(size: 10, weight: .bold))
483 .rotationEffect(.degrees(overdueShown ? 90 : 0))
484 Text("Overdue").font(.system(size: 12, weight: .semibold))
485 Text("\(count)")
486 .font(.system(size: 10, weight: .bold).monospacedDigit())
487 .padding(.horizontal, 6)
488 .padding(.vertical, 1)
489 .background(Capsule().fill(color.opacity(0.15)))
490 Spacer()
491 }
492 .foregroundStyle(color)
493 .padding(.horizontal, 16)
494 .padding(.top, 8)
495 .padding(.bottom, 4)
496 .contentShape(Rectangle())
497 }
498 .buttonStyle(.plain)
499 .help(overdueShown ? "Hide entries from earlier days" : "Show entries from earlier days")
500 }
501
502 private var nowLine: some View {
503 HStack(spacing: 6) {
504 Text(now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute()))
505 .font(.system(size: 10, weight: .semibold).monospacedDigit())
506 .frame(width: AgendaRowView.gutterWidth, alignment: .leading)
507 Circle().frame(width: 6, height: 6)
508 Rectangle().frame(height: 1)
509 }
510 .foregroundStyle(todayColor)
511 .padding(.horizontal, 16)
512 .frame(height: 10)
513 .accessibilityLabel("Now")
514 }
515
516 private func rowView(_ line: Line, showsGutter: Bool = true) -> some View {
517 AgendaRowView(
518 row: line.row, day: line.day, showsGutter: showsGutter, selected: selection == line.id, hovered: hovered == line.id,
519 marked: line.row.item.flatMap(EntryRef.init).map(marked.contains) ?? false
520 )
521 .id(line.id)
522 .contentShape(Rectangle())
523 .onHover { inside in
524 if inside { hovered = line.id } else if hovered == line.id { hovered = nil }
525 }
526 .onTapGesture(count: 2) { open(line) }
527 .simultaneousGesture(TapGesture().onEnded {
528 selection = line.id
529 focused = true
530 })
531 .contextMenu { menu(line) }
532 }
533
534 @ViewBuilder
535 private func menu(_ line: Line) -> some View {
536 if let event = line.row.event {
537 Button("Show in Calendar") { openEvent(event) }
538 } else if line.row.item != nil {
539 Button("Open") { selection = line.id; jump(line.id) }
540 Divider()
541 Button("Cycle TODO State") { selection = line.id; run(TodoCycle()) }
542 Button("Set Priority…") { selection = line.id; run(SetPriority()) }
543 Button("Set Tags…") { selection = line.id; run(SetTags()) }
544 Button("Schedule…") { selection = line.id; run(SetPlanning(deadline: false)) }
545 Button("Set Deadline…") { selection = line.id; run(SetPlanning(deadline: true)) }
546 Divider()
547 Button("Clock In") { selection = line.id; clockIn() }
548 Button(EntryRef(line.row.item!).map(marked.contains) == true ? "Unmark" : "Mark") {
549 selection = line.id
550 mark(!(EntryRef(line.row.item!).map(marked.contains) ?? false))
551 }
552 Button("Archive") { selection = line.id; archive() }
553 }
554 }
555
556 @AppStorage("reminders") var remindersEnabled = true
557
558 // MARK: - Items
559
560 func item(_ id: String) -> AgendaItem? { line(id)?.row.item }
561
562 /// Return and double click: the entry in the main window, or the event in Calendar.
563 func open(_ line: Line) {
564 selection = line.id
565 if let event = line.row.event { openEvent(event) } else { jump(line.id) }
566 }
567
568 /// Calendar shows an event from its identifier (`AgendaEvent.id` adds `@` and the start).
569 private func openEvent(_ event: AgendaEvent) {
570 let identifier = event.id.split(separator: "@").dropLast().joined(separator: "@")
571 guard !identifier.isEmpty, let encoded = identifier.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
572 let url = URL(string: "ical://ekevent/\(encoded)?method=show&options=more") else { return }
573 NSWorkspace.shared.open(url)
574 }
575
576 /// Moves the selection by `step` lines.
577 func step(_ step: Int) {
578 let all = lines(groups)
579 guard !all.isEmpty else { return }
580 let index = selection.flatMap { id in all.firstIndex { $0.id == id } }
581 let next = index.map { min(max($0 + step, 0), all.count - 1) } ?? (step > 0 ? 0 : all.count - 1)
582 selection = all[next].id
583 }
584}
585
586/// A horizontal line through the middle of its frame.
587struct GridRule: Shape {
588 func path(in rect: CGRect) -> Path {
589 Path { path in
590 path.move(to: CGPoint(x: rect.minX, y: rect.midY))
591 path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
592 }
593 }
594}