diff --git a/AGENTS.md b/AGENTS.md index 5189649..c39b27e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -98,18 +98,18 @@ Simulator names are version-specific and go stale — `xcodebuild` prints the va - **Coverage standard.** 100% line coverage on every file the branch touches, measured once at the gate. The same gate runs in CI on every pull request, in the one job that also runs the Dynamic Type check: [`scripts/coverage_gate.py`](scripts/coverage_gate.py) diffs the branch against its base and fails on any Swift file under `FitCheck/` short of 100%, with [`scripts/coverage-allowlist.txt`](scripts/coverage-allowlist.txt) the only way past it — so a new service arrives with its tests rather than borrowing coverage from its neighbours. - **Coverage allowlist.** Some files cannot reach 100% from the unit target. They are named here, with the reason, so an exclusion is a decision on the record instead of a silent gap — **anything not on this list is expected at 100%, and a gap there is a defect in the branch.** The prose below is documentation; the copy CI actually reads is [`scripts/coverage-allowlist.txt`](scripts/coverage-allowlist.txt), one path and its reason per line, and the two must not disagree — a reason changed here changes there in the same commit. The list is the final gate measurement against base `20a90fc` (304 tests, 48 suites, app target 23.00%, 3481/15132); remove an entry when its reason stops being true, never by lowering the standard. 1. **SwiftUI view bodies** — `FitCheck/Features/**`, `RootView`, `ComposerView`, `SettingsView`, `WeatherSheet`, `SavedLookSheet`, and in `DesignSystem` the views themselves: `GarmentViews`, `GlassComponents`, `SnappingSlider.swift` (a `Slider` wrapper, body only) and `Theme.swift` (palette, metric constants and the scaled-control wrapper, read only from view bodies). The unit target cannot evaluate a view body, so their logic was pushed into services and `AppState` and is tested there (`ComposerView` 82.2%, `HomeView` 41.0%, the rest 0–41%); the views themselves are only reachable from the UI tests. This one does not expire — it is the boundary the architecture was built around, and a view that grows logic gets the logic moved out rather than a test bolted on. The Debug-only [`ClassifierBenchmarkView`](FitCheck/Features/Diagnostics/ClassifierBenchmarkView.swift) is here for a sharper reason than its body: its runner reads 39 bundled PNGs and asks the live model, so nothing in it can execute in the unit target. Everything it decides is the pure `ClassifierBenchmark` — which labels are equal, which colour family a name belongs to, what a percentage is out of, how a value is quoted — and that is the half the unit target covers — the gap here is the runner, not a rule. The file is compiled into Debug builds alone, so a release build carries neither the screen nor the runner. - 2. **Apple-framework adapters** — `MapKitPlaceNamer`, `MapKitPlaceSearch`, the `CLLocationManager` delegate callbacks and its `recentLocation` extension, and `ReminderScheduler`'s `UNUserNotificationCenter` calls. They are the real CoreLocation, MapKit and UserNotifications, which cannot answer in the unit target, and the rules around them are tested through the `PlaceNaming` / `PlaceSearching` / `LocationFixRequester` fakes; the adapters themselves are exercised in a running app. `ReminderScheduler.storedLocalization` is here for the same reason: its only path is `sync`, which awaits `UNUserNotificationCenter.current().notificationSettings()` first, so covering it from the unit target would fire a real authorisation prompt against the host app and write the host's preference domain (the code hardcodes `UserDefaults.forCurrentRun`). [`TabSwipeReader`](FitCheck/App/TabSwipeReader.swift) is here for the same hand-off: it is a `UIViewRepresentable` that installs swipe recognisers on the window and fills a `TabSwipePolicy.Traits` from the view hierarchy under the touch, so every line of it needs a launched app and a window on screen, and the UI tests are its only caller. The refusal rule is not on this list: `TabSwipePolicy` is traits in and verdict out, it holds no recogniser, and [`TabSwipePolicyTests`](FitCheckTests/TabSwipePolicyTests.swift) argues every refusal and the precedence between them, so that file is at 100%. Removed per adapter only by pulling logic out of it and behind a fakeable seam — never by faking the framework to chase the number. + 2. **Apple-framework adapters** — `MapKitPlaceNamer`, `MapKitPlaceSearch`, the `CLLocationManager` delegate callbacks and its `recentLocation` extension, and `ReminderScheduler`'s `UNUserNotificationCenter` calls. They are the real CoreLocation, MapKit and UserNotifications, which cannot answer in the unit target, and the rules around them are tested through the `PlaceNaming` / `PlaceSearching` / `LocationFixRequester` fakes; the adapters themselves are exercised in a running app. `ReminderScheduler.storedLocalization` is here for the same reason: its only path is `sync`, which awaits `UNUserNotificationCenter.current().notificationSettings()` first, so covering it from the unit target would fire a real authorisation prompt against the host app and write the host's preference domain (the code hardcodes `UserDefaults.forCurrentRun`). Removed per adapter only by pulling logic out of it and behind a fakeable seam — never by faking the framework to chase the number. 3. **`WeatherKitProvider`** — compiled and deliberately unwired. A free provisioning profile cannot carry the WeatherKit entitlement, so it can neither run nor be tested. Removed by the release flip: the entitlement in `project.yml`, WeatherKit enabled on the App ID, and `WeatherProviderKind.active` moved to `.weatherKit`. 4. **Apple Intelligence paths** — `OutfitGenerator.generate` past the empty-closet guard, `ModelUnavailability.current` (which reads the device's own answer), and in `GarmentClassifier` only Vision and the live inference. Neither CI nor the Simulator carries model assets, and faking the model is forbidden: the product promises to say the model is unavailable, not to guess. The classifier's **prompt builder is not on this list**: `GarmentClassifier.instructions(language:)`, `vocabulary` and `prompt(for:)` are pure — no session, no device, no image; the evidence they render is a `GarmentEvidence` value — and [`ClassifierPromptTests`](FitCheckTests/LocalizationPromptTests.swift) covers them, which is why the file reads 45.98% instead of 0%. The cut-out `Attachment` on iOS 27 is inside the live inference, so it is on the list with the model call it belongs to. Removed when the suite runs on a device that has Apple Intelligence. 5. **Defensive branches unreachable by construction** — `OpenMeteoProvider`'s `components.url` guard (the base URL is hardcoded and valid), the `@unknown default` arms, and `UserSettings.reminderDate`'s nil-coalescing on a valid hour and minute. They exist for the day the input changes; no input reaches them today. Removed when an input can actually produce one, at which point its test arrives with it. 6. **Process wiring** — `FitCheckApp`'s container creation and seeding, the store opener it builds and hands to the scene along with the deleter behind `Start over`, and `UserDefaults.forCurrentRun`'s UI-testing branch. They need a launched app, which makes them the UI tests' business rather than the unit target's: the wiring and the deleter in `FitCheckApp` only run inside a launched app, and a store that fails to open cannot be produced from the unit target. `-failFirstStoreOpen` is what closes that gap: on a `-uiTesting` launch it makes the first open throw and every later one succeed, so [`RecoveryUITests.testUnreadableStoreRecoversThroughStartOver`](FitCheckUITests/RecoveryUITests.swift) can reach the recovery screen, tap through `Start over`, land on the empty closet, and then relaunch without the argument to prove the failure is one-shot and a normal launch unaffected — which is also the test the [`StoreRecoveryView`](FitCheck/Features/Recovery/StoreRecoveryView.swift) allowlist reason names. `StoreOpener`'s own decision is not here — it takes its opener and deleter as closures precisely so it is unit-tested — and `StoreRecoveryView` is a view body, under entry 1. - 7. **`AppState` (99.13%, 227/229)** — `generate` is covered through the injected `OutfitGenerating`: the four outcomes, the exclusion set, cancellation, the deleted-garment guard and the toast dismissal are all driven by a stub. The two lines still uncovered are line 290 (`ToastMessage.id`) and line 315 (`Confirmation.id`), the compiler-generated `UUID()` default initialisers, which xccov reports as unexecuted although both types are constructed in covered tests — an instrumentation gap, not untested behaviour. Kept because those lines cannot be covered from the unit target; removed when the instrumentation reports them, or when the ids stop being `UUID()` properties. `Tab.adjacent(by:)` is not part of this gap: it is at standard, covered by [`TabAdjacencyTests`](FitCheckTests/AppStateTests.swift) for both directions and both ends. + 7. **`AppState` (99.13%, 227/229)** — `generate` is covered through the injected `OutfitGenerating`: the four outcomes, the exclusion set, cancellation, the deleted-garment guard and the toast dismissal are all driven by a stub. The two lines still uncovered are line 290 (`ToastMessage.id`) and line 315 (`Confirmation.id`), the compiler-generated `UUID()` default initialisers, which xccov reports as unexecuted although both types are constructed in covered tests — an instrumentation gap, not untested behaviour. Kept because those lines cannot be covered from the unit target; removed when the instrumentation reports them, or when the ids stop being `UUID()` properties. 8. **Vision's foreground instances** — in `GarmentSegmenter` the request itself, the per-instance masks it returns and the selection that reads them: `VNGenerateForegroundInstanceMaskRequest` answers only against a real image on the Vision stack, and the unit target carries neither, so the request and the instance selection cannot be unit-tested. It is not the whole file: the matte refinement and the compositing are [`CutoutMatte`](FitCheck/Services/CutoutMatte.swift), which knows nothing of Vision or SwiftData and takes bytes in and bytes out — its erosion, feather, transparent margin, soft alpha range and largest-instance comparison by non-zero area are tested on synthetic masks — and the colour measurement, `colourShares(in:limit:)`, is bytes in and hex-plus-share out, testable on a rendered image. That is the same split as the classifier's prompt builder. Removed when the suite runs where the request can answer. 9. **Photo policy adapters** — `SystemPhotoSafety` and `VisionPhotoSafety` in [`PhotoSafety`](FitCheck/Services/PhotoSafety.swift): the first answers only when the system's own Sensitive Content Analysis runs, which the unit target cannot produce and which is inert without the paid-account entitlement ([`docs/photo-policy.md`](docs/photo-policy.md) §5); the second reads a Vision taxonomy that carries no nudity or gore identifier to match. The rule they feed is not on this list: `PhotoVerdict` and the `PhotoIntake` decision above the adapters are pure and expected at 100% through a fake `PhotoSafetyChecking`. Removed per adapter only by pulling logic out of it and behind a fakeable seam — never by faking the framework to chase the number. -**This branch, file by file.** Every touched file once, with its gate number and the entry that covers it, so the account is complete and nobody has to reconstruct it: `StylistPrompt` 100% (at standard) · `Outfit` 100% (at standard) · `ClothingItem` 100% (at standard) · `Localization` 98.7% (entry 4, the live model probe default) · `UserSettings` 79.6% (entries 5 and 6) · `ComposerView` 82.2% (entry 1) · `WeatherService` 83.5% (entry 2) · `OutfitGenerator` 73.7% (entry 4) · `ReminderScheduler` 73.4% (entry 2) · `FitCheckApp` 56.80% (71/125, entry 6) · `HomeView` 41.0%, `RootView` 40.97% (320/781) (entry 1) · `OutfitGenerating` 100% (at standard) · `AppState` 99.13% (227/229) (entry 7) · `GarmentClassifier` 45.98% (entry 4; its prompt builder is 100%) · `ClosetView`, `ClosetCells`, `SettingsView`, `OutfitsView`, `SavedLookSheet`, `WeatherSheet`, `AddGarmentFlow`, `ProcessingViews`, `CameraController`, `OutfitResultView`, `GeneratingView`, `StoreRecoveryView`, `GarmentViews` 0–6%, `GlassComponents` 18.5% (entry 1). New on the closet-import branch: `ZipReader` and `ClosetImporter`, both at standard and absent from the allowlist — the reader is production code and the plan above it is pure. New on the classifier-benchmark branch: `FitCheckApp` 56.80% (71/125) (entry 6; `launchRoot` itself 100%) · `ClassifierBenchmarkView` 0.46% (entry 1, the Debug-only runner) · `SettingsView` 0.54% (entry 1, the Debug-only Diagnostics row) · and `ClassifierBenchmark` 100% (at standard): its comparison and its CSV are pure, and [`ClassifierBenchmarkTests`](FitCheckTests/ClassifierBenchmarkTests.swift) covers every branch of them, so it carries no allowlist line. New on the photo-policy branch: `PhotoSafety` is on the allowlist (entry 9) for its two adapters, while `PhotoVerdict` and the `PhotoIntake` decision above them are at standard through a fake `PhotoSafetyChecking`. New on the tab-swipe branch: `TabSwipePolicy` 100% (at standard, every refusal and the precedence between them argued as values by [`TabSwipePolicyTests`](FitCheckTests/TabSwipePolicyTests.swift)) · `TabSwipeReader` 39.84% (entry 2, the window-gesture adapter — it has no code path without a launched app, and the rule it applies is the policy's) · `RootView` still entry 1 for the shell it now also hangs the swipe on · and `AppState` still entry 7, with `Tab.adjacent(by:)` at standard through `TabAdjacencyTests`. New on the benchmark-attribution branch: `BenchmarkMetadata` 100% (at standard) — the header keys and the two enumerations behind them are values in and values out, so the CSV's opening block is provable without a device — and `ClassifierBenchmarkView` still entry 1 for the runner that reads those values and asks the live model. +**This branch, file by file.** Every touched file once, with its gate number and the entry that covers it, so the account is complete and nobody has to reconstruct it: `StylistPrompt` 100% (at standard) · `Outfit` 100% (at standard) · `ClothingItem` 100% (at standard) · `Localization` 98.7% (entry 4, the live model probe default) · `UserSettings` 79.6% (entries 5 and 6) · `ComposerView` 82.2% (entry 1) · `WeatherService` 83.5% (entry 2) · `OutfitGenerator` 73.7% (entry 4) · `ReminderScheduler` 73.4% (entry 2) · `FitCheckApp` 56.80% (71/125, entry 6) · `HomeView` 41.0%, `RootView` 40.97% (320/781) (entry 1) · `OutfitGenerating` 100% (at standard) · `AppState` 99.13% (227/229) (entry 7) · `GarmentClassifier` 45.98% (entry 4; its prompt builder is 100%) · `ClosetView`, `ClosetCells`, `SettingsView`, `OutfitsView`, `SavedLookSheet`, `WeatherSheet`, `AddGarmentFlow`, `ProcessingViews`, `CameraController`, `OutfitResultView`, `GeneratingView`, `StoreRecoveryView`, `GarmentViews` 0–6%, `GlassComponents` 18.5% (entry 1). New on the closet-import branch: `ZipReader` and `ClosetImporter`, both at standard and absent from the allowlist — the reader is production code and the plan above it is pure. New on the classifier-benchmark branch: `FitCheckApp` 56.80% (71/125) (entry 6; `launchRoot` itself 100%) · `ClassifierBenchmarkView` 0.46% (entry 1, the Debug-only runner) · `SettingsView` 0.54% (entry 1, the Debug-only Diagnostics row) · and `ClassifierBenchmark` 100% (at standard): its comparison and its CSV are pure, and [`ClassifierBenchmarkTests`](FitCheckTests/ClassifierBenchmarkTests.swift) covers every branch of them, so it carries no allowlist line. New on the photo-policy branch: `PhotoSafety` is on the allowlist (entry 9) for its two adapters, while `PhotoVerdict` and the `PhotoIntake` decision above them are at standard through a fake `PhotoSafetyChecking`. New on the benchmark-attribution branch: `BenchmarkMetadata` 100% (at standard) — the header keys and the two enumerations behind them are values in and values out, so the CSV's opening block is provable without a device — and `ClassifierBenchmarkView` still entry 1 for the runner that reads those values and asks the live model. -**Final gate.** The board measured this batch against base `20a90fc`: 24 touched files, 5 at the standard (`TabSwipePolicy`, `ClassifierBenchmark`, `ClosetImporter`, `CutoutMatte`, `ZipReader`) and 19 allowlisted, with the suite green. +**Final gate.** The board measured this batch against base `20a90fc`: `ClassifierBenchmark`, `ClosetImporter`, `CutoutMatte` and `ZipReader` at the standard, the rest of the touched files allowlisted, with the suite green. ## Architecture diff --git a/FitCheck/App/AppState.swift b/FitCheck/App/AppState.swift index 55f8d9c..7083ec1 100644 --- a/FitCheck/App/AppState.swift +++ b/FitCheck/App/AppState.swift @@ -30,20 +30,8 @@ final class AppState { case failed(code: String, reason: ModelUnavailability? = nil) } - /// The four tabs in the order the bar draws them. That order is what "next" - /// and "previous" mean, so it is the declaration order and nothing else. - enum Tab: CaseIterable { + enum Tab { case home, closet, outfits, settings - - /// The tab one step along the bar — `1` for the next, `-1` for the - /// previous — or `nil` at either end. A swipe never wraps round, because - /// the bar has no ring either: the last tab has nothing after it. - func adjacent(by step: Int) -> Tab? { - guard let index = Self.allCases.firstIndex(of: self) else { return nil } - let target = index + step - guard Self.allCases.indices.contains(target) else { return nil } - return Self.allCases[target] - } } // MARK: - Init diff --git a/FitCheck/App/RootView.swift b/FitCheck/App/RootView.swift index cbc9323..fcf8c5c 100644 --- a/FitCheck/App/RootView.swift +++ b/FitCheck/App/RootView.swift @@ -190,10 +190,6 @@ private struct AppContent: View { // selected — the way back now that no screen carries a New Fit Check // button. Invisible, and it changes nothing else about the bar. .background { TabBarRetapReader { retapHomeTab() } } - // A sideways swipe on the content selects the tab beside it, through - // the same `app.tab` a tap writes, so the change is the bar's own - // rather than an animation of this view's. - .background { TabSwipeReader { swipeTabs(by: $0) } } .overlay(alignment: .bottom) { if app.isSelecting, app.tab == .closet { SelectionToolbar() @@ -300,17 +296,6 @@ private struct AppContent: View { app.reset() } - /// One step along the bar, from a swipe. - /// - /// Nothing happens while the selection toolbar is up: it stands in for the - /// bar, and leaving the closet would carry the tools onto a screen with - /// nothing selected on it. - private func swipeTabs(by step: Int) { - guard !app.isSelecting else { return } - guard let target = app.tab.adjacent(by: step) else { return } - app.tab = target - } - private func confirmDelete(_ item: ClothingItem) { // Read the context *now* and capture the value. `@Environment` is only // valid while the view graph is evaluating this view; a closure that @@ -350,6 +335,20 @@ extension View { // MARK: - Tab re-tap +/// An invisible view whose only job is to notice the window it lands in: the +/// re-tap recogniser has to live on the window to see a tap on the bar, which +/// is never this view's own. +/// +/// It takes no touches of its own. +private final class WindowAnchor: UIView { + var onWindow: ((UIWindow) -> Void)? + + override func didMoveToWindow() { + super.didMoveToWindow() + if let window { onWindow?(window) } + } +} + /// Runs `onRetap` when the wearer taps the tab bar item that is already /// selected. /// diff --git a/FitCheck/App/TabSwipePolicy.swift b/FitCheck/App/TabSwipePolicy.swift deleted file mode 100644 index 462d0dc..0000000 --- a/FitCheck/App/TabSwipePolicy.swift +++ /dev/null @@ -1,88 +0,0 @@ -import Foundation - -/// What the shell does with a sideways swipe, decided from the surface it -/// began on rather than from the recogniser that saw it. -/// -/// The rule is traits in, verdict out. Every question it asks is a value — is -/// this a slider, does the scroll view under it move sideways, is a sheet up — -/// so the unit target can argue with it directly, and the reader that holds the -/// UIKit recognisers is left with nothing but plumbing: fill a `Traits`, ask -/// the policy, forward the step when the answer is `takesTheStep`. -/// -/// The refusals are deliberate and up front rather than left to whichever -/// gesture wins the race. A sideways drag is already spoken for on the saved -/// looks list (a row opens its own actions), the tab bar (its lens follows a -/// finger across it), a slider (the thumb is dragged), and any horizontal -/// scroller — the closet's chip row, a carousel. Anything else is the shell's, -/// including the closet's grid and list: they scroll vertically, so a sideways -/// drag across them asks for another tab. -/// -/// The closet garment card is outside this rule rather than refused by it. Its -/// press-and-drag starts selection and takes the touch before a window -/// recogniser is offered it, so it needs no trait and no verdict could give the -/// drag back. A swipe across the closet starts on its plain bands instead. -enum TabSwipePolicy { - - /// The surface under the finger, as far as this rule is concerned. - /// - /// Every field is an observation, never a decision: the reader fills them in - /// and the verdict is worked out in one place. - struct Traits: Equatable, Sendable { - /// VoiceOver or Switch Control is running: a one-finger sideways drag - /// reads the screen, so nothing on it belongs to the shell. - var readsTheScreen = false - /// A sheet, a cover or an alert is presented over the tabs. - var isUnderAPresentation = false - /// The touch starts on a control that drags its own thumb. - var isSlider = false - /// A scroll view between the touch and the window can move sideways. - var isHorizontalScroller = false - /// The touch starts on the tab bar. - var isTabBar = false - /// The touch starts inside the saved looks list, whose rows carry - /// swipe actions. Observed by identifier, never by cell type: the - /// closet's grid and list are built from the same kinds of cell. - var isSavedOutfitsList = false - } - - /// What the shell does with a swipe that began on these traits. - enum Verdict: Equatable, Sendable { - /// Nothing under the finger claims a sideways drag: one step. - case takesTheStep - /// Something already answers this drag, and keeps it whole. - case standsAside(Reason) - } - - /// Which surface the shell stood aside for. - enum Reason: Equatable, Sendable, CaseIterable { - case readsTheScreen - case slider - case horizontalScroller - case tabBar - case savedOutfitsList - case presentation - } - - /// The identifier the saved looks list carries, so the reader can recognise - /// its rows from the hierarchy without knowing how `List` builds them, and - /// the list itself does not have to leak a `UICollectionViewCell` type test. - static let savedOutfitsListIdentifier = "savedOutfitsList" - - /// The rule, in one order. - /// - /// The order is precedence, not performance: a touch can sit on several of - /// these at once — a slider inside a presented sheet, a row under a screen - /// reader — and the verdict names the one that made the shell stand aside. - /// The screen reader comes first because it is the reason no drag on the - /// screen is the shell's at all; the surfaces follow in the order a finger - /// would meet them, and the presentation last because it is the widest. - static func verdict(for traits: Traits) -> Verdict { - if traits.readsTheScreen { return .standsAside(.readsTheScreen) } - if traits.isSlider { return .standsAside(.slider) } - if traits.isHorizontalScroller { return .standsAside(.horizontalScroller) } - if traits.isTabBar { return .standsAside(.tabBar) } - if traits.isSavedOutfitsList { return .standsAside(.savedOutfitsList) } - if traits.isUnderAPresentation { return .standsAside(.presentation) } - return .takesTheStep - } -} diff --git a/FitCheck/App/TabSwipeReader.swift b/FitCheck/App/TabSwipeReader.swift deleted file mode 100644 index ef94521..0000000 --- a/FitCheck/App/TabSwipeReader.swift +++ /dev/null @@ -1,250 +0,0 @@ -import SwiftUI -import UIKit - -/// A horizontal swipe across a tab's content selects the tab beside it. -/// -/// The gesture belongs to the shell, so Fit Check, the closet, the looks and -/// Settings all get it from one place and no screen carries gesture code of its -/// own. It watches and never takes: the system's bar stays untouched, no -/// `UITabBarController` delegate is replaced, and `cancelsTouchesInView` is off, -/// so every touch still reaches the view under the finger. -/// -/// Watching is also why it has to stand aside deliberately. A sideways drag is -/// already spoken for in five places — the closet's chip row scrolls, a saved -/// look row swipes open its actions, the cold-sensitivity slider drags its own -/// thumb, the bar's lens follows a finger across it, and a sheet is its own -/// surface — so the delegate below refuses a swipe that starts on any of them -/// rather than competing for the drag. Nothing it refuses is cancelled or -/// delayed: the view that owns the drag keeps it whole. -/// -/// Which touches those are is not decided here: `TabSwipePolicy` holds the rule -/// as traits in and verdict out, so the rule is unit-tested and this file only -/// fills the traits in from the view hierarchy it is looking at. Everything the -/// policy allows is the shell's, including the closet's grid and list — they -/// scroll vertically, not sideways, and their cards claim nothing. -/// -/// The closet's garment-card drag is the one surface deliberately *not* -/// modelled. A card's press-and-drag selection is its own recogniser and takes -/// the touch before a window recogniser can be handed it, so refusing it here -/// would only mean refusing the grid around it — and that would leave the -/// closet without the swipe at all. The card keeps its drag; a swipe across the -/// closet starts on its plain bands, as the UI test does. -/// -/// Under VoiceOver and Switch Control a one-finger sideways drag is how the -/// screen is read, so the recognisers stay out of it entirely and the bar -/// remains their way across. -/// -/// The direction-to-tab mapping is not here: the swipe reports one step forward -/// or back, and `AppState.Tab.adjacent(by:)` is the single place that says what -/// the next tab is — including the `nil` at either end that makes it never wrap. -struct TabSwipeReader: UIViewRepresentable { - /// One step along the bar: `1` is the next tab, `-1` the previous. - let onSwipe: (Int) -> Void - - func makeCoordinator() -> Coordinator { Coordinator(onSwipe: onSwipe) } - - func makeUIView(context: Context) -> UIView { - let anchor = WindowAnchor() - anchor.onWindow = { [weak coordinator = context.coordinator] window in - coordinator?.attach(to: window) - } - return anchor - } - - func updateUIView(_ uiView: UIView, context: Context) { - context.coordinator.onSwipe = onSwipe - } - - static func dismantleUIView(_ uiView: UIView, coordinator: Coordinator) { - coordinator.detach() - } - - @MainActor - final class Coordinator: NSObject, UIGestureRecognizerDelegate { - var onSwipe: (Int) -> Void - - /// One finger, sixty points sideways: any less is a sloppy tap on a card - /// rather than a request for another tab. The system's own swipe - /// threshold is undocumented, so the shell states its own on top of it. - private static let minimumTravel: CGFloat = 60 - - /// Left is forward: the content leaves to the left and the tab after it - /// arrives from the right, which is the order the bar draws. - private static let steps: [(direction: UISwipeGestureRecognizer.Direction, step: Int)] = [ - (.left, 1), - (.right, -1), - ] - - private weak var window: UIWindow? - private var swipes: [TabSwipeGestureRecognizer] = [] - - init(onSwipe: @escaping (Int) -> Void) { - self.onSwipe = onSwipe - } - - /// One pair of recognisers per window, moved when SwiftUI hands the view - /// to another window rather than stacked on top of the previous. - func attach(to window: UIWindow) { - guard self.window !== window else { return } - detach() - - for entry in Self.steps { - let swipe = TabSwipeGestureRecognizer( - target: self, - action: #selector(handleSwipe(_:)) - ) - swipe.direction = entry.direction - swipe.numberOfTouchesRequired = 1 - // The touch belongs to whatever is under the finger: this must - // neither cancel it nor hold its end back. - swipe.cancelsTouchesInView = false - swipe.delaysTouchesEnded = false - swipe.delegate = self - window.addGestureRecognizer(swipe) - swipes.append(swipe) - } - - self.window = window - } - - func detach() { - for swipe in swipes { swipe.view?.removeGestureRecognizer(swipe) } - swipes = [] - window = nil - } - - @objc private func handleSwipe(_ swipe: TabSwipeGestureRecognizer) { - guard swipe.state == .ended, - let travel = swipe.horizontalTravel, - travel >= Self.minimumTravel, - let step = Self.steps.first(where: { $0.direction == swipe.direction })?.step - else { return } - - onSwipe(step) - } - - /// A scroll view's own pan shares the drag with this one: every tab's - /// content scrolls, that pan begins on the same touch, and refusing to - /// recognise alongside it left the swipe dead on all four tabs. - /// - /// Sharing is safe because anything that owns a sideways drag was - /// already refused the touch below: this grants coexistence with a - /// vertical scroll, never with a row or a control that wants the drag - /// for itself. - func gestureRecognizer( - _ gestureRecognizer: UIGestureRecognizer, - shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer - ) -> Bool { - return true - } - - /// Only a touch that starts on plain content is worth watching. - /// - /// The refusal is deliberate and up front, not left to whatever wins - /// the race: at the end of a drag this recogniser competes with a List - /// row, the bar's lens, a slider's thumb and the chip row's own pan, - /// and the touch is gone before the swipe can be told apart from them. - /// Standing aside on the first touch keeps the rosette of simultaneous - /// recognition for the vertical scroll it is actually needed for. - func gestureRecognizer( - _ gestureRecognizer: UIGestureRecognizer, - shouldReceive touch: UITouch - ) -> Bool { - guard let view = touch.view else { return false } - return TabSwipePolicy.verdict(for: Self.traits(for: view)) == .takesTheStep - } - - /// A one-finger sideways drag reads the screen under these, so the - /// shell's swipe would be intercepted at the reader's expense. - private static var isReadingScreen: Bool { - UIAccessibility.isVoiceOverRunning || UIAccessibility.isSwitchControlRunning - } - - /// Everything the policy asks about the surface under the finger, - /// measured from the view and the views it sits in. - /// - /// The saved looks are recognised by identifier rather than by type: - /// every `List` row is a collection-view cell, and refusing the type - /// would refuse the closet's grid and list along with them. - private static func traits(for view: UIView) -> TabSwipePolicy.Traits { - var traits = TabSwipePolicy.Traits( - readsTheScreen: isReadingScreen, - isUnderAPresentation: isUnderAPresentation(view) - ) - - var current: UIView? = view - while let candidate = current { - if candidate is UISlider { traits.isSlider = true } - if candidate is UITabBar { traits.isTabBar = true } - if candidate.accessibilityIdentifier == TabSwipePolicy.savedOutfitsListIdentifier { - traits.isSavedOutfitsList = true - } - if let scrollView = candidate as? UIScrollView, - scrollsHorizontally(scrollView) { - traits.isHorizontalScroller = true - } - current = candidate.superview - } - - return traits - } - - /// A scroll view is the finger's when it can move sideways: the closet's - /// chip row, a paging carousel. The vertical ones — every tab's content — - /// are not, and a sideways drag across them is still the shell's. - private static func scrollsHorizontally(_ scrollView: UIScrollView) -> Bool { - if scrollView.alwaysBounceHorizontal || scrollView.isPagingEnabled { return true } - if let collection = scrollView as? UICollectionView, - (collection.collectionViewLayout as? UICollectionViewFlowLayout)?.scrollDirection - == .horizontal { - return true - } - // A point of slack absorbs the fractional rounding a layout leaves - // behind; a content column that is genuinely wider is not slack. - return scrollView.contentSize.width > scrollView.bounds.width + 1 - } - - /// A sheet, a cover or an alert is presented over the tabs and owns the - /// whole screen while it is up: a drag inside one never reaches the bar. - private static func isUnderAPresentation(_ view: UIView) -> Bool { - guard let root = view.window?.rootViewController else { return false } - return root.presentedViewController != nil - } - } -} - -/// An invisible view whose only job is to notice the window it lands in: a -/// recogniser has to live on the window to see a swipe anywhere on screen. -/// -/// It takes no touches of its own, and both shell arguments share it. -final class WindowAnchor: UIView { - var onWindow: ((UIWindow) -> Void)? - - override func didMoveToWindow() { - super.didMoveToWindow() - if let window { onWindow?(window) } - } -} - -/// The system's swipe, with the one thing it does not publish: where the finger -/// came down, and so how far it travelled. -private final class TabSwipeGestureRecognizer: UISwipeGestureRecognizer { - private var start: CGPoint? - - override func touchesBegan(_ touches: Set, with event: UIEvent) { - if start == nil { start = touches.first?.location(in: view) } - super.touchesBegan(touches, with: event) - } - - override func reset() { - super.reset() - start = nil - } - - /// How far the finger travelled sideways from where it came down. `nil` - /// before a touch lands and after `reset()`. - var horizontalTravel: CGFloat? { - guard let start, let view else { return nil } - return abs(location(in: view).x - start.x) - } -} diff --git a/FitCheck/Features/Outfits/OutfitsView.swift b/FitCheck/Features/Outfits/OutfitsView.swift index 6e4e07e..85271ad 100644 --- a/FitCheck/Features/Outfits/OutfitsView.swift +++ b/FitCheck/Features/Outfits/OutfitsView.swift @@ -91,11 +91,6 @@ struct OutfitsView: View { /// the full-swipe, the rubber-banding and the VoiceOver actions that come /// with it. The list's own chrome is stripped back to the card layout the /// rest of the app uses. - /// - /// The identifier is what tells the shell's swipe reader that the rows under - /// a finger here own their sideways drag, so it stands aside for them — - /// and only for them: the closet's grid and list scroll the same way and - /// still hand the drag to the shell. private var list: some View { List { ForEach(outfits) { outfit in @@ -137,7 +132,6 @@ struct OutfitsView: View { .listStyle(.plain) .scrollContentBackground(.hidden) .scrollIndicators(.hidden) - .accessibilityIdentifier(TabSwipePolicy.savedOutfitsListIdentifier) } private var emptyState: some View { diff --git a/FitCheckTests/AppStateTests.swift b/FitCheckTests/AppStateTests.swift index 9e0503b..52027b9 100644 --- a/FitCheckTests/AppStateTests.swift +++ b/FitCheckTests/AppStateTests.swift @@ -275,50 +275,3 @@ struct AppStateTests { #expect(testSubject.exclusionSet.isEmpty) } } - -/// The bar walks in one direction and has two ends, not a ring: a swipe asks -/// for one step and the tab answers with the neighbour the bar draws beside it, -/// or with nothing at all past the first and the last. The mapping lives here so -/// the gesture layer only ever reports a step. -@Suite("Tab adjacency") -struct TabAdjacencyTests { - - @Test( - "One step forward lands on the tab the bar draws next", - arguments: [ - (AppState.Tab.home, AppState.Tab.closet), - (.closet, .outfits), - (.outfits, .settings), - ] - ) - func forward(from tab: AppState.Tab, to neighbour: AppState.Tab) { - let testSubject = tab - #expect(testSubject.adjacent(by: 1) == neighbour) - } - - @Test( - "One step back lands on the tab the bar draws before it", - arguments: [ - (AppState.Tab.settings, AppState.Tab.outfits), - (.outfits, .closet), - (.closet, .home), - ] - ) - func back(from tab: AppState.Tab, to neighbour: AppState.Tab) { - let testSubject = tab - #expect(testSubject.adjacent(by: -1) == neighbour) - } - - /// No wrap: the ends are ends, and nothing is invented past them. - @Test( - "The first and the last tab have no neighbour past their end", - arguments: [ - (AppState.Tab.home, -1), - (AppState.Tab.settings, 1), - ] - ) - func edges(tab: AppState.Tab, step: Int) { - let testSubject = tab - #expect(testSubject.adjacent(by: step) == nil) - } -} diff --git a/FitCheckTests/TabSwipePolicyTests.swift b/FitCheckTests/TabSwipePolicyTests.swift deleted file mode 100644 index 3e3dbab..0000000 --- a/FitCheckTests/TabSwipePolicyTests.swift +++ /dev/null @@ -1,111 +0,0 @@ -import Testing -@testable import FitCheck - -/// The shell's refusal rule, argued as a value. -/// -/// Each row is a surface and the verdict it has to earn: the five that already -/// answer a sideways drag keep it, plain content hands it to the shell, and the -/// reading modes take the whole screen. The reader that installs the -/// recognisers only fills these traits in, so this is where the rule is proved. -@Suite("Tab swipe policy") -struct TabSwipePolicyTests { - - /// One surface, its traits, and the verdict those traits have to produce. - struct Case: Sendable, CustomTestStringConvertible { - let name: String - let traits: TabSwipePolicy.Traits - let verdict: TabSwipePolicy.Verdict - - var testDescription: String { name } - } - - /// A touch that lands on plain content: nothing under it drags sideways. - private static let plain = TabSwipePolicy.Traits() - - static let cases: [Case] = [ - Case( - name: "plain content takes the step", - traits: plain, - verdict: .takesTheStep - ), - Case( - name: "a slider keeps its thumb's drag", - traits: TabSwipePolicy.Traits(isSlider: true), - verdict: .standsAside(.slider) - ), - Case( - name: "a horizontal scroller keeps its pan", - traits: TabSwipePolicy.Traits(isHorizontalScroller: true), - verdict: .standsAside(.horizontalScroller) - ), - Case( - name: "the tab bar keeps its lens's drag", - traits: TabSwipePolicy.Traits(isTabBar: true), - verdict: .standsAside(.tabBar) - ), - Case( - name: "a saved look row keeps its swipe actions", - traits: TabSwipePolicy.Traits(isSavedOutfitsList: true), - verdict: .standsAside(.savedOutfitsList) - ), - Case( - name: "a presented sheet is its own surface", - traits: TabSwipePolicy.Traits(isUnderAPresentation: true), - verdict: .standsAside(.presentation) - ), - Case( - name: "a screen reader reads the drag instead", - traits: TabSwipePolicy.Traits(readsTheScreen: true), - verdict: .standsAside(.readsTheScreen) - ), - Case( - name: "the screen reader outranks the control under the finger", - traits: TabSwipePolicy.Traits(readsTheScreen: true, isSlider: true), - verdict: .standsAside(.readsTheScreen) - ), - Case( - name: "a control outranks the sheet it sits in", - traits: TabSwipePolicy.Traits(isUnderAPresentation: true, isTabBar: true), - verdict: .standsAside(.tabBar) - ), - Case( - name: "a saved look outranks the sheet it sits in", - traits: TabSwipePolicy.Traits(isUnderAPresentation: true, isSavedOutfitsList: true), - verdict: .standsAside(.savedOutfitsList) - ), - Case( - name: "a slider outranks the row it sits in", - traits: TabSwipePolicy.Traits(isSlider: true, isHorizontalScroller: true), - verdict: .standsAside(.slider) - ), - Case( - name: "everything at once is still refused", - traits: TabSwipePolicy.Traits( - readsTheScreen: true, - isUnderAPresentation: true, - isSlider: true, - isHorizontalScroller: true, - isTabBar: true, - isSavedOutfitsList: true - ), - verdict: .standsAside(.readsTheScreen) - ), - ] - - @Test("The shell steps only where nothing else owns the drag", arguments: cases) - func verdict(for testCase: Case) { - let testSubject = TabSwipePolicy.self - - #expect(testSubject.verdict(for: testCase.traits) == testCase.verdict) - } - - /// The identifier is the agreement between the saved looks list and the - /// reader: the view tags itself with it and the reader looks for it, so a - /// rename on one side alone would silently give the rows back to the shell. - @Test("The saved looks list is recognised by the identifier it carries") - func savedOutfitsListIdentifier() { - let testSubject = TabSwipePolicy.self - - #expect(testSubject.savedOutfitsListIdentifier == "savedOutfitsList") - } -} diff --git a/FitCheckUITests/TabNavigationUITests.swift b/FitCheckUITests/TabNavigationUITests.swift new file mode 100644 index 0000000..6c5df9c --- /dev/null +++ b/FitCheckUITests/TabNavigationUITests.swift @@ -0,0 +1,165 @@ +import XCTest + +/// A sideways swipe across a tab's content changes no tab. +/// +/// The shell used to carry a window-level swipe recogniser that walked the bar +/// one tab per drag. It is gone on purpose: a deliberate sideways drag belongs +/// to the screen under the finger — a row's swipe actions, a chip row, a slider +/// — and the bar is the one way across. This guard exists so the gesture cannot +/// come back unnoticed, and it reads the app the way a person does: the bar's +/// own selected item plus the first thing the tab draws. +final class TabNavigationUITests: XCTestCase { + + /// The four tabs, in the order the bar draws them. + private enum Tab: String { + case home = "Fit Check" + case closet = "Closet" + case outfits = "Outfits" + case settings = "Settings" + + /// The first thing the tab draws, so a selection is read off the screen + /// and not only off the bar. The saved look is a row, so it is found by + /// its identifier; everything else is plain text. + var marker: String { + switch self { + case .home: "Ready for a Fit Check?" + case .closet: "5 items · background removed on device" + case .outfits: "savedLook-Everyday Layers" + case .settings: "Appearance" + } + } + + var markerIsControl: Bool { self == .outfits } + } + + /// Left is forward, right is back — the direction the old shell read as one + /// step along the bar. + private enum Direction { + case forward + case back + } + + private var app: XCUIApplication! + + override func setUpWithError() throws { + continueAfterFailure = false + app = XCUIApplication() + app.launchArguments += [ + "-uiTesting", "-seedCloset", + "-AppleLocale", "en_US", + ] + app.launch() + } + + // MARK: - Reading the shell + + private var bar: XCUIElement { app.tabBars.firstMatch } + + private func tabButton(_ tab: Tab) -> XCUIElement { + bar.buttons[tab.rawValue].firstMatch + } + + private func markerElement(for tab: Tab) -> XCUIElement { + tab.markerIsControl ? app.buttons[tab.marker] : app.staticTexts[tab.marker] + } + + /// The selected tab, read off the bar and confirmed on the screen. + /// + /// Both halves matter: the bar is what a person checks first, and the + /// screen is what proves the tab behind it actually moved. + private func assertSelected( + _ tab: Tab, + file: StaticString = #filePath, + line: UInt = #line + ) { + let button = tabButton(tab) + XCTAssertTrue( + button.waitForExistence(timeout: 10), + "The \(tab.rawValue) tab should be in the bar", + file: file, + line: line + ) + XCTAssertTrue( + button.isSelected, + "The bar should still have \(tab.rawValue) selected", + file: file, + line: line + ) + XCTAssertTrue( + markerElement(for: tab).firstMatch.waitForExistence(timeout: 10), + "\(tab.rawValue) should still be the tab on screen", + file: file, + line: line + ) + } + + // MARK: - The swipe + + /// A fast one-finger drag from one edge of the screen to the other, along + /// the band the tab's own marker sits on. + /// + /// The marker's band is the plainest content the tab has: a text label owns + /// no gesture of its own, so the drag is delivered whole and there is no + /// refusal to explain a quiet result away. A drag that begins on a saved + /// look row or a garment card would start something the screen owns, and + /// passing then would prove nothing about the shell. + private func swipeContent(of tab: Tab, toward direction: Direction) { + let marker = markerElement(for: tab).firstMatch + let band = marker.frame.midY / app.frame.height + let leading = app.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: band)) + let trailing = app.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: band)) + + switch direction { + case .forward: + trailing.press( + forDuration: 0.05, thenDragTo: leading, + withVelocity: .fast, thenHoldForDuration: 0 + ) + case .back: + leading.press( + forDuration: 0.05, thenDragTo: trailing, + withVelocity: .fast, thenHoldForDuration: 0 + ) + } + } + + private func capture(_ name: String) { + let attachment = XCTAttachment(screenshot: app.screenshot()) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } + + // MARK: - The promise + + /// The regression guard: a fast sideways drag on the content, in both + /// directions, leaves the selected tab exactly where it was on more than + /// one tab — so neither a first nor a last tab can be reached by accident. + func testASidewaysSwipeOnTheContentChangesNoTab() { + for tab in [Tab.home, Tab.closet] { + tabButton(tab).tap() + assertSelected(tab) + + for direction in [Direction.forward, .back] { + swipeContent(of: tab, toward: direction) + assertSelected(tab) + } + + capture("82-\(tab.rawValue)-keeps-its-tab") + } + } + + /// The bar still works: a tap moves to the tab beside it, with the screen + /// following. Without this, a shell that ignored every touch would pass the + /// guard above. + func testTappingATabStillSwitchesTheScreen() { + assertSelected(.home) + + for tab in [Tab.closet, .outfits, .home] { + tabButton(tab).tap() + assertSelected(tab) + } + + capture("82-tap-returns-home") + } +} diff --git a/FitCheckUITests/TabSwipeUITests.swift b/FitCheckUITests/TabSwipeUITests.swift deleted file mode 100644 index 6d16a6a..0000000 --- a/FitCheckUITests/TabSwipeUITests.swift +++ /dev/null @@ -1,423 +0,0 @@ -import XCTest - -/// The shell's sideways swipe: the content moves to the tab beside it, stops at -/// both ends, and nothing that already owns a sideways drag loses it. -/// -/// The bar is the app's, so the tab selection is read the way a person reads it: -/// the bar's own selected item, and the first thing the tab draws. The language -/// comes from the simulator, which the run sets to English: the app's own -/// language setting follows the device, and forcing it here would hide that. -final class TabSwipeUITests: XCTestCase { - - /// The four tabs, in the order the bar draws them — which is also the order - /// the swipe walks, and the reason "the next one" means nothing else. - private enum Tab: String, CaseIterable { - case home = "Fit Check" - case closet = "Closet" - case outfits = "Outfits" - case settings = "Settings" - - /// The first thing the tab draws, so a selection is confirmed on the - /// screen and not only on the bar. - var marker: String { - switch self { - case .home: "Ready for a Fit Check?" - case .closet: "5 items · background removed on device" - case .outfits: SavedLook.row - case .settings: "Appearance" - } - } - } - - /// What `-seedCloset` puts in the store. - private enum SavedLook { - static let name = "Everyday Layers" - static let row = "savedLook-\(name)" - } - - private enum Direction { - case forward - case back - } - - /// The two type settings every capture is taken at: the platform's own, and - /// the largest accessibility size, where the bar is at its widest. - private static let typeSettings: [(name: String, arguments: [String])] = [ - ("default", []), - ("ax5", ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]), - ] - - private var app: XCUIApplication! - - override func setUpWithError() throws { - continueAfterFailure = false - app = XCUIApplication() - app.launchArguments += [ - "-uiTesting", "-seedCloset", - "-AppleLocale", "en_US", - ] - app.launch() - } - - // MARK: - Reading the shell - - private var bar: XCUIElement { app.tabBars.firstMatch } - - private func tabButton(_ tab: Tab) -> XCUIElement { - bar.buttons[tab.rawValue].firstMatch - } - - /// The selected tab, read off the bar and confirmed on the screen. - /// - /// The screen matters as much as the bar: a swipe that wrote the selection - /// without moving the content would leave the bar pointing at a tab that is - /// not drawn. - private func assertSelected( - _ tab: Tab, - file: StaticString = #filePath, - line: UInt = #line - ) { - let button = tabButton(tab) - XCTAssertTrue( - button.waitForExistence(timeout: 10), - "The \(tab.rawValue) tab should be in the bar", - file: file, - line: line - ) - XCTAssertTrue( - button.isSelected, - "The bar should have \(tab.rawValue) selected", - file: file, - line: line - ) - - let marker = tab == .outfits ? app.buttons[tab.marker] : app.staticTexts[tab.marker] - XCTAssertTrue( - marker.firstMatch.waitForExistence(timeout: 10), - "\(tab.rawValue) should be the tab on screen", - file: file, - line: line - ) - } - - /// A swipe across the tab's content, near the top of it and never through - /// the middle of the screen. - /// - /// `app.swipeLeft()` starts at the app's centre, which is whatever the tab - /// happens to be drawing there — on Outfits that is the saved-look row, a - /// `List` cell that owns its own sideways drag, so the shell correctly - /// refuses the touch before the direction can be told. The tab's own header - /// band is plain content by construction: the drag goes across it, from one - /// edge of the screen to the other. - private func swipeContent(_ direction: Direction) { - let crossing = contentCrossing - switch direction { - case .forward: - crossing.right.press( - forDuration: 0.05, thenDragTo: crossing.left, - withVelocity: .fast, thenHoldForDuration: 0 - ) - case .back: - crossing.left.press( - forDuration: 0.05, thenDragTo: crossing.right, - withVelocity: .fast, thenHoldForDuration: 0 - ) - } - } - - /// Where a swipe may be put down on the tab that is up. - /// - /// A tab that draws a `List` hands every point below its first row to a - /// collection-view cell, which the shell stands aside for: the swipe has to - /// stay above it. The rest draw grids, forms and fields that do not own a - /// sideways drag, so the top third of the page is plain everywhere. - private var contentCrossing: (left: XCUICoordinate, right: XCUICoordinate) { - let height = app.frame.height - let rowTop = app.cells.allElementsBoundByIndex.map { $0.frame.minY }.min() - // Just above the first row when there is one, at the top third of the - // page otherwise. - let y = rowTop.map { $0 * 0.75 } ?? height * 0.3 - let offset = CGVector(dx: 0, dy: y / height) - let anchor = app.coordinate(withNormalizedOffset: offset) - return ( - left: anchor.withOffset(CGVector(dx: app.frame.width * 0.2, dy: 0)), - right: anchor.withOffset(CGVector(dx: app.frame.width * 0.8, dy: 0)) - ) - } - - private func capture(_ name: String) { - let attachment = XCTAttachment(screenshot: app.screenshot()) - attachment.name = name - attachment.lifetime = .keepAlways - add(attachment) - } - - /// Relaunches with a type setting of this test's own, keeping the language - /// and the seeded store. - private func relaunch(typeSetting: [String]) { - app.terminate() - app = XCUIApplication() - app.launchArguments = - ["-uiTesting", "-seedCloset"] - + typeSetting - + ["-AppleLocale", "en_US"] - app.launch() - } - - // MARK: - The walk - - /// Forward is left, back is right, and each step lands on the tab the bar - /// draws beside the one before it. - func testSwipeWalksForwardAndBackThroughTheTabs() { - assertSelected(.home) - - swipeContent(.forward) - assertSelected(.closet) - - swipeContent(.forward) - assertSelected(.outfits) - - swipeContent(.forward) - assertSelected(.settings) - capture("55-swipe-forward-settings") - - swipeContent(.back) - assertSelected(.outfits) - - swipeContent(.back) - assertSelected(.closet) - capture("55-swipe-back-closet") - - swipeContent(.back) - assertSelected(.home) - } - - /// The same walk at the default size and at AX5, so the captures show the - /// bar and the content agreeing at both. - func testSwipeSelectsTheNextTabAtEveryTextSize() { - for setting in Self.typeSettings { - relaunch(typeSetting: setting.arguments) - - assertSelected(.home) - swipeContent(.forward) - assertSelected(.closet) - capture("55-tab-swipe-closet-\(setting.name)") - - swipeContent(.forward) - assertSelected(.outfits) - capture("55-tab-swipe-outfits-\(setting.name)") - - swipeContent(.back) - assertSelected(.closet) - } - } - - /// The bar has two ends, not a ring: no swipe past the first or the last tab - /// changes anything. - func testSwipeDoesNotWrapAtEitherEnd() { - tabButton(.settings).tap() - assertSelected(.settings) - - swipeContent(.forward) - assertSelected(.settings) - capture("55-swipe-past-last-tab") - - tabButton(.home).tap() - assertSelected(.home) - - swipeContent(.back) - assertSelected(.home) - capture("55-swipe-before-first-tab") - } - - // MARK: - Content the shell takes - - /// The closet's count band is plain content, so a sideways drag across it - /// asks for the next tab. - /// - /// The band is the line the tab draws above its cards, beside the layout - /// toggle, and it is what the refusal rule has to keep: the saved look rows - /// are the only list the shell stands aside for, and a rule written as - /// "every collection-view cell keeps the drag" would leave this dead. The - /// cards below it are the carve-out — their press-and-drag starts selection - /// and takes the touch before the window recogniser is offered it — so the - /// drag starts on the count line instead. - func testSwipingAcrossTheClosetCountBandTakesTheStep() { - tabButton(.closet).tap() - assertSelected(.closet) - - let count = app.staticTexts[Tab.closet.marker].firstMatch - XCTAssertTrue( - count.waitForExistence(timeout: 10), - "The closet should draw its count band" - ) - XCTAssertTrue( - count.isHittable, - "The count band should be on screen without scrolling" - ) - - // The finger comes down on the count line and leaves for the leading - // edge, so the drag is longer than the shell's threshold and stays on - // the band the whole way. - let band = count.frame.midY / app.frame.height - let start = count.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - let end = app.coordinate(withNormalizedOffset: CGVector(dx: 0.05, dy: band)) - start.press( - forDuration: 0.05, thenDragTo: end, - withVelocity: .fast, thenHoldForDuration: 0 - ) - - assertSelected(.outfits) - capture("55-closet-count-band-takes-the-step") - } - - // MARK: - Controls that keep their own drag - - /// The closet's chip row scrolls sideways on its own; a drag across a chip - /// is a scroll, not a request for the next tab. - func testSwipeOnTheFilterChipsLeavesTheTabAlone() { - tabButton(.closet).tap() - assertSelected(.closet) - - // The row scrolls, so a category past the fold would make this a test - // about reachability rather than about the drag: "All garments" is the - // one chip the print fixes at the leading edge, and it is what the - // finger comes down on. The drag then runs along the row's own band, - // which is the surface that has to keep the gesture. - let chip = app.buttons["All garments"].firstMatch - XCTAssertTrue(chip.waitForExistence(timeout: 10), "The closet should offer its filters") - XCTAssertTrue(chip.isHittable, "The All garments chip should be on screen without scrolling") - - let band = chip.frame.midY / app.frame.height - let leading = app.coordinate(withNormalizedOffset: CGVector(dx: 0.05, dy: band)) - let trailing = app.coordinate(withNormalizedOffset: CGVector(dx: 0.85, dy: band)) - trailing.press(forDuration: 0.05, thenDragTo: leading) - leading.press(forDuration: 0.05, thenDragTo: trailing) - - assertSelected(.closet) - capture("55-chips-keep-the-tab") - } - - /// The cold-sensitivity slider drags its own thumb. The drag has to move the - /// value — that is the proof the slider kept the gesture — and the tab has - /// to stay where it was. - func testDraggingTheColdSensitivitySliderLeavesTheTabAlone() { - tabButton(.settings).tap() - assertSelected(.settings) - - let slider = app.sliders["Cold Sensitivity"].firstMatch - XCTAssertTrue(slider.waitForExistence(timeout: 10), "Settings should offer the cold slider") - // The slider sits below the first screenful, and XCUITest scrolls for a - // tap but not for a drag: it has to be on screen before the finger can - // start on it. - for _ in 0..<4 where !slider.isHittable { app.swipeUp() } - XCTAssertTrue(slider.isHittable, "The cold slider should be reachable by scrolling") - - // The thumb starts on the middle stop, so the finger has to come down - // there: a drag that begins on the bare track is the slider jumping to - // the touch, not a thumb being dragged, and it proves nothing about who - // owns a drag that started on the control. - XCTAssertEqual(slider.value as? String, "Normal", "The slider should start on the middle stop") - - let thumb = slider.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - let hotEnd = slider.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)) - thumb.press(forDuration: 0.1, thenDragTo: hotEnd) - - XCTAssertEqual( - slider.value as? String, - "Runs hot", - "The slider must keep its own drag and settle on the hot stop" - ) - // The bar minimises on a scroll, so the screen is what says which tab - // is up: Settings' own row is on it, and no other tab draws it. - XCTAssertTrue( - app.staticTexts["Cold Sensitivity"].exists, - "Settings must still be the tab on screen" - ) - XCTAssertFalse( - app.staticTexts["Ready for a Fit Check?"].exists, - "The drag must not have left Settings" - ) - capture("55-slider-keeps-the-tab") - } - - /// A saved look row swipes open its actions, which is a sideways drag the - /// row owns. The tab behind it must not follow the finger. - func testSwipingASavedLookKeepsItsActionsAndTheTab() { - tabButton(.outfits).tap() - assertSelected(.outfits) - - let row = app.buttons[SavedLook.row].firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 10), "The seeded look should be listed") - row.swipeLeft() - - XCTAssertTrue( - app.buttons["Delete"].firstMatch.waitForExistence(timeout: 5), - "The look's own swipe action should open" - ) - assertSelected(.outfits) - capture("55-saved-look-keeps-the-tab") - } - - // MARK: - Everything else that is not the shell's - - /// A vertical drag scrolls; it never asks for another tab. Settings is the - /// long page, so the scroll is real, and scrolling back restores the top. - func testVerticalScrollingNeverChangesTheTab() { - tabButton(.settings).tap() - assertSelected(.settings) - - app.swipeUp() - app.swipeUp() - app.swipeDown() - app.swipeDown() - - XCTAssertTrue( - app.staticTexts["Appearance"].waitForExistence(timeout: 10), - "Settings should be back at the top of its own scroll" - ) - assertSelected(.settings) - } - - /// A sheet is its own surface: a swipe inside the saved look sheet moves - /// nothing behind it. - func testSwipeInsideASheetLeavesTheTabAlone() { - tabButton(.outfits).tap() - - let row = app.buttons[SavedLook.row].firstMatch - XCTAssertTrue(row.waitForExistence(timeout: 10), "The seeded look should be listed") - row.tap() - - let sheet = app.descendants(matching: .any)["savedLookSheet"].firstMatch - XCTAssertTrue(sheet.waitForExistence(timeout: 5), "The look's sheet should open") - - app.swipeLeft() - app.swipeRight() - - XCTAssertTrue(sheet.exists, "The sheet should still be up after a swipe inside it") - assertSelected(.outfits) - capture("55-sheet-keeps-the-tab") - } - - /// The bar's lens follows a finger across the bar by itself. The drag lands - /// on Outfits, and that — exactly one step — is what the shell must leave - /// it at: proving only "not Settings" would pass even if the shell never - /// received the drag at all. - func testDraggingAcrossTheBarTakesOnlyTheBarsStep() { - tabButton(.closet).tap() - assertSelected(.closet) - - let from = tabButton(.closet).coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - let to = tabButton(.outfits).coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)) - from.press(forDuration: 0.1, thenDragTo: to) - - // The bar picked Outfits itself; the shell adding its own step would - // have carried the selection on to Settings. - assertSelected(.outfits) - XCTAssertFalse( - app.tabBars.buttons[Tab.settings.rawValue].firstMatch.isSelected, - "The shell must not advance past the tab the bar itself chose" - ) - capture("55-bar-drag") - } -} diff --git a/scripts/coverage-allowlist.txt b/scripts/coverage-allowlist.txt index e020255..6d3ed92 100644 --- a/scripts/coverage-allowlist.txt +++ b/scripts/coverage-allowlist.txt @@ -10,14 +10,13 @@ # entry, is in AGENTS.md under Testing; the two must not disagree. # # Final gate measurement against base 20a90fc: 304 tests, 48 suites, app -# target 23.00% (3481/15132). Of the 24 touched files, 5 are at the standard -# (TabSwipePolicy, ClassifierBenchmark, ClosetImporter, CutoutMatte, ZipReader) -# and 19 are allowlisted; the suite is green. +# target 23.00% (3481/15132). Of the touched files, the ones at the standard are +# ClassifierBenchmark, ClosetImporter, CutoutMatte and ZipReader; the rest are +# allowlisted, and the suite is green. -FitCheck/App/AppState.swift 99.13% (227/229): the two uncovered lines are 290 (ToastMessage.id) and 315 (Confirmation.id), the compiler-generated UUID() default initialisers, which xccov reports unexecuted although both types are built in covered tests — an instrumentation gap, not untested behaviour; the OutfitGenerating seam's four outcomes are covered through a stub, and Tab.adjacent is covered by TabAdjacencyTests +FitCheck/App/AppState.swift 99.13% (227/229): the two uncovered lines are 290 (ToastMessage.id) and 315 (Confirmation.id), the compiler-generated UUID() default initialisers, which xccov reports unexecuted although both types are built in covered tests — an instrumentation gap, not untested behaviour; the OutfitGenerating seam's four outcomes are covered through a stub FitCheck/App/FitCheckApp.swift process wiring: container creation and the store opener and deleter need a launched app FitCheck/App/RootView.swift SwiftUI view body: the tab shell is only reachable from the UI tests -FitCheck/App/TabSwipeReader.swift UIKit gesture adapter: it installs the swipe recognisers on the window and fills TabSwipePolicy.Traits from the view hierarchy, so every line of it needs a launched app and a real touch, and the UI tests are its only caller — the refusal rule is TabSwipePolicy, which holds no gesture and is unit-tested FitCheck/DesignSystem/GarmentViews.swift SwiftUI view body: only reachable from the UI tests, the uncovered remainder is layout FitCheck/DesignSystem/GlassComponents.swift SwiftUI view body: only reachable from the UI tests, the uncovered remainder is material and layout FitCheck/DesignSystem/SnappingSlider.swift SwiftUI Slider wrapper, body only; the label is passed in and the track is the platform's