// Search's ANSWER — the recent searches at rest, the database's grouped reply // once a query bites — as a view two hosts draw (picture 29). // // `SearchScreen` (`/search`, the pushed page) and Home (the search pill along // its foot, design 2026-09-13 §4.4) both show what a search found, and the // rules are the same on both: a PLACE is a swap, a RECORD is a push, a search // is remembered only when it opened something, an empty list means three // different things and only two of them are an answer. So the answer is ONE // view, fed by one `SearchModel`, and the two hosts differ only in where the // field sits. Nothing about ranking or sections lives here; the core and // `searchItems` decide, this draws. // // **Every hit is drawn as its kind's own object, small.** A todo is a cut card // with its ring, a note a torn row, a person a typed card beside the words, a // message a strip, a document a sheet with its page number, a location a // postcard — the objects the tools themselves draw, at a size a list can hold. // The matched words wear a red pencil underline (`UnderlinedLine`), which is // how a hit shows WHERE it matched without being opened. // // ONE list, because the rest state and the typed state are the same scroller // trading sections. `SearchItem` carries a stable id per row. // // **A drag puts the keyboard down** — `.scrollDismissesKeyboard(.immediately)`. import CottonFaces import CottonKit import SwiftUI /// Which of the four things the answer area is showing. A VALUE, so the rule /// "a verdict on somebody's records only after a query actually ran" is a /// function with a test rather than a chain of `if`s inside a `body`. enum SearchArm: Equatable { /// Nothing has been asked yet: a hint, never an empty state. case rest /// The query ran and fell over. case failed /// The query ran and the database holds nothing like it. case noMatch /// There are hits. case results static func of(settled: String, failed: Bool, items: Int) -> SearchArm { if items > 0 { return .results } if settled.isEmpty { return .rest } return failed ? .failed : .noMatch } } /// Search's sentences, in one place so the two hosts and the tests read the /// same words. enum SearchWords { static var scope: String { ShellLines.line("search", "words.scope") } static var restHint: String { ShellLines.line("search", "rest_hint") } static var failed: String { ShellLines.line("search", "words.failed") } static var failedHint: String { ShellLines.line("search", "words.failed_hint") } static var noMatch: String { ShellLines.line("search", "words.no_match") } static var noMatchHint: String { ShellLines.line("search", "words.no_match_hint") } } struct SearchResults: View { private let model: SearchModel /// A record hit — a PUSH. @Environment(Navigator.self) private var navigator /// The held databases and this window's: a hit from another database opens /// once the window shows it (`FeedRowOpening`). @Environment(DatabasesModel.self) private var databases: DatabasesModel? @Environment(DatabaseScene.self) private var scene: DatabaseScene? @Environment(ToastCenter.self) private var toasts: ToastCenter? @Environment(\.theme) private var theme init(model: SearchModel) { self.model = model } var body: some View { content(for: model.items) // The recents, off this device. There is nothing else to load: // search asks the database nothing until it is typed into. .task { model.databases = databases model.load() } } /// A record hit's tap — the ONE way a hit opens. A PUSH, so back belongs /// on the search that found it; a hit from a database opens once this /// window shows that database. private func open(_ hit: FindHit) { guard let route = model.open(hit) else { return } FeedRowOpening(model: databases, scene: scene, toasts: toasts) .open(route, in: hit.database, on: navigator) } // MARK: - The three things an empty list can mean @ViewBuilder private func content(for items: [SearchItem]) -> some View { switch SearchArm.of(settled: model.settled, failed: model.searchFailed, items: items.count) { // An empty list means three different things here, and only two of // them are an answer. At REST — no query, no recents, which is every // first week — it means "you have not asked yet", so the area carries // a HINT and no verdict: telling that person their database holds no // match would be a verdict on a search that never ran, and leaving the // area blank (which is what the Mac walk photographed, finding 15) // tells them nothing at all about what search reaches. The arms are // gated on the SETTLED query, not the raw one, so nothing can flash // between keystrokes while the debounce is out. case .rest: hint(SearchWords.restHint) case .failed: // A search that FAILED is not an empty answer either. The sentence // below is a verdict on the person's records; only a query that // actually ran has earned it. notice(SearchWords.failed, line2: SearchWords.failedHint, identifier: "search-failed") case .noMatch: notice(SearchWords.noMatch, line2: SearchWords.noMatchHint, identifier: "search-empty") case .results: // The hits are a deck (`SearchDeck`); the recents at rest stay // the short list they are. let hits = SearchDeckHit.of(items) if hits.isEmpty { list(items) } else { SearchDeck(hits: hits, query: model.settled) { open($0.hit) } } } } private func notice(_ sentence: String, line2: String?, identifier: String) -> some View { VStack { Spacer(minLength: 0) ObjectEmpty(sheet: .cream, edge: .cut, line1: sentence, line2: line2) Spacer(minLength: 0) } .frame(maxWidth: .infinity, maxHeight: .infinity) .accessibilityIdentifier(identifier) } /// The rest state's one line: what search reaches, said once, under the /// field. Not an `ObjectEmpty` — an empty state is an answer about /// somebody's records, and nothing has been asked yet. /// /// **In the paper's own voice.** It arrived wearing `.cottonType(.caption)` /// — `Typography.swift`'s chrome roles, which are `Font.system(.default)`, /// i.e. San Francisco — and it was the only sentence on the search surface /// in the system sans (the walk's re-shoot, walk-15-v2): the clear verb is /// handwriting, a recent query is typed, and the sibling hints inside /// `ObjectEmpty` are typed at 13 in secondary ink. This is that, said the /// same way. private func hint(_ sentence: String) -> some View { Text(sentence) .paperBody(13, ink: .pencil) .multilineTextAlignment(.center) .cottonContentMargin() .padding(.top, 28) .frame(maxWidth: .infinity, alignment: .top) .accessibilityIdentifier("search-hint") } // MARK: - The one list private func list(_ items: [SearchItem]) -> some View { ScrollView { LazyVStack(alignment: .leading, spacing: 0) { ForEach(Array(items.enumerated()), id: \.element.id) { index, item in row(item, at: index, of: items.count) } } .cottonContentMargin() .padding(.bottom, 24) } .scrollIndicators(.hidden) .scrollDismissesKeyboard(.immediately) .accessibilityIdentifier("search-list") } @ViewBuilder private func row(_ item: SearchItem, at index: Int, of count: Int) -> some View { switch item { case .recentsLabel: // The one heading wearing a verb: the list it names is the one // section here that is ABOUT you rather than in your database, so // the way out is on the sign. HStack(spacing: 10) { PaperSection(title: ShellLines.line("search", "recent.title")) Button(action: model.clearRecents) { Text(ShellLines.line("search", "recent.clear")).paperHand(14) } .buttonStyle(OpacityButtonStyle()) .accessibilityLabel(ShellLines.line("search", "recent.clear_all")) .accessibilityIdentifier("search-recents-clear") } .padding(.bottom, 8) .padding(.top, index == 0 ? 0 : 24) .accessibilityIdentifier("search-recents-label") case .recent(_, let query): Button { model.type(query) } label: { HStack(spacing: 10) { Image(systemName: "clock") .font(.system(size: 13)) .foregroundStyle(theme.print(.pencil)) Text(query) .paperBody(15) .lineLimit(1) Spacer(minLength: 0) } .padding(.vertical, 9) .contentShape(Rectangle()) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("search-recent-\(query)") case .placeChips(_, let chips): SearchChipRail(chips: chips) { chip in // A SWAP, not a push. if let route = model.openPlace(chip) { navigator.replace(with: route) } } .padding(.bottom, 12) case .sectionLabel(_, let section, let words, let count): // Named for the TOOL it searched, not "Results": each section // answers for one kind and says so, so nobody reads its silence as // "you have no notes about this". PaperSection(title: words, count: count > 0 ? "\(count)" : nil) .padding(.bottom, 10) .padding(.top, index == 0 ? 0 : 22) .accessibilityIdentifier("search-section-\(section)") case .hit(_, let hit, let section, let words): SearchHitCard(hit: hit, section: section, words: words, query: model.settled) { open(hit) } .padding(.bottom, 10) case .seeAll(_, let section, let words, let remaining): // Closed, it opens the section; open, it is the section's tail, and // reaching it reads the next page (`search_page` hits). let page = Int(theme.scale[.searchPage]) Button { model.expanded.contains(section) ? model.more(section, page: page) : model.expand(section, page: page) } label: { Text(ShellLines.line("search", "section.more", ["n": String(remaining)])) .paperHand(16) .padding(.vertical, 4) .padding(.leading, 6) .contentShape(Rectangle()) } .buttonStyle(OpacityButtonStyle()) .accessibilityLabel(ShellLines.line("search", "section.see_all", ["section": words])) .accessibilityIdentifier("search-see-all-\(section)") .onAppear { model.more(section, page: page) } } } } // MARK: - The places rail /// The tools whose names matched, as one wrapping rail of small cut papers. struct SearchChipRail: View { let chips: [SearchPlaceChip] let onPick: (SearchPlaceChip) -> Void @Environment(\.theme) private var theme public var body: some View { // A ragged wrap with an 8pt gap. `LazyVGrid` cannot do a ragged wrap, // so this is one of the two places a row is laid out by hand — the // rail is capped at eight chips (`searchPlaceChipCap`), so the count is // bounded and a `ViewThatFits` chain would be the wrong tool for it. SearchWrapLayout(spacing: 8, lineSpacing: 8) { ForEach(chips) { chip in Button { onPick(chip) } label: { HStack(spacing: 5) { if let symbol = Glyph.symbol(chip.icon) { Image(systemName: symbol) .font(.system(size: 12)) .foregroundStyle(theme.print(.pencil)) } Text(chip.label) .font(CottonFonts.type(13)) .foregroundStyle(theme.print(.ink)) } .padding(.horizontal, 12) .frame(height: 34) .background(PaperSurface(dye: .cream, edge: .cut, seed: "chip-\(chip.key)")) } .buttonStyle(MotionButtonStyle()) .accessibilityLabel(chip.label) .accessibilityIdentifier("search-place-\(chip.key)") } } } } /// A ragged wrap — what `flex-row flex-wrap gap-2` draws. struct SearchWrapLayout: Layout { let spacing: CGFloat let lineSpacing: CGFloat func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { let width = proposal.width ?? .infinity var lineWidth: CGFloat = 0 var lineHeight: CGFloat = 0 var total: CGFloat = 0 var widest: CGFloat = 0 for view in subviews { let size = view.sizeThatFits(.unspecified) if lineWidth > 0 && lineWidth + spacing + size.width > width { total += lineHeight + lineSpacing widest = max(widest, lineWidth) lineWidth = size.width lineHeight = size.height } else { lineWidth += lineWidth > 0 ? spacing + size.width : size.width lineHeight = max(lineHeight, size.height) } } widest = max(widest, lineWidth) // Placement must wrap at the width used to measure the height. Shrinking // to the widest measured line can create another line during placement. return CGSize(width: width.isFinite ? width : widest, height: total + lineHeight) } func placeSubviews( in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout () ) { var x = bounds.minX var y = bounds.minY var lineHeight: CGFloat = 0 for view in subviews { let size = view.sizeThatFits(.unspecified) if x > bounds.minX && x + size.width > bounds.maxX { x = bounds.minX y += lineHeight + lineSpacing lineHeight = 0 } view.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size)) x += size.width + spacing lineHeight = max(lineHeight, size.height) } } } // MARK: - The underlined line /// A run of typewriter text whose matched WORDS wear a red pencil underline. /// /// Words are laid out by the wrap layout rather than as one `Text`, because an /// underline is geometry — a `Shape` under a word — and one `Text` gives no /// word its own frame. `underlineWords` decides which words; this only draws. struct UnderlinedLine: View { let text: String let query: String var size: CGFloat = 14 var ink: PaperInk = .ink var struck = false var seed: String = "line" var markdown = false @Environment(\.theme) private var theme private var words: [(word: UnderlineWord, set: AttributedString)] { let set = markdown ? FaceMarkdown.set(text, theme: theme) : AttributedString(text) let plain = String(set.characters) var cursor = plain.startIndex return underlineWords(plain, query: query).map { word in let label = word.text.trimmingCharacters(in: .whitespacesAndNewlines) guard let range = plain.range(of: label, range: cursor.. Void @Environment(DatabasesModel.self) private var databases: DatabasesModel? @Environment(\.theme) private var theme @Environment(\.tableDefinitions) private var definitions /// The hit's table keeps Markdown in its card's body: its title and /// subtitle are set as its page is. private var marksDown: Bool { definitions[hit.kind]?.bodySetsMarkdown == true } private var title: String { marksDown ? String(FaceMarkdown.set(hit.title, theme: theme).characters) : hit.title } private var seed: String { "hit-\(hit.kind)-\(hit.recordId)" } private var source: String { let database = hit.database.flatMap { row in row.databaseName.isEmpty ? databases?.held.first(where: { $0.databaseId == row.databaseId })?.name : row.databaseName } ?? (databases?.held.count == 1 ? databases?.held.first?.name : nil) return database.map { "\(words) · \($0)" } ?? words } var body: some View { Button(action: onTap) { VStack(alignment: .leading, spacing: 6) { object Text(source) .paperMeta(11.5) .accessibilityIdentifier("search-hit-source") } .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) // Which database the hit is in, when the search read several. .overlay(alignment: .topTrailing) { DatabaseMark(hit.database).padding(6) } } .buttonStyle(OpacityButtonStyle()) .accessibilityLabel("\(title), \(source)") .accessibilityIdentifier("search-hit-\(hit.kind)-\(hit.recordId)") } @ViewBuilder private var object: some View { switch section { case "todo": // The todo card, small: the ring it is ticked in, the words. Paper(dye: .cream, edge: .cut, seed: seed, tilt: false, inset: 12) { HStack(alignment: .top, spacing: 10) { Circle() .stroke(theme.print(.pencil), lineWidth: 1.2) .frame(width: 18, height: 18) .padding(.top, 1) lines } } case "note", "thought", "memory": // A note row — torn, straw. Paper(dye: .straw, edge: .torn, seed: seed, tilt: false, inset: 12) { lines } case "person": // The typed card, beside the words. HStack(alignment: .center, spacing: 12) { TypedCard(name: title, seed: hit.recordId) .frame(width: 58, height: 58) lines } case "message", "email", "session_message", "session": // A message strip — blue, cut, narrow. Paper(dye: .blue, edge: .cut, seed: seed, tilt: false, inset: 10) { lines } case "document", "page": // A document sheet — the caption (its page) handwritten in its corner. Paper(dye: .cream, edge: .cut, seed: seed, tilt: false, inset: 14) { VStack(alignment: .leading, spacing: 4) { UnderlinedLine(text: title, query: query, size: 14.5, struck: hit.struck, seed: seed) if let subtitle = hit.subtitle { UnderlinedLine(text: subtitle, query: query, size: 12.5, ink: .pencil, seed: "\(seed)-snippet") .accessibilityIdentifier("search-hit-\(hit.kind)-\(hit.recordId)-snippet") } } .padding(.trailing, 44) } .overlay(alignment: .bottomTrailing) { if let caption = hit.caption { Text(caption) .paperHand(13) .padding(.trailing, 14) .padding(.bottom, 10) } } case "location": // A postcard — sage, the words on the left, the stamp corner right. Paper(dye: .sage, edge: .cut, seed: seed, tilt: false, inset: 12) { HStack(alignment: .top, spacing: 12) { lines Rectangle() .stroke(theme.print(.pencil), style: StrokeStyle(lineWidth: 1, dash: [2, 2])) .frame(width: 22, height: 26) } } default: // Every other kind — an event, a meeting, a transaction, a goal, a // check-in, a photo, a video, a call, a password, an imported // table's record — a plain cut slip. Paper(dye: .cream, edge: .cut, seed: seed, tilt: false, inset: 12) { lines } } } /// The words every object carries: the name, the matched line, the caption. private var lines: some View { VStack(alignment: .leading, spacing: 4) { UnderlinedLine(text: title, query: query, size: 14.5, struck: hit.struck, seed: seed) if let subtitle = hit.subtitle { UnderlinedLine(text: subtitle, query: query, size: 12.5, ink: .pencil, seed: "\(seed)-snippet", markdown: marksDown) .accessibilityIdentifier("search-hit-\(hit.kind)-\(hit.recordId)-snippet") } if let caption = hit.caption { Text(caption) .paperMeta(11.5) } } .frame(maxWidth: .infinity, alignment: .leading) } }