Branchwell

Bucksley / app / Apps / Mac / TransactionFilterBar.swift

1import SwiftUI
2import BucksleyKit
3import BucksleyUI
4
5/// Which list the Transactions screen shows.
6enum TransactionsMode: Hashable { case all, review, suggestions }
7
8extension TransactionsFilter {
9 var mode: TransactionsMode {
10 get { suggestedOnly ? .suggestions : unreviewedOnly ? .review : .all }
11 set { unreviewedOnly = newValue == .review; suggestedOnly = newValue == .suggestions }
12 }
13
14 /// True when search, category, account or tag narrows the list.
15 var isNarrowed: Bool { !text.isEmpty || categoryID != nil || accountID != nil || tag != nil }
16
17 func clearNarrowing() { text = ""; categoryID = nil; accountID = nil; tag = nil }
18 func clearAll() { clearNarrowing(); mode = .all }
19}
20
21extension Account {
22 /// A name short enough for a pill: the nickname, or the bank's name cut down to its first part
23 /// plus the last four digits ("CORP Account ••2779").
24 var shortName: String {
25 let limit = 24
26 if let nickname, !nickname.isEmpty { return Self.clipped(nickname, to: limit + 4) }
27 let digits = name.split(whereSeparator: { !$0.isNumber }).last { $0.count >= 3 }.map { String($0.suffix(4)) }
28 var base = name
29 while let range = base.range(of: #"[\s\-–#(*•.x]*\d{3,}\)?\s*$"#, options: .regularExpression) { base.removeSubrange(range) }
30 base = base.trimmingCharacters(in: .whitespaces)
31 if base.count > limit, let first = base.components(separatedBy: " - ").first, first.count >= 3 { base = first }
32 if base.isEmpty { base = institution }
33 base = Self.clipped(base, to: limit)
34 return digits.map { "\(base) ••\($0)" } ?? base
35 }
36
37 private static func clipped(_ text: String, to limit: Int) -> String {
38 text.count <= limit ? text : text.prefix(limit - 1).trimmingCharacters(in: .whitespaces) + "…"
39 }
40}
41
42/// Search, the view mode, and the category, account and tag filters above the transaction list.
43struct TransactionFilterBar: View {
44 @Environment(\.palette) private var palette
45 @Bindable var filter: TransactionsFilter
46 let ledger: Ledger
47 let hasSuggestions: Bool
48 let export: () -> Void
49
50 var body: some View {
51 VStack(alignment: .leading, spacing: 8) {
52 ViewThatFits(in: .horizontal) {
53 HStack(spacing: 8) { search.frame(minWidth: 170, maxWidth: 280); modePicker; Spacer(minLength: 8); exportButton(titled: true) }
54 VStack(alignment: .leading, spacing: 8) {
55 search
56 ViewThatFits(in: .horizontal) {
57 HStack(spacing: 8) { modePicker; Spacer(minLength: 8); exportButton(titled: true) }
58 HStack(spacing: 8) { modePicker; Spacer(minLength: 8); exportButton(titled: false) }
59 VStack(alignment: .leading, spacing: 8) { modePicker; exportButton(titled: true) }
60 }
61 }
62 }
63 FlowLayout(spacing: 6) {
64 FilterPill(symbol: "square.grid.2x2", title: "Category", allTitle: "All categories",
65 options: ledger.workspace.categories.map { FilterOption(id: $0.id, title: $0.name, emoji: $0.icon) },
66 selection: $filter.categoryID)
67 FilterPill(symbol: "building.columns", title: "Account", allTitle: "All accounts",
68 options: ledger.workspace.accounts.map { account in
69 FilterOption(id: account.id, title: account.shortName, pillTitle: account.shortName,
70 detail: account.displayName == account.shortName ? account.institution : account.displayName,
71 tint: palette.color(for: account))
72 },
73 selection: $filter.accountID)
74 if !ledger.allTags.isEmpty || filter.tag != nil {
75 FilterPill(symbol: "number", title: "Tag", allTitle: "All tags",
76 options: ledger.allTags.map { FilterOption(id: $0, title: "#" + $0) },
77 selection: $filter.tag)
78 }
79 if filter.isNarrowed {
80 Button { filter.clearNarrowing() } label: {
81 Text("Clear all").font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.muted)
82 .padding(.horizontal, 8).padding(.vertical, 6).contentShape(Capsule())
83 }
84 .buttonStyle(.plain).help("Remove the search, category, account and tag filters")
85 }
86 }
87 }
88 .padding(.bottom, 10)
89 #if DEBUG
90 // Screenshot fixture: BUCKSLEY_FIXTURE_FILTER=1 shows the bar with an account and category picked.
91 .onAppear {
92 if ProcessInfo.processInfo.environment["BUCKSLEY_FIXTURE_FILTER"] != nil, filter.accountID == nil, let entry = ledger.entries.first {
93 filter.accountID = entry.accountID; filter.categoryID = entry.categoryID
94 }
95 }
96 #endif
97 }
98
99 private var search: some View {
100 HStack(spacing: 6) {
101 Image(systemName: "magnifyingglass").foregroundStyle(palette.muted)
102 TextField("Search", text: $filter.text).textFieldStyle(.plain)
103 if !filter.text.isEmpty {
104 Button { filter.text = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(palette.muted) }
105 .buttonStyle(.plain).help("Clear search")
106 }
107 }
108 .font(.system(size: 12))
109 .padding(.horizontal, 10).padding(.vertical, 6)
110 .background(palette.card, in: Capsule())
111 .overlay { Capsule().strokeBorder(filter.text.isEmpty ? palette.line : palette.accent) }
112 }
113
114 private var modePicker: some View {
115 var options: [(TransactionsMode, String)] = [(.all, "All"), (.review, "To review")]
116 if hasSuggestions || filter.suggestedOnly { options.append((.suggestions, "Suggestions")) }
117 return PillPicker(options, selection: $filter.mode)
118 .fixedSize()
119 .overlay { Capsule().strokeBorder(palette.line) }
120 .help("To review puts charges worth a look first, then ones without a category, then the biggest. Suggestions shows the categories Bucksley would pick.")
121 }
122
123 private func exportButton(titled: Bool) -> some View {
124 Button(action: export) {
125 if titled { Label("Export CSV", systemImage: "square.and.arrow.up").lineLimit(1).fixedSize() }
126 else { Image(systemName: "square.and.arrow.up").accessibilityLabel("Export CSV") }
127 }
128 .buttonStyle(SecondaryButtonStyle()).help("Save every transaction as a CSV file")
129 }
130}
131
132struct FilterOption: Identifiable {
133 let id: String
134 let title: String
135 /// What the pill shows when this option is picked; the title when nil.
136 var pillTitle: String?
137 var detail: String?
138 var emoji: String?
139 var tint: Color?
140}
141
142/// One filter as a pill. Idle it is an outlined button that opens a searchable list; with a value
143/// picked it fills with the accent color, shows the value, and gets its own clear button.
144struct FilterPill: View {
145 @Environment(\.palette) private var palette
146 let symbol: String
147 let title: String
148 let allTitle: String
149 let options: [FilterOption]
150 @Binding var selection: String?
151 @State private var open = false
152
153 var body: some View {
154 let picked = selection.map { id in options.first { $0.id == id } ?? FilterOption(id: id, title: id) }
155 let fill = palette.theme == .almanac ? palette.text : palette.accent
156 let ink = palette.theme == .almanac ? palette.canvas : palette.accentText
157 HStack(spacing: 0) {
158 Button { open = true } label: {
159 HStack(spacing: 5) {
160 Image(systemName: symbol).font(.system(size: 10.5, weight: .semibold))
161 Text(picked.map { $0.pillTitle ?? $0.title } ?? title).lineLimit(1).fixedSize()
162 if picked == nil { Image(systemName: "chevron.down").font(.system(size: 8, weight: .bold)).opacity(0.7) }
163 }
164 .padding(.leading, 11).padding(.trailing, picked == nil ? 11 : 6).padding(.vertical, 6)
165 .contentShape(Rectangle())
166 }
167 .buttonStyle(.plain)
168 .help(picked.map { "\(title): \($0.detail ?? $0.title). Click to change." } ?? "Filter by \(title.lowercased())")
169 if picked != nil {
170 Button { selection = nil } label: {
171 Image(systemName: "xmark").font(.system(size: 8.5, weight: .bold))
172 .frame(width: 16, height: 16).background(ink.opacity(0.18), in: Circle())
173 .padding(.trailing, 6).padding(.vertical, 4).contentShape(Rectangle())
174 }
175 .buttonStyle(.plain).help("Clear the \(title.lowercased()) filter")
176 .accessibilityLabel("Clear the \(title.lowercased()) filter")
177 }
178 }
179 .font(.system(size: 12, weight: picked == nil ? .regular : .semibold))
180 .foregroundStyle(picked == nil ? palette.text : ink)
181 .background(picked == nil ? palette.card : fill, in: Capsule())
182 .overlay { Capsule().strokeBorder(picked == nil ? palette.line : Color.clear) }
183 .popover(isPresented: $open, arrowEdge: .bottom) {
184 FilterOptionList(allTitle: allTitle, options: options, selection: $selection, open: $open)
185 .environment(\.palette, palette)
186 }
187 }
188}
189
190/// The list a filter pill opens: every option as a full-width row, with a search box once the list is long.
191struct FilterOptionList: View {
192 @Environment(\.palette) private var palette
193 /// The "All …" row on top; nil for a plain choice with no "all".
194 let allTitle: String?
195 let options: [FilterOption]
196 @Binding var selection: String?
197 @Binding var open: Bool
198 @State private var query = ""
199 @FocusState private var searching: Bool
200
201 var body: some View {
202 let shown = query.isEmpty ? options : options.filter { ($0.title + " " + ($0.detail ?? "")).localizedCaseInsensitiveContains(query) }
203 let rowHeight: CGFloat = options.contains { $0.detail != nil } ? 42 : 30
204 VStack(alignment: .leading, spacing: 6) {
205 if options.count > 8 {
206 HStack(spacing: 6) {
207 Image(systemName: "magnifyingglass").foregroundStyle(palette.muted)
208 TextField("Find", text: $query).textFieldStyle(.plain).focused($searching)
209 .onSubmit { if let first = shown.first { pick(first.id) } }
210 }
211 .font(.system(size: 12))
212 .padding(.horizontal, 10).padding(.vertical, 6)
213 .background(palette.card, in: Capsule())
214 .overlay { Capsule().strokeBorder(palette.line) }
215 }
216 ScrollView {
217 VStack(alignment: .leading, spacing: 1) {
218 if query.isEmpty, let allTitle { FilterOptionRow(option: FilterOption(id: "", title: allTitle), on: selection == nil) { pick(nil) } }
219 ForEach(shown) { option in
220 FilterOptionRow(option: option, on: selection == option.id) { pick(option.id) }
221 }
222 if shown.isEmpty { Text("Nothing matches.").font(.system(size: 12)).foregroundStyle(palette.muted).padding(8) }
223 }
224 }
225 .frame(height: min(CGFloat(options.count) * (rowHeight + 1) + (allTitle == nil ? 0 : 31), 330))
226 }
227 .padding(10)
228 .frame(width: 300)
229 .foregroundStyle(palette.text)
230 .background(palette.canvas)
231 .onAppear { searching = options.count > 8 }
232 }
233
234 private func pick(_ id: String?) { selection = id; open = false }
235}
236
237private struct FilterOptionRow: View {
238 @Environment(\.palette) private var palette
239 let option: FilterOption
240 let on: Bool
241 let action: () -> Void
242 @State private var hovering = false
243
244 var body: some View {
245 Button(action: action) {
246 HStack(spacing: 8) {
247 if let emoji = option.emoji { Text(emoji).font(.system(size: 12)).frame(width: 18) }
248 if let tint = option.tint { Circle().fill(tint).frame(width: 7, height: 7).frame(width: 18) }
249 VStack(alignment: .leading, spacing: 1) {
250 Text(option.title).font(.system(size: 12.5, weight: on ? .semibold : .regular)).lineLimit(1)
251 if let detail = option.detail {
252 Text(detail).font(.system(size: 10.5)).foregroundStyle(palette.muted).lineLimit(1).truncationMode(.middle)
253 }
254 }
255 Spacer(minLength: 6)
256 if on { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.accent) }
257 }
258 .padding(.horizontal, 8).padding(.vertical, 6)
259 .frame(maxWidth: .infinity, alignment: .leading)
260 .background(on ? palette.accent.opacity(0.12) : hovering ? palette.text.opacity(palette.dark ? 0.07 : 0.05) : .clear,
261 in: RoundedRectangle(cornerRadius: 7, style: .continuous))
262 .contentShape(Rectangle())
263 }
264 .buttonStyle(.plain)
265 .onHover { hovering = $0 }
266 .help(option.detail ?? option.title)
267 .accessibilityAddTraits(on ? .isSelected : [])
268 }
269}
270
271/// Lays pills out left to right and wraps to a new line when the row is full, so none get squeezed.
272struct FlowLayout: Layout {
273 var spacing: CGFloat = 6
274
275 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
276 let rows = arrange(subviews, width: proposal.width ?? .infinity)
277 return CGSize(width: rows.map(\.width).max() ?? 0, height: rows.last.map { $0.y + $0.height } ?? 0)
278 }
279
280 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
281 for row in arrange(subviews, width: bounds.width) {
282 var x = bounds.minX
283 for index in row.items {
284 let size = subviews[index].sizeThatFits(.unspecified)
285 subviews[index].place(at: CGPoint(x: x, y: bounds.minY + row.y + (row.height - size.height) / 2), proposal: ProposedViewSize(size))
286 x += size.width + spacing
287 }
288 }
289 }
290
291 private struct Row { var items: [Int] = []; var width: CGFloat = 0; var height: CGFloat = 0; var y: CGFloat = 0 }
292
293 private func arrange(_ subviews: Subviews, width: CGFloat) -> [Row] {
294 var rows = [Row()]
295 for index in subviews.indices {
296 let size = subviews[index].sizeThatFits(.unspecified)
297 var row = rows[rows.count - 1]
298 if !row.items.isEmpty, row.width + spacing + size.width > width {
299 rows.append(Row(y: row.y + row.height + spacing))
300 row = rows[rows.count - 1]
301 }
302 row.width += (row.items.isEmpty ? 0 : spacing) + size.width
303 row.height = max(row.height, size.height)
304 row.items.append(index)
305 rows[rows.count - 1] = row
306 }
307 return rows
308 }
309}
310
311/// A styled replacement for a system pop-up button: a quiet capsule showing the current choice that opens
312/// the same list as the filter pills. Use PillPicker instead when there are only a few short choices.
313struct ChoiceButton<Value: Hashable>: View {
314 @Environment(\.palette) private var palette
315 let options: [(value: Value, title: String, emoji: String?)]
316 @Binding var selection: Value
317 @State private var open = false
318 @State private var hovering = false
319
320 init(_ options: [(value: Value, title: String, emoji: String?)], selection: Binding<Value>) {
321 self.options = options; _selection = selection
322 }
323
324 var body: some View {
325 let current = options.first { $0.value == selection }
326 Button { open = true } label: {
327 HStack(spacing: 6) {
328 if let emoji = current?.emoji { Text(emoji).font(.system(size: 12)) }
329 Text(current?.title ?? "Choose").lineLimit(1)
330 Spacer(minLength: 4)
331 Image(systemName: "chevron.up.chevron.down").font(.system(size: 8.5, weight: .bold)).foregroundStyle(palette.muted)
332 }
333 .font(.system(size: 12.5))
334 .foregroundStyle(palette.text)
335 .padding(.horizontal, 11).padding(.vertical, 6)
336 .background(hovering ? palette.text.opacity(palette.dark ? 0.1 : 0.06) : palette.card, in: Capsule())
337 .overlay { Capsule().strokeBorder(palette.line) }
338 .contentShape(Capsule())
339 }
340 .buttonStyle(.plain)
341 .onHover { hovering = $0 }
342 .popover(isPresented: $open, arrowEdge: .bottom) {
343 FilterOptionList(allTitle: nil,
344 options: options.indices.map { FilterOption(id: String($0), title: options[$0].title, emoji: options[$0].emoji) },
345 selection: Binding(get: { options.firstIndex { $0.value == selection }.map(String.init) },
346 set: { if let index = $0.flatMap(Int.init), options.indices.contains(index) { selection = options[index].value } }),
347 open: $open)
348 .environment(\.palette, palette)
349 }
350 }
351}
352
353extension Workspace {
354 /// Categories for a ChoiceButton, grouped in the order the person keeps their groups.
355 func categoryChoices(_ keep: (BucksleyKit.Category) -> Bool = { _ in true }) -> [(value: String, title: String, emoji: String?)] {
356 groups.flatMap { g in categories.filter { $0.groupID == g.id && keep($0) }.map { (value: $0.id, title: $0.name, emoji: Optional($0.icon)) } }
357 + categories.filter { c in keep(c) && !groups.contains { $0.id == c.groupID } }.map { (value: $0.id, title: $0.name, emoji: Optional($0.icon)) }
358 }
359}