373 lines
16 KiB
Swift
373 lines
16 KiB
Swift
import AppKit
|
|
import HelderCore
|
|
import SwiftUI
|
|
|
|
/// ⌘F: this file | project | files, one query, keyboard-driven.
|
|
struct SearchOverlay: View {
|
|
@State private var model: SearchModel
|
|
/// Paths with a git change get a dot in the files column.
|
|
var changedPaths: Set<String>
|
|
/// Full screen hides the traffic lights, so the query bar reclaims their inset.
|
|
var isFullScreen: Bool
|
|
var onOpen: (SearchModel.Target) -> Void
|
|
var onClose: () -> Void
|
|
|
|
/// Where the pointer was when the keyboard last moved; hover ignores rows that scroll under a parked pointer.
|
|
@State private var parkedPointer: CGPoint?
|
|
@State private var hoveredGroup: String?
|
|
|
|
init(model: SearchModel, changedPaths: Set<String>, isFullScreen: Bool,
|
|
onOpen: @escaping (SearchModel.Target) -> Void, onClose: @escaping () -> Void) {
|
|
_model = State(initialValue: model)
|
|
self.changedPaths = changedPaths
|
|
self.isFullScreen = isFullScreen
|
|
self.onOpen = onOpen
|
|
self.onClose = onClose
|
|
}
|
|
|
|
var body: some View {
|
|
OverlayShell(.fullScreen, onDismiss: onClose) {
|
|
VStack(spacing: 0) {
|
|
queryBar.zIndex(1)
|
|
columns
|
|
footer
|
|
}
|
|
}
|
|
.task { await model.start() }
|
|
}
|
|
|
|
// MARK: Query bar
|
|
|
|
private var queryBar: some View {
|
|
HStack(spacing: 12) {
|
|
Image(systemName: "magnifyingglass").font(.system(size: 13)).foregroundStyle(Palette.text4)
|
|
OverlayCommandField(
|
|
text: Binding(get: { model.query }, set: { model.setQuery($0) }),
|
|
placeholder: "Search this file, the project, and file names…",
|
|
font: Typography.searchQuery.nsFont,
|
|
initialSelection: nil,
|
|
onKey: handle
|
|
)
|
|
.frame(maxWidth: .infinity)
|
|
chips
|
|
Text(model.summary)
|
|
.typeRole(Typography.meta)
|
|
.foregroundStyle(Palette.text4)
|
|
.lineLimit(1)
|
|
.fixedSize()
|
|
.padding(.leading, 12)
|
|
.hairline(.leading)
|
|
}
|
|
.padding(.leading, isFullScreen ? 18 : Metrics.trafficLightInset)
|
|
.padding(.trailing, 18)
|
|
.frame(height: Metrics.searchQueryBar)
|
|
.hairline(.bottom)
|
|
}
|
|
|
|
private var chips: some View {
|
|
HStack(spacing: 4) {
|
|
ForEach(model.chips, id: \.ext) { chip in
|
|
let on = model.extensionFilter == nil || model.extensionFilter == chip.ext
|
|
Button { model.toggleExtension(chip.ext) } label: {
|
|
Text(chip.ext)
|
|
.font(TypeRole(.monoSemiBold, 10).font)
|
|
.foregroundStyle(on ? Palette.ink : Palette.text3)
|
|
.padding(.horizontal, 6)
|
|
.padding(.vertical, 4)
|
|
.background(on ? Palette.amber : Color.clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
|
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall)
|
|
.strokeBorder(on ? Palette.amber : Palette.raised, lineWidth: Metrics.hairline))
|
|
}
|
|
.buttonStyle(.plain)
|
|
.pointerHand()
|
|
.tip(SearchModel.chipTooltip(count: chip.count, isChosen: model.extensionFilter == chip.ext))
|
|
}
|
|
}
|
|
.fixedSize()
|
|
}
|
|
|
|
// MARK: Columns
|
|
|
|
private var columns: some View {
|
|
GeometryReader { proxy in
|
|
let widths = SearchModel.widths(total: proxy.size.width, columns: model.columns)
|
|
HStack(spacing: 0) {
|
|
if model.columns.contains(.thisFile) {
|
|
thisFileColumn.frame(width: widths[.thisFile])
|
|
divider
|
|
}
|
|
projectColumn.frame(width: max(0, (widths[.project] ?? 0) - dividerCount * Metrics.hairline))
|
|
divider
|
|
filesColumn.frame(width: widths[.files])
|
|
}
|
|
}
|
|
}
|
|
|
|
private var dividerCount: CGFloat { CGFloat(model.columns.count - 1) }
|
|
|
|
private var divider: some View {
|
|
Hairline(.vertical)
|
|
}
|
|
|
|
private func columnHeader(_ column: SearchModel.Column, title: String, count: Int?, badgePath: String? = nil) -> some View {
|
|
let focused = model.column == column
|
|
return HStack(spacing: 10) {
|
|
if let badgePath { TypeBadge(path: badgePath) }
|
|
Text(title)
|
|
.typeRole(Typography.panelLabel)
|
|
.foregroundStyle(focused ? Palette.amber : Palette.text4)
|
|
.lineLimit(1)
|
|
.truncationMode(.middle)
|
|
if let count {
|
|
Text("\(count)")
|
|
.font(TypeRole(.monoSemiBold, 10).font)
|
|
.foregroundStyle(focused ? Palette.ink : Palette.text4)
|
|
.padding(.horizontal, focused ? 6 : 0)
|
|
.padding(.vertical, focused ? 3 : 0)
|
|
.background(focused ? Palette.amber : Color.clear, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
|
}
|
|
Spacer(minLength: 0)
|
|
}
|
|
.padding(.horizontal, column == .project ? 16 : 14)
|
|
.padding(.top, 12)
|
|
.padding(.bottom, 10)
|
|
.background(Palette.panel)
|
|
}
|
|
|
|
private func empty(_ text: String) -> some View {
|
|
Text(text)
|
|
.typeRole(Typography.tooltip)
|
|
.foregroundStyle(Palette.text4)
|
|
.padding(.horizontal, 14)
|
|
.frame(maxWidth: .infinity, alignment: .leading)
|
|
}
|
|
|
|
private var thisFileColumn: some View {
|
|
let hits = model.inFileHits
|
|
let path = model.activePath ?? ""
|
|
return VStack(spacing: 0) {
|
|
columnHeader(.thisFile, title: PathUtils.basename(path), count: hits.isEmpty ? nil : hits.count, badgePath: path)
|
|
ScrollViewReader { proxy in
|
|
ScrollView {
|
|
LazyVStack(alignment: .leading, spacing: 0) {
|
|
if let message = model.emptyMessage(for: .thisFile) { empty(message) }
|
|
ForEach(Array(hits.enumerated()), id: \.offset) { index, hit in
|
|
let selected = model.column == .thisFile && model.inFileSelection == index
|
|
hitLine(hit, selected: selected)
|
|
.id(index)
|
|
.onHover { inside in if inside { hover(.thisFile, row: index) } }
|
|
.pointerHand()
|
|
.onTapGesture { open(SearchModel.Target(path: path, line: hit.line)) }
|
|
}
|
|
}
|
|
}
|
|
.onChange(of: model.inFileSelection) { _, row in proxy.scrollTo(row) }
|
|
}
|
|
}
|
|
}
|
|
|
|
private var projectColumn: some View {
|
|
let groups = model.groups
|
|
return VStack(spacing: 0) {
|
|
columnHeader(.project, title: "Project", count: model.totalHits > 0 ? model.totalHits : nil)
|
|
ScrollViewReader { proxy in
|
|
ScrollView {
|
|
LazyVStack(alignment: .leading, spacing: 0) {
|
|
if let message = model.emptyMessage(for: .project) { empty(message) }
|
|
ForEach(groups) { group in
|
|
groupHeader(group)
|
|
ForEach(group.rows) { row in
|
|
let selected = model.column == .project && model.projectSelection == row.index
|
|
hitLine(row.hit, selected: selected)
|
|
.onHover { inside in if inside { hover(.project, row: row.index) } }
|
|
.pointerHand()
|
|
.onTapGesture { open(SearchModel.Target(path: row.path, line: row.hit.line)) }
|
|
}
|
|
}
|
|
}
|
|
.padding(.bottom, 12)
|
|
}
|
|
// Scrolls by the ForEach id: an extra `.id` on a row makes the LazyVStack keep stale rows.
|
|
.onChange(of: model.projectSelection) { _, row in
|
|
if model.hitRows.indices.contains(row) { proxy.scrollTo(model.hitRows[row].id) }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func groupHeader(_ group: SearchModel.Group) -> some View {
|
|
HStack(spacing: 8) {
|
|
TypeBadge(path: group.path)
|
|
Text(group.path)
|
|
.typeRole(Typography.path)
|
|
.foregroundStyle(Palette.text3)
|
|
.lineLimit(1)
|
|
.truncationMode(.middle)
|
|
Spacer(minLength: 8)
|
|
Text("\(group.hitCount)").typeRole(Typography.path).foregroundStyle(Palette.text4)
|
|
}
|
|
.padding(EdgeInsets(top: 14, leading: 16, bottom: 6, trailing: 16))
|
|
.contentShape(Rectangle())
|
|
.selectableRow(isSelected: false, isHovered: hoveredGroup == group.path)
|
|
.onHover { inside in
|
|
if inside { hoveredGroup = group.path } else if hoveredGroup == group.path { hoveredGroup = nil }
|
|
}
|
|
.pointerHand()
|
|
.onTapGesture {
|
|
if let first = group.rows.first { open(SearchModel.Target(path: group.path, line: first.hit.line)) }
|
|
}
|
|
}
|
|
|
|
private func hitLine(_ hit: ContentHit, selected: Bool) -> some View {
|
|
HStack(spacing: 0) {
|
|
Text("\(hit.line)")
|
|
.typeRole(Typography.searchHit)
|
|
.foregroundStyle(selected ? Palette.amber : Palette.text5)
|
|
.frame(width: Metrics.searchHitGutter - 14, alignment: .trailing)
|
|
.padding(.trailing, 14)
|
|
Text(SearchHighlight.line(hit, length: (model.term as NSString).length, selected: selected))
|
|
.typeRole(Typography.searchHit)
|
|
.lineLimit(1)
|
|
.truncationMode(.tail)
|
|
.padding(.trailing, 14)
|
|
Spacer(minLength: 0)
|
|
}
|
|
.frame(height: Metrics.searchHitLine)
|
|
.contentShape(Rectangle())
|
|
.selectableRow(isSelected: selected)
|
|
}
|
|
|
|
private var filesColumn: some View {
|
|
let matches = model.shownFileMatches
|
|
return VStack(spacing: 0) {
|
|
columnHeader(.files, title: "Files", count: model.fileMatches.count)
|
|
ScrollViewReader { proxy in
|
|
ScrollView {
|
|
LazyVStack(alignment: .leading, spacing: 0) {
|
|
if let message = model.emptyMessage(for: .files) { empty(message) }
|
|
ForEach(Array(matches.enumerated()), id: \.element.path) { index, match in
|
|
let selected = model.column == .files && model.fileSelection == index
|
|
fileRow(match, selected: selected)
|
|
.onHover { inside in if inside { hover(.files, row: index) } }
|
|
.pointerHand()
|
|
.onTapGesture { open(SearchModel.Target(path: match.path, line: nil)) }
|
|
}
|
|
}
|
|
}
|
|
.onChange(of: model.fileSelection) { _, row in
|
|
if matches.indices.contains(row) { proxy.scrollTo(matches[row].path) }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func fileRow(_ match: FileNameMatch, selected: Bool) -> some View {
|
|
let directory = PathUtils.dirname(match.path)
|
|
return HStack(spacing: 8) {
|
|
TypeBadge(path: match.path)
|
|
VStack(alignment: .leading, spacing: 1) {
|
|
Text(SearchHighlight.name(PathUtils.basename(match.path), indices: match.nameIndices, selected: selected))
|
|
.typeRole(selected ? Typography.rowSelected : Typography.rowSmall)
|
|
.lineLimit(1)
|
|
if !directory.isEmpty {
|
|
Text(directory + "/").typeRole(Typography.meta).foregroundStyle(Palette.text4).lineLimit(1).truncationMode(.head)
|
|
}
|
|
}
|
|
Spacer(minLength: 0)
|
|
if changedPaths.contains(match.path) {
|
|
Text("•").typeRole(Typography.statusLetter).foregroundStyle(Palette.changedDot)
|
|
}
|
|
}
|
|
.padding(.horizontal, 14)
|
|
.padding(.vertical, 4)
|
|
.frame(minHeight: 26)
|
|
.contentShape(Rectangle())
|
|
.selectableRow(isSelected: selected)
|
|
}
|
|
|
|
// MARK: Footer
|
|
|
|
private var footer: some View {
|
|
OverlayFooter(Self.footerHints) { EscChip() }
|
|
}
|
|
|
|
/// "⌘← / ⌘→ column ⌘↑ / ⌘↓ row ↵ open": amber keys, grey slashes and words.
|
|
private static let footerHints: Text = {
|
|
let hints: [(keys: [String], action: String)] = [(["⌘←", "⌘→"], "column"), (["⌘↑", "⌘↓"], "row"), (["↵"], "open")]
|
|
return hints.enumerated().reduce(Text("")) { text, item in
|
|
let (index, hint) = item
|
|
let keys = hint.keys.enumerated().reduce(Text("")) { keys, key in
|
|
keys + (key.offset == 0 ? Text("") : Text(" / ").foregroundColor(Palette.text4))
|
|
+ Text(key.element).foregroundColor(Palette.amber)
|
|
}
|
|
return text + Text(index == 0 ? "" : " ") + keys + Text(" " + hint.action).foregroundColor(Palette.text4)
|
|
}
|
|
}()
|
|
|
|
// MARK: Actions
|
|
|
|
private func handle(_ key: OverlayKey) -> Bool {
|
|
switch key {
|
|
case .commandLeft: model.moveColumn(by: -1)
|
|
case .commandRight: model.moveColumn(by: 1)
|
|
case .up, .commandUp: park(); model.moveRow(by: -1)
|
|
case .down, .commandDown: park(); model.moveRow(by: 1)
|
|
case .enter: if let target = model.target() { open(target) }
|
|
case .escape: onClose()
|
|
case .commandP, .commandEnter: return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
private func park() {
|
|
parkedPointer = NSEvent.mouseLocation
|
|
}
|
|
|
|
private func hover(_ column: SearchModel.Column, row: Int) {
|
|
if let parked = parkedPointer, parked == NSEvent.mouseLocation { return }
|
|
parkedPointer = nil
|
|
model.select(column, row: row)
|
|
}
|
|
|
|
private func open(_ target: SearchModel.Target) {
|
|
onClose()
|
|
onOpen(target)
|
|
}
|
|
}
|
|
|
|
/// The amber runs inside search results.
|
|
enum SearchHighlight {
|
|
/// The match run: amber fill with ink text on the selected row, amber-soft text elsewhere.
|
|
static func line(_ hit: ContentHit, length: Int, selected: Bool) -> AttributedString {
|
|
let text = hit.text as NSString
|
|
let start = min(max(0, hit.matchOffset), text.length)
|
|
let end = min(start + max(0, length), text.length)
|
|
var before = AttributedString(text.substring(to: start))
|
|
var match = AttributedString(text.substring(with: NSRange(location: start, length: end - start)))
|
|
var after = AttributedString(text.substring(from: end))
|
|
let plain = selected ? Palette.text2 : Palette.text3
|
|
before.foregroundColor = plain
|
|
after.foregroundColor = plain
|
|
match.foregroundColor = selected ? Palette.ink : Palette.amberSoft
|
|
if selected { match.backgroundColor = Palette.amber }
|
|
return before + match + after
|
|
}
|
|
|
|
/// Fuzzy-matched letters of a file name in bold amber.
|
|
static func name(_ name: String, indices: [Int]?, selected: Bool) -> AttributedString {
|
|
let marked = Set(indices ?? [])
|
|
var result = AttributedString()
|
|
for (offset, character) in name.enumerated() {
|
|
var piece = AttributedString(String(character))
|
|
if marked.contains(offset) {
|
|
piece.foregroundColor = Palette.amber
|
|
piece.font = TypeRole(.sansMedium, 12).font.bold()
|
|
} else {
|
|
piece.foregroundColor = selected ? Palette.text1 : Palette.text3
|
|
}
|
|
result += piece
|
|
}
|
|
return result
|
|
}
|
|
}
|