// 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)`.importCottonFacesimportCottonKitimportSwiftUI/// 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`.enumSearchArm: 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 resultsstaticfunc 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.enumSearchWords {staticvar scope: String { ShellLines.line("search", "words.scope") }staticvar restHint: String { ShellLines.line("search", "rest_hint") }staticvar failed: String { ShellLines.line("search", "words.failed") }staticvar failedHint: String { ShellLines.line("search", "words.failed_hint") }staticvar noMatch: String { ShellLines.line("search", "words.no_match") }staticvar noMatchHint: String { ShellLines.line("search", "words.no_match_hint") }}structSearchResults: View {privatelet model: SearchModel/// A record hit — a PUSH. @Environment(Navigator.self) privatevar navigator/// The held databases and this window's: a hit from another database opens/// once the window shows it (`FeedRowOpening`). @Environment(DatabasesModel.self) privatevar databases: DatabasesModel? @Environment(DatabaseScene.self) privatevar scene: DatabaseScene? @Environment(ToastCenter.self) privatevar toasts: ToastCenter? @Environment(\.theme) privatevar themeinit(model: SearchModel) {self.model = model }var body: someView { 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.privatefuncopen(_ hit: FindHit) {guardlet 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 privatefunc content(for items: [SearchItem]) -> someView {switchSearchArm.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) } } } }privatefunc notice(_ sentence: String, line2: String?, identifier: String) -> someView { 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.privatefunc hint(_ sentence: String) -> someView {Text(sentence) .paperBody(13, ink: .pencil) .multilineTextAlignment(.center) .cottonContentMargin() .padding(.top, 28) .frame(maxWidth: .infinity, alignment: .top) .accessibilityIdentifier("search-hint") }// MARK: - The one listprivatefunc list(_ items: [SearchItem]) -> someView {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 privatefunc row(_ item: SearchItem, at index: Int, of count: Int) -> someView {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.iflet 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.structSearchChipRail: View {let chips: [SearchPlaceChip]let onPick: (SearchPlaceChip) -> Void @Environment(\.theme) privatevar themepublicvar body: someView {// 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 inButton { onPick(chip) } label: { HStack(spacing: 5) {iflet 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.structSearchWrapLayout: Layout {let spacing: CGFloatlet lineSpacing: CGFloatfunc sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {let width = proposal.width ?? .infinityvar lineWidth: CGFloat = 0var lineHeight: CGFloat = 0var total: CGFloat = 0var widest: CGFloat = 0for 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.minXvar y = bounds.minYvar lineHeight: CGFloat = 0for 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.structUnderlinedLine: View {let text: Stringlet query: Stringvar size: CGFloat = 14var ink: PaperInk = .inkvar struck = falsevar seed: String = "line"var markdown = false @Environment(\.theme) privatevar themeprivatevar words: [(word: UnderlineWord, set: AttributedString)] {let set = markdown ? FaceMarkdown.set(text, theme: theme) : AttributedString(text)let plain = String(set.characters)var cursor = plain.startIndexreturn underlineWords(plain, query: query).map { word inlet label = word.text.trimmingCharacters(in: .whitespacesAndNewlines)guardlet range = plain.range(of: label, range: cursor..<plain.endIndex) else { return (word, AttributedString(word.text)) }let from = set.characters.index(set.startIndex, offsetBy: plain.distance(from: plain.startIndex, to: range.lowerBound))let to = set.characters.index(from, offsetBy: plain[range].count) cursor = range.upperBoundreturn (word, AttributedString(set[from..<to]) + AttributedString(word.text.hasSuffix(" ") ? " " : "")) } }var body: someView {SearchWrapLayout(spacing: 0, lineSpacing: 3) {ForEach(words, id: \.word.index) { entry inlet word = entry.wordText(entry.set) .font(CottonFonts.type(size)) .foregroundStyle(theme.print(ink)) .strikethrough(struck) .overlay(alignment: .bottom) {if word.underlined {PencilUnderline(seed: "\(seed)-\(word.index)", theme: theme) .stroke(theme.print(.red), style: StrokeStyle(lineWidth: 1.3, lineCap: .round)) .frame(height: 5) .padding(.trailing, word.text.hasSuffix(" ") ? size * 0.5 : 0) .offset(y: 3) .blendMode(theme.printBlend) .accessibilityHidden(true) } } } } .frame(maxWidth: .infinity, alignment: .leading) }}// MARK: - A record hit, as its kind's object/// A record hit — the search's answer, drawn as the small form of the object/// its tool draws: a cut card, a torn row, a typed card, a strip, a sheet, a/// postcard. The matched words wear the pencil wherever they stand. Every word/// on it is the core's (`read.find`'s worded hit).structSearchHitCard: View {let hit: FindHit/// The section the hit stands in, which picks its object, and its words.let section: Stringlet words: String/// The SETTLED query, for the underline.let query: Stringlet onTap: () -> Void @Environment(DatabasesModel.self) privatevar databases: DatabasesModel? @Environment(\.theme) privatevar theme @Environment(\.tableDefinitions) privatevar definitions/// The hit's table keeps Markdown in its card's body: its title and/// subtitle are set as its page is.privatevar marksDown: Bool { definitions[hit.kind]?.bodySetsMarkdown == true }privatevar title: String { marksDown ? String(FaceMarkdown.set(hit.title, theme: theme).characters) : hit.title }privatevar seed: String { "hit-\(hit.kind)-\(hit.recordId)" }privatevar 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: someView {Button(action: onTap) { VStack(alignment: .leading, spacing: 6) { objectText(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 privatevar object: someView {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)iflet 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) {iflet 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) { linesRectangle() .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.privatevar lines: someView { VStack(alignment: .leading, spacing: 4) {UnderlinedLine(text: title, query: query, size: 14.5, struck: hit.struck, seed: seed)iflet 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") }iflet caption = hit.caption {Text(caption) .paperMeta(11.5) } } .frame(maxWidth: .infinity, alignment: .leading) }}