From 6d05d04fb96d8e2614801da660e794289bdc81ac Mon Sep 17 00:00:00 2001 From: ykisana Date: Wed, 18 Nov 2026 19:20:32 -0600 Subject: [PATCH 1/3] style: add a swift-format config Apple's defaults, with the 4-space indentation the code already uses and a 150-character line length. --- .swift-format | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .swift-format diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..42302dc --- /dev/null +++ b/.swift-format @@ -0,0 +1,7 @@ +{ + "version": 1, + "indentation": { + "spaces": 4 + }, + "lineLength": 150 +} From eda5eb5b9fcdbc72c51311801803bd28778719ad Mon Sep 17 00:00:00 2001 From: ykisana Date: Wed, 18 Nov 2026 19:20:45 -0600 Subject: [PATCH 2/3] style: format the codebase with swift-format Generated by xcrun swift-format format -i -r -p . with the new config, plus one forEach turned into a for loop in FakeLocationProvider, the only warning the formatter can't fix itself. --- Normal/App/NormalApp.swift | 47 ++++---- Normal/App/UITestSupport.swift | 12 ++- Normal/Extensions/View+UnblockAlert.swift | 2 +- Normal/Intents/AppBlockIntentPerformer.swift | 6 +- .../Intents/AppUnblockIntentPerformer.swift | 33 +++--- Normal/Intents/IntentContext.swift | 2 +- Normal/Intents/UnblockIntents.swift | 14 +-- Normal/Models/AppGroup.swift | 7 +- Normal/Models/BlockSchedule.swift | 2 +- Normal/Models/LocationRadiusKind.swift | 6 +- Normal/Models/OnboardingStep.swift | 2 +- Normal/Models/Settings+GroupDefaults.swift | 4 +- Normal/Models/Settings+UnblockDurations.swift | 6 +- Normal/Models/UsageLimitEditPolicy.swift | 6 +- .../DeleteConfirmationModifier.swift | 13 +-- .../EditDeleteContextMenuModifier.swift | 15 +-- .../Modifiers/ProtectedActionModifier.swift | 15 +-- Normal/Modifiers/WidgetActionResponder.swift | 22 ++-- Normal/Services/AppReviewService.swift | 2 +- Normal/Services/BlockActions.swift | 2 +- Normal/Services/DeviceActivityProviding.swift | 3 +- Normal/Services/DonationService.swift | 6 +- .../Keys/BackgroundLocationVerifier.swift | 2 +- Normal/Services/Keys/KeyCheckFlow.swift | 2 +- Normal/Services/Keys/LocationFixPolicy.swift | 6 +- Normal/Services/Keys/ProtectedAction.swift | 4 +- Normal/Services/LocationService.swift | 2 +- Normal/Services/NFCService.swift | 42 ++++---- Normal/Services/NavigationCoordinator.swift | 4 +- Normal/Services/ScanError.swift | 4 +- Normal/Services/ScheduleService.swift | 12 ++- Normal/Services/ScreenTimeService.swift | 5 +- Normal/Services/ShieldStoring.swift | 12 ++- Normal/Services/TimedUnblockService.swift | 3 +- Normal/Services/UnblockTarget.swift | 22 ++-- Normal/Services/UsageLimitService.swift | 8 +- Normal/Services/WidgetSync.swift | 26 ++--- Normal/Shared/Components/AdaptiveStack.swift | 3 +- .../Components/CustomDomainsEditor.swift | 11 +- .../Components/DurationWheelPicker.swift | 2 +- .../Components/SelectionIconsView.swift | 4 +- .../Components/SelectionTokenLabel.swift | 6 +- Normal/Shared/Util/FamilyControlsUtil.swift | 30 +++--- Normal/Views/AppSelect/AppSelectView.swift | 4 +- .../KeySelect/KeySelectModifier.swift | 17 +-- .../KeySelect/LocationUnlockView.swift | 4 +- .../KeySelect/QRCameraView.swift | 8 +- .../TimedUnlock/TimedUnlockBannerView.swift | 2 +- .../TimedUnlock/UnblockDurationSheet.swift | 2 +- Normal/Views/Groups/GroupFormSheet.swift | 14 ++- Normal/Views/Groups/GroupListCardView.swift | 4 +- Normal/Views/Groups/GroupsView.swift | 55 +++++----- .../Groups/SelectAppsForGroupRowView.swift | 6 +- .../Groups/SelectAppsForGroupSheet.swift | 4 +- Normal/Views/Key/GroupKeyRow.swift | 4 +- Normal/Views/Key/KeyFormSheet.swift | 39 +++---- .../Views/Key/KeyFormSheetSetupSection.swift | 28 +++-- Normal/Views/Key/KeyTypeExamplesView.swift | 38 +++++-- Normal/Views/Key/KeysView.swift | 25 +++-- Normal/Views/Key/LocationCamera.swift | 6 +- Normal/Views/Key/LocationKeyMapPreview.swift | 11 +- Normal/Views/Key/LocationPickerSheet.swift | 9 +- Normal/Views/Key/LocationRadiusControls.swift | 2 +- Normal/Views/Schedules/ScheduleCardView.swift | 2 +- .../Views/Schedules/ScheduleFormSheet.swift | 6 +- Normal/Views/Schedules/SchedulesView.swift | 17 +-- .../Views/Schedules/WeekdayPickerView.swift | 2 +- Normal/Views/Schedules/WeekdayStrip.swift | 4 +- .../Settings/AdultContentToggleView.swift | 2 +- Normal/Views/Settings/ContactUsView.swift | 6 +- Normal/Views/Settings/DonationView.swift | 10 +- Normal/Views/Settings/FAQ/FAQAnswers.swift | 45 +++++--- Normal/Views/Settings/FAQ/FAQContent.swift | 56 ++++++---- .../Settings/FAQ/SettingsBypassGuide.swift | 36 ++++--- .../Views/Settings/GeneralSettingsView.swift | 13 ++- Normal/Views/Settings/SettingsView.swift | 8 +- .../Views/Settings/UnblockDurationsView.swift | 15 ++- Normal/Views/Usage/UsageLimitEditor.swift | 36 ++++--- Normal/Views/Usage/UsageLimitRow.swift | 2 +- Normal/Views/Usage/UsageLimitsGuideView.swift | 27 +++-- Normal/Views/Usage/UsageLockDeadline.swift | 2 +- Normal/Views/Usage/UsageView.swift | 20 ++-- NormalMonitor/NormalMonitor.swift | 20 ++-- .../ShieldConfigurationExtension.swift | 3 +- NormalTests/App/UITestSupportTests.swift | 3 +- NormalTests/Models/AppGroupTests.swift | 3 +- NormalTests/Models/AppTabTests.swift | 3 +- NormalTests/Models/BlockScheduleTests.swift | 3 +- .../Models/CustomDomainMigrationTests.swift | 3 +- NormalTests/Models/DonationCatalogTests.swift | 3 +- NormalTests/Models/GroupKeyCascadeTests.swift | 3 +- .../Models/GroupUnblockDefaultsTests.swift | 3 +- NormalTests/Models/KeyMigrationTests.swift | 3 +- NormalTests/Models/KeyTests.swift | 12 ++- NormalTests/Models/KeyTypeTests.swift | 3 +- NormalTests/Models/LocationZonesTests.swift | 5 +- NormalTests/Models/OnboardingStepTests.swift | 3 +- NormalTests/Models/ScanCodeKindTests.swift | 3 +- NormalTests/Models/SettingsTests.swift | 5 +- .../Models/SettingsUnblockDurationTests.swift | 3 +- NormalTests/Models/StoreUpgradeTests.swift | 102 ++++++++++-------- .../Models/TimedUnblockDurationTests.swift | 3 +- .../UnblockDurationMigrationTests.swift | 3 +- NormalTests/Models/UnblockDurationTests.swift | 3 +- .../Models/UsageLimitEditPolicyTests.swift | 15 +-- .../AppBlockIntentPerformerTests.swift | 3 +- .../AppUnblockIntentPerformerTests.swift | 5 +- .../BackgroundLocationVerifierTests.swift | 3 +- NormalTests/Services/BlockActionsTests.swift | 6 +- NormalTests/Services/BlockStatusTests.swift | 3 +- .../Services/BlockingMigrationTests.swift | 44 ++++---- .../Services/BlockingScenarioTests.swift | 25 ++--- .../Services/CameraPermissionTests.swift | 3 +- .../EmergencyUnblockServiceTests.swift | 3 +- NormalTests/Services/KeyCheckFlowTests.swift | 19 ++-- NormalTests/Services/KeyProofTests.swift | 3 +- .../Services/KeySelectLogicTests.swift | 3 +- .../Services/LiveActivityPlanTests.swift | 9 +- .../Services/LocationFixPolicyTests.swift | 3 +- .../Services/LocationUnlockModelTests.swift | 3 +- NormalTests/Services/NFCKeyMethodTests.swift | 3 +- .../Services/NavigationCoordinatorTests.swift | 3 +- .../NavigationCoordinatorWidgetTests.swift | 8 +- .../Services/OnboardingServiceTests.swift | 3 +- NormalTests/Services/QRServiceTests.swift | 3 +- .../Services/SafetyInvariantTests.swift | 7 +- NormalTests/Services/ScanErrorTests.swift | 3 +- .../Services/ScheduleServiceTests.swift | 56 ++++++---- .../Services/ScheduleSummaryTests.swift | 3 +- .../Services/ScreenTimeServiceTests.swift | 3 +- NormalTests/Services/TagDecisionTests.swift | 3 +- .../Services/TimedUnblockServiceTests.swift | 78 ++++++++------ NormalTests/Services/UnblockTargetTests.swift | 3 +- .../Services/UnlockRequestInboxTests.swift | 3 +- .../Services/UsageLimitServiceTests.swift | 3 +- NormalTests/Shared/CopyNamingTests.swift | 3 +- NormalTests/Shared/CustomDomainsTests.swift | 7 +- NormalTests/Shared/DTOBackCompatTests.swift | 3 +- NormalTests/Shared/DataExtensionTests.swift | 3 +- .../Shared/DomainNormalizerTests.swift | 3 +- NormalTests/Shared/DurationFormatTests.swift | 3 +- .../Shared/FamilyControlsUtilTests.swift | 38 ++++--- .../Shared/ScheduleActiveDayTests.swift | 5 +- NormalTests/Shared/SharedConstantsTests.swift | 3 +- NormalTests/Shared/SharedDTOTests.swift | 3 +- NormalTests/Shared/SharedStoreTests.swift | 3 +- .../Shared/ShieldReconcilerTests.swift | 7 +- NormalTests/Shared/ShieldResolverTests.swift | 7 +- .../Shared/SortIndexingPersistenceTests.swift | 5 +- NormalTests/Shared/SortIndexingTests.swift | 5 +- .../Shared/UnblockDurationEntityTests.swift | 3 +- NormalTests/Shared/UsageDTOTests.swift | 39 ++++--- NormalTests/Shared/WebFilterTests.swift | 3 +- NormalTests/Shared/WidgetDeepLinkTests.swift | 10 +- .../Shared/WidgetGroupStateTests.swift | 8 +- .../Shared/WidgetSharedStoreTests.swift | 3 +- NormalTests/TestSupport/BlockingHarness.swift | 5 +- .../TestSupport/ControlledScanner.swift | 1 + .../TestSupport/FakeCameraAuthorizer.swift | 1 + .../FakeDeviceActivityCenter.swift | 5 +- NormalTests/TestSupport/FakeKeyScanning.swift | 1 + .../TestSupport/FakeLocationProvider.swift | 7 +- .../TestSupport/FakeScreenTimeService.swift | 3 +- NormalTests/TestSupport/FakeSharedStore.swift | 1 + .../TestSupport/InMemoryModelContainer.swift | 3 +- .../TestSupport/StatefulScreenTimeSpy.swift | 1 + NormalTests/Views/LocationCameraTests.swift | 3 +- NormalTests/Views/LocationFormatTests.swift | 3 +- .../Views/QRScanWindowMetricsTests.swift | 3 +- NormalUITests/BlockingUITests.swift | 2 +- NormalUITests/NormalUITests.swift | 4 +- NormalUITests/RecoveryUITests.swift | 2 +- NormalWidget/GroupUnlockWidgetView.swift | 2 +- NormalWidget/SelectGroupIntent.swift | 3 +- NormalWidget/TimedUnblockLiveActivity.swift | 2 +- Shared/CallbackLog.swift | 2 +- Shared/CustomDomainFilter.swift | 4 +- Shared/DismissUnblockActivityIntent.swift | 3 +- Shared/DomainNormalizer.swift | 6 +- Shared/ManagedSettingsUtil.swift | 2 +- Shared/SharedDTO.swift | 23 ++-- Shared/SharedStore.swift | 3 +- Shared/ShieldReconciler.swift | 6 +- Shared/ShieldResolver.swift | 20 ++-- Shared/TimedUnblockDuration.swift | 6 +- Shared/UnblockDurationEntity.swift | 15 +-- Shared/WidgetSharedData.swift | 2 +- 187 files changed, 1103 insertions(+), 760 deletions(-) diff --git a/Normal/App/NormalApp.swift b/Normal/App/NormalApp.swift index cda645d..24c6ca9 100644 --- a/Normal/App/NormalApp.swift +++ b/Normal/App/NormalApp.swift @@ -38,10 +38,11 @@ struct NormalApp: App { } if UITestSupport.isActive { - context.insert(SelectedApps( - selection: UITestSupport.mainSelection, - customDomains: UITestSupport.mainCustomDomains - )) + context.insert( + SelectedApps( + selection: UITestSupport.mainSelection, + customDomains: UITestSupport.mainCustomDomains + )) if !UITestSupport.noKeys { context.insert(Key(name: "Test Key", type: .qr, rawValue: UITestSupport.stubScanValue)) } @@ -55,26 +56,28 @@ struct NormalApp: App { context.insert(Key(name: "Group Key", type: .qr, rawValue: "GROUP-VALUE", groupID: group.id)) } if UITestSupport.seedLocationKey { - context.insert(Key( - name: "Test Place", - latitude: UITestSupport.locationKeyFarAway ? 40.7484 : 37.33182, - longitude: UITestSupport.locationKeyFarAway ? -73.9857 : -122.03118, - radiusMeters: 400, - radiusKind: .unblock - )) + context.insert( + Key( + name: "Test Place", + latitude: UITestSupport.locationKeyFarAway ? 40.7484 : 37.33182, + longitude: UITestSupport.locationKeyFarAway ? -73.9857 : -122.03118, + radiusMeters: 400, + radiusKind: .unblock + )) } if UITestSupport.seedSchedule { - context.insert(BlockSchedule( - name: "Test Schedule", - selection: FamilyActivitySelection(), - startHour: 9, - startMinute: 0, - durationMinutes: 60, - weekdays: [2, 3, 4, 5, 6], - shouldBlock: true, - isTimed: false, - isEnabled: true - )) + context.insert( + BlockSchedule( + name: "Test Schedule", + selection: FamilyActivitySelection(), + startHour: 9, + startMinute: 0, + durationMinutes: 60, + weekdays: [2, 3, 4, 5, 6], + shouldBlock: true, + isTimed: false, + isEnabled: true + )) } } diff --git a/Normal/App/UITestSupport.swift b/Normal/App/UITestSupport.swift index 656c8b2..21906d6 100644 --- a/Normal/App/UITestSupport.swift +++ b/Normal/App/UITestSupport.swift @@ -7,7 +7,8 @@ enum UITestSupport { static let isActive = arguments.contains("-uiTestMode") - static let isUnitTestHost = !isActive + static let isUnitTestHost = + !isActive && ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil static let skipOnboarding = arguments.contains("-uiTestSkipOnboarding") @@ -54,10 +55,11 @@ enum UITestSupport { private static func selection(apps: [UInt8]) -> FamilyActivitySelection { var selection = FamilyActivitySelection() - selection.applicationTokens = Set(apps.compactMap { id in - let json = #"{"data":"\#(Data([id]).base64EncodedString())"}"# - return try? JSONDecoder().decode(ApplicationToken.self, from: Data(json.utf8)) - }) + selection.applicationTokens = Set( + apps.compactMap { id in + let json = #"{"data":"\#(Data([id]).base64EncodedString())"}"# + return try? JSONDecoder().decode(ApplicationToken.self, from: Data(json.utf8)) + }) return selection } diff --git a/Normal/Extensions/View+UnblockAlert.swift b/Normal/Extensions/View+UnblockAlert.swift index 3b4a015..c6be0a5 100644 --- a/Normal/Extensions/View+UnblockAlert.swift +++ b/Normal/Extensions/View+UnblockAlert.swift @@ -18,7 +18,7 @@ enum UnblockAlert { var message: Text { switch self { - case let .failed(error): + case .failed(let error): Text(error.localizedDescription) case .mayEndLate: Text("iOS only tracks 20 schedules and timers at once, so this unblock may end up to 30 minutes late.") diff --git a/Normal/Intents/AppBlockIntentPerformer.swift b/Normal/Intents/AppBlockIntentPerformer.swift index ccf6f2e..aa8f464 100644 --- a/Normal/Intents/AppBlockIntentPerformer.swift +++ b/Normal/Intents/AppBlockIntentPerformer.swift @@ -33,7 +33,8 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { logger.info("Block intent: all") let settings = try intents.validatedSettings(requiringKey: true) let mainSelection = try intents.mainSelection(settings: settings) - let wasAlreadyBlocked = intents.screenTimeService.blockStatus(of: .all(mainSelection), settings: settings) == .all + let wasAlreadyBlocked = + intents.screenTimeService.blockStatus(of: .all(mainSelection), settings: settings) == .all && intents.timedUnblockService.activeUnblocks.isEmpty BlockActions.blockAll( @@ -50,7 +51,8 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { logger.info("Block intent: group") let settings = try intents.validatedSettings(requiringKey: true, groupID: id) let group = try intents.group(id: id) - let wasAlreadyBlocked = intents.screenTimeService.blockStatus(of: .group(group), settings: settings) == .all + let wasAlreadyBlocked = + intents.screenTimeService.blockStatus(of: .group(group), settings: settings) == .all && !intents.timedUnblockService.isGroupUnblockActive(groupId: id) BlockActions.blockGroup( diff --git a/Normal/Intents/AppUnblockIntentPerformer.swift b/Normal/Intents/AppUnblockIntentPerformer.swift index fbfa2b7..bd89306 100644 --- a/Normal/Intents/AppUnblockIntentPerformer.swift +++ b/Normal/Intents/AppUnblockIntentPerformer.swift @@ -42,16 +42,16 @@ final class AppUnblockIntentPerformer: UnblockIntentPerforming { let settings: Settings let target: UnblockTarget switch try readiness(for: request) { - case let .settled(outcome): + case .settled(let outcome): return outcome - case let .ready(readySettings, readyTarget): + case .ready(let readySettings, let readyTarget): settings = readySettings target = readyTarget } let keys = try Key.scoped(intents.keys(), toGroup: request.groupID) guard keyType(for: request, keys: keys, settings: settings, group: target.group) == .location, - settings.unblockLength(for: request.duration, group: target.group) != nil + settings.unblockLength(for: request.duration, group: target.group) != nil else { return .continueInApp(.checkKey) } let radiusKind = Key.existingLocationKind(in: keys) ?? .unblock @@ -74,27 +74,28 @@ final class AppUnblockIntentPerformer: UnblockIntentPerforming { } switch try readiness(for: request) { - case let .settled(outcome): + case .settled(let outcome): return outcome - case let .ready(settings, target): + case .ready(let settings, let target): guard let length = settings.unblockLength(for: request.duration, group: target.group), - let grant = UnblockGrant(target, proof: proof) + let grant = UnblockGrant(target, proof: proof) else { return .continueInApp(.checkKey) } return try start(grant, for: length, settings: settings) } } func continueInApp(_ request: UnblockRequest) { - unlockInbox.post(UnblockRequest( - groupID: request.groupID, - duration: request.duration, - keyType: keyType( - for: request, - keys: Key.scoped((try? intents.keys()) ?? [], toGroup: request.groupID), - settings: intents.settings(), - group: request.groupID.flatMap { try? intents.group(id: $0) } - ) - )) + unlockInbox.post( + UnblockRequest( + groupID: request.groupID, + duration: request.duration, + keyType: keyType( + for: request, + keys: Key.scoped((try? intents.keys()) ?? [], toGroup: request.groupID), + settings: intents.settings(), + group: request.groupID.flatMap { try? intents.group(id: $0) } + ) + )) } private enum Readiness { diff --git a/Normal/Intents/IntentContext.swift b/Normal/Intents/IntentContext.swift index e95cd3e..67a478b 100644 --- a/Normal/Intents/IntentContext.swift +++ b/Normal/Intents/IntentContext.swift @@ -47,7 +47,7 @@ struct IntentContext { func mainSelection(settings: Settings) throws -> SelectedApps { guard let mainSelection = try context.fetch(FetchDescriptor()).first, - mainSelection.hasItemsToBlock(customDomainsEnabled: settings.enableCustomDomains) + mainSelection.hasItemsToBlock(customDomainsEnabled: settings.enableCustomDomains) else { throw BlockIntentError.noAppsSelected } return mainSelection } diff --git a/Normal/Intents/UnblockIntents.swift b/Normal/Intents/UnblockIntents.swift index 52d1a27..ab8c13b 100644 --- a/Normal/Intents/UnblockIntents.swift +++ b/Normal/Intents/UnblockIntents.swift @@ -95,7 +95,7 @@ struct UnblockAllIntent: LiveActivityIntent { return .result(dialog: "").withoutDialog case .timedUnblockRunning: return .result(dialog: "A timed unblock is already running for all apps.") - case let .continueInApp(reason): + case .continueInApp(let reason): return try await continueInApp( request, reason: reason, @@ -139,9 +139,9 @@ struct UnblockGroupIntent: LiveActivityIntent { switch try await performer.unblock(request) { case .unblocked, .alreadyUnblocked: return .result(dialog: "").withoutDialog - case let .timedUnblockRunning(name): + case .timedUnblockRunning(let name): return .result(dialog: "A timed unblock is already running for \(name).") - case let .continueInApp(reason): + case .continueInApp(let reason): return try await continueInApp( request, reason: reason, @@ -193,8 +193,8 @@ struct OpenUnblockIntent: AppIntent { } } -private extension AppIntent { - func continueInApp( +extension AppIntent { + fileprivate func continueInApp( _ request: UnblockRequest, reason: HandOffReason, performer: any UnblockIntentPerforming, @@ -222,8 +222,8 @@ private extension AppIntent { } } -private extension IntentResultContainer { - var withoutDialog: Self { +extension IntentResultContainer { + fileprivate var withoutDialog: Self { var result = self result.dialog = nil return result diff --git a/Normal/Models/AppGroup.swift b/Normal/Models/AppGroup.swift index 1edd970..a24cc3c 100644 --- a/Normal/Models/AppGroup.swift +++ b/Normal/Models/AppGroup.swift @@ -27,13 +27,14 @@ final class AppGroup: Identifiable { var durationOverride: DefaultOverride { get { guard overridesDefaultDuration else { return .appDefault } - return defaultUnblockSeconds + return + defaultUnblockSeconds .flatMap(TimedUnblockDuration.init(validating:)) .map(DefaultOverride.value) ?? .none } set { overridesDefaultDuration = newValue != .appDefault - if case let .value(duration) = newValue { + if case .value(let duration) = newValue { defaultUnblockSeconds = duration.seconds } else { defaultUnblockSeconds = nil @@ -48,7 +49,7 @@ final class AppGroup: Identifiable { } set { overridesDefaultKey = newValue != .appDefault - if case let .value(keyType) = newValue { + if case .value(let keyType) = newValue { defaultKeyType = keyType } else { defaultKeyType = nil diff --git a/Normal/Models/BlockSchedule.swift b/Normal/Models/BlockSchedule.swift index 1a5cfc0..b582408 100644 --- a/Normal/Models/BlockSchedule.swift +++ b/Normal/Models/BlockSchedule.swift @@ -52,7 +52,7 @@ final class BlockSchedule: Identifiable { var weekdayLabels: [String] { let symbols = Calendar.current.shortWeekdaySymbols return weekdays.sorted().compactMap { day in - guard (1 ... 7).contains(day) else { return nil } + guard (1...7).contains(day) else { return nil } return symbols[day - 1] } } diff --git a/Normal/Models/LocationRadiusKind.swift b/Normal/Models/LocationRadiusKind.swift index 740ed51..ea3137e 100644 --- a/Normal/Models/LocationRadiusKind.swift +++ b/Normal/Models/LocationRadiusKind.swift @@ -56,8 +56,10 @@ enum LocationRadiusKind: String, Codable, CaseIterable, Identifiable, Sendable { var pickerFooter: String { switch self { - case .unblock: "Your location key will only work while you're inside one of these areas. Set one up to unlock at the office, the gym, or anywhere you choose." - case .block: "Your location key will only work while you're outside the selected areas. Set one up to lock yourself out at home, school, or anywhere you choose." + case .unblock: + "Your location key will only work while you're inside one of these areas. Set one up to unlock at the office, the gym, or anywhere you choose." + case .block: + "Your location key will only work while you're outside the selected areas. Set one up to lock yourself out at home, school, or anywhere you choose." } } } diff --git a/Normal/Models/OnboardingStep.swift b/Normal/Models/OnboardingStep.swift index 34e7247..e496bf7 100644 --- a/Normal/Models/OnboardingStep.swift +++ b/Normal/Models/OnboardingStep.swift @@ -50,7 +50,7 @@ enum OnboardingStep: String, CaseIterable, Sendable { func next() -> OnboardingStep { guard let index = Self.allCases.firstIndex(of: self), - index + 1 < Self.allCases.count + index + 1 < Self.allCases.count else { return .complete } return Self.allCases[index + 1] } diff --git a/Normal/Models/Settings+GroupDefaults.swift b/Normal/Models/Settings+GroupDefaults.swift index b980c17..1e267c2 100644 --- a/Normal/Models/Settings+GroupDefaults.swift +++ b/Normal/Models/Settings+GroupDefaults.swift @@ -3,7 +3,7 @@ extension Settings { switch group?.durationOverride ?? .appDefault { case .appDefault: defaultDuration case .none: nil - case let .value(duration): unblockDurations.contains(duration) ? duration : nil + case .value(let duration): unblockDurations.contains(duration) ? duration : nil } } @@ -11,7 +11,7 @@ extension Settings { switch group?.keyOverride ?? .appDefault { case .appDefault: defaultKeyType case .none: nil - case let .value(keyType): keyType + case .value(let keyType): keyType } } } diff --git a/Normal/Models/Settings+UnblockDurations.swift b/Normal/Models/Settings+UnblockDurations.swift index b32a22b..39e928e 100644 --- a/Normal/Models/Settings+UnblockDurations.swift +++ b/Normal/Models/Settings+UnblockDurations.swift @@ -22,8 +22,8 @@ extension Settings { var defaultDuration: TimedUnblockDuration? { get { guard let seconds = defaultUnblockSeconds ?? defaultUnblockDuration?.rawValue, - let duration = TimedUnblockDuration(validating: seconds), - unblockDurations.contains(duration) + let duration = TimedUnblockDuration(validating: seconds), + unblockDurations.contains(duration) else { return nil } return duration } @@ -35,7 +35,7 @@ extension Settings { func unblockLength(for request: UnlockDurationRequest, group: AppGroup?) -> UnblockLength? { switch request { - case let .fixed(duration): .timed(duration) + case .fixed(let duration): .timed(duration) case .permanent: .permanent case .useDefault: defaultDuration(for: group).map(UnblockLength.timed) case .ask: nil diff --git a/Normal/Models/UsageLimitEditPolicy.swift b/Normal/Models/UsageLimitEditPolicy.swift index 34ffb33..efda373 100644 --- a/Normal/Models/UsageLimitEditPolicy.swift +++ b/Normal/Models/UsageLimitEditPolicy.swift @@ -16,7 +16,7 @@ nonisolated enum UsageLimitEdit: Equatable, Sendable { var isLoosening: Bool { switch self { case .create: false - case let .adjust(from, to, dropsCoverage): to > from || dropsCoverage + case .adjust(let from, let to, let dropsCoverage): to > from || dropsCoverage case .delete, .changeReset: true } } @@ -48,7 +48,7 @@ nonisolated enum UsageLimitLockState: Equatable, Sendable { case locked(until: Date) var lockedUntil: Date? { - if case let .locked(until) = self { + if case .locked(let until) = self { return until } return nil @@ -88,7 +88,7 @@ nonisolated enum UsageLimitEditPolicy { switch lockState(anchor: anchor, now: now) { case .unlocked: return .allowed(.cooldownElapsed) case .grace: return .allowed(.grace) - case let .locked(until): return .locked(until: until) + case .locked(let until): return .locked(until: until) } } diff --git a/Normal/Modifiers/DeleteConfirmationModifier.swift b/Normal/Modifiers/DeleteConfirmationModifier.swift index 0794277..b17ed73 100644 --- a/Normal/Modifiers/DeleteConfirmationModifier.swift +++ b/Normal/Modifiers/DeleteConfirmationModifier.swift @@ -23,11 +23,12 @@ extension View { isPresented: Binding, onDelete: @escaping () -> Void ) -> some View { - modifier(DeleteConfirmationModifier( - title: title, - itemName: itemName, - isPresented: isPresented, - onDelete: onDelete - )) + modifier( + DeleteConfirmationModifier( + title: title, + itemName: itemName, + isPresented: isPresented, + onDelete: onDelete + )) } } diff --git a/Normal/Modifiers/EditDeleteContextMenuModifier.swift b/Normal/Modifiers/EditDeleteContextMenuModifier.swift index 9fc1d62..b91eb9d 100644 --- a/Normal/Modifiers/EditDeleteContextMenuModifier.swift +++ b/Normal/Modifiers/EditDeleteContextMenuModifier.swift @@ -37,12 +37,13 @@ extension View { onDuplicate: (() -> Void)? = nil, onDelete: @escaping () -> Void ) -> some View { - modifier(EditDeleteContextMenuModifier( - onEdit: onEdit, - onDuplicate: onDuplicate, - onDelete: onDelete, - isDisabled: isDisabled, - isDuplicateDisabled: isDuplicateDisabled - )) + modifier( + EditDeleteContextMenuModifier( + onEdit: onEdit, + onDuplicate: onDuplicate, + onDelete: onDelete, + isDisabled: isDisabled, + isDuplicateDisabled: isDuplicateDisabled + )) } } diff --git a/Normal/Modifiers/ProtectedActionModifier.swift b/Normal/Modifiers/ProtectedActionModifier.swift index 23a4222..11f74ff 100644 --- a/Normal/Modifiers/ProtectedActionModifier.swift +++ b/Normal/Modifiers/ProtectedActionModifier.swift @@ -28,12 +28,13 @@ extension View { keyGroupID: UUID? = nil, requestID: UUID? = nil ) -> some View { - modifier(ProtectedActionModifier( - action: action, - defaultKeyType: defaultKeyType, - requestedKeyType: requestedKeyType, - keyGroupID: keyGroupID, - requestID: requestID - )) + modifier( + ProtectedActionModifier( + action: action, + defaultKeyType: defaultKeyType, + requestedKeyType: requestedKeyType, + keyGroupID: keyGroupID, + requestID: requestID + )) } } diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index 6e9505a..fc6ae10 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -70,15 +70,15 @@ private struct WidgetActionResponder: ViewModifier { private func takeInboxRequest() { guard scenePhase == .active, - screenTimeService.authorizationState == .authorized, - durationGrant == nil, - let request = unlockInbox.take(), - let settings = allSettings.first, - let target = target(for: request.groupID), - target.canUnblock( - status: screenTimeService.blockStatus(of: target, settings: settings), - timedUnblockService: timedUnblockService - ) + screenTimeService.authorizationState == .authorized, + durationGrant == nil, + let request = unlockInbox.take(), + let settings = allSettings.first, + let target = target(for: request.groupID), + target.canUnblock( + status: screenTimeService.blockStatus(of: target, settings: settings), + timedUnblockService: timedUnblockService + ) else { return } coordinator.requestUnblock(request) } @@ -98,11 +98,11 @@ private struct WidgetActionResponder: ViewModifier { guard allSettings.first?.hasCompletedOnboarding == true else { return } switch request.action { - case let .unblock(unblock): + case .unblock(let unblock): guard let target = target(for: unblock.groupID) else { return } present(ActiveRequest(token: request.token, target: target, keyType: unblock.keyType)) authAction = .weaken { unlock(target, duration: unblock.duration, proof: $0) } - case let .blockGroup(groupID): + case .blockGroup(let groupID): guard let group = groups.first(where: { $0.id == groupID }) else { return } present(ActiveRequest(token: request.token, target: .group(group), keyType: nil)) authAction = .tighten { block(group) } diff --git a/Normal/Services/AppReviewService.swift b/Normal/Services/AppReviewService.swift index d01b070..32a2968 100644 --- a/Normal/Services/AppReviewService.swift +++ b/Normal/Services/AppReviewService.swift @@ -18,7 +18,7 @@ final class AppReviewService { guard count >= minSuccessfulUnblocks else { return } if let last = defaults.object(forKey: Key.lastRequestedDate) as? Date, - now.timeIntervalSince(last) < minDaysBetweenPrompts + now.timeIntervalSince(last) < minDaysBetweenPrompts { return } diff --git a/Normal/Services/BlockActions.swift b/Normal/Services/BlockActions.swift index b4a425f..63b200b 100644 --- a/Normal/Services/BlockActions.swift +++ b/Normal/Services/BlockActions.swift @@ -41,7 +41,7 @@ enum BlockActions { ) throws -> UnblockTiming { let timing: UnblockTiming switch length { - case let .timed(duration): + case .timed(let duration): timing = try timedUnblockService.start( grant, duration: duration, diff --git a/Normal/Services/DeviceActivityProviding.swift b/Normal/Services/DeviceActivityProviding.swift index dce4bd2..8440fbb 100644 --- a/Normal/Services/DeviceActivityProviding.swift +++ b/Normal/Services/DeviceActivityProviding.swift @@ -41,7 +41,8 @@ extension DeviceActivityProviding { func syncHeartbeat(sharedStore: any SharedStoreProviding, at date: Date) { let name = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) let monitored = monitoredActivityNames - let needed = sharedStore.loadSchedules().contains { $0.isEffectivelyEnabled(monitoredActivities: monitored) } + let needed = + sharedStore.loadSchedules().contains { $0.isEffectivelyEnabled(monitoredActivities: monitored) } || sharedStore.loadTimedUnblocks().contains { $0.endDate > date } let heartbeat = DeviceActivityScheduleFactory.heartbeat() let current = registeredSchedule(for: name) diff --git a/Normal/Services/DonationService.swift b/Normal/Services/DonationService.swift index 3e048e9..dd4d4b5 100644 --- a/Normal/Services/DonationService.swift +++ b/Normal/Services/DonationService.swift @@ -17,7 +17,7 @@ final class DonationService { init() { updatesTask = Task { for await update in Transaction.updates { - guard case let .verified(transaction) = update else { continue } + guard case .verified(let transaction) = update else { continue } await transaction.finish() } } @@ -69,8 +69,8 @@ final class DonationService { do { let result = try await product.purchase() switch result { - case let .success(verification): - if case let .verified(transaction) = verification { + case .success(let verification): + if case .verified(let transaction) = verification { await transaction.finish() showThankYou = true } diff --git a/Normal/Services/Keys/BackgroundLocationVerifier.swift b/Normal/Services/Keys/BackgroundLocationVerifier.swift index 9100297..974446b 100644 --- a/Normal/Services/Keys/BackgroundLocationVerifier.swift +++ b/Normal/Services/Keys/BackgroundLocationVerifier.swift @@ -39,7 +39,7 @@ struct BackgroundLocationVerifier { switch zones.fit(fix) { case .satisfied: return .verified - case let .unsatisfied(margin): + case .unsatisfied(let margin): if Self.isOutOfReach(margin, within: clock.now.duration(to: end)) { return .outOfRange } diff --git a/Normal/Services/Keys/KeyCheckFlow.swift b/Normal/Services/Keys/KeyCheckFlow.swift index b4ffcde..c1002ff 100644 --- a/Normal/Services/Keys/KeyCheckFlow.swift +++ b/Normal/Services/Keys/KeyCheckFlow.swift @@ -100,7 +100,7 @@ final class KeyCheckFlow { ) { case .showNoKeysAlert: stage = .missingKey(request.keys.isEmpty ? .noKeyToUnblock : .unsupportedOnDevice) - case let .autoSelect(keyType): + case .autoSelect(let keyType): begin(keyType, fromPicker: false) case .showSheet: sheetScreen = .picker diff --git a/Normal/Services/Keys/LocationFixPolicy.swift b/Normal/Services/Keys/LocationFixPolicy.swift index 35c2f3d..8ffbb8e 100644 --- a/Normal/Services/Keys/LocationFixPolicy.swift +++ b/Normal/Services/Keys/LocationFixPolicy.swift @@ -12,9 +12,9 @@ struct LocationFixPolicy { func accepts(_ fix: CLLocation, now: Date = .now) -> Bool { let age = now.timeIntervalSince(fix.timestamp) guard age >= -Self.clockTolerance, - age <= Self.maxAge, - fix.horizontalAccuracy >= 0, - fix.sourceInformation?.isSimulatedBySoftware != true + age <= Self.maxAge, + fix.horizontalAccuracy >= 0, + fix.sourceInformation?.isSimulatedBySoftware != true else { return false } guard let maxAccuracy else { return true } return fix.horizontalAccuracy <= maxAccuracy diff --git a/Normal/Services/Keys/ProtectedAction.swift b/Normal/Services/Keys/ProtectedAction.swift index 61bca11..bf90645 100644 --- a/Normal/Services/Keys/ProtectedAction.swift +++ b/Normal/Services/Keys/ProtectedAction.swift @@ -13,9 +13,9 @@ enum ProtectedAction { func run(with proof: KeyProof?) { switch self { - case let .tighten(action): + case .tighten(let action): action() - case let .weaken(action): + case .weaken(let action): if let proof { action(proof) } diff --git a/Normal/Services/LocationService.swift b/Normal/Services/LocationService.swift index 6347b84..041c919 100644 --- a/Normal/Services/LocationService.swift +++ b/Normal/Services/LocationService.swift @@ -135,7 +135,7 @@ final class LocationService: NSObject, LocationProviding { } private func flushLocation(_ result: Result) { - if case let .success(location) = result { + if case .success(let location) = result { lastFix = (location, .now) } let pending = locationContinuations diff --git a/Normal/Services/NFCService.swift b/Normal/Services/NFCService.swift index 426a82f..cccf98e 100644 --- a/Normal/Services/NFCService.swift +++ b/Normal/Services/NFCService.swift @@ -3,32 +3,34 @@ import Foundation import Observation import UIKit -private extension NFCTag { - var hexId: String? { - let bytes: Data? = switch self { - case let .feliCa(t): t.currentIDm - case let .miFare(t): t.identifier - case let .iso7816(t): t.identifier - case let .iso15693(t): t.identifier - @unknown default: nil - } +extension NFCTag { + fileprivate var hexId: String? { + let bytes: Data? = + switch self { + case .feliCa(let t): t.currentIDm + case .miFare(let t): t.identifier + case .iso7816(let t): t.identifier + case .iso15693(let t): t.identifier + @unknown default: nil + } return bytes?.hexString } - var hasRandomIdentifier: Bool { - let id: Data? = switch self { - case let .miFare(t): t.identifier - case let .iso7816(t): t.identifier - default: nil - } + fileprivate var hasRandomIdentifier: Bool { + let id: Data? = + switch self { + case .miFare(let t): t.identifier + case .iso7816(let t): t.identifier + default: nil + } return id?.count == 4 && id?.first == 0x08 } } private let mrtdAID = Data([0xA0, 0x00, 0x00, 0x02, 0x47, 0x10, 0x01]) -private extension NFCISO7816Tag { - func hasMRTDApplication() async -> Bool { +extension NFCISO7816Tag { + fileprivate func hasMRTDApplication() async -> Bool { let apdu = NFCISO7816APDU( instructionClass: 0x00, instructionCode: 0xA4, @@ -180,15 +182,15 @@ extension NFCService: NFCTagReaderSessionDelegate { hasRandomIdentifier: hasRandomID, hasMRTDApplication: hasMRTD ) { - case let .proceed(hexId): + case .proceed(let hexId): complete(session: session, hexId: hexId) - case let .reject(err): + case .reject(let err): fail(session: session, with: err) } } private func checkMRTD(tag: NFCTag, skipping skip: Bool) async -> Bool { - guard !skip, case let .iso7816(iso) = tag else { return false } + guard !skip, case .iso7816(let iso) = tag else { return false } return await iso.hasMRTDApplication() } diff --git a/Normal/Services/NavigationCoordinator.swift b/Normal/Services/NavigationCoordinator.swift index 577b9ba..6e498ea 100644 --- a/Normal/Services/NavigationCoordinator.swift +++ b/Normal/Services/NavigationCoordinator.swift @@ -50,12 +50,12 @@ final class NavigationCoordinator { func handle(url: URL) { guard url.scheme == WidgetDeepLink.scheme, - let components = URLComponents(url: url, resolvingAgainstBaseURL: false) + let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return } let items = components.queryItems ?? [] guard let groupValue = items.first(where: { $0.name == WidgetDeepLink.groupQueryItem })?.value, - let groupID = UUID(uuidString: groupValue) + let groupID = UUID(uuidString: groupValue) else { return } switch url.host { diff --git a/Normal/Services/ScanError.swift b/Normal/Services/ScanError.swift index 75ec47b..91381a5 100644 --- a/Normal/Services/ScanError.swift +++ b/Normal/Services/ScanError.swift @@ -42,8 +42,8 @@ enum ScanError: LocalizedError { case .alreadyScanning: "A scan is already in progress." case .userCanceled: "Scanning was canceled." case .invalidKey: "This key hasn't been registered." - case let .systemError(e): e.localizedDescription - case let .nfc(nfcError): nfcError.errorDescription ?? "Unknown NFC error" + case .systemError(let e): e.localizedDescription + case .nfc(let nfcError): nfcError.errorDescription ?? "Unknown NFC error" } } } diff --git a/Normal/Services/ScheduleService.swift b/Normal/Services/ScheduleService.swift index 7b76ed8..dadb9d3 100644 --- a/Normal/Services/ScheduleService.swift +++ b/Normal/Services/ScheduleService.swift @@ -108,9 +108,10 @@ final class ScheduleService { for dto in sharedStore.loadSchedules() { previous[dto.id] = dto.activatedAt } - sharedStore.saveSchedules(schedules.compactMap { schedule in - schedule.toDTO(activatedAt: schedule.id == activatedID ? clock() : previous[schedule.id]) - }) + sharedStore.saveSchedules( + schedules.compactMap { schedule in + schedule.toDTO(activatedAt: schedule.id == activatedID ? clock() : previous[schedule.id]) + }) } func syncAndPersist( @@ -154,6 +155,9 @@ enum ScheduleRegistrationError: LocalizedError { case tooManyActivities var errorDescription: String? { - String(localized: "Saved, but iOS only tracks 20 schedules and timers at once, so this schedule may start or end up to 30 minutes late. Turn off another schedule to make it exact.") + String( + localized: + "Saved, but iOS only tracks 20 schedules and timers at once, so this schedule may start or end up to 30 minutes late. Turn off another schedule to make it exact." + ) } } diff --git a/Normal/Services/ScreenTimeService.swift b/Normal/Services/ScreenTimeService.swift index 58e7636..c85251c 100644 --- a/Normal/Services/ScreenTimeService.swift +++ b/Normal/Services/ScreenTimeService.swift @@ -1,8 +1,8 @@ import DeviceActivity import FamilyControls import Foundation -import Observation import OSLog +import Observation @MainActor @Observable @@ -28,7 +28,8 @@ final class ScreenTimeService: ScreenTimeProviding { clock: @escaping () -> Date = { .now } ) { self.defaults = defaults - self.shield = shield + self.shield = + shield ?? (UITestSupport.isActive ? InMemoryShieldStore() : ManagedSettingsShieldStore()) self.sharedStore = sharedStore self.activityCenter = activityCenter diff --git a/Normal/Services/ShieldStoring.swift b/Normal/Services/ShieldStoring.swift index 6381621..140a705 100644 --- a/Normal/Services/ShieldStoring.swift +++ b/Normal/Services/ShieldStoring.swift @@ -36,7 +36,8 @@ extension ShieldPlan { guard let selection else { return .none } let targetDomains = Set((domains ?? []).compactMap(DomainNormalizer.normalize)) - let disjoint = selection.applicationTokens.isDisjoint(with: applications) + let disjoint = + selection.applicationTokens.isDisjoint(with: applications) && selection.webDomainTokens.isDisjoint(with: webDomains) && selection.categoryTokens.isDisjoint(with: categories) && targetDomains.isDisjoint(with: customDomains) @@ -44,7 +45,8 @@ extension ShieldPlan { return .none } - let subset = selection.applicationTokens.isSubset(of: applications) + let subset = + selection.applicationTokens.isSubset(of: applications) && selection.webDomainTokens.isSubset(of: webDomains) && selection.categoryTokens.isSubset(of: categories) && targetDomains.isSubset(of: customDomains) @@ -53,9 +55,9 @@ extension ShieldPlan { func isShielded(_ token: SelectedTokenKind) -> Bool { switch token { - case let .application(t): applications.contains(t) - case let .webDomain(t): webDomains.contains(t) - case let .category(t): categories.contains(t) + case .application(let t): applications.contains(t) + case .webDomain(let t): webDomains.contains(t) + case .category(let t): categories.contains(t) } } } diff --git a/Normal/Services/TimedUnblockService.swift b/Normal/Services/TimedUnblockService.swift index bd647de..29dba3c 100644 --- a/Normal/Services/TimedUnblockService.swift +++ b/Normal/Services/TimedUnblockService.swift @@ -159,7 +159,8 @@ final class TimedUnblockService { guard let endDate = activeUnblocks[Self.mainID] else { return } let activityName = SharedConstants.mainTimedUnblockActivityName let existing = sharedStore.findTimedUnblock(activityName: activityName) - let previous = existing.flatMap { try? FamilyActivitySelection.fromData($0.selectionData) } + let previous = + existing.flatMap { try? FamilyActivitySelection.fromData($0.selectionData) } ?? FamilyActivitySelection() screenTimeService.updateMainList( from: previous, diff --git a/Normal/Services/UnblockTarget.swift b/Normal/Services/UnblockTarget.swift index 6627aab..ba61ce6 100644 --- a/Normal/Services/UnblockTarget.swift +++ b/Normal/Services/UnblockTarget.swift @@ -8,19 +8,19 @@ enum UnblockTarget: Identifiable { var id: String { switch self { case .all: "all" - case let .group(group): group.id.uuidString + case .group(let group): group.id.uuidString } } var group: AppGroup? { - if case let .group(group) = self { + if case .group(let group) = self { return group } return nil } var groupID: UUID? { - if case let .group(group) = self { + if case .group(let group) = self { return group.id } return nil @@ -29,14 +29,14 @@ enum UnblockTarget: Identifiable { var name: String { switch self { case .all: String(localized: "All Apps") - case let .group(group): group.name + case .group(let group): group.name } } var selection: FamilyActivitySelection { switch self { - case let .all(mainSelection): mainSelection.selection - case let .group(group): group.selection + case .all(let mainSelection): mainSelection.selection + case .group(let group): group.selection } } @@ -44,7 +44,7 @@ enum UnblockTarget: Identifiable { switch self { case .all: status.canUnblockAll(timedUnblockActive: timedUnblockService.isMainUnblockActive) - case let .group(group): + case .group(let group): status.canUnblockGroup(timedUnblockActive: timedUnblockService.isGroupUnblockActive(groupId: group.id)) } } @@ -52,8 +52,8 @@ enum UnblockTarget: Identifiable { func customDomains(settings: Settings) -> [String] { guard settings.enableCustomDomains else { return [] } return switch self { - case let .all(mainSelection): mainSelection.customDomains - case let .group(group): group.customDomains + case .all(let mainSelection): mainSelection.customDomains + case .group(let group): group.customDomains } } } @@ -68,14 +68,14 @@ extension TimedUnblockService { ) throws -> UnblockTiming { let target = grant.target switch target { - case let .all(mainSelection): + case .all(let mainSelection): return try startMain( duration: duration, mainSelection: mainSelection, settings: settings, screenTimeService: screenTimeService ) - case let .group(group): + case .group(let group): return try startGroup( duration: duration, groupId: group.id, diff --git a/Normal/Services/UsageLimitService.swift b/Normal/Services/UsageLimitService.swift index 72156f8..2f1e587 100644 --- a/Normal/Services/UsageLimitService.swift +++ b/Normal/Services/UsageLimitService.swift @@ -1,8 +1,8 @@ import DeviceActivity import FamilyControls import Foundation -import Observation import OSLog +import Observation @MainActor @Observable @@ -32,7 +32,8 @@ final class UsageLimitService { self.activityCenter = activityCenter self.sharedStore = sharedStore self.ledger = ledger - self.limitShield = limitShield + self.limitShield = + limitShield ?? (UITestSupport.isActive ? InMemoryDailyLimitShield() : ManagedSettingsDailyLimitShield()) resetAnchor = ledger.loadLastLoosened() } @@ -138,7 +139,8 @@ final class UsageLimitService { } static func fingerprint(for dtos: [UsageLimitDTO], period: UsagePeriod, on date: Date) -> String { - let body = dtos + let body = + dtos .map { "\($0.id.uuidString):\($0.minutesPerDay):\($0.selectionData.stableChecksum)" } .sorted() .joined(separator: "|") diff --git a/Normal/Services/WidgetSync.swift b/Normal/Services/WidgetSync.swift index 20a5349..001873a 100644 --- a/Normal/Services/WidgetSync.swift +++ b/Normal/Services/WidgetSync.swift @@ -9,19 +9,21 @@ enum WidgetSync { screenTimeService: any ScreenTimeProviding ) { let customDomainsEnabled = settings?.enableCustomDomains ?? false - let blockStatuses = Dictionary(uniqueKeysWithValues: groups.map { group in - ( - group.id.uuidString, - screenTimeService.blockStatus( - selection: group.selection, - customDomains: customDomainsEnabled ? group.customDomains : [] - ).widget.rawValue - ) - }) + let blockStatuses = Dictionary( + uniqueKeysWithValues: groups.map { group in + ( + group.id.uuidString, + screenTimeService.blockStatus( + selection: group.selection, + customDomains: customDomainsEnabled ? group.customDomains : [] + ).widget.rawValue + ) + }) let store = WidgetSharedStore() - store.saveGroups(groups.map { - WidgetGroupDTO(id: $0.id, name: $0.name, sortIndex: $0.sortIndex, detail: $0.selection.selectedTokenCounts) - }) + store.saveGroups( + groups.map { + WidgetGroupDTO(id: $0.id, name: $0.name, sortIndex: $0.sortIndex, detail: $0.selection.selectedTokenCounts) + }) store.saveKeyTypes(KeyType.selectable(registered: keys.map(\.type)).map(\.rawValue)) store.saveBlockStatuses(blockStatuses) store.saveUnblockDurations((settings?.unblockDurations ?? TimedUnblockDuration.presets).map(\.seconds)) diff --git a/Normal/Shared/Components/AdaptiveStack.swift b/Normal/Shared/Components/AdaptiveStack.swift index 66a3df5..4f6baad 100644 --- a/Normal/Shared/Components/AdaptiveStack.swift +++ b/Normal/Shared/Components/AdaptiveStack.swift @@ -9,7 +9,8 @@ struct AdaptiveStack: View { @ViewBuilder var content: Content var body: some View { - let layout = dynamicTypeSize.isAccessibilitySize + let layout = + dynamicTypeSize.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: horizontalAlignment, spacing: spacing)) : AnyLayout(HStackLayout(alignment: verticalAlignment, spacing: spacing)) layout { content } diff --git a/Normal/Shared/Components/CustomDomainsEditor.swift b/Normal/Shared/Components/CustomDomainsEditor.swift index 5ed1245..5020e5f 100644 --- a/Normal/Shared/Components/CustomDomainsEditor.swift +++ b/Normal/Shared/Components/CustomDomainsEditor.swift @@ -107,15 +107,16 @@ struct CustomDomainsEditor: View { switch CustomDomains.evaluateAdd(input, existing: domains, otherItemCount: otherItemCount) { case .invalid: show(.error("Enter a valid domain like example.com.")) - case let .duplicate(domain): + case .duplicate(let domain): show(.error("\(domain) already added")) input = "" - case let .added(domain, overLimit): + case .added(let domain, let overLimit): withAnimation(.snappy(duration: 0.2)) { domains.append(domain) } input = "" - show(overLimit - ? .warning("\(ScreenTimeLimits.maxBlockedItems)+ items can't be blocked at once and may cause issues") - : nil) + show( + overLimit + ? .warning("\(ScreenTimeLimits.maxBlockedItems)+ items can't be blocked at once and may cause issues") + : nil) } } diff --git a/Normal/Shared/Components/DurationWheelPicker.swift b/Normal/Shared/Components/DurationWheelPicker.swift index 3b33a26..1877784 100644 --- a/Normal/Shared/Components/DurationWheelPicker.swift +++ b/Normal/Shared/Components/DurationWheelPicker.swift @@ -8,7 +8,7 @@ struct DurationWheelPicker: View { var identifierPrefix: String? private var hourOptions: [Int] { - Array(0 ... (maxMinutes / 60)) + Array(0...(maxMinutes / 60)) } private var minuteOptions: [Int] { diff --git a/Normal/Shared/Components/SelectionIconsView.swift b/Normal/Shared/Components/SelectionIconsView.swift index 695143a..fb9b986 100644 --- a/Normal/Shared/Components/SelectionIconsView.swift +++ b/Normal/Shared/Components/SelectionIconsView.swift @@ -20,11 +20,11 @@ struct SelectionIconsView: View { ForEach(shown, id: \.self) { item in Group { switch item { - case let .token(token): + case .token(let token): if let kind = SelectedTokenKind(token) { SelectionTokenLabel(kind: kind) } - case let .domain(domain): + case .domain(let domain): Image(systemName: "globe") .foregroundStyle(.blue.opacity(0.45)) .overlay { diff --git a/Normal/Shared/Components/SelectionTokenLabel.swift b/Normal/Shared/Components/SelectionTokenLabel.swift index 81b9883..92d8912 100644 --- a/Normal/Shared/Components/SelectionTokenLabel.swift +++ b/Normal/Shared/Components/SelectionTokenLabel.swift @@ -7,9 +7,9 @@ struct SelectionTokenLabel: View { var body: some View { switch kind { - case let .application(token): Label(token) - case let .webDomain(token): Label(token) - case let .category(token): Label(token) + case .application(let token): Label(token) + case .webDomain(let token): Label(token) + case .category(let token): Label(token) } } } diff --git a/Normal/Shared/Util/FamilyControlsUtil.swift b/Normal/Shared/Util/FamilyControlsUtil.swift index af3bb52..365ebff 100644 --- a/Normal/Shared/Util/FamilyControlsUtil.swift +++ b/Normal/Shared/Util/FamilyControlsUtil.swift @@ -33,15 +33,18 @@ extension FamilyActivitySelection { static func selectedTokenCounts(apps: Int, websites: Int, categories: Int) -> String { let parts: [String] = [ - pluralized(count: apps, - singular: String(localized: "1 App"), - plural: String(localized: "\(apps) Apps")), - pluralized(count: websites, - singular: String(localized: "1 Website"), - plural: String(localized: "\(websites) Websites")), - pluralized(count: categories, - singular: String(localized: "1 Category"), - plural: String(localized: "\(categories) Categories")), + pluralized( + count: apps, + singular: String(localized: "1 App"), + plural: String(localized: "\(apps) Apps")), + pluralized( + count: websites, + singular: String(localized: "1 Website"), + plural: String(localized: "\(websites) Websites")), + pluralized( + count: categories, + singular: String(localized: "1 Category"), + plural: String(localized: "\(categories) Categories")), ].compactMap(\.self) if parts.isEmpty { @@ -85,13 +88,16 @@ enum SelectedTokenKind: Hashable { nonisolated init?(_ hashable: AnyHashable) { let base = hashable.base if let token = base as? ApplicationToken { - self = .application(token); return + self = .application(token) + return } if let token = base as? WebDomainToken { - self = .webDomain(token); return + self = .webDomain(token) + return } if let token = base as? ActivityCategoryToken { - self = .category(token); return + self = .category(token) + return } return nil } diff --git a/Normal/Views/AppSelect/AppSelectView.swift b/Normal/Views/AppSelect/AppSelectView.swift index d2c38a9..c0e5b38 100644 --- a/Normal/Views/AppSelect/AppSelectView.swift +++ b/Normal/Views/AppSelect/AppSelectView.swift @@ -92,7 +92,9 @@ struct AppSelectView: View { isFamilyActivityPickerPresented = true } } message: { - Text("Updating your app selection will affect the functionality of your groups. After updating selection please update your groups to ensure consistency.") + Text( + "Updating your app selection will affect the functionality of your groups. After updating selection please update your groups to ensure consistency." + ) } .familyActivityPicker(isPresented: $isFamilyActivityPickerPresented, selection: $selection) .onAppear { diff --git a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift index 2150160..8cc192b 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift @@ -141,7 +141,7 @@ struct KeySelectModifier: ViewModifier { } private var missingKey: KeyCheckFlow.MissingKey? { - if case let .missingKey(missingKey) = flow.stage { + if case .missingKey(let missingKey) = flow.stage { return missingKey } return nil @@ -206,12 +206,13 @@ extension View { keyGroupID: UUID? = nil, requestID: UUID? = nil ) -> some View { - modifier(KeySelectModifier( - action: action, - defaultKeyType: defaultKeyType, - requestedKeyType: requestedKeyType, - keyGroupID: keyGroupID, - requestID: requestID - )) + modifier( + KeySelectModifier( + action: action, + defaultKeyType: defaultKeyType, + requestedKeyType: requestedKeyType, + keyGroupID: keyGroupID, + requestID: requestID + )) } } diff --git a/Normal/Views/BlockUnblockViews/KeySelect/LocationUnlockView.swift b/Normal/Views/BlockUnblockViews/KeySelect/LocationUnlockView.swift index e75c747..de360b5 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/LocationUnlockView.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/LocationUnlockView.swift @@ -178,9 +178,9 @@ struct LocationUnlockView: View { } } -private extension View { +extension View { @ViewBuilder - func opaqueNavigationBarBeforeLiquidGlass() -> some View { + fileprivate func opaqueNavigationBarBeforeLiquidGlass() -> some View { if #available(iOS 26.0, *) { self } else { diff --git a/Normal/Views/BlockUnblockViews/KeySelect/QRCameraView.swift b/Normal/Views/BlockUnblockViews/KeySelect/QRCameraView.swift index 8f199c2..7f80693 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/QRCameraView.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/QRCameraView.swift @@ -74,8 +74,8 @@ final class QRCameraController: UIViewController { private func configureSession() { guard !isConfigured, - let device = AVCaptureDevice.default(for: .video), - let input = try? AVCaptureDeviceInput(device: device) + let device = AVCaptureDevice.default(for: .video), + let input = try? AVCaptureDeviceInput(device: device) else { return } session.beginConfiguration() @@ -114,8 +114,8 @@ extension QRCameraController: AVCaptureMetadataOutputObjectsDelegate { from _: AVCaptureConnection ) { guard !hasScanned, - let object = metadataObjects.first as? AVMetadataMachineReadableCodeObject, - let value = object.stringValue + let object = metadataObjects.first as? AVMetadataMachineReadableCodeObject, + let value = object.stringValue else { return } hasScanned = true diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockBannerView.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockBannerView.swift index 0f386df..94e3a14 100644 --- a/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockBannerView.swift +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockBannerView.swift @@ -16,7 +16,7 @@ struct TimedUnblockBannerView: View { .foregroundStyle(.orange) VStack(alignment: .leading, spacing: DS.Spacing.xs - 2) { Text("Timed Unblock Active").font(.headline) - Text(timerInterval: .now ... endDate, countsDown: true) + Text(timerInterval: .now...endDate, countsDown: true) .font(.subheadline.monospacedDigit()) .foregroundStyle(.secondary) } diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift index 3b77fbc..3e1a26c 100644 --- a/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift @@ -16,7 +16,7 @@ struct UnblockDurationSheet: View { private var title: String { switch grant.target { case .all: "Unblock All" - case let .group(group): "Unblock \(group.name)" + case .group(let group): "Unblock \(group.name)" } } diff --git a/Normal/Views/Groups/GroupFormSheet.swift b/Normal/Views/Groups/GroupFormSheet.swift index 0c62799..822b0b0 100644 --- a/Normal/Views/Groups/GroupFormSheet.swift +++ b/Normal/Views/Groups/GroupFormSheet.swift @@ -53,7 +53,7 @@ struct GroupFormSheet: View { private var durationSelection: Binding> { Binding( get: { - if case let .value(duration) = durationOverride, !durations.contains(duration) { + if case .value(let duration) = durationOverride, !durations.contains(duration) { return .none } return durationOverride @@ -65,7 +65,7 @@ struct GroupFormSheet: View { private var keySelection: Binding> { Binding( get: { - if case let .value(keyType) = keyOverride, !groupKeyTypes.contains(keyType) { + if case .value(let keyType) = keyOverride, !groupKeyTypes.contains(keyType) { return .none } return keyOverride @@ -152,7 +152,9 @@ struct GroupFormSheet: View { if !isNew, !isReadOnly { Section { - Button(role: .destructive) { showDeleteConfirmation = true } label: { + Button(role: .destructive) { + showDeleteConfirmation = true + } label: { Text("Delete Group") .frame(maxWidth: .infinity) } @@ -272,7 +274,7 @@ struct GroupFormSheet: View { switch choice { case .appDefault: String(localized: "App Default") case .none: String(localized: "None") - case let .value(chosen): value(chosen) + case .value(let chosen): value(chosen) } } @@ -283,7 +285,9 @@ struct GroupFormSheet: View { } .onDelete(perform: groupKeyDeleteAction) if !isReadOnly { - Button { showAddKey = true } label: { + Button { + showAddKey = true + } label: { Label("Add Key", systemImage: "plus") } } diff --git a/Normal/Views/Groups/GroupListCardView.swift b/Normal/Views/Groups/GroupListCardView.swift index 3a6747e..a95b411 100644 --- a/Normal/Views/Groups/GroupListCardView.swift +++ b/Normal/Views/Groups/GroupListCardView.swift @@ -57,7 +57,7 @@ struct GroupListCardView: View { return true } if settings.enableCustomDomains, - CustomDomains.needsResync(appGroup.customDomains, main: main.customDomains) + CustomDomains.needsResync(appGroup.customDomains, main: main.customDomains) { return true } @@ -197,7 +197,7 @@ struct GroupListCardView: View { AdaptiveStack(spacing: DS.Spacing.sm) { HStack(spacing: DS.Spacing.sm) { Image(systemName: "timer").foregroundStyle(.orange) - Text(timerInterval: .now ... endDate, countsDown: true) + Text(timerInterval: .now...endDate, countsDown: true) .font(.subheadline.monospacedDigit()) .foregroundStyle(.secondary) } diff --git a/Normal/Views/Groups/GroupsView.swift b/Normal/Views/Groups/GroupsView.swift index dd098d2..7f3a0a1 100644 --- a/Normal/Views/Groups/GroupsView.swift +++ b/Normal/Views/Groups/GroupsView.swift @@ -47,33 +47,36 @@ struct GroupsView: View { if appGroups.isEmpty { emptyState } else { - ReorderableListView(items: appGroups, rowContent: { group in - GroupListCardView( - appGroup: group, - authAction: $authAction, - pendingGroupID: $pendingGroupID, - durationGrant: $durationGrant, - unblockAlert: $unblockAlert - ) - }, onMove: move) - .bottomFooter { - if isBlocked { - FooterMessage(text: BlockedMessage.groups) - } - } - // Host the key prompt on the stable list, scoped to whichever card - // triggered it, instead of on the card row. - .protectedAction( - $authAction, - defaultKeyType: allSettings.unwrapped.defaultKeyType( - for: appGroups.first { $0.id == pendingGroupID } - ), - keyGroupID: pendingGroupID - ) - .sheet(item: $durationGrant) { grant in - UnblockDurationSheet(grant: grant) { unblockAlert = UnblockAlert($0) } + ReorderableListView( + items: appGroups, + rowContent: { group in + GroupListCardView( + appGroup: group, + authAction: $authAction, + pendingGroupID: $pendingGroupID, + durationGrant: $durationGrant, + unblockAlert: $unblockAlert + ) + }, onMove: move + ) + .bottomFooter { + if isBlocked { + FooterMessage(text: BlockedMessage.groups) } - .unblockAlert($unblockAlert) + } + // Host the key prompt on the stable list, scoped to whichever card + // triggered it, instead of on the card row. + .protectedAction( + $authAction, + defaultKeyType: allSettings.unwrapped.defaultKeyType( + for: appGroups.first { $0.id == pendingGroupID } + ), + keyGroupID: pendingGroupID + ) + .sheet(item: $durationGrant) { grant in + UnblockDurationSheet(grant: grant) { unblockAlert = UnblockAlert($0) } + } + .unblockAlert($unblockAlert) } } diff --git a/Normal/Views/Groups/SelectAppsForGroupRowView.swift b/Normal/Views/Groups/SelectAppsForGroupRowView.swift index a2d72a8..33754d1 100644 --- a/Normal/Views/Groups/SelectAppsForGroupRowView.swift +++ b/Normal/Views/Groups/SelectAppsForGroupRowView.swift @@ -22,9 +22,9 @@ struct SelectAppForGroupRowView: View { @ViewBuilder private var tokenLabel: some View { switch SelectedTokenKind(token as AnyHashable) { - case let .application(token): Label(token) - case let .webDomain(token): Label(token) - case let .category(token): Label(token) + case .application(let token): Label(token) + case .webDomain(let token): Label(token) + case .category(let token): Label(token) case nil: EmptyView() } } diff --git a/Normal/Views/Groups/SelectAppsForGroupSheet.swift b/Normal/Views/Groups/SelectAppsForGroupSheet.swift index 372f00a..1d8fd1d 100644 --- a/Normal/Views/Groups/SelectAppsForGroupSheet.swift +++ b/Normal/Views/Groups/SelectAppsForGroupSheet.swift @@ -142,8 +142,8 @@ struct SelectAppsForGroupSheet: View { } } -private extension Set { - mutating func toggle(_ element: Element) { +extension Set { + fileprivate mutating func toggle(_ element: Element) { if contains(element) { remove(element) } else { diff --git a/Normal/Views/Key/GroupKeyRow.swift b/Normal/Views/Key/GroupKeyRow.swift index baa51b0..6a83bca 100644 --- a/Normal/Views/Key/GroupKeyRow.swift +++ b/Normal/Views/Key/GroupKeyRow.swift @@ -13,7 +13,9 @@ struct GroupKeyRow: View { } var body: some View { - Button { isEditing = true } label: { + Button { + isEditing = true + } label: { HStack { Label { VStack(alignment: .leading, spacing: DS.Spacing.xs - 2) { diff --git a/Normal/Views/Key/KeyFormSheet.swift b/Normal/Views/Key/KeyFormSheet.swift index 6a5e796..a975aab 100644 --- a/Normal/Views/Key/KeyFormSheet.swift +++ b/Normal/Views/Key/KeyFormSheet.swift @@ -134,7 +134,8 @@ struct KeyFormSheet: View { } if isReadOnly { - Section {} footer: { + Section { + } footer: { Text(BlockedMessage.keys) .frame(maxWidth: .infinity, alignment: .center) } @@ -229,25 +230,27 @@ struct KeyFormSheet: View { switch keyType { case .nfc, .qr: guard let rawValue = scannedKeyId else { return } - modelContext.insert(Key( - name: trimmed, - type: keyType, - rawValue: rawValue, - scanKind: scannedKind, - sortIndex: nextIndex, - groupID: groupID - )) + modelContext.insert( + Key( + name: trimmed, + type: keyType, + rawValue: rawValue, + scanKind: scannedKind, + sortIndex: nextIndex, + groupID: groupID + )) case .location: guard let captured = capturedLocation else { return } - modelContext.insert(Key( - name: trimmed, - latitude: captured.latitude, - longitude: captured.longitude, - radiusMeters: captured.radiusMeters, - radiusKind: captured.kind, - sortIndex: nextIndex, - groupID: groupID - )) + modelContext.insert( + Key( + name: trimmed, + latitude: captured.latitude, + longitude: captured.longitude, + radiusMeters: captured.radiusMeters, + radiusKind: captured.kind, + sortIndex: nextIndex, + groupID: groupID + )) } } dismiss() diff --git a/Normal/Views/Key/KeyFormSheetSetupSection.swift b/Normal/Views/Key/KeyFormSheetSetupSection.swift index d078d64..9d43122 100644 --- a/Normal/Views/Key/KeyFormSheetSetupSection.swift +++ b/Normal/Views/Key/KeyFormSheetSetupSection.swift @@ -94,9 +94,13 @@ struct KeyFormSheetSetupSection: View { .foregroundStyle(.secondary) stepLabel(number: hasMultipleTypes ? 3 : 2, title: "Set Location") - Button { showLocationPicker = true } label: { locationButtonContent } - .buttonStyle(.plain) - .accessibilityIdentifier("key.locationButton") + Button { + showLocationPicker = true + } label: { + locationButtonContent + } + .buttonStyle(.plain) + .accessibilityIdentifier("key.locationButton") } .padding(.vertical, DS.Spacing.sm) } @@ -105,9 +109,11 @@ struct KeyFormSheetSetupSection: View { HStack(alignment: .top, spacing: DS.Spacing.sm) { Image(systemName: "info.circle.fill") .foregroundStyle(.blue) - Text("Normal checks a location key when you unblock. With Background Location on in Settings, a shortcut can check it without opening Normal. Your NFC and QR keys work from anywhere!") - .font(.caption) - .foregroundStyle(.secondary) + Text( + "Normal checks a location key when you unblock. With Background Location on in Settings, a shortcut can check it without opening Normal. Your NFC and QR keys work from anywhere!" + ) + .font(.caption) + .foregroundStyle(.secondary) } .frame(maxWidth: .infinity, alignment: .leading) .padding(DS.Spacing.md) @@ -124,10 +130,12 @@ struct KeyFormSheetSetupSection: View { Image(systemName: "lock.fill").foregroundStyle(.tertiary) } .font(.subheadline.weight(.medium)) - Text("You currently have \(kind.label) keys. You can only have one type of location key at a time. To change the type, delete all existing location keys of this type.") - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) + Text( + "You currently have \(kind.label) keys. You can only have one type of location key at a time. To change the type, delete all existing location keys of this type." + ) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } .padding(DS.Spacing.md) .frame(maxWidth: .infinity, alignment: .leading) diff --git a/Normal/Views/Key/KeyTypeExamplesView.swift b/Normal/Views/Key/KeyTypeExamplesView.swift index 632738e..4c97d9a 100644 --- a/Normal/Views/Key/KeyTypeExamplesView.swift +++ b/Normal/Views/Key/KeyTypeExamplesView.swift @@ -21,15 +21,27 @@ struct KeyTypeExamplesView: View { cardTitle("NFC tag examples", systemImage: "wave.3.right") FeatureRow(systemImage: "tag.fill", text: "Almost any NFC tag works. AirTags, Amiibo, and even Credit Cards have NFC chips you can use.") FeatureRow(systemImage: "cart.fill", text: "You can also buy packs of blank NFC tags online for very little.") - FeatureRow(systemImage: "lock.shield.fill", text: "Normal only reads the tag's unique ID, never the data on it. That means only the tag you register can unblock your apps, and your privacy stays protected.") + FeatureRow( + systemImage: "lock.shield.fill", + text: + "Normal only reads the tag's unique ID, never the data on it. That means only the tag you register can unblock your apps, and your privacy stays protected." + ) } } private var qrCard: some View { card { cardTitle("QR code or barcode examples", systemImage: "qrcode") - FeatureRow(systemImage: "doc.fill", text: "Any QR code or barcode works, even a product barcode off a snack wrapper. Print one on paper, put it on a sticker, or show it on a second device's screen.") - FeatureRow(systemImage: "arrow.triangle.2.circlepath", text: "Normal reads the value inside the QR code or barcode. Use something you can recreate later if you lose it, or make it random so it's hard to reproduce.") + FeatureRow( + systemImage: "doc.fill", + text: + "Any QR code or barcode works, even a product barcode off a snack wrapper. Print one on paper, put it on a sticker, or show it on a second device's screen." + ) + FeatureRow( + systemImage: "arrow.triangle.2.circlepath", + text: + "Normal reads the value inside the QR code or barcode. Use something you can recreate later if you lose it, or make it random so it's hard to reproduce." + ) VStack(alignment: .leading, spacing: DS.Spacing.xs) { Text("Getting one").font(.subheadline.weight(.semibold)) BulletRow(text: "Any product barcode, like one off a snack wrapper or book") @@ -43,9 +55,19 @@ struct KeyTypeExamplesView: View { private var locationCard: some View { card { cardTitle("Location examples", systemImage: KeyType.location.icon) - FeatureRow(systemImage: "location.circle.fill", text: "Unblock radius: your key only works inside the areas you choose, like your office or the gym.", tint: LocationRadiusKind.unblock.zoneColor) - FeatureRow(systemImage: "location.slash.circle.fill", text: "Block radius: your key only works outside the areas you choose, like home or school, so you can't unblock while you're there.", tint: LocationRadiusKind.block.zoneColor) - FeatureRow(systemImage: "iphone", text: "Normal only checks your location at the moment you unblock. With Background Location on in Settings, a shortcut can unblock without opening Normal.") + FeatureRow( + systemImage: "location.circle.fill", + text: "Unblock radius: your key only works inside the areas you choose, like your office or the gym.", + tint: LocationRadiusKind.unblock.zoneColor) + FeatureRow( + systemImage: "location.slash.circle.fill", + text: "Block radius: your key only works outside the areas you choose, like home or school, so you can't unblock while you're there.", + tint: LocationRadiusKind.block.zoneColor) + FeatureRow( + systemImage: "iphone", + text: + "Normal only checks your location at the moment you unblock. With Background Location on in Settings, a shortcut can unblock without opening Normal." + ) } } @@ -55,7 +77,9 @@ struct KeyTypeExamplesView: View { FeatureRow(systemImage: "door.left.hand.closed", text: "Another room, a closet, or a high shelf", tint: .orange) FeatureRow(systemImage: "car.fill", text: "Your car, office, mailbox or with a trusted person", tint: .orange) FeatureRow(systemImage: "location.fill", text: "For location keys, the park, office or somewhere random far away.", tint: .orange) - FeatureRow(systemImage: "person.2.fill", text: "However difficult you make it to reach is how difficult it will be to unblock your device.", tint: .orange) + FeatureRow( + systemImage: "person.2.fill", text: "However difficult you make it to reach is how difficult it will be to unblock your device.", + tint: .orange) BulletRow(text: "Setup an accessible backup key so you're never fully locked out.") .font(.footnote) .foregroundStyle(.secondary) diff --git a/Normal/Views/Key/KeysView.swift b/Normal/Views/Key/KeysView.swift index 65ca351..0fbe234 100644 --- a/Normal/Views/Key/KeysView.swift +++ b/Normal/Views/Key/KeysView.swift @@ -23,7 +23,9 @@ struct KeysView: View { .settingsToolbar() .toolbar { ToolbarItem(placement: .primaryAction) { - Button { isShowingSheet.toggle() } label: { + Button { + isShowingSheet.toggle() + } label: { Label("Add Key", systemImage: "plus") } .accessibilityIdentifier("keys.addButton") @@ -41,9 +43,11 @@ struct KeysView: View { if keys.isEmpty { KeysEmptyStateView { isShowingSheet = true } } else { - ReorderableListView(items: keys, rowContent: { key in - KeyListCardView(key: key) - }, onMove: move, footer: { groupKeysRow }) + ReorderableListView( + items: keys, + rowContent: { key in + KeyListCardView(key: key) + }, onMove: move, footer: { groupKeysRow }) } } .bottomFooter { @@ -63,12 +67,13 @@ struct KeysView: View { groupKeysLink .listRowBackground(Color.clear) .listRowSeparator(.hidden) - .listRowInsets(EdgeInsets( - top: DS.Spacing.sm - 2, - leading: DS.Spacing.lg, - bottom: DS.Spacing.sm - 2, - trailing: DS.Spacing.lg - )) + .listRowInsets( + EdgeInsets( + top: DS.Spacing.sm - 2, + leading: DS.Spacing.lg, + bottom: DS.Spacing.sm - 2, + trailing: DS.Spacing.lg + )) } } diff --git a/Normal/Views/Key/LocationCamera.swift b/Normal/Views/Key/LocationCamera.swift index c563517..91a09e7 100644 --- a/Normal/Views/Key/LocationCamera.swift +++ b/Normal/Views/Key/LocationCamera.swift @@ -11,8 +11,10 @@ enum LocationCamera { } static func boundingRegion(user: CLLocationCoordinate2D, keys: [Key]) -> MKCoordinateRegion { - var minLat = user.latitude, maxLat = user.latitude - var minLon = user.longitude, maxLon = user.longitude + var minLat = user.latitude + var maxLat = user.latitude + var minLon = user.longitude + var maxLon = user.longitude for key in keys { guard let center = key.coordinate, let radius = key.radiusMeters else { continue } let latPad = radius / 111_000 diff --git a/Normal/Views/Key/LocationKeyMapPreview.swift b/Normal/Views/Key/LocationKeyMapPreview.swift index 4764c9d..0e84a57 100644 --- a/Normal/Views/Key/LocationKeyMapPreview.swift +++ b/Normal/Views/Key/LocationKeyMapPreview.swift @@ -8,11 +8,12 @@ struct LocationKeyMapPreview: View { if let coordinate = key.coordinate, let radius = key.radiusMeters { let kind = key.radiusKind ?? .unblock Map( - initialPosition: .region(MKCoordinateRegion( - center: coordinate, - latitudinalMeters: radius * 4, - longitudinalMeters: radius * 4 - )), + initialPosition: .region( + MKCoordinateRegion( + center: coordinate, + latitudinalMeters: radius * 4, + longitudinalMeters: radius * 4 + )), interactionModes: [] ) { MapCircle(center: coordinate, radius: radius) diff --git a/Normal/Views/Key/LocationPickerSheet.swift b/Normal/Views/Key/LocationPickerSheet.swift index 76c448a..e25ea06 100644 --- a/Normal/Views/Key/LocationPickerSheet.swift +++ b/Normal/Views/Key/LocationPickerSheet.swift @@ -87,10 +87,11 @@ struct LocationPickerSheet: View { private func centerOnCurrent() { guard let currentLocation else { return } pin = currentLocation.coordinate - position = .region(LocationCamera.focusRegion( - around: currentLocation.coordinate, - radiusMeters: radiusMeters - )) + position = .region( + LocationCamera.focusRegion( + around: currentLocation.coordinate, + radiusMeters: radiusMeters + )) } @MainActor diff --git a/Normal/Views/Key/LocationRadiusControls.swift b/Normal/Views/Key/LocationRadiusControls.swift index 671db91..6097ab3 100644 --- a/Normal/Views/Key/LocationRadiusControls.swift +++ b/Normal/Views/Key/LocationRadiusControls.swift @@ -25,7 +25,7 @@ struct LocationRadiusControls: View { .disabled(!canUseCurrentLocation) } - Slider(value: $radiusMeters, in: Self.minRadius ... Self.maxRadius, step: 50) { + Slider(value: $radiusMeters, in: Self.minRadius...Self.maxRadius, step: 50) { Text("Radius") } .tint(kind.zoneColor) diff --git a/Normal/Views/Schedules/ScheduleCardView.swift b/Normal/Views/Schedules/ScheduleCardView.swift index d73a030..cb75df2 100644 --- a/Normal/Views/Schedules/ScheduleCardView.swift +++ b/Normal/Views/Schedules/ScheduleCardView.swift @@ -39,7 +39,7 @@ struct ScheduleCardView: View { return true } if allSettings.first?.enableCustomDomains ?? false, - CustomDomains.needsResync(schedule.customDomains, main: main.customDomains) + CustomDomains.needsResync(schedule.customDomains, main: main.customDomains) { return true } diff --git a/Normal/Views/Schedules/ScheduleFormSheet.swift b/Normal/Views/Schedules/ScheduleFormSheet.swift index 300a3d8..4621b82 100644 --- a/Normal/Views/Schedules/ScheduleFormSheet.swift +++ b/Normal/Views/Schedules/ScheduleFormSheet.swift @@ -80,7 +80,7 @@ struct ScheduleFormSheet: View { self.existing = existing _name = State(initialValue: existing?.name ?? "") _selection = State(initialValue: existing?.selection ?? FamilyActivitySelection()) - _selectedWeekdays = State(initialValue: existing?.weekdays ?? Set(2 ... 6)) + _selectedWeekdays = State(initialValue: existing?.weekdays ?? Set(2...6)) _shouldBlock = State(initialValue: existing?.shouldBlock ?? false) _isTimed = State(initialValue: existing?.isTimed ?? true) _isEnabled = State(initialValue: existing?.isEnabled ?? false) @@ -160,7 +160,9 @@ struct ScheduleFormSheet: View { private var deleteSection: some View { Section { - Button(role: .destructive) { showDeleteConfirmation = true } label: { + Button(role: .destructive) { + showDeleteConfirmation = true + } label: { Text("Delete Schedule") .frame(maxWidth: .infinity) } diff --git a/Normal/Views/Schedules/SchedulesView.swift b/Normal/Views/Schedules/SchedulesView.swift index 79e932f..4c27f0f 100644 --- a/Normal/Views/Schedules/SchedulesView.swift +++ b/Normal/Views/Schedules/SchedulesView.swift @@ -53,14 +53,17 @@ struct SchedulesView: View { if schedules.isEmpty { emptyState } else { - ReorderableListView(items: schedules, rowContent: { schedule in - ScheduleCardView(schedule: schedule) - }, onMove: move) - .bottomFooter { - if let message = bottomMessage { - FooterMessage(text: message) - } + ReorderableListView( + items: schedules, + rowContent: { schedule in + ScheduleCardView(schedule: schedule) + }, onMove: move + ) + .bottomFooter { + if let message = bottomMessage { + FooterMessage(text: message) } + } } } diff --git a/Normal/Views/Schedules/WeekdayPickerView.swift b/Normal/Views/Schedules/WeekdayPickerView.swift index ac9da36..c27908a 100644 --- a/Normal/Views/Schedules/WeekdayPickerView.swift +++ b/Normal/Views/Schedules/WeekdayPickerView.swift @@ -5,7 +5,7 @@ struct WeekdayPickerView: View { private let days: [(Int, String)] = { let symbols = Calendar.current.veryShortWeekdaySymbols - return (1 ... 7).map { ($0, symbols[$0 - 1]) } + return (1...7).map { ($0, symbols[$0 - 1]) } }() var body: some View { diff --git a/Normal/Views/Schedules/WeekdayStrip.swift b/Normal/Views/Schedules/WeekdayStrip.swift index 7d1df3a..f5501c3 100644 --- a/Normal/Views/Schedules/WeekdayStrip.swift +++ b/Normal/Views/Schedules/WeekdayStrip.swift @@ -7,14 +7,14 @@ struct WeekdayStrip: View { private var accessibilityDays: String { let names = Calendar.current.weekdaySymbols return weekdays.sorted() - .filter { (1 ... 7).contains($0) } + .filter { (1...7).contains($0) } .map { names[$0 - 1] } .formatted(.list(type: .and)) } var body: some View { HStack(spacing: DS.Spacing.xs) { - ForEach(1 ... 7, id: \.self) { day in + ForEach(1...7, id: \.self) { day in let isOn = weekdays.contains(day) Text(Calendar.current.veryShortWeekdaySymbols[day - 1]) .font(.caption2.weight(.medium)) diff --git a/Normal/Views/Settings/AdultContentToggleView.swift b/Normal/Views/Settings/AdultContentToggleView.swift index 2a47509..a5be241 100644 --- a/Normal/Views/Settings/AdultContentToggleView.swift +++ b/Normal/Views/Settings/AdultContentToggleView.swift @@ -12,6 +12,6 @@ struct AdultContentToggleView: View { onEnable: { screenTimeService.blockAdultContent() }, onDisable: { screenTimeService.allowAdultContent($0) } ) - .accessibilityIdentifier("settings.blockAdultContentToggle") + .accessibilityIdentifier("settings.blockAdultContentToggle") } } diff --git a/Normal/Views/Settings/ContactUsView.swift b/Normal/Views/Settings/ContactUsView.swift index e670547..92f0bb2 100644 --- a/Normal/Views/Settings/ContactUsView.swift +++ b/Normal/Views/Settings/ContactUsView.swift @@ -6,8 +6,10 @@ struct ContactUsView: View { var body: some View { List { Section { - Text("Since Normal collects no data, contacting us is the only way to share suggestions, give feedback, or report a bug. We appreciate your feedback!") - .font(.callout) + Text( + "Since Normal collects no data, contacting us is the only way to share suggestions, give feedback, or report a bug. We appreciate your feedback!" + ) + .font(.callout) } Section("Email") { diff --git a/Normal/Views/Settings/DonationView.swift b/Normal/Views/Settings/DonationView.swift index f0850d9..57cda7f 100644 --- a/Normal/Views/Settings/DonationView.swift +++ b/Normal/Views/Settings/DonationView.swift @@ -18,8 +18,10 @@ struct DonationView: View { .foregroundStyle(.pink) Text("Support Normal") .font(.title2.bold()) - Text("Normal is free and open-source, and always will be. No paywalls, subscriptions, ads or data-collection. If you would like to support Normal, donations are greatly appreciated.") - .foregroundStyle(.secondary) + Text( + "Normal is free and open-source, and always will be. No paywalls, subscriptions, ads or data-collection. If you would like to support Normal, donations are greatly appreciated." + ) + .foregroundStyle(.secondary) } .padding(.vertical, DS.Spacing.sm) } @@ -109,7 +111,7 @@ struct DonationView: View { .font(.headline) .monospacedDigit() .redacted(reason: .placeholder) - case let .available(displayPrice): + case .available(let displayPrice): Text(displayPrice) .font(.headline) .monospacedDigit() @@ -124,7 +126,7 @@ struct DonationView: View { let cadence = option.cadence == .monthly ? "per month" : "one-time" switch state { case .loading: return "Loading price, \(cadence)" - case let .available(displayPrice): return "\(displayPrice) \(cadence)" + case .available(let displayPrice): return "\(displayPrice) \(cadence)" case .unavailable: return "Currently unavailable, \(cadence)" } } diff --git a/Normal/Views/Settings/FAQ/FAQAnswers.swift b/Normal/Views/Settings/FAQ/FAQAnswers.swift index 5259f18..c857596 100644 --- a/Normal/Views/Settings/FAQ/FAQAnswers.swift +++ b/Normal/Views/Settings/FAQ/FAQAnswers.swift @@ -6,7 +6,9 @@ enum FAQAnswer { static let isNormalFree = AnyView( VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("Yes, it shouldn't cost anything to use your phone less.") - Text("Normal is 100% free with no in-app purchases, subscriptions, or hidden fees. It's an open-source project and the source code is available on GitHub for you to modify and tinker with.") + Text( + "Normal is 100% free with no in-app purchases, subscriptions, or hidden fees. It's an open-source project and the source code is available on GitHub for you to modify and tinker with." + ) } .font(body) .foregroundStyle(.secondary) @@ -16,7 +18,9 @@ enum FAQAnswer { VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("We don't collect or sell any data. You can view the source code to verify this yourself.") Text("There are no accounts, no internet connection required, and no data logging.") - Text("Normal uses Apple's Screen Time API and the Managed Settings framework to enforce app limits entirely on your device. All blocking rules, schedules, and configurations are stored locally, nothing is ever sent to a server.") + Text( + "Normal uses Apple's Screen Time API and the Managed Settings framework to enforce app limits entirely on your device. All blocking rules, schedules, and configurations are stored locally, nothing is ever sent to a server." + ) } .font(body) .foregroundStyle(.secondary) @@ -25,7 +29,9 @@ enum FAQAnswer { static let bugsWithoutCollection = AnyView( VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("We rely on community feedback and contributions to identify issues and implement improvements.") - Text("Since all data remains on your device, we can't gather usage statistics. Instead, we encourage users to report bugs and suggest features directly through our GitHub repository.") + Text( + "Since all data remains on your device, we can't gather usage statistics. Instead, we encourage users to report bugs and suggest features directly through our GitHub repository." + ) VStack(alignment: .leading, spacing: DS.Spacing.xs) { Text("You can also reach us at") Link("info@normalengineering.org", destination: URL(string: "mailto:info@normalengineering.org")!) @@ -50,11 +56,15 @@ enum FAQAnswer { VStack(alignment: .leading, spacing: DS.Spacing.md) { VStack(alignment: .leading, spacing: DS.Spacing.xs) { Text("Apple's Screen Time").fontWeight(.medium).foregroundStyle(.primary) - Text("works on an opt-out basis. When you hit a limit, you're simply asked whether to continue or not. It's easy to dismiss with a single tap, easy to bypass with a passcode, and tedious to set up.") + Text( + "works on an opt-out basis. When you hit a limit, you're simply asked whether to continue or not. It's easy to dismiss with a single tap, easy to bypass with a passcode, and tedious to set up." + ) } VStack(alignment: .leading, spacing: DS.Spacing.xs) { Text("Normal").fontWeight(.medium).foregroundStyle(.primary) - Text("takes an opt-in approach. Apps you select are blocked by default. To use them, you have to physically scan an NFC tag, QR code, or barcode you've placed somewhere intentional.") + Text( + "takes an opt-in approach. Apps you select are blocked by default. To use them, you have to physically scan an NFC tag, QR code, or barcode you've placed somewhere intentional." + ) } VStack(alignment: .leading, spacing: DS.Spacing.xs) { BulletRow(text: "Stronger, harder-to-bypass blocking") @@ -71,7 +81,8 @@ enum FAQAnswer { Text("Aside from being completely free and open source, Normal is built to be much stronger and better serve its purpose.") FAQHeadedParagraph( title: "Opt-in approach", - text: "Most screen time apps use an opt-out approach, like Apple's Screen Time, where you're asked to confirm each time you exceed a limit. With Normal, selected apps are blocked by default. To use them, you have to physically scan an NFC tag, QR code, or barcode you've placed somewhere intentional." + text: + "Most screen time apps use an opt-out approach, like Apple's Screen Time, where you're asked to confirm each time you exceed a limit. With Normal, selected apps are blocked by default. To use them, you have to physically scan an NFC tag, QR code, or barcode you've placed somewhere intentional." ) FAQHeadedParagraph( title: "Physical layer", @@ -79,11 +90,13 @@ enum FAQAnswer { ) FAQHeadedParagraph( title: "Timed unblocks", - text: "Other apps require you to manually reblock when you're done, and users commonly report forgetting to reblock or falling back into doom-scrolling. With Normal, set a timed unblock for 15 minutes and you'll be automatically blocked again when it's up. Going to an event where you need to stay reachable? Unblock for a few hours and Normal handles the rest. You can add your own durations in Settings, under Unblock Durations." + text: + "Other apps require you to manually reblock when you're done, and users commonly report forgetting to reblock or falling back into doom-scrolling. With Normal, set a timed unblock for 15 minutes and you'll be automatically blocked again when it's up. Going to an event where you need to stay reachable? Unblock for a few hours and Normal handles the rest. You can add your own durations in Settings, under Unblock Durations." ) FAQHeadedParagraph( title: "App groups", - text: "Only need to unblock Instagram to post quickly? Create an app group for it. Select a 15-minute unblock and only the apps you need will be available, no excuse to check anything else. Complete granular control with Normal." + text: + "Only need to unblock Instagram to post quickly? Create an app group for it. Select a 15-minute unblock and only the apps you need will be available, no excuse to check anything else. Complete granular control with Normal." ) } .font(body) @@ -122,14 +135,18 @@ enum FAQAnswer { static let reselectAppLimitation = AnyView( VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("This is an Apple limitation, not a Normal one.") - Text("Apple's Screen Time API is restrictive for privacy reasons. The app-selection pop-over is made by Apple, not us, and is the only way to select apps for Screen Time.") + Text( + "Apple's Screen Time API is restrictive for privacy reasons. The app-selection pop-over is made by Apple, not us, and is the only way to select apps for Screen Time." + ) Text("Here's the technical reason:") VStack(alignment: .leading, spacing: DS.Spacing.xs) { BulletRow(text: "Apple creates a random ID for each app every time you use the picker") BulletRow(text: "Developers aren't told which apps were previously selected") BulletRow(text: "There's no way for us to carry over your previous selections automatically") } - Text("We require reselecting schedules and groups to ensure Normal's groups, apps, and timed unlocks work consistently. We wish we could make this smoother, but Apple enforces this strictly to protect user privacy.") + Text( + "We require reselecting schedules and groups to ensure Normal's groups, apps, and timed unlocks work consistently. We wish we could make this smoother, but Apple enforces this strictly to protect user privacy." + ) } .font(body) .foregroundStyle(.secondary) @@ -154,13 +171,17 @@ enum FAQAnswer { static let nfcTypeSupport = AnyView( VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("Normal identifies an NFC tag by its unique ID, not by the data stored inside it.") - Text("Some high-security tags, like certain bank or transit cards, deliberately use a rotating ID that changes on every scan, for privacy and anti-tracking reasons.") + Text( + "Some high-security tags, like certain bank or transit cards, deliberately use a rotating ID that changes on every scan, for privacy and anti-tracking reasons." + ) VStack(alignment: .leading, spacing: DS.Spacing.xs) { BulletRow(text: "Their ID is different every time you tap them") BulletRow(text: "We can't confirm it's the same tag you registered") BulletRow(text: "So they can't be used as a reliable key") } - Text("Use a tag with a fixed unique ID; AirTags, Amiibo, most Credit Cards and most everyday NFC tags work well. Or use a QR code/barcode or Location as a key instead.") + Text( + "Use a tag with a fixed unique ID; AirTags, Amiibo, most Credit Cards and most everyday NFC tags work well. Or use a QR code/barcode or Location as a key instead." + ) } .font(body) .foregroundStyle(.secondary) diff --git a/Normal/Views/Settings/FAQ/FAQContent.swift b/Normal/Views/Settings/FAQ/FAQContent.swift index 4482b46..11b8974 100644 --- a/Normal/Views/Settings/FAQ/FAQContent.swift +++ b/Normal/Views/Settings/FAQ/FAQContent.swift @@ -2,27 +2,39 @@ import SwiftUI enum FAQContent { static let sections: [FAQSection] = [ - FAQSection(title: "Getting Started & Setup", entries: [ - FAQEntry(question: "What can I use as a key?", answer: FAQAnswer.keyTypes), - FAQEntry(question: "Are Any NFC tags not supported?", answer: FAQAnswer.nfcTypeSupport), - FAQEntry(question: "Can I unblock from Shortcuts or Siri?", answer: FAQAnswer.shortcutsUnblock), - FAQEntry(question: "Can I use Normal to make my iPhone a dumbphone or semi-dumb feature phone?", answer: FAQAnswer.dumbphone), - FAQEntry(question: "Why do I have to reselect apps in my schedules and groups when I update my selected apps?", answer: FAQAnswer.reselectAppLimitation), - FAQEntry(question: "Can I prevent disabling Normal via Settings? I want to make it impossible to access blocked apps.", answer: FAQAnswer.settingsBypass), - ]), - FAQSection(title: "Privacy & Cost", entries: [ - FAQEntry(question: "Is Normal really free?", answer: FAQAnswer.isNormalFree), - FAQEntry(question: "Is it really privacy friendly?", answer: FAQAnswer.privacyFriendly), - FAQEntry(question: "Does Normal work without an internet connection?", answer: FAQAnswer.worksOffline), - FAQEntry(question: "How does Normal fix bugs and improve without data collection?", answer: FAQAnswer.bugsWithoutCollection), - ]), - FAQSection(title: "Why Normal?", entries: [ - FAQEntry(question: "How is Normal different from Apple's built-in Screen Time?", answer: FAQAnswer.vsAppleScreenTime), - FAQEntry(question: "How is Normal different from the other screen time apps?", answer: FAQAnswer.vsOtherApps), - ]), - FAQSection(title: "Project & Support", entries: [ - FAQEntry(question: "Can I contribute to the project?", answer: FAQAnswer.contribute), - FAQEntry(question: "How can I contact you?", answer: FAQAnswer.contact), - ]), + FAQSection( + title: "Getting Started & Setup", + entries: [ + FAQEntry(question: "What can I use as a key?", answer: FAQAnswer.keyTypes), + FAQEntry(question: "Are Any NFC tags not supported?", answer: FAQAnswer.nfcTypeSupport), + FAQEntry(question: "Can I unblock from Shortcuts or Siri?", answer: FAQAnswer.shortcutsUnblock), + FAQEntry(question: "Can I use Normal to make my iPhone a dumbphone or semi-dumb feature phone?", answer: FAQAnswer.dumbphone), + FAQEntry( + question: "Why do I have to reselect apps in my schedules and groups when I update my selected apps?", + answer: FAQAnswer.reselectAppLimitation), + FAQEntry( + question: "Can I prevent disabling Normal via Settings? I want to make it impossible to access blocked apps.", + answer: FAQAnswer.settingsBypass), + ]), + FAQSection( + title: "Privacy & Cost", + entries: [ + FAQEntry(question: "Is Normal really free?", answer: FAQAnswer.isNormalFree), + FAQEntry(question: "Is it really privacy friendly?", answer: FAQAnswer.privacyFriendly), + FAQEntry(question: "Does Normal work without an internet connection?", answer: FAQAnswer.worksOffline), + FAQEntry(question: "How does Normal fix bugs and improve without data collection?", answer: FAQAnswer.bugsWithoutCollection), + ]), + FAQSection( + title: "Why Normal?", + entries: [ + FAQEntry(question: "How is Normal different from Apple's built-in Screen Time?", answer: FAQAnswer.vsAppleScreenTime), + FAQEntry(question: "How is Normal different from the other screen time apps?", answer: FAQAnswer.vsOtherApps), + ]), + FAQSection( + title: "Project & Support", + entries: [ + FAQEntry(question: "Can I contribute to the project?", answer: FAQAnswer.contribute), + FAQEntry(question: "How can I contact you?", answer: FAQAnswer.contact), + ]), ] } diff --git a/Normal/Views/Settings/FAQ/SettingsBypassGuide.swift b/Normal/Views/Settings/FAQ/SettingsBypassGuide.swift index b4e41b8..c92145c 100644 --- a/Normal/Views/Settings/FAQ/SettingsBypassGuide.swift +++ b/Normal/Views/Settings/FAQ/SettingsBypassGuide.swift @@ -27,9 +27,11 @@ struct SettingsBypassGuide: View { Label("Proceed at your own risk", systemImage: "exclamationmark.triangle.fill") .font(.headline) .foregroundStyle(.orange) - Text("Preventing the Settings bypass is possible, but with it in place the only ways to turn off blocks are through Normal or resetting your phone. If you lock yourself out of your apps, we are not responsible, even if Normal stops working as expected. We are also not responsible for any data loss if you have to reset your device to regain access.") - .font(.subheadline) - .foregroundStyle(.primary) + Text( + "Preventing the Settings bypass is possible, but with it in place the only ways to turn off blocks are through Normal or resetting your phone. If you lock yourself out of your apps, we are not responsible, even if Normal stops working as expected. We are also not responsible for any data loss if you have to reset your device to regain access." + ) + .font(.subheadline) + .foregroundStyle(.primary) } .padding() .frame(maxWidth: .infinity, alignment: .leading) @@ -91,7 +93,9 @@ struct SettingsBypassGuide: View { private var howItWorks: some View { VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("How it works").font(.headline) - Text("Screen Time opens authentication in Settings. The automation detects Settings closing and immediately returns you to the Home Screen, preventing you from reaching the disable option.") + Text( + "Screen Time opens authentication in Settings. The automation detects Settings closing and immediately returns you to the Home Screen, preventing you from reaching the disable option." + ) VStack(alignment: .leading, spacing: DS.Spacing.xs) { BulletRow(text: "You may need to enable Face ID for this to work") BulletRow(text: "You can still access other device settings normally") @@ -103,7 +107,10 @@ struct SettingsBypassGuide: View { VStack(alignment: .leading, spacing: DS.Spacing.md) { Text("Important notes").font(.headline) VStack(alignment: .leading, spacing: DS.Spacing.sm) { - BulletRow(text: "When you update your selected apps in Normal, you'll need to reselect apps in your schedules and groups due to an Apple Screen Time limitation.") + BulletRow( + text: + "When you update your selected apps in Normal, you'll need to reselect apps in your schedules and groups due to an Apple Screen Time limitation." + ) VStack(alignment: .leading, spacing: DS.Spacing.xs) { BulletRow(text: "After this setup, the only ways to disable Normal are:") @@ -117,7 +124,8 @@ struct SettingsBypassGuide: View { BulletRow(text: "Unblocking Shortcuts or all apps won't turn off this automation. To manage it:") VStack(alignment: .leading, spacing: DS.Spacing.xs) { BulletRow(text: "To disable: Unblock Shortcuts, then manually turn off the automation", indent: DS.Spacing.lg) - BulletRow(text: "To re-enable: Unblock Shortcuts, turn the automation back on, then re-block Shortcuts", indent: DS.Spacing.lg) + BulletRow( + text: "To re-enable: Unblock Shortcuts, turn the automation back on, then re-block Shortcuts", indent: DS.Spacing.lg) } } } @@ -164,9 +172,11 @@ struct SettingsBypassGuide: View { Text("Why the Apple ID matters") .font(.subheadline.weight(.semibold)) .foregroundStyle(.blue) - Text("Apple lets you reset a forgotten Screen Time passcode using the Apple ID you registered. If that's your own account, you can bypass the lock yourself. Which is why it's important to use credentials you don't have easy access to.") - .font(.footnote) - .foregroundStyle(.primary) + Text( + "Apple lets you reset a forgotten Screen Time passcode using the Apple ID you registered. If that's your own account, you can bypass the lock yourself. Which is why it's important to use credentials you don't have easy access to." + ) + .font(.footnote) + .foregroundStyle(.primary) } .padding() .frame(maxWidth: .infinity, alignment: .leading) @@ -200,9 +210,11 @@ struct SettingsBypassGuide: View { HStack(alignment: .top, spacing: DS.Spacing.sm) { Text("3.") .foregroundStyle(.secondary) - Text("Set a Screen Time passcode (have a friend enter it, use [password-locker](https://password-locker.com/), or type a random PIN yourself)") - .fixedSize(horizontal: false, vertical: true) - .frame(maxWidth: .infinity, alignment: .leading) + Text( + "Set a Screen Time passcode (have a friend enter it, use [password-locker](https://password-locker.com/), or type a random PIN yourself)" + ) + .fixedSize(horizontal: false, vertical: true) + .frame(maxWidth: .infinity, alignment: .leading) } } diff --git a/Normal/Views/Settings/GeneralSettingsView.swift b/Normal/Views/Settings/GeneralSettingsView.swift index 854000d..c3e2776 100644 --- a/Normal/Views/Settings/GeneralSettingsView.swift +++ b/Normal/Views/Settings/GeneralSettingsView.swift @@ -53,10 +53,13 @@ struct GeneralSettingsView: View { } .accessibilityIdentifier("settings.unblockDurationsLink") - Picker("Default Duration", selection: Binding( - get: { settings.defaultDuration }, - set: { settings.defaultDuration = $0 } - )) { + Picker( + "Default Duration", + selection: Binding( + get: { settings.defaultDuration }, + set: { settings.defaultDuration = $0 } + ) + ) { Text("None").tag(TimedUnblockDuration?.none) ForEach(settings.unblockDurations) { duration in Text(duration.label).tag(TimedUnblockDuration?.some(duration)) @@ -68,7 +71,7 @@ struct GeneralSettingsView: View { selection: Binding( get: { guard let keyType = settings.defaultKeyType, - availableKeyTypes.contains(keyType) + availableKeyTypes.contains(keyType) else { return KeyType?.none } return keyType }, diff --git a/Normal/Views/Settings/SettingsView.swift b/Normal/Views/Settings/SettingsView.swift index 7d7b109..50bb6cc 100644 --- a/Normal/Views/Settings/SettingsView.swift +++ b/Normal/Views/Settings/SettingsView.swift @@ -46,12 +46,16 @@ struct SettingsView: View { Button("Unblock All Apps", role: .destructive, action: performEmergencyUnblock) Button("Cancel", role: .cancel) {} } message: { - Text("This will immediately remove all app blocks. Each unblock regenerates after 6 months. You have \(settings.emergencyUnblocksAvailable) remaining.") + Text( + "This will immediately remove all app blocks. Each unblock regenerates after 6 months. You have \(settings.emergencyUnblocksAvailable) remaining." + ) } .alert("All Apps Unblocked", isPresented: $showSuccessAlert) { Button("OK", role: .cancel) {} } message: { - Text("All app blocks have been removed. You have \(settings.emergencyUnblocksAvailable) emergency unblock\(settings.emergencyUnblocksAvailable == 1 ? "" : "s") remaining.") + Text( + "All app blocks have been removed. You have \(settings.emergencyUnblocksAvailable) emergency unblock\(settings.emergencyUnblocksAvailable == 1 ? "" : "s") remaining." + ) } } } diff --git a/Normal/Views/Settings/UnblockDurationsView.swift b/Normal/Views/Settings/UnblockDurationsView.swift index a162f44..3259e1f 100644 --- a/Normal/Views/Settings/UnblockDurationsView.swift +++ b/Normal/Views/Settings/UnblockDurationsView.swift @@ -25,16 +25,19 @@ struct UnblockDurationsView: View { offsets.map { durations[$0] }.first.map(attemptDelete) } } footer: { - Text(isAtLimit - ? "You can save up to \(Settings.maxUnblockDurations) durations." - : "Durations you can pick when unblocking. Minimum 15 minutes.") + Text( + isAtLimit + ? "You can save up to \(Settings.maxUnblockDurations) durations." + : "Durations you can pick when unblocking. Minimum 15 minutes.") } } .navigationTitle("Unblock Durations") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .primaryAction) { - Button { isAdding = true } label: { + Button { + isAdding = true + } label: { Label("Add Duration", systemImage: "plus") } .disabled(isAtLimit) @@ -91,7 +94,9 @@ struct UnblockDurationsView: View { } .contextMenu { defaultToggleButton(duration, isDefault: isDefault) - Button(role: .destructive) { attemptDelete(duration) } label: { + Button(role: .destructive) { + attemptDelete(duration) + } label: { Label("Delete", systemImage: "trash") } } diff --git a/Normal/Views/Usage/UsageLimitEditor.swift b/Normal/Views/Usage/UsageLimitEditor.swift index 91fa1db..b2c2876 100644 --- a/Normal/Views/Usage/UsageLimitEditor.swift +++ b/Normal/Views/Usage/UsageLimitEditor.swift @@ -10,13 +10,13 @@ enum UsageLimitTarget: Identifiable { var id: String { switch self { - case let .existing(limit): limit.id.uuidString + case .existing(let limit): limit.id.uuidString case .new: "new" } } var limit: UsageLimit? { - if case let .existing(limit) = self { + if case .existing(let limit) = self { return limit } return nil @@ -89,7 +89,8 @@ struct UsageLimitEditor: View { } private var duplicates: FamilyActivitySelection { - let others = limits + let others = + limits .filter { $0.id != existing?.id } .reduce(FamilyActivitySelection()) { $0.union($1.selection) } let added = existing.map { selection.subtracting($0.selection) } ?? selection @@ -151,7 +152,9 @@ struct UsageLimitEditor: View { private var appsSection: some View { Section { - Button { screenTimeService.ifAuthorized { isPickingApps = true } } label: { + Button { + screenTimeService.ifAuthorized { isPickingApps = true } + } label: { CountChevronRow(title: "Select Apps", count: selection.count) } .accessibilityIdentifier("usage.selectApps") @@ -206,7 +209,8 @@ struct UsageLimitEditor: View { private var explanation: LocalizedStringKey { let reset = usageLimitService.nextReset().formatted(date: .omitted, time: .shortened) - return "After \(DurationFormat.spelled(minutes: minutes)) of combined use, these stay blocked until \(reset), even if unblocked with a key. Time already used today counts; if you're already past it, the limit starts at the next reset." + return + "After \(DurationFormat.spelled(minutes: minutes)) of combined use, these stay blocked until \(reset), even if unblocked with a key. Time already used today counts; if you're already past it, the limit starts at the next reset." } private func lockNotice(at now: Date) -> (text: Text, color: Color)? { @@ -216,10 +220,16 @@ struct UsageLimitEditor: View { switch existing.lockState(now: now) { case .unlocked: return nil - case let .grace(until): - return (Text("You can raise, delete, or remove apps from this limit for another \(UsageLockDeadline.countdown(to: until, now: now))."), .blue) - case let .locked(until): - return (Text("You can lower this limit or add apps anytime. Raising it, removing apps, or deleting it is available again \(UsageLockDeadline.phrase(until: until, now: now))."), .orange) + case .grace(let until): + return ( + Text("You can raise, delete, or remove apps from this limit for another \(UsageLockDeadline.countdown(to: until, now: now))."), .blue + ) + case .locked(let until): + return ( + Text( + "You can lower this limit or add apps anytime. Raising it, removing apps, or deleting it is available again \(UsageLockDeadline.phrase(until: until, now: now))." + ), .orange + ) } } @@ -233,13 +243,15 @@ struct UsageLimitEditor: View { private func deleteSection(now: Date) -> some View { Section { - Button(role: .destructive) { showDeleteConfirmation = true } label: { + Button(role: .destructive) { + showDeleteConfirmation = true + } label: { Text("Delete Limit").frame(maxWidth: .infinity) } .disabled(!deleteDecision(at: now).isAllowed) .accessibilityIdentifier("usage.delete") } footer: { - if case let .locked(until) = deleteDecision(at: now) { + if case .locked(let until) = deleteDecision(at: now) { Text("Deleting a limit loosens it. You can delete it \(UsageLockDeadline.phrase(until: until, now: now)).") } } @@ -248,7 +260,7 @@ struct UsageLimitEditor: View { // MARK: - Actions private func save() { - guard case let .allowed(allowance) = decision(at: .now) else { return } + guard case .allowed(let allowance) = decision(at: .now) else { return } var updated = limits if let existing { diff --git a/Normal/Views/Usage/UsageLimitRow.swift b/Normal/Views/Usage/UsageLimitRow.swift index 12cc3cf..293ccf9 100644 --- a/Normal/Views/Usage/UsageLimitRow.swift +++ b/Normal/Views/Usage/UsageLimitRow.swift @@ -15,7 +15,7 @@ struct UsageLimitRow: View { .font(.caption) .foregroundStyle(.secondary) StatusBadge(title: state.label, systemImage: state.icon, tint: state.color) - if case let .grace(until) = limit.lockState(now: now) { + if case .grace(let until) = limit.lockState(now: now) { UsageGraceCountdown(until: until, now: now) .accessibilityIdentifier("usage.graceCountdown") } diff --git a/Normal/Views/Usage/UsageLimitsGuideView.swift b/Normal/Views/Usage/UsageLimitsGuideView.swift index 5484b92..7ab1475 100644 --- a/Normal/Views/Usage/UsageLimitsGuideView.swift +++ b/Normal/Views/Usage/UsageLimitsGuideView.swift @@ -18,11 +18,22 @@ struct UsageLimitsGuideView: View { } Section("How It Works") { - FeatureRow(systemImage: "square.grid.2x2.fill", text: "Pick apps, websites, or categories. You can group multiple apps in a single limit.") + FeatureRow( + systemImage: "square.grid.2x2.fill", text: "Pick apps, websites, or categories. You can group multiple apps in a single limit.") FeatureRow(systemImage: "timer", text: "Choose how much time they get each day. Time you've already used today counts.") - FeatureRow(systemImage: "lock.fill", text: "When the time runs out, they stay blocked until the reset. Only Emergency Unblock lifts them early.", tint: .red) - FeatureRow(systemImage: "pencil", text: "Tighten anytime: lowering a limit or adding apps always works. After creating a limit raising or deleting it is allowed once every 7 days.", tint: .orange) - FeatureRow(systemImage: "arrow.counterclockwise", text: "Every limit resets at the time you set. Once you have limits, it can be changed once every 7 days. Unused time doesn't carry over.") + FeatureRow( + systemImage: "lock.fill", text: "When the time runs out, they stay blocked until the reset. Only Emergency Unblock lifts them early.", + tint: .red) + FeatureRow( + systemImage: "pencil", + text: + "Tighten anytime: lowering a limit or adding apps always works. After creating a limit raising or deleting it is allowed once every 7 days.", + tint: .orange) + FeatureRow( + systemImage: "arrow.counterclockwise", + text: + "Every limit resets at the time you set. Once you have limits, it can be changed once every 7 days. Unused time doesn't carry over." + ) } Section("Ideas") { @@ -38,9 +49,11 @@ struct UsageLimitsGuideView: View { .font(.largeTitle) .foregroundStyle(.tint) Text("No Max Daily Limits").font(.title2.bold()) - Text("Cap how long you can use apps each day. Once a limit runs out, those apps stay blocked until the day is over, even if you unblock with a key.") - .font(.subheadline) - .foregroundStyle(.secondary) + Text( + "Cap how long you can use apps each day. Once a limit runs out, those apps stay blocked until the day is over, even if you unblock with a key." + ) + .font(.subheadline) + .foregroundStyle(.secondary) } } } diff --git a/Normal/Views/Usage/UsageLockDeadline.swift b/Normal/Views/Usage/UsageLockDeadline.swift index 251db80..54bec3a 100644 --- a/Normal/Views/Usage/UsageLockDeadline.swift +++ b/Normal/Views/Usage/UsageLockDeadline.swift @@ -17,7 +17,7 @@ enum UsageLockDeadline { } static func countdown(to until: Date, now: Date) -> Text { - Text(timerInterval: now ... max(now, until), countsDown: true) + Text(timerInterval: now...max(now, until), countsDown: true) .monospacedDigit() } } diff --git a/Normal/Views/Usage/UsageView.swift b/Normal/Views/Usage/UsageView.swift index 6e6d7d6..890b68e 100644 --- a/Normal/Views/Usage/UsageView.swift +++ b/Normal/Views/Usage/UsageView.swift @@ -30,7 +30,9 @@ struct UsageView: View { .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .primaryAction) { - Button { editing = .new } label: { + Button { + editing = .new + } label: { Label("Add Limit", systemImage: "plus") } .accessibilityIdentifier("usage.addLimit") @@ -55,7 +57,9 @@ struct UsageView: View { let states = usageLimitService.states(for: limits) return Section { ForEach(limits) { limit in - Button { editing = .existing(limit) } label: { + Button { + editing = .existing(limit) + } label: { UsageLimitRow(limit: limit, state: states[limit.id] ?? .under, now: now) } .tint(.primary) @@ -75,7 +79,7 @@ struct UsageView: View { LabeledContent("Resets At") { Text(usageLimitService.nextReset(), style: .time) } - if !limits.isEmpty, case let .grace(until) = usageLimitService.resetLockState(now: now) { + if !limits.isEmpty, case .grace(let until) = usageLimitService.resetLockState(now: now) { UsageGraceCountdown(until: until, now: now) .accessibilityIdentifier("usage.resetGraceCountdown") } @@ -129,9 +133,9 @@ struct UsageResetTimeView: View { switch usageLimitService.resetLockState(now: now) { case .unlocked: return nil - case let .grace(until): + case .grace(let until): return Text("You can change the reset time for another \(UsageLockDeadline.countdown(to: until, now: now)).") - case let .locked(until): + case .locked(let until): return Text("You can change the reset time again \(UsageLockDeadline.phrase(until: until, now: now)).") } } @@ -161,7 +165,9 @@ struct UsageResetTimeView: View { .frame(maxWidth: .infinity) .accessibilityIdentifier("usage.resetPicker") } footer: { - Text("Every limit's time resets at this time each day. While you have limits, it can be changed once every 7 days, with 10 minutes to adjust after each change.") + Text( + "Every limit's time resets at this time each day. While you have limits, it can be changed once every 7 days, with 10 minutes to adjust after each change." + ) } } .toolbar { @@ -175,7 +181,7 @@ struct UsageResetTimeView: View { } private func save() { - guard case let .allowed(allowance) = decision(at: .now) else { return } + guard case .allowed(let allowance) = decision(at: .now) else { return } usageLimitService.commitResetChange(allowance) settings.dailyLimitResetMinutes = newMinutes usageLimitService.registerAll(limits, config: settings.usageLimitConfig) diff --git a/NormalMonitor/NormalMonitor.swift b/NormalMonitor/NormalMonitor.swift index 8f50b89..bf0a819 100644 --- a/NormalMonitor/NormalMonitor.swift +++ b/NormalMonitor/NormalMonitor.swift @@ -50,12 +50,14 @@ final class NormalMonitor: DeviceActivityMonitor { private func reconcile(_ callback: String, activity: String) { let now = Date.now let before = store.currentShields() - guard let plan = ShieldReconciler.reconcile( - sharedStore: sharedStore, - shields: store, - monitoredActivities: Set(DeviceActivityCenter().activities.map(\.rawValue)), - at: now - ) else { return } + guard + let plan = ShieldReconciler.reconcile( + sharedStore: sharedStore, + shields: store, + monitoredActivities: Set(DeviceActivityCenter().activities.map(\.rawValue)), + at: now + ) + else { return } CallbackLog.record( "monitor \(callback) \(label(for: activity)): " + "[shields \(summary(before)) -> \(summary(plan))]" @@ -67,12 +69,12 @@ final class NormalMonitor: DeviceActivityMonitor { minutes: (UsageLimitDTO) -> Int ) -> UsageLimitDTO? { guard !sharedStore.isUsageDayOverridden(), - let id = SharedConstants.usageLimitID(fromEventName: eventName), - let limit = sharedStore.loadUsageLimits().first(where: { $0.id == id }) + let id = SharedConstants.usageLimitID(fromEventName: eventName), + let limit = sharedStore.loadUsageLimits().first(where: { $0.id == id }) else { return nil } if let start = sharedStore.loadUsageLimitsIntervalStart(), - Date.now.timeIntervalSince(start) < Self.thresholdGraceSeconds + Date.now.timeIntervalSince(start) < Self.thresholdGraceSeconds { return nil } diff --git a/NormalShield/ShieldConfigurationExtension.swift b/NormalShield/ShieldConfigurationExtension.swift index 2d256f5..e72343a 100644 --- a/NormalShield/ShieldConfigurationExtension.swift +++ b/NormalShield/ShieldConfigurationExtension.swift @@ -55,7 +55,8 @@ final class ShieldConfigurationExtension: ShieldConfigurationDataSource { } private func makeConfiguration(subject: String, isDailyLimit: Bool) -> ShieldConfiguration { - let subtitle = isDailyLimit + let subtitle = + isDailyLimit ? "You've reached your max daily limit." : "If you need to use this \(subject), unblock with a key in Normal." diff --git a/NormalTests/App/UITestSupportTests.swift b/NormalTests/App/UITestSupportTests.swift index f189dca..bf283d2 100644 --- a/NormalTests/App/UITestSupportTests.swift +++ b/NormalTests/App/UITestSupportTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct UITestSupportTests { @Test func unitTestBundleRunsInUnitTestHostMode() { #expect(UITestSupport.isUnitTestHost) diff --git a/NormalTests/Models/AppGroupTests.swift b/NormalTests/Models/AppGroupTests.swift index 45048b9..d317bfc 100644 --- a/NormalTests/Models/AppGroupTests.swift +++ b/NormalTests/Models/AppGroupTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct AppGroupTests { @Test func storesNameAndSelection() { let selection = FamilyActivitySelection() diff --git a/NormalTests/Models/AppTabTests.swift b/NormalTests/Models/AppTabTests.swift index afb6b66..647b1b3 100644 --- a/NormalTests/Models/AppTabTests.swift +++ b/NormalTests/Models/AppTabTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct AppTabTests { @Test func labelsAreNonEmpty() { for tab in AppTab.allCases { diff --git a/NormalTests/Models/BlockScheduleTests.swift b/NormalTests/Models/BlockScheduleTests.swift index ac0d813..055d36d 100644 --- a/NormalTests/Models/BlockScheduleTests.swift +++ b/NormalTests/Models/BlockScheduleTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct BlockScheduleTests { private func makeSchedule( startHour: Int = 9, diff --git a/NormalTests/Models/CustomDomainMigrationTests.swift b/NormalTests/Models/CustomDomainMigrationTests.swift index 7d01df5..f6ce72c 100644 --- a/NormalTests/Models/CustomDomainMigrationTests.swift +++ b/NormalTests/Models/CustomDomainMigrationTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + @MainActor struct CustomDomainMigrationTests { private func storeURL() -> URL { diff --git a/NormalTests/Models/DonationCatalogTests.swift b/NormalTests/Models/DonationCatalogTests.swift index 520e6a2..f441181 100644 --- a/NormalTests/Models/DonationCatalogTests.swift +++ b/NormalTests/Models/DonationCatalogTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct DonationCatalogTests { @Test func amountsAreTheExpectedTiers() { #expect(DonationCatalog.amounts(for: .oneTime) == [5, 10, 20, 50, 100, 200]) diff --git a/NormalTests/Models/GroupKeyCascadeTests.swift b/NormalTests/Models/GroupKeyCascadeTests.swift index fb0ffc2..46a87ba 100644 --- a/NormalTests/Models/GroupKeyCascadeTests.swift +++ b/NormalTests/Models/GroupKeyCascadeTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + @MainActor struct GroupKeyCascadeTests { private func makeContainer() throws -> ModelContainer { diff --git a/NormalTests/Models/GroupUnblockDefaultsTests.swift b/NormalTests/Models/GroupUnblockDefaultsTests.swift index d21bf6b..23c18b3 100644 --- a/NormalTests/Models/GroupUnblockDefaultsTests.swift +++ b/NormalTests/Models/GroupUnblockDefaultsTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct GroupUnblockDefaultsTests { private let settings = Settings() private let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) diff --git a/NormalTests/Models/KeyMigrationTests.swift b/NormalTests/Models/KeyMigrationTests.swift index 8da8fd2..2705f1d 100644 --- a/NormalTests/Models/KeyMigrationTests.swift +++ b/NormalTests/Models/KeyMigrationTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + @MainActor struct KeyMigrationTests { private func storeURL() -> URL { diff --git a/NormalTests/Models/KeyTests.swift b/NormalTests/Models/KeyTests.swift index 533c40f..56190e0 100644 --- a/NormalTests/Models/KeyTests.swift +++ b/NormalTests/Models/KeyTests.swift @@ -1,7 +1,8 @@ import CoreLocation -@testable import Normal import Testing +@testable import Normal + struct KeyTests { @Test func storesNameAndType() { let key = Key(name: "Front Door", type: .nfc, rawValue: "abc") @@ -224,10 +225,11 @@ struct KeyTests { let groupA = UUID() #expect(!Key.hasGlobalKey(in: [])) #expect(!Key.hasGlobalKey(in: [Key(name: "g", type: .qr, rawValue: "a", groupID: groupA)])) - #expect(Key.hasGlobalKey(in: [ - Key(name: "global", type: .qr, rawValue: "b"), - Key(name: "g", type: .qr, rawValue: "a", groupID: groupA), - ])) + #expect( + Key.hasGlobalKey(in: [ + Key(name: "global", type: .qr, rawValue: "b"), + Key(name: "g", type: .qr, rawValue: "a", groupID: groupA), + ])) } @Test func groupKeyMatchesOnlyWithinItsScope() { diff --git a/NormalTests/Models/KeyTypeTests.swift b/NormalTests/Models/KeyTypeTests.swift index 73b0e79..2204c47 100644 --- a/NormalTests/Models/KeyTypeTests.swift +++ b/NormalTests/Models/KeyTypeTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct KeyTypeTests { @Test func qrAlwaysAvailableOnDevice() { #expect(KeyType.qr.isAvailableOnDevice) diff --git a/NormalTests/Models/LocationZonesTests.swift b/NormalTests/Models/LocationZonesTests.swift index c584f63..1b1a2fb 100644 --- a/NormalTests/Models/LocationZonesTests.swift +++ b/NormalTests/Models/LocationZonesTests.swift @@ -1,7 +1,8 @@ import CoreLocation -@testable import Normal import Testing +@testable import Normal + struct LocationZonesTests { private static let center = CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090) @@ -33,7 +34,7 @@ struct LocationZonesTests { } @Test func outsideAnUnblockZoneIsUnsatisfied() { - guard case let .unsatisfied(margin) = fit(zone(kind: .unblock), fix(metersNorth: 400)) else { + guard case .unsatisfied(let margin) = fit(zone(kind: .unblock), fix(metersNorth: 400)) else { Issue.record("Expected unsatisfied") return } diff --git a/NormalTests/Models/OnboardingStepTests.swift b/NormalTests/Models/OnboardingStepTests.swift index 222e1c8..36ad516 100644 --- a/NormalTests/Models/OnboardingStepTests.swift +++ b/NormalTests/Models/OnboardingStepTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct OnboardingStepTests { @Test func welcomeHasNoRequiredTab() { #expect(OnboardingStep.welcome.requiredTab == nil) diff --git a/NormalTests/Models/ScanCodeKindTests.swift b/NormalTests/Models/ScanCodeKindTests.swift index 644a20a..74ce37c 100644 --- a/NormalTests/Models/ScanCodeKindTests.swift +++ b/NormalTests/Models/ScanCodeKindTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct ScanCodeKindTests { @Test func labelsAreUserFacing() { #expect(ScanCodeKind.qr.label == "QR Code") diff --git a/NormalTests/Models/SettingsTests.swift b/NormalTests/Models/SettingsTests.swift index 6f01f3c..af92e92 100644 --- a/NormalTests/Models/SettingsTests.swift +++ b/NormalTests/Models/SettingsTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct SettingsTests { @Test func freshSettingsStartsWithAllUnblocksAvailable() { let s = Settings() @@ -24,7 +25,7 @@ struct SettingsTests { @Test func availableNeverNegative() { let s = Settings() - for _ in 0 ..< (Settings.maxEmergencyUnblocks + 5) { + for _ in 0..<(Settings.maxEmergencyUnblocks + 5) { s.recordEmergencyUnblock() } #expect(s.emergencyUnblocksAvailable == 0) diff --git a/NormalTests/Models/SettingsUnblockDurationTests.swift b/NormalTests/Models/SettingsUnblockDurationTests.swift index 9cbd4e4..87c51f8 100644 --- a/NormalTests/Models/SettingsUnblockDurationTests.swift +++ b/NormalTests/Models/SettingsUnblockDurationTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct SettingsUnblockDurationTests { private func duration(_ seconds: Int) -> TimedUnblockDuration { TimedUnblockDuration(validating: seconds)! diff --git a/NormalTests/Models/StoreUpgradeTests.swift b/NormalTests/Models/StoreUpgradeTests.swift index 37a7e0d..6657286 100644 --- a/NormalTests/Models/StoreUpgradeTests.swift +++ b/NormalTests/Models/StoreUpgradeTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + enum Version14Schema { enum KeyType: String, Codable, Sendable { case nfc = "NFC" @@ -254,46 +255,52 @@ struct StoreUpgradeTests { let schema = Schema(Version14Schema.models) let container = try ModelContainer(for: schema, configurations: ModelConfiguration(schema: schema, url: url)) let context = container.mainContext - context.insert(Version14Schema.AppGroup( - id: Self.groupID, - name: "Social", - selection: TokenFixtures.selection(apps: [1, 2], categories: [1]), - lastUpdated: Self.updated, - sortIndex: 2, - customDomains: ["reddit.com"] - )) - context.insert(Version14Schema.SelectedApps( - selection: TokenFixtures.selection(apps: [1, 2, 3], webDomains: [1]), - lastUpdated: Self.updated, - customDomains: ["example.com"] - )) - context.insert(Version14Schema.Key( - name: "Desk", - type: .qr, - scanKind: .barcode, - sortIndex: 0, - hashedValue: Self.keyHash, - salt: Self.keySalt - )) - context.insert(Version14Schema.Key( - name: "Social Tag", - type: .nfc, - sortIndex: 1, - groupID: Self.groupID, - hashedValue: Self.keyHash, - salt: Self.keySalt - )) - context.insert(Version14Schema.Key( - name: "Office", - type: .location, - location: (latitude: 37.3349, longitude: -122.009, radiusMeters: 150, kind: .block), - sortIndex: 2 - )) - context.insert(Version14Schema.BlockSchedule( - name: "Night", - selection: TokenFixtures.selection(apps: [3]), - customDomains: ["news.com"] - )) + context.insert( + Version14Schema.AppGroup( + id: Self.groupID, + name: "Social", + selection: TokenFixtures.selection(apps: [1, 2], categories: [1]), + lastUpdated: Self.updated, + sortIndex: 2, + customDomains: ["reddit.com"] + )) + context.insert( + Version14Schema.SelectedApps( + selection: TokenFixtures.selection(apps: [1, 2, 3], webDomains: [1]), + lastUpdated: Self.updated, + customDomains: ["example.com"] + )) + context.insert( + Version14Schema.Key( + name: "Desk", + type: .qr, + scanKind: .barcode, + sortIndex: 0, + hashedValue: Self.keyHash, + salt: Self.keySalt + )) + context.insert( + Version14Schema.Key( + name: "Social Tag", + type: .nfc, + sortIndex: 1, + groupID: Self.groupID, + hashedValue: Self.keyHash, + salt: Self.keySalt + )) + context.insert( + Version14Schema.Key( + name: "Office", + type: .location, + location: (latitude: 37.3349, longitude: -122.009, radiusMeters: 150, kind: .block), + sortIndex: 2 + )) + context.insert( + Version14Schema.BlockSchedule( + name: "Night", + selection: TokenFixtures.selection(apps: [3]), + customDomains: ["news.com"] + )) context.insert(Version14Schema.Settings(emergencyUnblockDates: Self.emergencyDates)) try context.save() } @@ -404,12 +411,13 @@ struct StoreUpgradeTests { let schema = Schema(Version15Schema.models) let container = try ModelContainer(for: schema, configurations: ModelConfiguration(schema: schema, url: url)) container.mainContext.insert(Version15Schema.Settings()) - container.mainContext.insert(Version15Schema.UsageLimit( - id: limitID, - selection: TokenFixtures.selection(apps: [4]), - minutesPerDay: 45, - lockAnchor: Self.updated - )) + container.mainContext.insert( + Version15Schema.UsageLimit( + id: limitID, + selection: TokenFixtures.selection(apps: [4]), + minutesPerDay: 45, + lockAnchor: Self.updated + )) try container.mainContext.save() } diff --git a/NormalTests/Models/TimedUnblockDurationTests.swift b/NormalTests/Models/TimedUnblockDurationTests.swift index 35fb735..26141f6 100644 --- a/NormalTests/Models/TimedUnblockDurationTests.swift +++ b/NormalTests/Models/TimedUnblockDurationTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct TimedUnblockDurationTests { @Test(arguments: [900, 1200, 5700, 86100]) func acceptsValidSeconds(_ seconds: Int) { diff --git a/NormalTests/Models/UnblockDurationMigrationTests.swift b/NormalTests/Models/UnblockDurationMigrationTests.swift index ff83c91..83bc783 100644 --- a/NormalTests/Models/UnblockDurationMigrationTests.swift +++ b/NormalTests/Models/UnblockDurationMigrationTests.swift @@ -1,8 +1,9 @@ import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + enum LegacySettingsSchema { @Model final class Settings { diff --git a/NormalTests/Models/UnblockDurationTests.swift b/NormalTests/Models/UnblockDurationTests.swift index c3e5a1d..b4f15df 100644 --- a/NormalTests/Models/UnblockDurationTests.swift +++ b/NormalTests/Models/UnblockDurationTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct UnblockDurationTests { @Test func fifteenMinutesEquals900Seconds() { #expect(UnblockDuration.fifteenMinutes.timeInterval == 900) diff --git a/NormalTests/Models/UsageLimitEditPolicyTests.swift b/NormalTests/Models/UsageLimitEditPolicyTests.swift index fd7aeff..db4cbaf 100644 --- a/NormalTests/Models/UsageLimitEditPolicyTests.swift +++ b/NormalTests/Models/UsageLimitEditPolicyTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct UsageLimitEditPolicyTests { private let anchor = Date(timeIntervalSinceReferenceDate: 1_000_000) @@ -137,11 +138,13 @@ struct UsageLimitEditPolicyTests { var current: Date? = anchor for step in stride(from: 1, through: 5, by: 1) { let now = anchor + .minutes(step) - guard case let .allowed(allowance) = UsageLimitEditPolicy.decide( - .adjust(from: 30, to: 30 + step, dropsCoverage: false), - anchor: current, - now: now - ) else { + guard + case .allowed(let allowance) = UsageLimitEditPolicy.decide( + .adjust(from: 30, to: 30 + step, dropsCoverage: false), + anchor: current, + now: now + ) + else { Issue.record("edit inside grace should be allowed") return } diff --git a/NormalTests/Services/AppBlockIntentPerformerTests.swift b/NormalTests/Services/AppBlockIntentPerformerTests.swift index a1463b9..753ca5c 100644 --- a/NormalTests/Services/AppBlockIntentPerformerTests.swift +++ b/NormalTests/Services/AppBlockIntentPerformerTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + @MainActor struct AppBlockIntentPerformerTests { private let container: ModelContainer diff --git a/NormalTests/Services/AppUnblockIntentPerformerTests.swift b/NormalTests/Services/AppUnblockIntentPerformerTests.swift index e3e3caf..8612d99 100644 --- a/NormalTests/Services/AppUnblockIntentPerformerTests.swift +++ b/NormalTests/Services/AppUnblockIntentPerformerTests.swift @@ -2,10 +2,11 @@ import CoreLocation import DeviceActivity import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + @MainActor struct AppUnblockIntentPerformerTests { private let container: ModelContainer @@ -427,7 +428,7 @@ struct AppUnblockIntentPerformerTests { startHour: 20, startMinute: 0, durationMinutes: 60, - weekdays: Set(1 ... 7), + weekdays: Set(1...7), shouldBlock: true, isTimed: true, isEnabled: true diff --git a/NormalTests/Services/BackgroundLocationVerifierTests.swift b/NormalTests/Services/BackgroundLocationVerifierTests.swift index 290e45b..d0693b5 100644 --- a/NormalTests/Services/BackgroundLocationVerifierTests.swift +++ b/NormalTests/Services/BackgroundLocationVerifierTests.swift @@ -1,8 +1,9 @@ import CoreLocation import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct BackgroundLocationVerifierTests { private nonisolated static let cupertino = CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090) diff --git a/NormalTests/Services/BlockActionsTests.swift b/NormalTests/Services/BlockActionsTests.swift index 41e9be9..199091e 100644 --- a/NormalTests/Services/BlockActionsTests.swift +++ b/NormalTests/Services/BlockActionsTests.swift @@ -1,9 +1,10 @@ import DeviceActivity import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct BlockActionsTests { private let screenTime = FakeScreenTimeService() @@ -173,7 +174,8 @@ struct BlockActionsTests { timedUnblockService: timedUnblock ?? makeTimedUnblock(), scheduleService: makeSchedule(), usageLimitService: usageLimit - ?? UsageLimitService(activityCenter: activity, sharedStore: store, ledger: InMemoryUsageLimitLedger(), limitShield: InMemoryDailyLimitShield()) + ?? UsageLimitService( + activityCenter: activity, sharedStore: store, ledger: InMemoryUsageLimitLedger(), limitShield: InMemoryDailyLimitShield()) ) } diff --git a/NormalTests/Services/BlockStatusTests.swift b/NormalTests/Services/BlockStatusTests.swift index 1ab1447..f6a8e82 100644 --- a/NormalTests/Services/BlockStatusTests.swift +++ b/NormalTests/Services/BlockStatusTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct BlockStatusTests { @Test func shortLabels() { #expect(BlockStatus.all.shortLabel == "Blocked") diff --git a/NormalTests/Services/BlockingMigrationTests.swift b/NormalTests/Services/BlockingMigrationTests.swift index 6ffd227..bc39b26 100644 --- a/NormalTests/Services/BlockingMigrationTests.swift +++ b/NormalTests/Services/BlockingMigrationTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation import ManagedSettings -@testable import Normal import Testing +@testable import Normal + @MainActor struct BlockingMigrationTests { private func legacyShields(_ h: BlockingHarness, apps: [UInt8], domains: [String] = [], deny: Bool = false) { @@ -30,7 +31,7 @@ struct BlockingMigrationTests { startHour: start.0, startMinute: start.1, durationMinutes: minutes, - weekdays: Set(1 ... 7), + weekdays: Set(1...7), shouldBlock: block, isTimed: timed ) @@ -48,14 +49,15 @@ struct BlockingMigrationTests { endDate: Date, preventsAppDelete: Bool? = nil ) throws { - try h.store.timedUnblocks.append(TimedUnblockDTO( - id: group ? UUID().uuidString : TimedUnblockService.mainID, - selectionData: TokenFixtures.selection(apps: apps).toData(), - endDate: endDate, - activityName: group ? "timedUnblock_group" : SharedConstants.mainTimedUnblockActivityName, - isGroupUnblock: group, - blockAllPreventsAppDelete: preventsAppDelete - )) + try h.store.timedUnblocks.append( + TimedUnblockDTO( + id: group ? UUID().uuidString : TimedUnblockService.mainID, + selectionData: TokenFixtures.selection(apps: apps).toData(), + endDate: endDate, + activityName: group ? "timedUnblock_group" : SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: group, + blockAllPreventsAppDelete: preventsAppDelete + )) } @Test func existingShieldsCarryOverUnchangedWhenNoWindowIsOpen() { @@ -182,7 +184,7 @@ struct BlockingMigrationTests { legacyShields(h, apps: [2, 3]) let mail = BlockSchedule( name: "Mail", selection: TokenFixtures.selection(apps: [1]), - startHour: 12, startMinute: 0, durationMinutes: 180, weekdays: Set(1 ... 7), + startHour: 12, startMinute: 0, durationMinutes: 180, weekdays: Set(1...7), shouldBlock: false, isTimed: true, isEnabled: true ) h.store.schedules = [try #require(mail.toDTO())].map { @@ -287,9 +289,10 @@ struct BlockingMigrationTests { @Test func manualRecordDoesNotDependOnDictionaryEncoding() throws { var state = ManualBlockState() state.blockAll(TokenFixtures.selection(apps: [1, 2]), customDomains: ["a.com"], at: Date(timeIntervalSince1970: 50)) - let plist = try PropertyListSerialization.propertyList( - from: PropertyListEncoder().encode(state), format: nil - ) as? [String: Any] + let plist = + try PropertyListSerialization.propertyList( + from: PropertyListEncoder().encode(state), format: nil + ) as? [String: Any] let applications = plist?["applications"] as? [String: Any] #expect(applications?["entries"] is [[String: Any]]) @@ -316,11 +319,12 @@ struct BlockingMigrationTests { @Test func unreadableScheduleSelectionIsSkippedDuringMigration() { let h = BlockingHarness() legacyShields(h, apps: [2]) - h.store.schedules.append(ScheduleDTO( - id: UUID(), name: "Corrupt", selectionData: Data("garbage".utf8), - startHour: 12, startMinute: 0, durationMinutes: 60, weekdays: Set(1 ... 7), - shouldBlock: false, isTimed: true, isEnabled: true - )) + h.store.schedules.append( + ScheduleDTO( + id: UUID(), name: "Corrupt", selectionData: Data("garbage".utf8), + startHour: 12, startMinute: 0, durationMinutes: 60, weekdays: Set(1...7), + shouldBlock: false, isTimed: true, isEnabled: true + )) h.wake(at: h.at(12, 30)) @@ -357,7 +361,7 @@ struct BlockingMigrationTests { let defaults = try #require(UserDefaults(suiteName: "v15-\(UUID().uuidString)")) let mail = try Version15ScheduleDTO( id: UUID(), name: "Mail", selectionData: TokenFixtures.selection(apps: [1]).toData(), - startHour: 12, startMinute: 0, durationMinutes: 180, weekdays: Set(1 ... 7), + startHour: 12, startMinute: 0, durationMinutes: 180, weekdays: Set(1...7), shouldBlock: false, isTimed: true, encodedCustomDomains: nil ) defaults.set(try PropertyListEncoder().encode([mail]), forKey: SharedConstants.DefaultsKey.schedules) diff --git a/NormalTests/Services/BlockingScenarioTests.swift b/NormalTests/Services/BlockingScenarioTests.swift index 3473895..c87e342 100644 --- a/NormalTests/Services/BlockingScenarioTests.swift +++ b/NormalTests/Services/BlockingScenarioTests.swift @@ -2,9 +2,10 @@ import DeviceActivity import FamilyControls import Foundation import ManagedSettings -@testable import Normal import Testing +@testable import Normal + @MainActor struct BlockingScenarioTests { @Test func blockAllShieldsTheMainListAndUnblockAllLiftsIt() { @@ -34,7 +35,7 @@ struct BlockingScenarioTests { h.blockAll() h.unblockGroupPermanently(h.group([3])) - for hour in 9 ... 20 { + for hour in 9...20 { h.wake(at: h.at(hour)) #expect(h.blocked == h.apps(1, 2)) } @@ -252,7 +253,7 @@ struct BlockingScenarioTests { @Test func weekdayFilterIsRespected() throws { let h = BlockingHarness() let weekday = Calendar.current.component(.weekday, from: h.day) - let otherDays = Set(1 ... 7).subtracting([weekday]) + let otherDays = Set(1...7).subtracting([weekday]) try h.addSchedule([1], from: (9, 0), minutes: 60, block: true, weekdays: otherDays) h.wake(at: h.at(9, 30)) @@ -304,7 +305,7 @@ struct BlockingScenarioTests { @Test func timedUnblockAllAtTheActivityLimitWithoutAHeartbeatStaysBlocked() throws { let h = BlockingHarness() - for minute in 0 ..< 20 { + for minute in 0..<20 { try h.addSchedule([4], from: (20, minute), minutes: 60, block: true) } let heartbeat = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) @@ -567,7 +568,7 @@ struct BlockingScenarioTests { ) let lunch = BlockSchedule( name: "Lunch", selection: TokenFixtures.selection(apps: [], categories: [1], webDomains: [3]), - startHour: 12, startMinute: 0, durationMinutes: 60, weekdays: Set(1 ... 7), + startHour: 12, startMinute: 0, durationMinutes: 60, weekdays: Set(1...7), shouldBlock: false, isTimed: true, isEnabled: true ) try h.scheduleService.syncAndPersist(lunch, allSchedules: [lunch], screenTimeService: h.screenTime) @@ -581,20 +582,20 @@ struct BlockingScenarioTests { } @Test func backToBackBlockSchedulesHandOverAtTheSameMinute() throws { - let h = BlockingHarness(mainApps: Array(1 ... 10), startingAt: 20) + let h = BlockingHarness(mainApps: Array(1...10), startingAt: 20) let weekday = { Calendar.current.component(.weekday, from: h.at(12, dayOffset: $0)) } - try h.addSchedule(Array(1 ... 10), from: (21, 0), minutes: 480, block: true, weekdays: [weekday(0), weekday(1)]) - try h.addSchedule(Array(3 ... 10), from: (5, 0), minutes: 720, block: true, weekdays: [weekday(1)]) + try h.addSchedule(Array(1...10), from: (21, 0), minutes: 480, block: true, weekdays: [weekday(0), weekday(1)]) + try h.addSchedule(Array(3...10), from: (5, 0), minutes: 720, block: true, weekdays: [weekday(1)]) h.wake(at: h.at(21, 30)) - #expect(h.blocked == Set((1 ... 10).map(TokenFixtures.app))) + #expect(h.blocked == Set((1...10).map(TokenFixtures.app))) h.wake(at: h.at(5, 0, dayOffset: 1)) - #expect(h.blocked == Set((3 ... 10).map(TokenFixtures.app))) + #expect(h.blocked == Set((3...10).map(TokenFixtures.app))) h.wake(at: h.at(12, 44, dayOffset: 1)) - #expect(h.blocked == Set((3 ... 10).map(TokenFixtures.app))) + #expect(h.blocked == Set((3...10).map(TokenFixtures.app))) h.wake(at: h.at(17, 30, dayOffset: 1)) #expect(h.blocked.isEmpty) h.wake(at: h.at(21, 30, dayOffset: 1)) - #expect(h.blocked == Set((1 ... 10).map(TokenFixtures.app))) + #expect(h.blocked == Set((1...10).map(TokenFixtures.app))) } } diff --git a/NormalTests/Services/CameraPermissionTests.swift b/NormalTests/Services/CameraPermissionTests.swift index e57a733..e9cb6d6 100644 --- a/NormalTests/Services/CameraPermissionTests.swift +++ b/NormalTests/Services/CameraPermissionTests.swift @@ -1,7 +1,8 @@ import AVFoundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct CameraPermissionTests { @Test func startsInCheckingState() { diff --git a/NormalTests/Services/EmergencyUnblockServiceTests.swift b/NormalTests/Services/EmergencyUnblockServiceTests.swift index c87ece0..5018b02 100644 --- a/NormalTests/Services/EmergencyUnblockServiceTests.swift +++ b/NormalTests/Services/EmergencyUnblockServiceTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct EmergencyUnblockServiceTests { private func makeService( diff --git a/NormalTests/Services/KeyCheckFlowTests.swift b/NormalTests/Services/KeyCheckFlowTests.swift index aff179e..c2c2349 100644 --- a/NormalTests/Services/KeyCheckFlowTests.swift +++ b/NormalTests/Services/KeyCheckFlowTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct KeyCheckFlowTests { private let nfc = ControlledScanner() @@ -40,14 +41,18 @@ struct KeyCheckFlowTests { private func start(_ request: KeyCheckFlow.Request, allowBypass: Bool = false) { let counter = counter - let action: ProtectedAction = allowBypass + let action: ProtectedAction = + allowBypass ? .tighten { counter.runs += 1 } - : .weaken { counter.proofs.append($0); counter.runs += 1 } + : .weaken { + counter.proofs.append($0) + counter.runs += 1 + } flow.start(request, action: action) } private func waitUntil(_ condition: () -> Bool) async { - for _ in 0 ..< 10000 where !condition() { + for _ in 0..<10000 where !condition() { await Task.yield() } #expect(condition()) @@ -266,7 +271,7 @@ struct KeyCheckFlowTests { flow.choose(.qr) #expect(flow.stage == .scanningQR) #expect(flow.sheetScreen == .qrScanner) - for _ in 0 ..< 100 { + for _ in 0..<100 { await Task.yield() } #expect(qr.scanCount == 0) @@ -340,7 +345,7 @@ struct KeyCheckFlowTests { flow.choose(.nfc) await waitUntil { nfc.isScanning } - for _ in 0 ..< 100 { + for _ in 0..<100 { await Task.yield() } #expect(flow.stage == .scanningNFC) @@ -383,7 +388,7 @@ struct KeyCheckFlowTests { #expect(!nfc.isScanning) nfc.present("tag") - for _ in 0 ..< 100 { + for _ in 0..<100 { await Task.yield() } diff --git a/NormalTests/Services/KeyProofTests.swift b/NormalTests/Services/KeyProofTests.swift index 5f17c5d..48a6a16 100644 --- a/NormalTests/Services/KeyProofTests.swift +++ b/NormalTests/Services/KeyProofTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct KeyProofTests { private let main = SelectedApps(selection: FamilyActivitySelection()) diff --git a/NormalTests/Services/KeySelectLogicTests.swift b/NormalTests/Services/KeySelectLogicTests.swift index aef5995..fef47ad 100644 --- a/NormalTests/Services/KeySelectLogicTests.swift +++ b/NormalTests/Services/KeySelectLogicTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct KeySelectLogicTests { @Test func noAvailableKeysShowsAlert() { let result = KeySelectLogic.decide(availableKeyTypes: [], allowBypass: false, defaultKeyType: nil) diff --git a/NormalTests/Services/LiveActivityPlanTests.swift b/NormalTests/Services/LiveActivityPlanTests.swift index eec638c..2714b36 100644 --- a/NormalTests/Services/LiveActivityPlanTests.swift +++ b/NormalTests/Services/LiveActivityPlanTests.swift @@ -1,7 +1,8 @@ import ActivityKit -@testable import Normal import Testing +@testable import Normal + struct LiveActivityPlanTests { @Test func startsActivitiesForNewlyActiveUnblocks() { let plan = LiveActivityPlan(activeIDs: ["main", "g1"], runningIDs: []) @@ -25,9 +26,9 @@ struct LiveActivityPlanTests { @Test func mixedStartUpdateEnd() { let plan = LiveActivityPlan(activeIDs: ["main", "g2"], runningIDs: ["main", "g1"]) - #expect(plan.toStart == ["g2"]) // newly active - #expect(plan.toUpdate == ["main"]) // still active - #expect(plan.toEnd == ["g1"]) // expired/cancelled + #expect(plan.toStart == ["g2"]) // newly active + #expect(plan.toUpdate == ["main"]) // still active + #expect(plan.toEnd == ["g1"]) // expired/cancelled } @Test func secondGroupStartsWhileFirstKeepsRunning() { diff --git a/NormalTests/Services/LocationFixPolicyTests.swift b/NormalTests/Services/LocationFixPolicyTests.swift index 16b2615..eefc550 100644 --- a/NormalTests/Services/LocationFixPolicyTests.swift +++ b/NormalTests/Services/LocationFixPolicyTests.swift @@ -1,8 +1,9 @@ import CoreLocation import Foundation -@testable import Normal import Testing +@testable import Normal + struct LocationFixPolicyTests { private let now = Date() diff --git a/NormalTests/Services/LocationUnlockModelTests.swift b/NormalTests/Services/LocationUnlockModelTests.swift index 8dce14c..9816937 100644 --- a/NormalTests/Services/LocationUnlockModelTests.swift +++ b/NormalTests/Services/LocationUnlockModelTests.swift @@ -1,7 +1,8 @@ import CoreLocation -@testable import Normal import Testing +@testable import Normal + @MainActor struct LocationUnlockModelTests { private nonisolated static let cupertino = CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090) diff --git a/NormalTests/Services/NFCKeyMethodTests.swift b/NormalTests/Services/NFCKeyMethodTests.swift index a8647cc..fe5fab6 100644 --- a/NormalTests/Services/NFCKeyMethodTests.swift +++ b/NormalTests/Services/NFCKeyMethodTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct NFCKeyMethodTests { @Test func unvalidatedScanIsRejected() async { let key = Key(name: "k", type: .nfc, rawValue: "abc") diff --git a/NormalTests/Services/NavigationCoordinatorTests.swift b/NormalTests/Services/NavigationCoordinatorTests.swift index e15b3af..6405e84 100644 --- a/NormalTests/Services/NavigationCoordinatorTests.swift +++ b/NormalTests/Services/NavigationCoordinatorTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct NavigationCoordinatorTests { @Test func startsDismissed() { diff --git a/NormalTests/Services/NavigationCoordinatorWidgetTests.swift b/NormalTests/Services/NavigationCoordinatorWidgetTests.swift index b72af7e..a5f3f85 100644 --- a/NormalTests/Services/NavigationCoordinatorWidgetTests.swift +++ b/NormalTests/Services/NavigationCoordinatorWidgetTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct NavigationCoordinatorWidgetTests { private func unlockURL(groupID: UUID, duration: UnlockDurationRequest = .useDefault, key: String? = nil) -> URL { @@ -55,8 +56,9 @@ struct NavigationCoordinatorWidgetTests { let id = UUID() try c.handle(url: #require(URL(string: "normal://unlock?group=\(id.uuidString)&duration=\(value)"))) - #expect(c.pendingAction?.action == .unblock(UnblockRequest(groupID: id, duration: .ask, keyType: nil)), - "An invalid duration shows the sheet rather than guessing") + #expect( + c.pendingAction?.action == .unblock(UnblockRequest(groupID: id, duration: .ask, keyType: nil)), + "An invalid duration shows the sheet rather than guessing") } @Test func handleParsesBlock() { diff --git a/NormalTests/Services/OnboardingServiceTests.swift b/NormalTests/Services/OnboardingServiceTests.swift index 695bb3c..a9d4329 100644 --- a/NormalTests/Services/OnboardingServiceTests.swift +++ b/NormalTests/Services/OnboardingServiceTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + @MainActor struct OnboardingServiceTests { @Test func startsAtWelcome() { diff --git a/NormalTests/Services/QRServiceTests.swift b/NormalTests/Services/QRServiceTests.swift index c07259a..21039e8 100644 --- a/NormalTests/Services/QRServiceTests.swift +++ b/NormalTests/Services/QRServiceTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + @MainActor struct QRServiceTests { private func waitUntilScanning(_ service: QRService) async { diff --git a/NormalTests/Services/SafetyInvariantTests.swift b/NormalTests/Services/SafetyInvariantTests.swift index 00d5ce9..d59333a 100644 --- a/NormalTests/Services/SafetyInvariantTests.swift +++ b/NormalTests/Services/SafetyInvariantTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct SafetyInvariantTests { @Test func registeredKeyAlwaysSelfValidatesAcrossArbitraryPayloads() { @@ -19,7 +20,7 @@ struct SafetyInvariantTests { } @Test func manyRandomKeysNeverFalseMatchOrFailToMatch() { - for _ in 0 ..< 200 { + for _ in 0..<200 { let value = UUID().uuidString + String(UInt64.random(in: .min ... .max)) let key = Key(name: "k", type: .qr, rawValue: value) #expect(key.matches(unhashedId: value)) @@ -29,7 +30,7 @@ struct SafetyInvariantTests { @Test func hashAndSaltFormatIsLowercaseHexWithFixedLength() { let hexOnly = CharacterSet(charactersIn: "0123456789abcdef") - for _ in 0 ..< 50 { + for _ in 0..<50 { let key = Key(name: "k", type: .nfc, rawValue: UUID().uuidString) #expect(key.hashedValue.count == 64) #expect(key.salt.count == 32) diff --git a/NormalTests/Services/ScanErrorTests.swift b/NormalTests/Services/ScanErrorTests.swift index 841c898..6094fd4 100644 --- a/NormalTests/Services/ScanErrorTests.swift +++ b/NormalTests/Services/ScanErrorTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct ScanErrorTests { @Test func alreadyScanningHasDescription() { #expect(ScanError.alreadyScanning.errorDescription == "A scan is already in progress.") diff --git a/NormalTests/Services/ScheduleServiceTests.swift b/NormalTests/Services/ScheduleServiceTests.swift index b93b691..ef34085 100644 --- a/NormalTests/Services/ScheduleServiceTests.swift +++ b/NormalTests/Services/ScheduleServiceTests.swift @@ -1,9 +1,10 @@ import DeviceActivity import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct ScheduleServiceTests { private struct TestError: Error {} @@ -162,8 +163,9 @@ struct ScheduleServiceTests { service.registerAll([enabled, disabled], screenTimeService: screenTime) #expect(store.schedules.count == 2) - #expect(activity.startCalls.map(\.name.rawValue).filter { $0.hasPrefix("schedule_") } - == [SharedConstants.scheduleActivityName(for: enabled.id)]) + #expect( + activity.startCalls.map(\.name.rawValue).filter { $0.hasPrefix("schedule_") } + == [SharedConstants.scheduleActivityName(for: enabled.id)]) #expect(screenTime.reconcileCallCount == 1) } @@ -247,13 +249,15 @@ struct ScheduleServiceTests { @Test func heartbeatStaysWhileATimedUnblockIsActiveEvenWithoutSchedules() throws { let (service, activity, store) = makeService() - store.timedUnblocks = try [TimedUnblockDTO( - id: TimedUnblockService.mainID, - selectionData: FamilyActivitySelection().toData(), - endDate: Date(timeIntervalSinceReferenceDate: 800_000_000).addingTimeInterval(3600), - activityName: SharedConstants.mainTimedUnblockActivityName, - isGroupUnblock: false - )] + store.timedUnblocks = try [ + TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: FamilyActivitySelection().toData(), + endDate: Date(timeIntervalSinceReferenceDate: 800_000_000).addingTimeInterval(3600), + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false + ) + ] service.registerAll([], screenTimeService: FakeScreenTimeService()) @@ -289,9 +293,11 @@ struct ScheduleServiceTests { repeats: true ) #expect(registered.hasSameWindow(as: desired)) - #expect(!registered.hasSameWindow(as: DeviceActivitySchedule( - intervalStart: desired.intervalStart, intervalEnd: desired.intervalEnd, repeats: false - ))) + #expect( + !registered.hasSameWindow( + as: DeviceActivitySchedule( + intervalStart: desired.intervalStart, intervalEnd: desired.intervalEnd, repeats: false + ))) } @Test func disableAllTogglesEverySchedulePersistsAndReconciles() { @@ -323,10 +329,10 @@ struct ScheduleServiceTests { components.month = 6 components.hour = hour components.minute = minute - for day in 1 ... 7 { + for day in 1...7 { components.day = day if let candidate = Self.utc.date(from: components), - Self.utc.component(.weekday, from: candidate) == weekday + Self.utc.component(.weekday, from: candidate) == weekday { return candidate } @@ -371,14 +377,18 @@ struct ScheduleServiceTests { @Test func isActiveHandlesMidnightWrap() { // Wed 23:00 for 3h → ends Thu 02:00. let s = schedule(startHour: 23, durationMinutes: 180, weekdays: [4]) - #expect(s.isActive(at: date(weekday: 4, hour: 23, minute: 30), calendar: Self.utc), - "Active late on the start day") - #expect(s.isActive(at: date(weekday: 5, hour: 1, minute: 0), calendar: Self.utc), - "Active early on the next day") - #expect(!s.isActive(at: date(weekday: 5, hour: 3, minute: 0), calendar: Self.utc), - "Inactive after the wrapped end") - #expect(!s.isActive(at: date(weekday: 4, hour: 22, minute: 0), calendar: Self.utc), - "Inactive before the start") + #expect( + s.isActive(at: date(weekday: 4, hour: 23, minute: 30), calendar: Self.utc), + "Active late on the start day") + #expect( + s.isActive(at: date(weekday: 5, hour: 1, minute: 0), calendar: Self.utc), + "Active early on the next day") + #expect( + !s.isActive(at: date(weekday: 5, hour: 3, minute: 0), calendar: Self.utc), + "Inactive after the wrapped end") + #expect( + !s.isActive(at: date(weekday: 4, hour: 22, minute: 0), calendar: Self.utc), + "Inactive before the start") } @Test func mirrorCustomDomainsEnabledWritesFlag() { diff --git a/NormalTests/Services/ScheduleSummaryTests.swift b/NormalTests/Services/ScheduleSummaryTests.swift index bf469b2..5f7cb5a 100644 --- a/NormalTests/Services/ScheduleSummaryTests.swift +++ b/NormalTests/Services/ScheduleSummaryTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct ScheduleSummaryTests { private let calendar = Calendar.current private var now: Date { diff --git a/NormalTests/Services/ScreenTimeServiceTests.swift b/NormalTests/Services/ScreenTimeServiceTests.swift index 274adf7..4113d89 100644 --- a/NormalTests/Services/ScreenTimeServiceTests.swift +++ b/NormalTests/Services/ScreenTimeServiceTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct ScreenTimeServiceTests { private func makeService() -> (ScreenTimeService, InMemoryShieldStore) { diff --git a/NormalTests/Services/TagDecisionTests.swift b/NormalTests/Services/TagDecisionTests.swift index 1c19c2a..c58494f 100644 --- a/NormalTests/Services/TagDecisionTests.swift +++ b/NormalTests/Services/TagDecisionTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct TagDecisionTests { @Test func proceedsWithHexIdForStableNonMRTDTag() { let decision = TagDecision.decide( diff --git a/NormalTests/Services/TimedUnblockServiceTests.swift b/NormalTests/Services/TimedUnblockServiceTests.swift index f5736a7..e091129 100644 --- a/NormalTests/Services/TimedUnblockServiceTests.swift +++ b/NormalTests/Services/TimedUnblockServiceTests.swift @@ -1,9 +1,10 @@ import DeviceActivity import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct TimedUnblockServiceTests { private func makeService() -> ( @@ -32,10 +33,11 @@ struct TimedUnblockServiceTests { ) #expect(screenTime.reconcileCallCount == 1) - #expect(activity.startCalls.map(\.name.rawValue) == [ - SharedConstants.mainTimedUnblockActivityName, - SharedConstants.reblockHeartbeatActivityName, - ]) + #expect( + activity.startCalls.map(\.name.rawValue) == [ + SharedConstants.mainTimedUnblockActivityName, + SharedConstants.reblockHeartbeatActivityName, + ]) #expect(store.timedUnblocks.count == 1) #expect(service.isMainUnblockActive) } @@ -53,10 +55,11 @@ struct TimedUnblockServiceTests { ) #expect(screenTime.reconcileCallCount == 1) - #expect(activity.startCalls.map(\.name.rawValue) == [ - SharedConstants.groupTimedUnblockActivityName(for: groupId), - SharedConstants.reblockHeartbeatActivityName, - ]) + #expect( + activity.startCalls.map(\.name.rawValue) == [ + SharedConstants.groupTimedUnblockActivityName(for: groupId), + SharedConstants.reblockHeartbeatActivityName, + ]) #expect(store.timedUnblocks.count == 1) #expect(service.isGroupUnblockActive(groupId: groupId)) } @@ -202,7 +205,7 @@ struct TimedUnblockServiceTests { endDate: .now.addingTimeInterval(600), activityName: SharedConstants.mainTimedUnblockActivityName, isGroupUnblock: false - ), + ) ] service.reconcile(screenTimeService: FakeScreenTimeService()) @@ -402,13 +405,15 @@ struct TimedUnblockServiceTests { @Test func reconcileRegistersHeartbeatWhileUnblocksArePending() throws { let (service, activity, store) = makeService() - store.timedUnblocks = try [TimedUnblockDTO( - id: TimedUnblockService.mainID, - selectionData: FamilyActivitySelection().toData(), - endDate: .now.addingTimeInterval(.hours(1)), - activityName: SharedConstants.mainTimedUnblockActivityName, - isGroupUnblock: false - )] + store.timedUnblocks = try [ + TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: FamilyActivitySelection().toData(), + endDate: .now.addingTimeInterval(.hours(1)), + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false + ) + ] service.reconcile(screenTimeService: FakeScreenTimeService()) @@ -436,13 +441,15 @@ struct TimedUnblockServiceTests { @Test func reconcileDropsExpiredGroupAndReconciles() throws { let store = FakeSharedStore() let groupId = UUID() - store.timedUnblocks = try [TimedUnblockDTO( - id: groupId.uuidString, - selectionData: FamilyActivitySelection().toData(), - endDate: Date.now.addingTimeInterval(-.minutes(1)), - activityName: SharedConstants.groupTimedUnblockActivityName(for: groupId), - isGroupUnblock: true - )] + store.timedUnblocks = try [ + TimedUnblockDTO( + id: groupId.uuidString, + selectionData: FamilyActivitySelection().toData(), + endDate: Date.now.addingTimeInterval(-.minutes(1)), + activityName: SharedConstants.groupTimedUnblockActivityName(for: groupId), + isGroupUnblock: true + ) + ] let screenTime = FakeScreenTimeService() let service = TimedUnblockService( @@ -493,13 +500,15 @@ struct TimedUnblockServiceTests { @Test func reconcileLeavesActiveUnblockArmedWithoutReblocking() throws { let store = FakeSharedStore() - store.timedUnblocks = try [TimedUnblockDTO( - id: TimedUnblockService.mainID, - selectionData: FamilyActivitySelection().toData(), - endDate: Date.now.addingTimeInterval(.minutes(30)), - activityName: SharedConstants.mainTimedUnblockActivityName, - isGroupUnblock: false - )] + store.timedUnblocks = try [ + TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: FamilyActivitySelection().toData(), + endDate: Date.now.addingTimeInterval(.minutes(30)), + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false + ) + ] let screenTime = FakeScreenTimeService() let service = TimedUnblockService( @@ -752,9 +761,10 @@ struct DeviceActivityScheduleFactoryTests { }() private func date(hour: Int, minute: Int, second: Int = 0) -> Date { - Self.utc.date(from: DateComponents( - year: 2026, month: 6, day: 1, hour: hour, minute: minute, second: second - ))! + Self.utc.date( + from: DateComponents( + year: 2026, month: 6, day: 1, hour: hour, minute: minute, second: second + ))! } private func intervalSeconds(_ schedule: DeviceActivitySchedule) -> TimeInterval { diff --git a/NormalTests/Services/UnblockTargetTests.swift b/NormalTests/Services/UnblockTargetTests.swift index 0d1b4a3..d03efac 100644 --- a/NormalTests/Services/UnblockTargetTests.swift +++ b/NormalTests/Services/UnblockTargetTests.swift @@ -1,7 +1,8 @@ import FamilyControls -@testable import Normal import Testing +@testable import Normal + @MainActor struct UnblockTargetTests { private let activity = FakeDeviceActivityCenter() diff --git a/NormalTests/Services/UnlockRequestInboxTests.swift b/NormalTests/Services/UnlockRequestInboxTests.swift index fecb818..09fe205 100644 --- a/NormalTests/Services/UnlockRequestInboxTests.swift +++ b/NormalTests/Services/UnlockRequestInboxTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct UnlockRequestInboxTests { private final class TestClock { diff --git a/NormalTests/Services/UsageLimitServiceTests.swift b/NormalTests/Services/UsageLimitServiceTests.swift index 185471c..0caa40e 100644 --- a/NormalTests/Services/UsageLimitServiceTests.swift +++ b/NormalTests/Services/UsageLimitServiceTests.swift @@ -1,9 +1,10 @@ import DeviceActivity import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + @MainActor struct UsageLimitServiceTests { /// Every test pins its own instant. The production APIs all accept an diff --git a/NormalTests/Shared/CopyNamingTests.swift b/NormalTests/Shared/CopyNamingTests.swift index 546f2bf..26c65ba 100644 --- a/NormalTests/Shared/CopyNamingTests.swift +++ b/NormalTests/Shared/CopyNamingTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct CopyNamingTests { @Test func appendsCopyWhenNameIsFree() { #expect(CopyNaming.name(for: "Work", existing: ["Work"]) == "Work Copy") diff --git a/NormalTests/Shared/CustomDomainsTests.swift b/NormalTests/Shared/CustomDomainsTests.swift index d3e2c31..40078b1 100644 --- a/NormalTests/Shared/CustomDomainsTests.swift +++ b/NormalTests/Shared/CustomDomainsTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct CustomDomainsTests { // MARK: - subset @@ -51,14 +52,14 @@ struct CustomDomainsTests { @Test func evaluateAddFlagsOverLimitAtTheCap() { // 40 other items + 9 existing + this one = 50 → at the cap. - let existing = (0 ..< 9).map { "d\($0).com" } + let existing = (0..<9).map { "d\($0).com" } let result = CustomDomains.evaluateAdd("new.com", existing: existing, otherItemCount: 40) #expect(result == .added("new.com", overLimit: true)) } @Test func evaluateAddNotOverLimitOneBelowTheCap() { // 40 other + 8 existing + this one = 49 → under the cap. - let existing = (0 ..< 8).map { "d\($0).com" } + let existing = (0..<8).map { "d\($0).com" } let result = CustomDomains.evaluateAdd("new.com", existing: existing, otherItemCount: 40) #expect(result == .added("new.com", overLimit: false)) } diff --git a/NormalTests/Shared/DTOBackCompatTests.swift b/NormalTests/Shared/DTOBackCompatTests.swift index 433cb6f..76d861e 100644 --- a/NormalTests/Shared/DTOBackCompatTests.swift +++ b/NormalTests/Shared/DTOBackCompatTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct DTOBackCompatTests { /// Mirrors the pre-customDomains shape of TimedUnblockDTO. private struct LegacyTimedUnblockDTO: Codable { diff --git a/NormalTests/Shared/DataExtensionTests.swift b/NormalTests/Shared/DataExtensionTests.swift index 52df9ad..930871e 100644 --- a/NormalTests/Shared/DataExtensionTests.swift +++ b/NormalTests/Shared/DataExtensionTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct DataExtensionTests { @Test func emptyDataHasEmptyHex() { #expect(Data().hexString == "") diff --git a/NormalTests/Shared/DomainNormalizerTests.swift b/NormalTests/Shared/DomainNormalizerTests.swift index e1df6a9..4194995 100644 --- a/NormalTests/Shared/DomainNormalizerTests.swift +++ b/NormalTests/Shared/DomainNormalizerTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct DomainNormalizerTests { @Test func stripsSchemeAndPath() { #expect(DomainNormalizer.normalize("https://reddit.com/r/swift") == "reddit.com") diff --git a/NormalTests/Shared/DurationFormatTests.swift b/NormalTests/Shared/DurationFormatTests.swift index 3b08f87..8a3fe73 100644 --- a/NormalTests/Shared/DurationFormatTests.swift +++ b/NormalTests/Shared/DurationFormatTests.swift @@ -1,6 +1,7 @@ -@testable import Normal import Testing +@testable import Normal + struct DurationFormatTests { @Test func compactDropsTheEmptyComponent() { #expect(DurationFormat.compact(minutes: 0) == "0m") diff --git a/NormalTests/Shared/FamilyControlsUtilTests.swift b/NormalTests/Shared/FamilyControlsUtilTests.swift index 89fe21a..cd37343 100644 --- a/NormalTests/Shared/FamilyControlsUtilTests.swift +++ b/NormalTests/Shared/FamilyControlsUtilTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct FamilyControlsUtilTests { @Test func emptySelectionIsEmpty() { #expect(FamilyActivitySelection().isEmpty) @@ -71,8 +72,9 @@ struct FamilyControlsUtilTests { // MARK: - selectedTokenCounts @Test func emptyCountsReturnEmptyStatePhrase() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 0, categories: 0) - == String(localized: "No items selected")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 0, categories: 0) + == String(localized: "No items selected")) } @Test func emptySelectionReturnsEmptyStatePhrase() { @@ -80,33 +82,39 @@ struct FamilyControlsUtilTests { } @Test func singleAppUsesSingularNoun() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 1, websites: 0, categories: 0) - == String(localized: "1 App")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 1, websites: 0, categories: 0) + == String(localized: "1 App")) } @Test func multipleAppsUsePluralNoun() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 5, websites: 0, categories: 0) - == String(localized: "\(5) Apps")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 5, websites: 0, categories: 0) + == String(localized: "\(5) Apps")) } @Test func singleWebsiteUsesSingularNoun() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 1, categories: 0) - == String(localized: "1 Website")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 1, categories: 0) + == String(localized: "1 Website")) } @Test func multipleWebsitesUsePluralNoun() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 3, categories: 0) - == String(localized: "\(3) Websites")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 3, categories: 0) + == String(localized: "\(3) Websites")) } @Test func singleCategoryUsesSingularNoun() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 0, categories: 1) - == String(localized: "1 Category")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 0, categories: 1) + == String(localized: "1 Category")) } @Test func multipleCategoriesUsePluralNoun() { - #expect(FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 0, categories: 4) - == String(localized: "\(4) Categories")) + #expect( + FamilyActivitySelection.selectedTokenCounts(apps: 0, websites: 0, categories: 4) + == String(localized: "\(4) Categories")) } @Test func allPluralSegmentsJoinInAppsWebsitesCategoriesOrder() { diff --git a/NormalTests/Shared/ScheduleActiveDayTests.swift b/NormalTests/Shared/ScheduleActiveDayTests.swift index e10e559..4f58802 100644 --- a/NormalTests/Shared/ScheduleActiveDayTests.swift +++ b/NormalTests/Shared/ScheduleActiveDayTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct ScheduleActiveDayTests { private let cal: Calendar = { var c = Calendar(identifier: .gregorian) @@ -40,7 +41,7 @@ struct ScheduleActiveDayTests { @Test func nonWrappingMondayToFridayActiveOnlyOnWeekdays() { let s = schedule(weekdays: [2, 3, 4, 5, 6]) for (day, weekday) in weekdayOfDay { - let expected = (2 ... 6).contains(weekday) + let expected = (2...6).contains(weekday) #expect(s.isActive(at: date(day: day, hour: 9), calendar: cal) == expected) } } diff --git a/NormalTests/Shared/SharedConstantsTests.swift b/NormalTests/Shared/SharedConstantsTests.swift index 97f498a..9e4fe30 100644 --- a/NormalTests/Shared/SharedConstantsTests.swift +++ b/NormalTests/Shared/SharedConstantsTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct SharedConstantsTests { @Test func appGroupIDIsStable() { #expect(SharedConstants.appGroupID == "group.com.normalengineering.block") diff --git a/NormalTests/Shared/SharedDTOTests.swift b/NormalTests/Shared/SharedDTOTests.swift index b04fa2b..e17f605 100644 --- a/NormalTests/Shared/SharedDTOTests.swift +++ b/NormalTests/Shared/SharedDTOTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct SharedDTOTests { @Test func timedUnblockDTORoundTrips() throws { let original = try TimedUnblockDTO( diff --git a/NormalTests/Shared/SharedStoreTests.swift b/NormalTests/Shared/SharedStoreTests.swift index ba210fe..a5198cb 100644 --- a/NormalTests/Shared/SharedStoreTests.swift +++ b/NormalTests/Shared/SharedStoreTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct SharedStoreTests { private func makeStore() -> (SharedStore, UserDefaults) { let defaults = UserDefaults(suiteName: "test-\(UUID().uuidString)")! diff --git a/NormalTests/Shared/ShieldReconcilerTests.swift b/NormalTests/Shared/ShieldReconcilerTests.swift index a047bee..70e09cd 100644 --- a/NormalTests/Shared/ShieldReconcilerTests.swift +++ b/NormalTests/Shared/ShieldReconcilerTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation import ManagedSettings -@testable import Normal import Testing +@testable import Normal + struct ShieldReconcilerTests { private final class RecordingShields: ShieldApplying, @unchecked Sendable { private let lock = NSLock() @@ -153,7 +154,7 @@ struct ShieldReconcilerTests { shields.readDelay = 0.01 await withTaskGroup(of: Void.self) { group in - for id in UInt8(1) ... 8 { + for id in UInt8(1)...8 { group.addTask { ShieldReconciler.reconcile(sharedStore: store, shields: shields, monitoredActivities: [], lockURL: lockURL) { $0.block(TokenFixtures.selection(apps: [id]), customDomains: [], at: .now) @@ -164,6 +165,6 @@ struct ShieldReconcilerTests { #expect(shields.applyCount == 8) #expect(shields.maxInFlight == 1) - #expect(shields.current.applications == Set((UInt8(1) ... 8).map(TokenFixtures.app))) + #expect(shields.current.applications == Set((UInt8(1)...8).map(TokenFixtures.app))) } } diff --git a/NormalTests/Shared/ShieldResolverTests.swift b/NormalTests/Shared/ShieldResolverTests.swift index 30784af..3a04c53 100644 --- a/NormalTests/Shared/ShieldResolverTests.swift +++ b/NormalTests/Shared/ShieldResolverTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation import ManagedSettings -@testable import Normal import Testing +@testable import Normal + struct ShieldResolverTests { private let cal: Calendar = { var c = Calendar(identifier: .gregorian) @@ -22,7 +23,7 @@ struct ShieldResolverTests { minutes: Int, block: Bool, timed: Bool = true, - weekdays: Set = Set(1 ... 7), + weekdays: Set = Set(1...7), activatedAt: Date? = nil ) throws -> ScheduleDTO { try ScheduleDTO( @@ -460,7 +461,7 @@ struct ShieldResolverTests { state.blockAll(TokenFixtures.selection(apps: [1], categories: [1], webDomains: [1]), customDomains: [], at: .distantPast) let allow = try ScheduleDTO( id: UUID(), name: "S", selectionData: TokenFixtures.selection(apps: [], categories: [1]).toData(), - startHour: 12, startMinute: 0, durationMinutes: 60, weekdays: Set(1 ... 7), + startHour: 12, startMinute: 0, durationMinutes: 60, weekdays: Set(1...7), shouldBlock: false, isTimed: true ) diff --git a/NormalTests/Shared/SortIndexingPersistenceTests.swift b/NormalTests/Shared/SortIndexingPersistenceTests.swift index 3b04417..92f8d05 100644 --- a/NormalTests/Shared/SortIndexingPersistenceTests.swift +++ b/NormalTests/Shared/SortIndexingPersistenceTests.swift @@ -1,9 +1,10 @@ import FamilyControls import Foundation -@testable import Normal import SwiftData import Testing +@testable import Normal + @MainActor struct SortIndexingPersistenceTests { @Test func appGroupsFetchInSortIndexOrderAfterReorder() throws { @@ -77,7 +78,7 @@ struct SortIndexingPersistenceTests { let container = try InMemoryModelContainer.make() let context = container.mainContext - let items = (0 ..< 5).map { i in + let items = (0..<5).map { i in makeSchedule(name: "S\(i)", sortIndex: i) } items.forEach(context.insert) diff --git a/NormalTests/Shared/SortIndexingTests.swift b/NormalTests/Shared/SortIndexingTests.swift index 4fb717b..50c81fc 100644 --- a/NormalTests/Shared/SortIndexingTests.swift +++ b/NormalTests/Shared/SortIndexingTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct SortIndexingTests { private final class Item { let id: Int @@ -13,7 +14,7 @@ struct SortIndexingTests { } private func makeItems(_ count: Int) -> [Item] { - (0 ..< count).map { Item(id: $0, sortIndex: $0) } + (0.. Calendar { var calendar = Calendar(identifier: .gregorian) @@ -77,7 +78,8 @@ struct UsageDTOTests { @Test func recordedStateReadsBackWithinTheSameDay() { let noon = date("2026-03-14T12:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) @@ -86,7 +88,8 @@ struct UsageDTOTests { @Test func statesOnlyEverAdvanceWithinADay() { let noon = date("2026-03-14T12:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) @@ -102,7 +105,8 @@ struct UsageDTOTests { @Test func aRecordExpiresOnceTheNextDayHasActuallyArrived() { let noon = date("2026-03-14T12:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) @@ -116,7 +120,8 @@ struct UsageDTOTests { /// passed, so the spent allowance stands. @Test func windingTheClockBackDoesNotRefundTheDay() { let noon = date("2026-03-14T12:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) @@ -131,7 +136,8 @@ struct UsageDTOTests { let other = UUID() let nextDay = date("2026-03-15T09:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) .recording(.reached, for: other, on: nextDay, period: nyPeriod) @@ -143,7 +149,8 @@ struct UsageDTOTests { @Test func clearingDropsOneRecordAndLeavesTheRest() { let noon = date("2026-03-14T12:00:00-04:00") let other = UUID() - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) .recording(.reached, for: other, on: noon, period: nyPeriod) @@ -166,7 +173,8 @@ struct UsageDTOTests { @Test func overridingClearsEveryRecordAndFlagsTheDay() { let noon = date("2026-03-14T12:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) .overriding(on: noon, period: nyPeriod) @@ -224,7 +232,8 @@ struct UsageDTOTests { @Test func movingTheResetLaterKeepsASpentRecordUntilTheNewReset() { let noon = date("2026-03-14T12:00:00-04:00") - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .recording(.reached, for: id, on: noon, period: nyPeriod) let later = newYorkPeriod(resetAt: 4) @@ -236,7 +245,8 @@ struct UsageDTOTests { @Test func movingTheResetEarlierReleasesASpentRecordAtTheNewReset() { let noon = date("2026-03-14T12:00:00-04:00") let later = newYorkPeriod(resetAt: 4) - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: later) .recording(.reached, for: id, on: noon, period: later) .moving(from: later, to: nyPeriod, on: noon + .hours(1)) @@ -248,7 +258,8 @@ struct UsageDTOTests { @Test func movingTheResetPastTheCurrentTimeReleasesASpentRecordAtTheNewReset() { let spentAt = date("2026-03-14T15:00:00-04:00") let later = newYorkPeriod(resetAt: 16) - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: spentAt, period: nyPeriod) .recording(.reached, for: id, on: spentAt, period: nyPeriod) .moving(from: nyPeriod, to: later, on: date("2026-03-14T15:30:00-04:00")) @@ -261,7 +272,8 @@ struct UsageDTOTests { let yesterday = date("2026-03-13T12:00:00-04:00") let now = date("2026-03-14T15:30:00-04:00") let later = newYorkPeriod(resetAt: 16) - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: yesterday, period: nyPeriod) .recording(.reached, for: id, on: yesterday, period: nyPeriod) .moving(from: nyPeriod, to: later, on: now) @@ -272,7 +284,8 @@ struct UsageDTOTests { @Test func movingTheResetKeepsTheOverride() { let noon = date("2026-03-14T12:00:00-04:00") let later = newYorkPeriod(resetAt: 16) - let state = UsageDayStateDTO + let state = + UsageDayStateDTO .fresh(on: noon, period: nyPeriod) .overriding(on: noon, period: nyPeriod) .moving(from: nyPeriod, to: later, on: noon) diff --git a/NormalTests/Shared/WebFilterTests.swift b/NormalTests/Shared/WebFilterTests.swift index 28c942d..b0800b4 100644 --- a/NormalTests/Shared/WebFilterTests.swift +++ b/NormalTests/Shared/WebFilterTests.swift @@ -1,7 +1,8 @@ import ManagedSettings -@testable import Normal import Testing +@testable import Normal + struct WebFilterTests { private func domains(_ strings: String...) -> Set { Set(strings.map { WebDomain(domain: $0) }) diff --git a/NormalTests/Shared/WidgetDeepLinkTests.swift b/NormalTests/Shared/WidgetDeepLinkTests.swift index a2498e8..b441f33 100644 --- a/NormalTests/Shared/WidgetDeepLinkTests.swift +++ b/NormalTests/Shared/WidgetDeepLinkTests.swift @@ -1,13 +1,15 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct WidgetDeepLinkTests { private func queryItems(_ url: URL) -> [String: String] { let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] - return Dictionary(uniqueKeysWithValues: items.compactMap { item in - item.value.map { (item.name, $0) } - }) + return Dictionary( + uniqueKeysWithValues: items.compactMap { item in + item.value.map { (item.name, $0) } + }) } @Test func buildsSchemeAndHost() { diff --git a/NormalTests/Shared/WidgetGroupStateTests.swift b/NormalTests/Shared/WidgetGroupStateTests.swift index 7c87d13..dde451f 100644 --- a/NormalTests/Shared/WidgetGroupStateTests.swift +++ b/NormalTests/Shared/WidgetGroupStateTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct WidgetGroupStateTests { private let now = Date(timeIntervalSinceReferenceDate: 1_000_000) @@ -22,8 +23,9 @@ struct WidgetGroupStateTests { } @Test func noTimedUnblockUsesMirroredShieldState() { - #expect(WidgetGroupState.resolve(timedUnblockEnd: nil, blockStatus: .unblocked, now: now) - == .unblocked(until: nil)) + #expect( + WidgetGroupState.resolve(timedUnblockEnd: nil, blockStatus: .unblocked, now: now) + == .unblocked(until: nil)) #expect(WidgetGroupState.resolve(timedUnblockEnd: nil, blockStatus: .blocked, now: now) == .blocked) } diff --git a/NormalTests/Shared/WidgetSharedStoreTests.swift b/NormalTests/Shared/WidgetSharedStoreTests.swift index e8807a4..3f56668 100644 --- a/NormalTests/Shared/WidgetSharedStoreTests.swift +++ b/NormalTests/Shared/WidgetSharedStoreTests.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Testing +@testable import Normal + struct WidgetSharedStoreTests { private func makeStore() -> (WidgetSharedStore, UserDefaults) { let defaults = UserDefaults(suiteName: "test-\(UUID().uuidString)")! diff --git a/NormalTests/TestSupport/BlockingHarness.swift b/NormalTests/TestSupport/BlockingHarness.swift index bf64b5f..5519faa 100644 --- a/NormalTests/TestSupport/BlockingHarness.swift +++ b/NormalTests/TestSupport/BlockingHarness.swift @@ -2,9 +2,10 @@ import DeviceActivity import FamilyControls import Foundation import ManagedSettings -@testable import Normal import Testing +@testable import Normal + @MainActor final class BlockingHarness { final class Clock { @@ -175,7 +176,7 @@ final class BlockingHarness { minutes: Int, block: Bool, timed: Bool = true, - weekdays: Set = Set(1 ... 7) + weekdays: Set = Set(1...7) ) throws -> BlockSchedule { let schedule = BlockSchedule( name: "S\(schedules.count)", diff --git a/NormalTests/TestSupport/ControlledScanner.swift b/NormalTests/TestSupport/ControlledScanner.swift index dfa8025..4bcc94c 100644 --- a/NormalTests/TestSupport/ControlledScanner.swift +++ b/NormalTests/TestSupport/ControlledScanner.swift @@ -1,4 +1,5 @@ import Foundation + @testable import Normal final class ControlledScanner: CancellableKeyScanning { diff --git a/NormalTests/TestSupport/FakeCameraAuthorizer.swift b/NormalTests/TestSupport/FakeCameraAuthorizer.swift index af6cd15..ac99a50 100644 --- a/NormalTests/TestSupport/FakeCameraAuthorizer.swift +++ b/NormalTests/TestSupport/FakeCameraAuthorizer.swift @@ -1,4 +1,5 @@ import AVFoundation + @testable import Normal final class FakeCameraAuthorizer: CameraAuthorizing { diff --git a/NormalTests/TestSupport/FakeDeviceActivityCenter.swift b/NormalTests/TestSupport/FakeDeviceActivityCenter.swift index b0c7d38..144e324 100644 --- a/NormalTests/TestSupport/FakeDeviceActivityCenter.swift +++ b/NormalTests/TestSupport/FakeDeviceActivityCenter.swift @@ -1,4 +1,5 @@ import DeviceActivity + @testable import Normal final class FakeDeviceActivityCenter: DeviceActivityProviding { @@ -24,8 +25,8 @@ final class FakeDeviceActivityCenter: DeviceActivityProviding { throw startError } if let activityLimit, - !monitoredActivityNames.contains(activityName.rawValue), - monitoredActivityNames.count >= activityLimit + !monitoredActivityNames.contains(activityName.rawValue), + monitoredActivityNames.count >= activityLimit { throw DeviceActivityCenter.MonitoringError.excessiveActivities } diff --git a/NormalTests/TestSupport/FakeKeyScanning.swift b/NormalTests/TestSupport/FakeKeyScanning.swift index 92b0800..e3c2d52 100644 --- a/NormalTests/TestSupport/FakeKeyScanning.swift +++ b/NormalTests/TestSupport/FakeKeyScanning.swift @@ -1,4 +1,5 @@ import Foundation + @testable import Normal final class FakeKeyScanning: KeyScanning, @unchecked Sendable { diff --git a/NormalTests/TestSupport/FakeLocationProvider.swift b/NormalTests/TestSupport/FakeLocationProvider.swift index 339017f..e426719 100644 --- a/NormalTests/TestSupport/FakeLocationProvider.swift +++ b/NormalTests/TestSupport/FakeLocationProvider.swift @@ -1,5 +1,6 @@ import CoreLocation import Foundation + @testable import Normal @MainActor @@ -41,12 +42,12 @@ final class FakeLocationProvider: LocationProviding { requestCount += 1 let ready = requestWaiters.filter { $0.count <= requestCount } requestWaiters.removeAll { $0.count <= requestCount } - ready.forEach { $0.continuation.resume() } + for waiter in ready { waiter.continuation.resume() } let next = queuedOutcomes.isEmpty ? outcome : queuedOutcomes.removeFirst() switch next { - case let .location(location): + case .location(let location): return location - case let .throwKeyError(error): + case .throwKeyError(let error): throw error case .throwGeneric: throw NSError(domain: "test", code: 0) diff --git a/NormalTests/TestSupport/FakeScreenTimeService.swift b/NormalTests/TestSupport/FakeScreenTimeService.swift index c3ff1da..4100c0a 100644 --- a/NormalTests/TestSupport/FakeScreenTimeService.swift +++ b/NormalTests/TestSupport/FakeScreenTimeService.swift @@ -1,8 +1,9 @@ import FamilyControls import Foundation -@testable import Normal import Observation +@testable import Normal + @MainActor @Observable final class FakeScreenTimeService: ScreenTimeProviding { diff --git a/NormalTests/TestSupport/FakeSharedStore.swift b/NormalTests/TestSupport/FakeSharedStore.swift index e3d6cc8..008b9bd 100644 --- a/NormalTests/TestSupport/FakeSharedStore.swift +++ b/NormalTests/TestSupport/FakeSharedStore.swift @@ -1,4 +1,5 @@ import Foundation + @testable import Normal final class FakeSharedStore: SharedStoreProviding, @unchecked Sendable { diff --git a/NormalTests/TestSupport/InMemoryModelContainer.swift b/NormalTests/TestSupport/InMemoryModelContainer.swift index 987ff7d..d693af3 100644 --- a/NormalTests/TestSupport/InMemoryModelContainer.swift +++ b/NormalTests/TestSupport/InMemoryModelContainer.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import SwiftData +@testable import Normal + @MainActor enum InMemoryModelContainer { static func make() throws -> ModelContainer { diff --git a/NormalTests/TestSupport/StatefulScreenTimeSpy.swift b/NormalTests/TestSupport/StatefulScreenTimeSpy.swift index 65f8381..88d8693 100644 --- a/NormalTests/TestSupport/StatefulScreenTimeSpy.swift +++ b/NormalTests/TestSupport/StatefulScreenTimeSpy.swift @@ -1,5 +1,6 @@ import FamilyControls import Foundation + @testable import Normal @MainActor diff --git a/NormalTests/Views/LocationCameraTests.swift b/NormalTests/Views/LocationCameraTests.swift index 262dce7..8f973a9 100644 --- a/NormalTests/Views/LocationCameraTests.swift +++ b/NormalTests/Views/LocationCameraTests.swift @@ -1,8 +1,9 @@ import CoreLocation import MapKit -@testable import Normal import Testing +@testable import Normal + struct LocationCameraTests { private static let cupertino = CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090) private static let london = CLLocationCoordinate2D(latitude: 51.5074, longitude: -0.1278) diff --git a/NormalTests/Views/LocationFormatTests.swift b/NormalTests/Views/LocationFormatTests.swift index 22d0b42..05f09be 100644 --- a/NormalTests/Views/LocationFormatTests.swift +++ b/NormalTests/Views/LocationFormatTests.swift @@ -1,7 +1,8 @@ import Foundation -@testable import Normal import Testing +@testable import Normal + struct LocationFormatTests { @Test func usesMetricUnitsForMetricLocale() { let label = LocationFormat.distance(meters: 1500, locale: Locale(identifier: "de_DE")) diff --git a/NormalTests/Views/QRScanWindowMetricsTests.swift b/NormalTests/Views/QRScanWindowMetricsTests.swift index 6476260..bee9a21 100644 --- a/NormalTests/Views/QRScanWindowMetricsTests.swift +++ b/NormalTests/Views/QRScanWindowMetricsTests.swift @@ -1,7 +1,8 @@ import CoreGraphics -@testable import Normal import Testing +@testable import Normal + struct QRScanWindowMetricsTests { private func assertSafe(_ m: QRScanWindowMetrics) { #expect(m.side.isFinite && m.side >= 0) diff --git a/NormalUITests/BlockingUITests.swift b/NormalUITests/BlockingUITests.swift index 4cbd869..e4c1d4b 100644 --- a/NormalUITests/BlockingUITests.swift +++ b/NormalUITests/BlockingUITests.swift @@ -318,7 +318,7 @@ final class BlockingUITests: XCTestCase { let strip = app.descendants(matching: .any)["schedule.weekdayStrip"] require(strip, "The days should switch to the week strip instead of breaking words") - let weekdays = Calendar.current.weekdaySymbols[1 ... 5] + let weekdays = Calendar.current.weekdaySymbols[1...5] XCTAssertEqual(strip.label, weekdays.formatted(.list(type: .and))) XCTAssertFalse(app.descendants(matching: .any)["schedule.weekdayChips"].exists) } diff --git a/NormalUITests/NormalUITests.swift b/NormalUITests/NormalUITests.swift index f4eb7bb..e9d664f 100644 --- a/NormalUITests/NormalUITests.swift +++ b/NormalUITests/NormalUITests.swift @@ -64,7 +64,7 @@ final class NormalUITests: XCTestCase { require(skipPermission, "Permission step should offer Skip") skipPermission.tap() - for _ in 0 ..< 5 { + for _ in 0..<5 { let next = app.buttons["Next"] require(next, "Each tab walkthrough step should offer Next") next.tap() @@ -350,7 +350,7 @@ final class NormalUITests: XCTestCase { var opened = Set() var cutOff = Set() var previousPage: [String] = [] - for _ in 0 ..< 300 { + for _ in 0..<300 { let headers = app.buttons.matching(identifier: "expandableSection").allElementsBoundByIndex if let next = headers.first(where: { $0.isHittable && !opened.contains($0.label) }) { opened.insert(next.label) diff --git a/NormalUITests/RecoveryUITests.swift b/NormalUITests/RecoveryUITests.swift index 6230030..37b4cd8 100644 --- a/NormalUITests/RecoveryUITests.swift +++ b/NormalUITests/RecoveryUITests.swift @@ -155,7 +155,7 @@ final class RecoveryUITests: XCTestCase { let app = launch([]) openEmergencyTab(app) - for use in 1 ... 3 { + for use in 1...3 { let button = app.buttons["emergency.unblockButton"] require(button, "Emergency button available on use \(use)") XCTAssertTrue(button.isEnabled, "Still enabled before use \(use)") diff --git a/NormalWidget/GroupUnlockWidgetView.swift b/NormalWidget/GroupUnlockWidgetView.swift index 5ed20da..dd693e6 100644 --- a/NormalWidget/GroupUnlockWidgetView.swift +++ b/NormalWidget/GroupUnlockWidgetView.swift @@ -78,7 +78,7 @@ struct GroupUnlockWidgetView: View { if let end = entry.countdownEnd { HStack(spacing: 4) { Image(systemName: "timer") - Text(timerInterval: entry.date ... end, countsDown: true) + Text(timerInterval: entry.date...end, countsDown: true) .monospacedDigit() } .font(.caption.weight(.medium)) diff --git a/NormalWidget/SelectGroupIntent.swift b/NormalWidget/SelectGroupIntent.swift index 6840b53..b20f4b2 100644 --- a/NormalWidget/SelectGroupIntent.swift +++ b/NormalWidget/SelectGroupIntent.swift @@ -28,7 +28,8 @@ struct SelectGroupIntent: WidgetConfigurationIntent { if let unblockDuration { return unblockDuration.request } - return duration + return + duration .flatMap { TimedUnblockDuration(validating: $0.rawValue) } .map(UnlockDurationRequest.fixed) ?? .useDefault } diff --git a/NormalWidget/TimedUnblockLiveActivity.swift b/NormalWidget/TimedUnblockLiveActivity.swift index 5ad2381..e393621 100644 --- a/NormalWidget/TimedUnblockLiveActivity.swift +++ b/NormalWidget/TimedUnblockLiveActivity.swift @@ -158,7 +158,7 @@ struct TimedUnblockLiveActivity: Widget { private func range( _ context: ActivityViewContext ) -> ClosedRange { - context.attributes.startDate ... context.state.endDate + context.attributes.startDate...context.state.endDate } private func isFinished( diff --git a/Shared/CallbackLog.swift b/Shared/CallbackLog.swift index be41b72..b670892 100644 --- a/Shared/CallbackLog.swift +++ b/Shared/CallbackLog.swift @@ -22,7 +22,7 @@ nonisolated enum CallbackLog { static func read() -> [String] { guard let fileURL, - let text = try? String(contentsOf: fileURL, encoding: .utf8) + let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return [] } return text.split(separator: "\n").map(String.init) } diff --git a/Shared/CustomDomainFilter.swift b/Shared/CustomDomainFilter.swift index a0ef1cb..9ff365c 100644 --- a/Shared/CustomDomainFilter.swift +++ b/Shared/CustomDomainFilter.swift @@ -3,8 +3,8 @@ import ManagedSettings extension ManagedSettingsStore { func filterDomains() -> Set { switch webContent.blockedByFilter { - case let .specific(domains)?: domains - case let .auto(domains, _)?: domains + case .specific(let domains)?: domains + case .auto(let domains, _)?: domains default: [] } } diff --git a/Shared/DismissUnblockActivityIntent.swift b/Shared/DismissUnblockActivityIntent.swift index a873de8..f7db854 100644 --- a/Shared/DismissUnblockActivityIntent.swift +++ b/Shared/DismissUnblockActivityIntent.swift @@ -28,8 +28,7 @@ struct DismissUnblockActivityIntent: LiveActivityIntent { @MainActor private static func dismiss(unblockID: String) async { for activity in Activity.activities - where activity.attributes.unblockID == unblockID - { + where activity.attributes.unblockID == unblockID { await activity.end(nil, dismissalPolicy: .immediate) } } diff --git a/Shared/DomainNormalizer.swift b/Shared/DomainNormalizer.swift index 529a19f..c68856d 100644 --- a/Shared/DomainNormalizer.swift +++ b/Shared/DomainNormalizer.swift @@ -47,9 +47,9 @@ nonisolated enum DomainNormalizer { let allowed = Set("abcdefghijklmnopqrstuvwxyz0123456789-") for label in labels { guard !label.isEmpty, - !label.hasPrefix("-"), - !label.hasSuffix("-"), - label.allSatisfy({ allowed.contains($0) }) + !label.hasPrefix("-"), + !label.hasSuffix("-"), + label.allSatisfy({ allowed.contains($0) }) else { return false } } diff --git a/Shared/ManagedSettingsUtil.swift b/Shared/ManagedSettingsUtil.swift index e9cae1d..ef26a68 100644 --- a/Shared/ManagedSettingsUtil.swift +++ b/Shared/ManagedSettingsUtil.swift @@ -3,7 +3,7 @@ import ManagedSettings extension ShieldSettings.ActivityCategoryPolicy? { var tokenSet: Set { - guard case let .specific(tokens, _) = self else { return [] } + guard case .specific(let tokens, _) = self else { return [] } return tokens } diff --git a/Shared/SharedDTO.swift b/Shared/SharedDTO.swift index 43e9188..2e70cf1 100644 --- a/Shared/SharedDTO.swift +++ b/Shared/SharedDTO.swift @@ -143,19 +143,20 @@ nonisolated enum ScheduleWindow { let startOfToday = calendar.startOfDay(for: date) for dayOffset in [0, -1] { guard let day = calendar.date(byAdding: .day, value: dayOffset, to: startOfToday), - let start = calendar.date( - bySettingHour: startHour, minute: startMinute, second: 0, of: day - ) + let start = calendar.date( + bySettingHour: startHour, minute: startMinute, second: 0, of: day + ) else { continue } - let end = end( - of: day, - startHour: startHour, - startMinute: startMinute, - durationMinutes: durationMinutes, - calendar: calendar - ) ?? start.addingTimeInterval(TimeInterval(durationMinutes * 60)) + let end = + end( + of: day, + startHour: startHour, + startMinute: startMinute, + durationMinutes: durationMinutes, + calendar: calendar + ) ?? start.addingTimeInterval(TimeInterval(durationMinutes * 60)) if weekdays.contains(calendar.component(.weekday, from: start)), - date >= start, date < end + date >= start, date < end { return start } diff --git a/Shared/SharedStore.swift b/Shared/SharedStore.swift index e9f57dd..9121378 100644 --- a/Shared/SharedStore.swift +++ b/Shared/SharedStore.swift @@ -4,7 +4,8 @@ struct SharedStore: SharedStoreProviding, Sendable { private nonisolated(unsafe) let defaults: UserDefaults init(defaults: UserDefaults? = nil) { - self.defaults = defaults + self.defaults = + defaults ?? UserDefaults(suiteName: SharedConstants.appGroupID) ?? UserDefaults.standard } diff --git a/Shared/ShieldReconciler.swift b/Shared/ShieldReconciler.swift index 5be6ead..6880a94 100644 --- a/Shared/ShieldReconciler.swift +++ b/Shared/ShieldReconciler.swift @@ -45,7 +45,8 @@ nonisolated enum ShieldReconciler { let current = shields.currentShields() let saved = sharedStore.loadManualBlockState() - var manual = saved + var manual = + saved ?? ShieldResolver.migratedManualState( shielded: current, enabledSchedules: schedules, @@ -104,7 +105,8 @@ extension ManagedSettingsStore: ShieldApplying { func apply(_ plan: ShieldPlan) { replaceShields(with: plan.selection) replaceFilter(domains: Array(plan.customDomains), blockingAdultContent: plan.blocksAdultContent) - application.blockedApplications = plan.hiddenApplications.isEmpty + application.blockedApplications = + plan.hiddenApplications.isEmpty ? nil : Set(plan.hiddenApplications.map { Application(token: $0) }) if let deny = plan.denyAppRemoval { diff --git a/Shared/ShieldResolver.swift b/Shared/ShieldResolver.swift index 8a75cf1..505c0f4 100644 --- a/Shared/ShieldResolver.swift +++ b/Shared/ShieldResolver.swift @@ -148,9 +148,10 @@ nonisolated enum ShieldResolver { at date: Date, calendar: Calendar = .current ) -> ShieldPlan { - let claims = enabledSchedules.compactMap { - claim(for: $0, migratedAt: manual.migratedAt, at: date, calendar: calendar) - } + let claims = + enabledSchedules.compactMap { + claim(for: $0, migratedAt: manual.migratedAt, at: date, calendar: calendar) + } + timedUnblocks.compactMap { claim(for: $0, at: date) } var plan = ShieldPlan() @@ -242,13 +243,14 @@ nonisolated enum ShieldResolver { at date: Date, calendar: Calendar ) -> Claim? { - let start = schedule.isTimed + let start = + schedule.isTimed ? schedule.activeWindowStart(at: date, calendar: calendar) : schedule.latestStart(atOrBefore: date, calendar: calendar) let activation = schedule.activatedAt ?? (schedule.isTimed ? nil : migratedAt) ?? .distantPast guard let start, - schedule.isTimed || start.addingTimeInterval(TimeInterval(schedule.durationMinutes * 60)) > activation, - let selection = try? FamilyActivitySelection.fromData(schedule.selectionData) + schedule.isTimed || start.addingTimeInterval(TimeInterval(schedule.durationMinutes * 60)) > activation, + let selection = try? FamilyActivitySelection.fromData(schedule.selectionData) else { return nil } return Claim( date: max(start, activation), @@ -262,7 +264,7 @@ nonisolated enum ShieldResolver { private static func claim(for unblock: TimedUnblockDTO, at date: Date) -> Claim? { guard unblock.endDate > date, - let selection = try? FamilyActivitySelection.fromData(unblock.selectionData) + let selection = try? FamilyActivitySelection.fromData(unblock.selectionData) else { return nil } return Claim( date: startDate(of: unblock), @@ -300,9 +302,9 @@ nonisolated enum ShieldResolver { nonisolated extension ScheduleDTO { func latestStart(atOrBefore date: Date, calendar: Calendar = .current) -> Date? { let startOfToday = calendar.startOfDay(for: date) - for dayOffset in 0 ... 7 { + for dayOffset in 0...7 { guard let day = calendar.date(byAdding: .day, value: -dayOffset, to: startOfToday), - let start = calendar.date(bySettingHour: startHour, minute: startMinute, second: 0, of: day) + let start = calendar.date(bySettingHour: startHour, minute: startMinute, second: 0, of: day) else { continue } if start <= date, weekdays.contains(calendar.component(.weekday, from: start)) { return start diff --git a/Shared/TimedUnblockDuration.swift b/Shared/TimedUnblockDuration.swift index 5068901..77ae5b3 100644 --- a/Shared/TimedUnblockDuration.swift +++ b/Shared/TimedUnblockDuration.swift @@ -28,7 +28,7 @@ nonisolated struct TimedUnblockDuration: Hashable, Comparable, Identifiable, Sen } static func isValid(_ seconds: Int) -> Bool { - (minimumSeconds ... maximumSeconds).contains(seconds) && seconds % stepSeconds == 0 + (minimumSeconds...maximumSeconds).contains(seconds) && seconds % stepSeconds == 0 } static func sanitized(_ seconds: [Int]?) -> [TimedUnblockDuration] { @@ -76,7 +76,7 @@ nonisolated enum UnlockDurationRequest: Equatable, Sendable { switch self { case .useDefault: nil case .ask: Self.askQueryValue - case let .fixed(duration): String(duration.seconds) + case .fixed(let duration): String(duration.seconds) case .permanent: Self.permanentQueryValue } } @@ -91,7 +91,7 @@ nonisolated enum UnlockDurationRequest: Equatable, Sendable { return } if let seconds = Int(queryValue), String(seconds) == queryValue, - let duration = TimedUnblockDuration(validating: seconds) + let duration = TimedUnblockDuration(validating: seconds) { self = .fixed(duration) } else { diff --git a/Shared/UnblockDurationEntity.swift b/Shared/UnblockDurationEntity.swift index 65ea5c8..a0aad98 100644 --- a/Shared/UnblockDurationEntity.swift +++ b/Shared/UnblockDurationEntity.swift @@ -16,12 +16,13 @@ struct UnblockDurationEntity: AppEntity { } init(_ request: UnlockDurationRequest) { - id = switch request { - case .useDefault: Self.appDefaultID - case .ask: Self.askEachTimeID - case .permanent: Self.permanentID - case let .fixed(duration): duration.seconds - } + id = + switch request { + case .useDefault: Self.appDefaultID + case .ask: Self.askEachTimeID + case .permanent: Self.permanentID + case .fixed(let duration): duration.seconds + } } static func request(forID id: Int) -> UnlockDurationRequest? { @@ -42,7 +43,7 @@ struct UnblockDurationEntity: AppEntity { case .useDefault: DisplayRepresentation(title: "Default Duration") case .ask: DisplayRepresentation(title: "Choose in Normal") case .permanent: DisplayRepresentation(title: "Until Manually Re-Blocked") - case let .fixed(duration): DisplayRepresentation(title: "\(duration.label)") + case .fixed(let duration): DisplayRepresentation(title: "\(duration.label)") } } } diff --git a/Shared/WidgetSharedData.swift b/Shared/WidgetSharedData.swift index ee1f2ba..b1e31dd 100644 --- a/Shared/WidgetSharedData.swift +++ b/Shared/WidgetSharedData.swift @@ -26,7 +26,7 @@ nonisolated enum WidgetGroupState: Equatable, Sendable { } var countdownEnd: Date? { - if case let .unblocked(until) = self { + if case .unblocked(let until) = self { until } else { nil From d07ef76c1be63fe525ee7f293ff2450808433bbd Mon Sep 17 00:00:00 2001 From: ykisana Date: Wed, 18 Nov 2026 19:21:04 -0600 Subject: [PATCH 3/3] ci: check formatting with swift-format A Format job runs swift-format lint --strict on every push and PR to main. AGENTS.md tells contributors and agents to format before committing. --- .github/workflows/ci.yml | 14 ++++++++++++++ AGENTS.md | 2 ++ 2 files changed, 16 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7beda5..303671e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,20 @@ concurrency: cancel-in-progress: true jobs: + format: + name: Format + runs-on: xcode-27 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Select latest stable Xcode + uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1.7.0 + with: + xcode-version: latest-stable + + - name: Check formatting + run: xcrun swift-format lint --strict --recursive --parallel . + unit-tests: name: Unit tests runs-on: xcode-27 diff --git a/AGENTS.md b/AGENTS.md index 930b134..77ee5b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,6 +33,8 @@ Folders are synchronized groups. Target membership comes from exception lists in - Don't change `CURRENT_PROJECT_VERSION`. Version changes only touch `MARKETING_VERSION`. ## Code +- Format before committing: `xcrun swift-format format -i -r -p .` (config in `.swift-format`). + CI fails on any formatting difference. - User-facing text lives in `Normal/Resources/Localizable.xcstrings` (English only). Xcode generates it, so don't edit it by hand. After changing text, sync it and commit the result. This adds new strings and removes unused ones; Xcode adds the comments