import SwiftUI import BucksleyKit import BucksleyUI /// Which list the Transactions screen shows. enum TransactionsMode: Hashable { case all, review, suggestions } extension TransactionsFilter { var mode: TransactionsMode { get { suggestedOnly ? .suggestions : unreviewedOnly ? .review : .all } set { unreviewedOnly = newValue == .review; suggestedOnly = newValue == .suggestions } } /// True when search, category, account or tag narrows the list. var isNarrowed: Bool { !text.isEmpty || categoryID != nil || accountID != nil || tag != nil } func clearNarrowing() { text = ""; categoryID = nil; accountID = nil; tag = nil } func clearAll() { clearNarrowing(); mode = .all } } extension Account { /// A name short enough for a pill: the nickname, or the bank's name cut down to its first part /// plus the last four digits ("CORP Account ••2779"). var shortName: String { let limit = 24 if let nickname, !nickname.isEmpty { return Self.clipped(nickname, to: limit + 4) } let digits = name.split(whereSeparator: { !$0.isNumber }).last { $0.count >= 3 }.map { String($0.suffix(4)) } var base = name while let range = base.range(of: #"[\s\-–#(*•.x]*\d{3,}\)?\s*$"#, options: .regularExpression) { base.removeSubrange(range) } base = base.trimmingCharacters(in: .whitespaces) if base.count > limit, let first = base.components(separatedBy: " - ").first, first.count >= 3 { base = first } if base.isEmpty { base = institution } base = Self.clipped(base, to: limit) return digits.map { "\(base) ••\($0)" } ?? base } private static func clipped(_ text: String, to limit: Int) -> String { text.count <= limit ? text : text.prefix(limit - 1).trimmingCharacters(in: .whitespaces) + "…" } } /// Search, the view mode, and the category, account and tag filters above the transaction list. struct TransactionFilterBar: View { @Environment(\.palette) private var palette @Bindable var filter: TransactionsFilter let ledger: Ledger let hasSuggestions: Bool let export: () -> Void var body: some View { VStack(alignment: .leading, spacing: 8) { ViewThatFits(in: .horizontal) { HStack(spacing: 8) { search.frame(minWidth: 170, maxWidth: 280); modePicker; Spacer(minLength: 8); exportButton(titled: true) } VStack(alignment: .leading, spacing: 8) { search ViewThatFits(in: .horizontal) { HStack(spacing: 8) { modePicker; Spacer(minLength: 8); exportButton(titled: true) } HStack(spacing: 8) { modePicker; Spacer(minLength: 8); exportButton(titled: false) } VStack(alignment: .leading, spacing: 8) { modePicker; exportButton(titled: true) } } } } FlowLayout(spacing: 6) { FilterPill(symbol: "square.grid.2x2", title: "Category", allTitle: "All categories", options: ledger.workspace.categories.map { FilterOption(id: $0.id, title: $0.name, emoji: $0.icon) }, selection: $filter.categoryID) FilterPill(symbol: "building.columns", title: "Account", allTitle: "All accounts", options: ledger.workspace.accounts.map { account in FilterOption(id: account.id, title: account.shortName, pillTitle: account.shortName, detail: account.displayName == account.shortName ? account.institution : account.displayName, tint: palette.color(for: account)) }, selection: $filter.accountID) if !ledger.allTags.isEmpty || filter.tag != nil { FilterPill(symbol: "number", title: "Tag", allTitle: "All tags", options: ledger.allTags.map { FilterOption(id: $0, title: "#" + $0) }, selection: $filter.tag) } if filter.isNarrowed { Button { filter.clearNarrowing() } label: { Text("Clear all").font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.muted) .padding(.horizontal, 8).padding(.vertical, 6).contentShape(Capsule()) } .buttonStyle(.plain).help("Remove the search, category, account and tag filters") } } } .padding(.bottom, 10) #if DEBUG // Screenshot fixture: BUCKSLEY_FIXTURE_FILTER=1 shows the bar with an account and category picked. .onAppear { if ProcessInfo.processInfo.environment["BUCKSLEY_FIXTURE_FILTER"] != nil, filter.accountID == nil, let entry = ledger.entries.first { filter.accountID = entry.accountID; filter.categoryID = entry.categoryID } } #endif } private var search: some View { HStack(spacing: 6) { Image(systemName: "magnifyingglass").foregroundStyle(palette.muted) TextField("Search", text: $filter.text).textFieldStyle(.plain) if !filter.text.isEmpty { Button { filter.text = "" } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(palette.muted) } .buttonStyle(.plain).help("Clear search") } } .font(.system(size: 12)) .padding(.horizontal, 10).padding(.vertical, 6) .background(palette.card, in: Capsule()) .overlay { Capsule().strokeBorder(filter.text.isEmpty ? palette.line : palette.accent) } } private var modePicker: some View { var options: [(TransactionsMode, String)] = [(.all, "All"), (.review, "To review")] if hasSuggestions || filter.suggestedOnly { options.append((.suggestions, "Suggestions")) } return PillPicker(options, selection: $filter.mode) .fixedSize() .overlay { Capsule().strokeBorder(palette.line) } .help("To review puts charges worth a look first, then ones without a category, then the biggest. Suggestions shows the categories Bucksley would pick.") } private func exportButton(titled: Bool) -> some View { Button(action: export) { if titled { Label("Export CSV", systemImage: "square.and.arrow.up").lineLimit(1).fixedSize() } else { Image(systemName: "square.and.arrow.up").accessibilityLabel("Export CSV") } } .buttonStyle(SecondaryButtonStyle()).help("Save every transaction as a CSV file") } } struct FilterOption: Identifiable { let id: String let title: String /// What the pill shows when this option is picked; the title when nil. var pillTitle: String? var detail: String? var emoji: String? var tint: Color? } /// One filter as a pill. Idle it is an outlined button that opens a searchable list; with a value /// picked it fills with the accent color, shows the value, and gets its own clear button. struct FilterPill: View { @Environment(\.palette) private var palette let symbol: String let title: String let allTitle: String let options: [FilterOption] @Binding var selection: String? @State private var open = false var body: some View { let picked = selection.map { id in options.first { $0.id == id } ?? FilterOption(id: id, title: id) } let fill = palette.theme == .almanac ? palette.text : palette.accent let ink = palette.theme == .almanac ? palette.canvas : palette.accentText HStack(spacing: 0) { Button { open = true } label: { HStack(spacing: 5) { Image(systemName: symbol).font(.system(size: 10.5, weight: .semibold)) Text(picked.map { $0.pillTitle ?? $0.title } ?? title).lineLimit(1).fixedSize() if picked == nil { Image(systemName: "chevron.down").font(.system(size: 8, weight: .bold)).opacity(0.7) } } .padding(.leading, 11).padding(.trailing, picked == nil ? 11 : 6).padding(.vertical, 6) .contentShape(Rectangle()) } .buttonStyle(.plain) .help(picked.map { "\(title): \($0.detail ?? $0.title). Click to change." } ?? "Filter by \(title.lowercased())") if picked != nil { Button { selection = nil } label: { Image(systemName: "xmark").font(.system(size: 8.5, weight: .bold)) .frame(width: 16, height: 16).background(ink.opacity(0.18), in: Circle()) .padding(.trailing, 6).padding(.vertical, 4).contentShape(Rectangle()) } .buttonStyle(.plain).help("Clear the \(title.lowercased()) filter") .accessibilityLabel("Clear the \(title.lowercased()) filter") } } .font(.system(size: 12, weight: picked == nil ? .regular : .semibold)) .foregroundStyle(picked == nil ? palette.text : ink) .background(picked == nil ? palette.card : fill, in: Capsule()) .overlay { Capsule().strokeBorder(picked == nil ? palette.line : Color.clear) } .popover(isPresented: $open, arrowEdge: .bottom) { FilterOptionList(allTitle: allTitle, options: options, selection: $selection, open: $open) .environment(\.palette, palette) } } } /// The list a filter pill opens: every option as a full-width row, with a search box once the list is long. struct FilterOptionList: View { @Environment(\.palette) private var palette /// The "All …" row on top; nil for a plain choice with no "all". let allTitle: String? let options: [FilterOption] @Binding var selection: String? @Binding var open: Bool @State private var query = "" @FocusState private var searching: Bool var body: some View { let shown = query.isEmpty ? options : options.filter { ($0.title + " " + ($0.detail ?? "")).localizedCaseInsensitiveContains(query) } let rowHeight: CGFloat = options.contains { $0.detail != nil } ? 42 : 30 VStack(alignment: .leading, spacing: 6) { if options.count > 8 { HStack(spacing: 6) { Image(systemName: "magnifyingglass").foregroundStyle(palette.muted) TextField("Find", text: $query).textFieldStyle(.plain).focused($searching) .onSubmit { if let first = shown.first { pick(first.id) } } } .font(.system(size: 12)) .padding(.horizontal, 10).padding(.vertical, 6) .background(palette.card, in: Capsule()) .overlay { Capsule().strokeBorder(palette.line) } } ScrollView { VStack(alignment: .leading, spacing: 1) { if query.isEmpty, let allTitle { FilterOptionRow(option: FilterOption(id: "", title: allTitle), on: selection == nil) { pick(nil) } } ForEach(shown) { option in FilterOptionRow(option: option, on: selection == option.id) { pick(option.id) } } if shown.isEmpty { Text("Nothing matches.").font(.system(size: 12)).foregroundStyle(palette.muted).padding(8) } } } .frame(height: min(CGFloat(options.count) * (rowHeight + 1) + (allTitle == nil ? 0 : 31), 330)) } .padding(10) .frame(width: 300) .foregroundStyle(palette.text) .background(palette.canvas) .onAppear { searching = options.count > 8 } } private func pick(_ id: String?) { selection = id; open = false } } private struct FilterOptionRow: View { @Environment(\.palette) private var palette let option: FilterOption let on: Bool let action: () -> Void @State private var hovering = false var body: some View { Button(action: action) { HStack(spacing: 8) { if let emoji = option.emoji { Text(emoji).font(.system(size: 12)).frame(width: 18) } if let tint = option.tint { Circle().fill(tint).frame(width: 7, height: 7).frame(width: 18) } VStack(alignment: .leading, spacing: 1) { Text(option.title).font(.system(size: 12.5, weight: on ? .semibold : .regular)).lineLimit(1) if let detail = option.detail { Text(detail).font(.system(size: 10.5)).foregroundStyle(palette.muted).lineLimit(1).truncationMode(.middle) } } Spacer(minLength: 6) if on { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.accent) } } .padding(.horizontal, 8).padding(.vertical, 6) .frame(maxWidth: .infinity, alignment: .leading) .background(on ? palette.accent.opacity(0.12) : hovering ? palette.text.opacity(palette.dark ? 0.07 : 0.05) : .clear, in: RoundedRectangle(cornerRadius: 7, style: .continuous)) .contentShape(Rectangle()) } .buttonStyle(.plain) .onHover { hovering = $0 } .help(option.detail ?? option.title) .accessibilityAddTraits(on ? .isSelected : []) } } /// Lays pills out left to right and wraps to a new line when the row is full, so none get squeezed. struct FlowLayout: Layout { var spacing: CGFloat = 6 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { let rows = arrange(subviews, width: proposal.width ?? .infinity) return CGSize(width: rows.map(\.width).max() ?? 0, height: rows.last.map { $0.y + $0.height } ?? 0) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { for row in arrange(subviews, width: bounds.width) { var x = bounds.minX for index in row.items { let size = subviews[index].sizeThatFits(.unspecified) subviews[index].place(at: CGPoint(x: x, y: bounds.minY + row.y + (row.height - size.height) / 2), proposal: ProposedViewSize(size)) x += size.width + spacing } } } private struct Row { var items: [Int] = []; var width: CGFloat = 0; var height: CGFloat = 0; var y: CGFloat = 0 } private func arrange(_ subviews: Subviews, width: CGFloat) -> [Row] { var rows = [Row()] for index in subviews.indices { let size = subviews[index].sizeThatFits(.unspecified) var row = rows[rows.count - 1] if !row.items.isEmpty, row.width + spacing + size.width > width { rows.append(Row(y: row.y + row.height + spacing)) row = rows[rows.count - 1] } row.width += (row.items.isEmpty ? 0 : spacing) + size.width row.height = max(row.height, size.height) row.items.append(index) rows[rows.count - 1] = row } return rows } } /// A styled replacement for a system pop-up button: a quiet capsule showing the current choice that opens /// the same list as the filter pills. Use PillPicker instead when there are only a few short choices. struct ChoiceButton: View { @Environment(\.palette) private var palette let options: [(value: Value, title: String, emoji: String?)] @Binding var selection: Value @State private var open = false @State private var hovering = false init(_ options: [(value: Value, title: String, emoji: String?)], selection: Binding) { self.options = options; _selection = selection } var body: some View { let current = options.first { $0.value == selection } Button { open = true } label: { HStack(spacing: 6) { if let emoji = current?.emoji { Text(emoji).font(.system(size: 12)) } Text(current?.title ?? "Choose").lineLimit(1) Spacer(minLength: 4) Image(systemName: "chevron.up.chevron.down").font(.system(size: 8.5, weight: .bold)).foregroundStyle(palette.muted) } .font(.system(size: 12.5)) .foregroundStyle(palette.text) .padding(.horizontal, 11).padding(.vertical, 6) .background(hovering ? palette.text.opacity(palette.dark ? 0.1 : 0.06) : palette.card, in: Capsule()) .overlay { Capsule().strokeBorder(palette.line) } .contentShape(Capsule()) } .buttonStyle(.plain) .onHover { hovering = $0 } .popover(isPresented: $open, arrowEdge: .bottom) { FilterOptionList(allTitle: nil, options: options.indices.map { FilterOption(id: String($0), title: options[$0].title, emoji: options[$0].emoji) }, selection: Binding(get: { options.firstIndex { $0.value == selection }.map(String.init) }, set: { if let index = $0.flatMap(Int.init), options.indices.contains(index) { selection = options[index].value } }), open: $open) .environment(\.palette, palette) } } } extension Workspace { /// Categories for a ChoiceButton, grouped in the order the person keeps their groups. func categoryChoices(_ keep: (BucksleyKit.Category) -> Bool = { _ in true }) -> [(value: String, title: String, emoji: String?)] { groups.flatMap { g in categories.filter { $0.groupID == g.id && keep($0) }.map { (value: $0.id, title: $0.name, emoji: Optional($0.icon)) } } + categories.filter { c in keep(c) && !groups.contains { $0.id == c.groupID } }.map { (value: $0.id, title: $0.name, emoji: Optional($0.icon)) } } }