import CottonKit import SwiftUI #if canImport(UIKit) import UIKit #elseif canImport(AppKit) import AppKit import ScreenCaptureKit #endif // MARK: - Shake to report (lane J4; to Cotton since 13 Nov 2026) // // A shake on the screen that looks wrong opens a sheet with one sentence in // it, and the app sends the sentence with what an agent needs to act on it: // a PNG of the screen as it was at the shake, the phone, the OS, the route // and the last two hundred lines of the log. Everything goes through // `feedback.send` in Rust, which keeps the report in its outbox and posts it // to Cotton's own database (`cotton-product`'s `app_report`), never the // reporter's Personal; the core stamps the app, the build and the platform. // This app has no HTTP client and never will (`SourceGuardTests`). // // Three pieces, in order of appearance: the SHAKE (a `UIWindow` override that // posts a notification, because SwiftUI has no motion event), the STAGING // (`RootView` takes the picture BEFORE the sheet is up, or the sheet would be // in it), and the MODEL, which holds a `ScreenWriter` and never the core // (`ScaffoldSweepTests`), gathers the facts, sends, and deletes the PNG. // // THE MAC HAS THE SAME REPORT AND A DIFFERENT GESTURE. A Mac has no motion // event; its way in is the Help menu's *Report a problem…* row // (`CottonHost/MainMenu.swift`), which posts the SAME notification, so the // staging, the picture, the sheet and the verb are one code path for both // destinations (H2: `CottonUI` compiles for both). The picture is the main // window's pixels as the window server has them, at the display's scale; the // report says `platform = "macos"` because the core stamps the platform it was // compiled for (`cotton-ffi/src/phone/feedback_send.rs`), never the caller. extension Notification.Name { /// The report gesture: posted by `UIWindow.motionEnded` on a shake, and by /// the Mac's Help › Report a problem… row. `RootView` listens. public static let cottonShake = Notification.Name("com.cottondb.shake") } #if os(iOS) extension UIWindow { /// The one place the OS delivers a shake: the first responder chain ends /// at the window, and a SwiftUI app owns no view controller to hear it on. open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { super.motionEnded(motion, with: event) if motion == .motionShake { NotificationCenter.default.post(name: .cottonShake, object: nil) } } } #endif /// The screen as a picture on disk, taken at the shake: a PNG when it fits /// under the core's ceiling, else a JPEG. public enum ScreenSnapshot { /// The core's ceiling for a report's picture (`feedback_send.rs` /// `SCREENSHOT_MAX`, the Worker's cap): a picture over it is refused, so /// it is never written. A full-resolution iPhone PNG of a photographic /// ground is about 6 MB (Books, walked 13 Nov 2026). public static let ceiling = 4 * 1024 * 1024 /// The bytes to write and their extension: the lossless PNG when it fits /// under `ceiling`, else a JPEG of the same pixels, lowered in quality /// until it fits. `nil` when nothing fits. static func encoded(png: Data?, jpeg: (Double) -> Data?) -> (bytes: Data, ext: String)? { if let png, png.count <= ceiling { return (png, "png") } for quality in [0.85, 0.6, 0.4] { if let bytes = jpeg(quality), bytes.count <= ceiling { return (bytes, "jpg") } } return nil } /// What was written: where, and how big in pixels. public struct Taken: Sendable, Equatable { public let path: String public let image: FeedbackImageSize /// How the picture was taken when it is NOT the screen as the person saw /// it — a line that rides in the report's log so the reader knows why the /// page may be missing. `nil` for a picture of the window as composited. public let fallback: String? public init(path: String, image: FeedbackImageSize, fallback: String? = nil) { self.path = path self.image = image self.fallback = fallback } } /// Draw the key window into a picture in the temp directory. `drawHierarchy` /// rather than `ImageRenderer`: the latter renders a SwiftUI value /// offscreen, and what the person is looking at is the window — every /// screen, the toast, the keyboard's inset — not a value. /// /// On the Mac the window is asked of the WINDOW SERVER (ScreenCaptureKit, /// over this process's own shareable content, on this one window), for /// the same reason: the pixels as they are on screen. Drawing the content view /// through `cacheDisplay` was measured 2026-09-18 to give the sidebar and /// the toolbar and NONE of the page — the scrolled columns are layers the /// window server composites, not ones AppKit redraws for a bitmap. /// `SCShareableContent.currentProcess` is the content a process may image /// WITHOUT Screen Recording — its own windows; that grant gates other apps' /// windows. (`CGWindowListCreateImage`, the old way, is unavailable from /// macOS 15.) A Mac where the window server still refuses (Screen /// Recording not granted — a Mac, 14 Oct 2026) falls back to AppKit's own /// window drawing (`cacheDisplay`) and the picture carries a `fallback` /// line saying so, which the report sends in its log: never a silent /// partial or empty capture. A window that is not on screen, which is what /// a test hands in, is drawn the same way. @MainActor public static func take(directory: URL = FileManager.default.temporaryDirectory) async -> Taken? { #if os(macOS) return await take(window: frontWindow(), directory: directory) #elseif os(iOS) let window = UIApplication.shared.connectedScenes .compactMap { $0 as? UIWindowScene } .flatMap(\.windows) .first(where: \.isKeyWindow) guard let window else { return nil } let format = UIGraphicsImageRendererFormat() format.scale = window.screen.scale let image = UIGraphicsImageRenderer(bounds: window.bounds, format: format).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: false) } guard let picture = encoded(png: image.pngData(), jpeg: { image.jpegData(compressionQuality: $0) }) else { return nil } let url = directory.appendingPathComponent("shake-\(UUID().uuidString).\(picture.ext)") do { try picture.bytes.write(to: url, options: .atomic) } catch { Log.write("shake: the screen could not be written: \(error)") return nil } return Taken( path: url.path, image: FeedbackImageSize( width: Int(image.size.width * image.scale), height: Int(image.size.height * image.scale) ) ) #else _ = directory return nil #endif } #if os(macOS) /// The window the person is looking at. The key window when the app is /// active; otherwise the largest ordinary window that is on screen — /// AppKit answers nil for both `keyWindow` and `mainWindow` while another /// app is frontmost, and a check with no hands launches this one from a /// shell, which never activates it. @MainActor static func frontWindow() -> NSWindow? { let app = NSApplication.shared if let window = app.keyWindow ?? app.mainWindow { return window } return app.windows .filter { $0.isVisible && $0.level == .normal && $0.contentView != nil } .max { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height } } /// The Mac's capture, with the window named so a test can hand it one /// that is not on screen. `nil` when there is no window or nothing to /// draw in it — the sheet then says the log alone goes. @MainActor public static func take(window: NSWindow?, directory: URL = FileManager.default.temporaryDirectory) async -> Taken? { guard let window, let view = window.contentView else { return nil } let bounds = view.bounds guard bounds.width > 0, bounds.height > 0 else { return nil } var bitmap: NSBitmapImageRep? var fallback: String? if window.isVisible, window.windowNumber > 0 { switch await composite(CGWindowID(window.windowNumber)) { case .success(let composited) where composited.width > 1 && composited.height > 1: bitmap = NSBitmapImageRep(cgImage: composited) case .success: fallback = drawnLine("the window server's picture was empty") case .failure(let error): fallback = drawnLine("the window server refused: \(error.localizedDescription)") } } if bitmap == nil { guard let drawn = view.bitmapImageRepForCachingDisplay(in: bounds) else { return nil } view.cacheDisplay(in: bounds, to: drawn) bitmap = drawn } guard let bitmap, let picture = encoded( png: bitmap.representation(using: .png, properties: [:]), jpeg: { bitmap.representation(using: .jpeg, properties: [.compressionFactor: $0]) } ) else { return nil } if let fallback { Log.write(fallback) } let url = directory.appendingPathComponent("shake-\(UUID().uuidString).\(picture.ext)") do { try picture.bytes.write(to: url, options: .atomic) } catch { Log.write("report: the window could not be written: \(error)") return nil } return Taken( path: url.path, image: FeedbackImageSize(width: bitmap.pixelsWide, height: bitmap.pixelsHigh), fallback: fallback ) } /// The line a drawn (not composited) picture carries into the report. /// Screen Recording is named because it is the grant that lets the window /// server answer on a Mac that refuses own-process content without it. static func drawnLine(_ why: String) -> String { let granted = CGPreflightScreenCaptureAccess() ? "granted" : "not granted" return "report: screen drawn by AppKit, not the window server (\(why); Screen Recording \(granted)) — scrolled page content may be missing" } /// One of this process's windows as the window server composites it, at /// full backing resolution and without its shadow; nil when the window /// server has no such window for us. private static func composite(_ id: CGWindowID) async -> Result { do { let content = try await SCShareableContent.currentProcess guard let window = content.windows.first(where: { $0.windowID == id }) else { return .failure(CompositeMissing()) } let filter = SCContentFilter(desktopIndependentWindow: window) let configuration = SCStreamConfiguration() configuration.width = Int(filter.contentRect.width * CGFloat(filter.pointPixelScale)) configuration.height = Int(filter.contentRect.height * CGFloat(filter.pointPixelScale)) configuration.showsCursor = false return .success(try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)) } catch { return .failure(error) } } private struct CompositeMissing: LocalizedError { var errorDescription: String? { "this window is not in the process's shareable content" } } #endif } /// What `RootView` captured at the shake, handed to the sheet whole. public struct ShakeStaged: Identifiable, Sendable, Equatable { public let id: UUID public let snapshot: ScreenSnapshot.Taken? public let route: String public init(snapshot: ScreenSnapshot.Taken?, route: String) { self.id = UUID() self.snapshot = snapshot self.route = route } } /// The facts about this phone. Gathered at SEND, so the ring holds what /// happened up to the moment the person tapped. The build is the core's to /// stamp, never the shell's. public struct ShakeFacts: Sendable, Equatable { public var device: String public var os: String public var log: [String] /// How many of the ring's newest lines a report carries. public static let logLines = 200 public init(device: String, os: String, log: [String]) { self.device = device self.os = os self.log = log } /// The live process: the same facts `Reporting.report` dresses with. public static func live() -> ShakeFacts { let hardware = Hardware.current() return ShakeFacts( device: hardware.model, os: hardware.os, log: Array(Log.ring.rendered().suffix(logLines)) ) } } /// `feedback.flush`: every report kept on this phone tried again. Once after /// the core opens and each time the app comes to the front; nobody asked for /// it, so its answer is only logged. public enum FeedbackOutbox { public static func flush(core: any CottonCalling) async { do { let answer = try await core.callJSON(CottonMethod.feedbackFlush) Log.write("reports kept on this phone: sent \(answer.number("sent") ?? 0), kept \(answer.number("kept") ?? 0), refused \(answer.number("refused") ?? 0)") } catch { Log.write("reports kept on this phone could not be sent again: \(error)") } } } @MainActor @Observable public final class ShakeReportModel { public enum Stage: Equatable { case writing case sending case sent } public private(set) var stage: Stage = .writing public var note = "" public private(set) var sent: FeedbackSent? public let staged: ShakeStaged /// The projects the sheet's caps draw — every one this device has, active /// and archived alike, exactly as the sheet's own rules /// (`offeredProjects`) then narrow them. `feedback.send` takes no project, /// so the pick files nothing: the caps stay drawn as they were (owner, /// 13 Nov 2026: no change to how the sheet looks). public private(set) var projects: [ProjectsSheetOption] = [] /// The one this report is about, or nothing. A REPORT MAY STAY UNFILED and /// most do: a sheet that demanded a project before it would take a /// sentence is a sheet nobody shakes twice. public var projectId: String? private let writer: ScreenWriter private let toasts: ToastCenter private let gather: @Sendable () -> ShakeFacts private let remove: (String) -> Void private let preferences: any DevicePreferences /// The open host the flavour hands `personal.code`, where a signed-out /// report goes. private let server: String? /// What the report's microphone listens for — the same hints every other /// microphone reads, so a report naming a person or a project is heard /// with that name. let hints: @MainActor () async -> DictationHints /// Where the last project a report was filed under is remembered. DEVICE /// LOCAL: which project you were last reporting about is a habit of this /// phone's, not a fact about the person's database. static let lastProjectKey = "report.lastProject" public init( writer: ScreenWriter, toasts: ToastCenter, staged: ShakeStaged, gather: @escaping @Sendable () -> ShakeFacts = { ShakeFacts.live() }, remove: @escaping (String) -> Void = { path in try? FileManager.default.removeItem(atPath: path) }, preferences: any DevicePreferences = UserDefaultsPreferences(), server: String? = FlavourManifest.current?.business?.server, hints: @escaping @MainActor () async -> DictationHints = { DictationHints() } ) { self.server = server self.hints = hints self.writer = writer self.toasts = toasts self.staged = staged self.gather = gather self.remove = remove self.preferences = preferences } /// The roster, and the project the sheet opens ticked. /// /// Asked ONCE, and a failure leaves the run of caps empty — the sheet then /// says "No projects yet…" in the picker's own words and the sentence can /// still be sent, because an unfiled report is a real report. public func loadProjects() async { guard projects.isEmpty else { return } guard let answer = try? await writer.call(CottonMethod.readProjects) else { return } projects = answer.list("projects").compactMap { row in guard let id = row.text("id") else { return nil } return ProjectsSheetOption( id: id, name: row.text("name") ?? id, status: row.text("status") == "archived" ? .archived : .active, slug: row.text("slug") ) } projectId = ReportProject.preselected( route: staged.route, lastUsed: preferences.string(ShakeReportModel.lastProjectKey), projects: projects ) } public var canSend: Bool { stage == .writing && !note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } /// Send, and say what happened. `false` is a refusal already shown as a /// toast, with the sentence still in the field. @discardableResult public func send() async -> Bool { guard canSend else { return false } stage = .sending let facts = gather() let request = FeedbackSendRequest( sentence: note.trimmingCharacters(in: .whitespacesAndNewlines), screenshotPath: staged.snapshot?.path, route: staged.route, device: facts.device, os: facts.os, log: facts.log + (staged.snapshot?.fallback.map { [$0] } ?? []), server: server ) do { let answer = try await writer.call(CottonMethod.feedbackSend, request, as: FeedbackSent.self) sent = answer stage = .sent // The caps' habit: the project last picked opens ticked next time. preferences.setString(projectId, ShakeReportModel.lastProjectKey) // The core copied the picture into its outbox: the temp PNG goes. discardSnapshot() Log.write("report \(answer.state)\(answer.sender.map { " as \($0)" } ?? ""): \(answer.id)") // No toast: the sheet's own card says what became of it. return true } catch let refusal as CottonCallError { // Refused in words: nothing was kept. The sentence and the picture // stay for another try. stage = .writing toasts.show(ShellLines.line("feedback", "reports.not_accepted_said", ["said": "\(refusal.message)"]), tone: .error) return false } catch { stage = .writing Reporting.report( Report(kind: .unreadableAnswer, message: "\(error)", context: ["method": CottonMethod.feedbackSend]) ) toasts.show(CottonStrings.somethingWentWrong, tone: .error) return false } } /// The app look's Send (`LookReportSheet`): the same `send`, the same /// request, then what became of it said once, quietly, in the app's own /// toast as the sheet closes, where the paper sheet turns to its card. @discardableResult public func sendAndSay() async -> Bool { guard await send() else { return false } toasts.show(outcomeLine) return true } /// What the sent card says: Cotton has it, or it is kept on this phone. public var outcomeLine: String { ShellLines.line("feedback", sent?.kept == true ? "sent.kept" : "sent.to_cotton") } /// The person changed their mind: the picture goes, nothing is written. public func cancel() { discardSnapshot() } private func discardSnapshot() { if let path = staged.snapshot?.path { remove(path) } } } /// The sheet, as a complaint slip: torn cream paper, the question in the serif, /// the sentence typed on ruled lines, what goes with it handwritten under it, /// and Send as the ink circle. When the screen was captured, it rides in the /// slip's corner as a small print — the person never saw the screenshot taken, /// so the slip shows what they are about to send. public struct ShakeReportSheet: View { @Bindable private var model: ShakeReportModel private let onClose: () -> Void @Environment(\.theme) private var theme /// Dictation into the sentence, the SAME host every other writing surface /// uses (`Capture/BodyDictation.swift`) over the app's ONE recogniser — so /// an improvement to speech lands here too, without this file knowing how /// speech works. Built in `.task`, never in `init`: a real recogniser opens /// the audio stack the moment it exists, and a `View.init` runs on every /// evaluation of the view value (`CapabilityGateSweepTests`). @State private var speech: BodyDictation? /// The centre and the taps the host publishes again for this sheet /// (`RootView`'s `.sheet`) — a sheet inherits neither on its own. @Environment(\.cottonHaptics) private var haptics @Environment(ToastCenter.self) private var toasts public init(model: ShakeReportModel, onClose: @escaping () -> Void) { self.model = model self.onClose = onClose } public var body: some View { VStack(alignment: .leading, spacing: 0) { if model.stage == .sent { thanks } else { writing } Spacer(minLength: 0) } .padding(20) .frame(maxWidth: .infinity, alignment: .leading) #if os(macOS) // A Mac sheet is sized by its content, and this one's content is a // paper that grows to fill: give it the slip's own size, or AppKit // opens a sheet the width of the field and the height of nothing. .frame(width: 520, height: 400) #endif .accessibilityIdentifier("report-sheet") .task { // Once, on arrival. `@State` survives every redraw, so a second // recogniser is never built for the same sheet. if speech == nil { speech = makeSpeech() } await model.loadProjects() } } /// The dictation host, with the two ends of the wire a `View.init` cannot /// reach. `VoiceTake` decides which ending becomes a sentence; a discard /// and a dictation that landed its words owe none. private func makeSpeech() -> BodyDictation { let model = model let toasts = toasts return BodyDictation( dictation: DictationModel.live(), haptics: haptics, body: { model.note }, setBody: { model.note = $0 }, onEnded: { outcome in if let sentence = VoiceTake.dictationMessage(outcome) { toasts.show(sentence, tone: .error) } } ) } /// What the field shows and what a keystroke writes. /// /// `BodyDictation` splices at the last cursor the field REPORTED, and a /// bare SwiftUI `TextField` reports none — so the words land at the end of /// whatever is already there. For one sentence that is the right place, and /// the note editor's cursor tracking is not worth carrying here. private var noteField: Binding { Binding( get: { speech?.displayBody ?? model.note }, set: { text in // Dictation owns the field while it is live: the sentence is // written on FINISH, and a partial echoed back would be typed // over the splice. guard speech?.isActive != true else { return } model.note = text } ) } /// The microphone, and the two endings it becomes while it is listening — /// the streaming sentence is its own feedback, so nothing else is drawn. /// Both endings are inert while the session is finishing. @ViewBuilder private var dictationControls: some View { if let speech { if speech.isActive { NavCircle(symbol: "xmark", label: CottonStrings.discardDictation) { guard !speech.isFinishing else { return } haptics.press() speech.cancel() } .accessibilityIdentifier("report-dictate-cancel") NavCircle(symbol: "checkmark", label: CottonStrings.finishDictation) { guard !speech.isFinishing else { return } haptics.press() Task { await speech.finish() } } .accessibilityIdentifier("report-dictate-finish") } else if model.stage == .writing { NavCircle(symbol: "mic", label: CottonStrings.dictateHint) { haptics.press() Task { await speech.start(hints: await model.hints()) } } .accessibilityIdentifier("report-dictate") } } } /// The slip, being written on. @ViewBuilder private var writing: some View { HStack(alignment: .center) { Button { model.cancel() onClose() } label: { Text(CottonStrings.cancel) .paperHand(18) .frame(minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(MotionButtonStyle()) .accessibilityIdentifier("report-cancel") Spacer() dictationControls Button { Task { await model.send() } } label: { Image(systemName: model.stage == .sending ? "ellipsis" : "arrow.up") .font(.system(size: 18, weight: .semibold)) .foregroundStyle(PaperDye.cream.fill) .frame(width: 48, height: 48) .background(Circle().fill(theme.print(.ink))) } .buttonStyle(MotionButtonStyle()) .disabled(!model.canSend) .opacity(model.canSend ? 1 : DisabledOpacity.control) .accessibilityLabel(ShellLines.line("feedback", model.stage == .sending ? "report.sending" : "report.send")) .accessibilityIdentifier("report-send") } ScrollView { Paper(dye: .cream, edge: .torn, seed: "shake-report", tilt: false, inset: 20) { VStack(alignment: .leading, spacing: 0) { HStack(alignment: .top, spacing: 12) { VStack(alignment: .leading, spacing: 4) { Text(ShellLines.line("feedback", "report.kicker")).paperMeta(12) Text(ShellLines.line("feedback", "report.title")) .paperTitle(24) .accessibilityAddTraits(.isHeader) } Spacer(minLength: 0) snapshotPrint } TextField(ShellLines.line("feedback", "report.placeholder"), text: noteField, axis: .vertical) // Plain on both: the Mac's default draws a white box // over the ruled lines the slip is typed on. .textFieldStyle(.plain) .font(CottonFonts.type(15)) .foregroundStyle(theme.print(.ink)) .lineSpacing(ReplySheetKnobs.paperRuledTypedSpacing) .lineLimit(3...) .padding(.top, 14) .background(alignment: .top) { RuledLines().padding(.top, 8) } .accessibilityIdentifier("report-note") Text(ShellLines.line("feedback", model.staged.snapshot == nil ? "report.goes_with.log" : "report.goes_with.screen_and_log")) .paperHand(15) .fixedSize(horizontal: false, vertical: true) .padding(.top, 14) projectCaps } .frame(maxWidth: .infinity, alignment: .leading) } .padding(.top, 8) } .scrollBounceBehavior(.basedOnSize) } /// Which project this is about, as the board's own caps — preselected to /// the project you were looking at, else the one you last reported under, /// else none. ONE at a time: a report is about one project or about none. @ViewBuilder private var projectCaps: some View { if !model.projects.isEmpty { ProjectsSheetContent( projects: model.projects, links: model.projectId.map { [ProjectsSheetLink(projectId: $0)] } ?? [], caption: ShellLines.line("feedback", "report.project_caption"), onLink: { model.projectId = $0 }, onUnlink: { _ in model.projectId = nil } ) .padding(.top, 18) } } /// What became of it, in the core's answer: Cotton has it, or it is kept /// on this phone until there is a connection. @ViewBuilder private var thanks: some View { Paper(dye: .cream, edge: .torn, seed: "shake-report-sent", tilt: false, inset: 20) { VStack(alignment: .leading, spacing: 0) { Text(model.outcomeLine) .paperTitle(24) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("report-outcome") Button { onClose() } label: { Text(ShellLines.line("feedback", "sent.done")) .paperHand(18) .frame(minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(MotionButtonStyle()) .padding(.top, 14) .accessibilityIdentifier("report-done") } .frame(maxWidth: .infinity, alignment: .leading) } } /// The captured screen, small, tucked into the slip's corner. @ViewBuilder private var snapshotPrint: some View { if let path = model.staged.snapshot?.path { SnapshotPrint(path: path) } } } /// The captured screen as a thumb print. A full-window capture is megapixels /// drawn 46 points wide, so it is decoded at that edge off the main actor /// (`MediaImages.thumbnail`) rather than read whole; until it is decoded the /// corner stays empty. `UIImage` is `NSImage` on the Mac /// (`Platform/AppKitAnswers.swift`), so one print serves both. private struct SnapshotPrint: View { let path: String @State private var picture: UIImage? @Environment(\.displayScale) private var displayScale private static var width: CGFloat { 46 } var body: some View { Group { if let picture { InstantPrint(seed: "shake-snapshot", size: .thumb) { Image(uiImage: picture) .resizable() .scaledToFill() } .frame(width: Self.width) .rotationEffect(.degrees(4)) .accessibilityLabel(ShellLines.line("feedback", "report.snapshot")) .accessibilityIdentifier("report-snapshot") } else { // Holds the corner's place so the task below has a view to run on. Color.clear.frame(width: Self.width, height: Self.width) } } .task(id: path) { // The capture is portrait, so its long edge is about twice the drawn width. let edge = Self.width * 2.5 * displayScale picture = await Task.detached(priority: .userInitiated) { MediaImages.thumbnail(at: path, edge: edge) }.value } } } /// Which project the caps open ticked. The pick files nothing since /// `feedback.send` (it takes no project); the caps keep their old behaviour so /// the sheet looks as it did. enum ReportProject { /// The project a route is INSIDE, by slug — nil for every screen that is /// not one of a project's own. static func projectSlug(inRoute path: String?) -> String? { guard let path, let route = Route.parse(path) else { return nil } switch route { case .projectsSlug(let slug), .projectsSlugSection(let slug, _), .projectsBrand(let slug), .projectsCode(let slug), .projectsFeedback(let slug), .projectsMemory(let slug), .projectsTodos(let slug): return slug.isEmpty ? nil : slug default: return nil } } /// Which project the report sheet opens with, as a project ID. /// /// The rule, in order: the project whose page the person was looking at /// when they shook; else the last project they filed a report under on this /// device; else nothing, because a report may stay unfiled and a sheet that /// demanded a project before it would take a sentence is a sheet nobody /// shakes twice. /// /// Either source may name a project this device no longer has — an /// archived slug in a stale deep link, a project deleted since the last /// report — and a preselection that named one would tick a cap that is not /// on the sheet. So each is resolved against the offered list, and an /// unresolvable route falls through to the remembered one rather than /// stopping there. static func preselected( route: String?, lastUsed: String?, projects: [ProjectsSheetOption] ) -> String? { if let slug = projectSlug(inRoute: route), let named = projects.first(where: { $0.slug == slug }) { return named.id } if let lastUsed, projects.contains(where: { $0.id == lastUsed }) { return lastUsed } return nil } }