diff --git a/Normal.xcodeproj/project.pbxproj b/Normal.xcodeproj/project.pbxproj index 036ba4d..c34f7bb 100644 --- a/Normal.xcodeproj/project.pbxproj +++ b/Normal.xcodeproj/project.pbxproj @@ -117,6 +117,7 @@ membershipExceptions = ( BlockingUITests.swift, DonationUITests.swift, + EditProtectionUITests.swift, NormalUITests.swift, NormalUITestsLaunchTests.swift, RecoveryUITests.swift, @@ -130,6 +131,7 @@ membershipExceptions = ( BlockingUITests.swift, DonationUITests.swift, + EditProtectionUITests.swift, NormalUITests.swift, NormalUITestsLaunchTests.swift, RecoveryUITests.swift, diff --git a/Normal/App/AppContainer.swift b/Normal/App/AppContainer.swift index f9cd81d..afc3a75 100644 --- a/Normal/App/AppContainer.swift +++ b/Normal/App/AppContainer.swift @@ -12,6 +12,7 @@ struct AppContainer: View { @State private var emergencyUnblockService: EmergencyUnblockService @State private var donationService = DonationService() @State private var usageLimitService: UsageLimitService + @State private var editSessionService: EditSessionService @State private var unlockInbox: UnlockRequestInbox init(services: AppServices) { @@ -21,6 +22,7 @@ struct AppContainer: View { _appReviewService = State(initialValue: services.appReview) _emergencyUnblockService = State(initialValue: services.emergencyUnblock) _usageLimitService = State(initialValue: services.usageLimit) + _editSessionService = State(initialValue: services.editSession) _unlockInbox = State(initialValue: services.unlockInbox) } @@ -37,6 +39,7 @@ struct AppContainer: View { .environment(emergencyUnblockService) .environment(donationService) .environment(usageLimitService) + .environment(editSessionService) .environment(unlockInbox) } } diff --git a/Normal/App/AppServices.swift b/Normal/App/AppServices.swift index 98dee3e..b566980 100644 --- a/Normal/App/AppServices.swift +++ b/Normal/App/AppServices.swift @@ -9,6 +9,7 @@ final class AppServices { let appReview: AppReviewService let emergencyUnblock: EmergencyUnblockService let usageLimit: UsageLimitService + let editSession: EditSessionService let unlockInbox = UnlockRequestInbox() init() { @@ -47,6 +48,9 @@ final class AppServices { sharedStore: store, ledger: InMemoryUsageLimitLedger() ) + editSession = EditSessionService( + defaults: UserDefaults(suiteName: "uitest-edit-\(UUID().uuidString)")! + ) } else { let screenTime = ScreenTimeService() self.screenTime = screenTime @@ -55,6 +59,7 @@ final class AppServices { appReview = AppReviewService() emergencyUnblock = EmergencyUnblockService(ledger: KeychainEmergencyUnblockLedger()) usageLimit = UsageLimitService() + editSession = EditSessionService() } } } diff --git a/Normal/App/ContentView.swift b/Normal/App/ContentView.swift index e0be189..481244a 100644 --- a/Normal/App/ContentView.swift +++ b/Normal/App/ContentView.swift @@ -8,6 +8,7 @@ struct ContentView: View { @Environment(ScheduleService.self) private var scheduleService @Environment(EmergencyUnblockService.self) private var emergencyUnblockService @Environment(UsageLimitService.self) private var usageLimitService + @Environment(EditSessionService.self) private var editSessionService @Environment(\.scenePhase) private var scenePhase @Query private var allSettings: [Settings] @Query private var schedules: [BlockSchedule] @@ -23,6 +24,7 @@ struct ContentView: View { var body: some View { ZStack { MainTabView(selectedTab: $navigationCoordinator.selectedTab) + .editUnblockHost() if onboardingService.isOnboardingActive { OnboardingOverlayView() } @@ -45,6 +47,7 @@ struct ContentView: View { if newPhase == .active { Task { await screenTimeService.checkAuthorizationStatus() } screenTimeService.notifyUpdate() + editSessionService.refresh() timedUnblockService.refresh(screenTimeService: screenTimeService) // The monitor extension may have spent a limit while we were away. usageLimitService.notifyUpdate() @@ -60,6 +63,7 @@ struct ContentView: View { scheduleService.mirrorCustomDomainsEnabled(settings.enableCustomDomains) } + editSessionService.refresh() timedUnblockService.reconcile(screenTimeService: screenTimeService) if settings?.hasCompletedOnboarding == true { onboardingService.isOnboardingActive = false diff --git a/Normal/App/NormalApp.swift b/Normal/App/NormalApp.swift index 52b5cf4..6b6a8ba 100644 --- a/Normal/App/NormalApp.swift +++ b/Normal/App/NormalApp.swift @@ -35,6 +35,9 @@ struct NormalApp: App { settings.skipBlockWithoutKeyConfirmation = UITestSupport.skipBypassConfirm settings.customUnblockDurationSeconds = UITestSupport.unblockDurationSeconds settings.defaultUnblockSeconds = UITestSupport.defaultDurationSeconds + if let editMode = UITestSupport.editProtectionMode { + settings.editProtectionMode = editMode + } context.insert(settings) } diff --git a/Normal/App/UITestSupport.swift b/Normal/App/UITestSupport.swift index 47608cc..2ca8459 100644 --- a/Normal/App/UITestSupport.swift +++ b/Normal/App/UITestSupport.swift @@ -58,6 +58,9 @@ enum UITestSupport { static let defaultDurationSeconds: Int? = value(after: "-uiTestDefaultDuration").flatMap(Int.init) + static let editProtectionMode: EditProtectionMode? = value(after: "-uiTestEditProtection") + .flatMap(EditProtectionMode.init(rawValue:)) + static let stubScanValue = "UITEST-SCAN-VALUE" static let mainSelection = selection(apps: websitesOnly ? [] : [1, 2, 3]) diff --git a/Normal/Models/EditProtectionMode.swift b/Normal/Models/EditProtectionMode.swift new file mode 100644 index 0000000..b6453bb --- /dev/null +++ b/Normal/Models/EditProtectionMode.swift @@ -0,0 +1,40 @@ +import Foundation + +enum EditProtectionMode: String, CaseIterable, Identifiable, Hashable, Sendable { + case unblockAll = "unblockAll" + case requireKey = "requireKey" + + var id: String { rawValue } + + var label: String { + switch self { + case .unblockAll: String(localized: "When All Apps Unblocked") + case .requireKey: String(localized: "With a Key") + } + } + + var shortLabel: String { + switch self { + case .unblockAll: String(localized: "All Unblocked") + case .requireKey: String(localized: "With a Key") + } + } + + var description: String { + switch self { + case .unblockAll: + String(localized: "Editing is available whenever no apps are blocked.") + case .requireKey: + String(localized: "Scan a global key to unblock editing. Blocked apps stay blocked.") + } + } + + var footer: String { + switch self { + case .unblockAll: + String(localized: "When a schedule unblocks all apps, editing becomes available without a key.") + case .requireKey: + String(localized: "Protects apps, groups, schedules, and keys even when no apps are blocked.") + } + } +} diff --git a/Normal/Models/EditProtectionPolicy.swift b/Normal/Models/EditProtectionPolicy.swift new file mode 100644 index 0000000..010073b --- /dev/null +++ b/Normal/Models/EditProtectionPolicy.swift @@ -0,0 +1,98 @@ +import Foundation + +nonisolated enum EditSessionState: Equatable, Sendable { + case blocked + case timed(endDate: Date) + case permanent +} + +nonisolated enum EditProtectionState: Equatable, Sendable { + case open + case sessionActive(endDate: Date?) + case requiresKey + case requiresUnblockAll + + var isBlocked: Bool { + switch self { + case .open, .sessionActive: false + case .requiresKey, .requiresUnblockAll: true + } + } +} + +enum EditProtectionPolicy { + static func hasUsableGlobalKey( + in keys: [Key], + availableKeyTypes: [KeyType] = KeyType.availableOnDevice + ) -> Bool { + let globalTypes = keys.filter(\.isGlobal).map(\.type) + return !KeyType.selectable(registered: globalTypes, onDevice: availableKeyTypes).isEmpty + } + + static func state( + mode: EditProtectionMode, + session: EditSessionState, + keys: [Key], + activeShieldCount: @autoclosure () -> Int, + allowWhenNoKeys: Bool = false, + now: Date = .now, + availableKeyTypes: [KeyType] = KeyType.availableOnDevice + ) -> EditProtectionState { + switch mode { + case .requireKey: + switch session { + case .permanent: + return .sessionActive(endDate: nil) + case .timed(let endDate) where endDate > now: + return .sessionActive(endDate: endDate) + case .blocked, .timed: + break + } + if hasUsableGlobalKey(in: keys, availableKeyTypes: availableKeyTypes) { + return .requiresKey + } + return fallbackUnblockAllState( + keys: keys, + activeShieldCount: activeShieldCount(), + allowWhenNoKeys: allowWhenNoKeys + ) + case .unblockAll: + return fallbackUnblockAllState( + keys: keys, + activeShieldCount: activeShieldCount(), + allowWhenNoKeys: allowWhenNoKeys + ) + } + } + + static func modeChangeAccess( + from current: EditProtectionMode, + to target: EditProtectionMode, + session: EditSessionState, + keys: [Key], + activeShieldCount: @autoclosure () -> Int = 0, + now: Date = .now, + availableKeyTypes: [KeyType] = KeyType.availableOnDevice + ) -> EditProtectionState { + guard current == .requireKey, target == .unblockAll else { return .open } + return state( + mode: current, + session: session, + keys: keys, + activeShieldCount: activeShieldCount(), + now: now, + availableKeyTypes: availableKeyTypes + ) + } + + private static func fallbackUnblockAllState( + keys: [Key], + activeShieldCount: @autoclosure () -> Int, + allowWhenNoKeys: Bool + ) -> EditProtectionState { + if allowWhenNoKeys, keys.isEmpty { + return .open + } + return activeShieldCount() > 0 ? .requiresUnblockAll : .open + } +} diff --git a/Normal/Models/Settings+EditProtection.swift b/Normal/Models/Settings+EditProtection.swift new file mode 100644 index 0000000..de6dba7 --- /dev/null +++ b/Normal/Models/Settings+EditProtection.swift @@ -0,0 +1,61 @@ +import Foundation + +extension Settings { + var editProtectionMode: EditProtectionMode { + get { + editProtectionRawValue.flatMap(EditProtectionMode.init(rawValue:)) ?? .unblockAll + } + set { + editProtectionRawValue = newValue.rawValue + } + } + + var editDurationOverride: DefaultOverride { + get { + guard overridesEditDefaultDuration else { return .appDefault } + return + editDefaultUnblockSeconds + .flatMap(TimedUnblockDuration.init(validating:)) + .map(DefaultOverride.value) ?? .none + } + set { + overridesEditDefaultDuration = newValue != .appDefault + if case .value(let duration) = newValue { + editDefaultUnblockSeconds = duration.seconds + } else { + editDefaultUnblockSeconds = nil + } + } + } + + var editKeyOverride: DefaultOverride { + get { + guard overridesEditDefaultKey else { return .appDefault } + return editDefaultKeyType.map(DefaultOverride.value) ?? .none + } + set { + overridesEditDefaultKey = newValue != .appDefault + if case .value(let keyType) = newValue { + editDefaultKeyType = keyType + } else { + editDefaultKeyType = nil + } + } + } + + var resolvedEditDefaultDuration: TimedUnblockDuration? { + switch editDurationOverride { + case .appDefault: defaultDuration + case .none: nil + case .value(let duration): unblockDurations.contains(duration) ? duration : nil + } + } + + var resolvedEditDefaultKeyType: KeyType? { + switch editKeyOverride { + case .appDefault: defaultKeyType + case .none: nil + case .value(let keyType): keyType + } + } +} diff --git a/Normal/Models/Settings.swift b/Normal/Models/Settings.swift index 42b464d..bcbc7a4 100644 --- a/Normal/Models/Settings.swift +++ b/Normal/Models/Settings.swift @@ -18,6 +18,11 @@ final class Settings { var enableCustomDomains: Bool = false var skipBlockWithoutKeyConfirmation: Bool = false var dailyLimitResetMinutes: Int = 0 + var editProtectionRawValue: String? + var overridesEditDefaultDuration: Bool = false + var editDefaultUnblockSeconds: Int? + var overridesEditDefaultKey: Bool = false + var editDefaultKeyType: KeyType? static let maxEmergencyUnblocks = 3 private static let emergencyWindowDays = 180 diff --git a/Normal/Models/UnblockLength.swift b/Normal/Models/UnblockLength.swift index e941be2..8d7c98e 100644 --- a/Normal/Models/UnblockLength.swift +++ b/Normal/Models/UnblockLength.swift @@ -1,6 +1,6 @@ import Foundation -enum UnblockLength: Equatable { +enum UnblockLength: Equatable, Hashable, Sendable { case timed(TimedUnblockDuration) case permanent } diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index d23c0c4..ecd001a 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -311,14 +311,12 @@ "After saving, you have 10 minutes to adjust this limit. Then raising or deleting it is allowed once every 7 days." : { }, - "All app blocks have been removed. You have %lld emergency unblock%@ remaining." : { - "comment" : "A message displayed after successfully unblocking all apps.", - "isCommentAutoGenerated" : true, + "All app blocks have been removed and editing is unblocked until you block it again. You have %lld emergency unblock%@ remaining." : { "localizations" : { "en" : { "stringUnit" : { "state" : "new", - "value" : "All app blocks have been removed. You have %1$lld emergency unblock%2$@ remaining." + "value" : "All app blocks have been removed and editing is unblocked until you block it again. You have %1$lld emergency unblock%2$@ remaining." } } } @@ -334,6 +332,12 @@ "All selected apps are already blocked." : { "comment" : "Text displayed in a dialog when all selected apps are already blocked.", "isCommentAutoGenerated" : true + }, + "All Unblocked" : { + + }, + "Allow Editing" : { + }, "Almost any NFC tag works. AirTags, Amiibo, and even Credit Cards have NFC chips you can use." : { "comment" : "Feature description for using an NFC tag as a key.", @@ -397,10 +401,6 @@ "comment" : "A section header for the list of individual apps.", "isCommentAutoGenerated" : true }, - "Apps Blocked" : { - "comment" : "A message indicating that apps are currently blocked.", - "isCommentAutoGenerated" : true - }, "Apps to Block" : { "comment" : "A section header in the \"Create App Group\" sheet, instructing the user to select apps to block.", "isCommentAutoGenerated" : true @@ -454,6 +454,9 @@ "Block All Apps" : { "comment" : "Title of the intent to block all apps.", "isCommentAutoGenerated" : true + }, + "Block Apps Again?" : { + }, "Block Group" : { "comment" : "Shortcut title for the \"Block Group\" shortcut.", @@ -529,6 +532,24 @@ "Categories" : { "comment" : "A section header for categories in the app picker.", "isCommentAutoGenerated" : true + }, + "Changing your app list will unblock all apps first." : { + + }, + "Changing your app list will unblock all apps first. Remember to block them again after." : { + + }, + "Changing your app list will unblock all apps first. Remember to block them again after. Groups and schedules that use apps you remove will need updating." : { + + }, + "Changing your app list will unblock all apps first. Remember to block them again after. Groups that use apps you remove will need updating." : { + + }, + "Changing your app list will unblock all apps first. Remember to block them again after. Schedules that use apps you remove will need updating." : { + + }, + "Choose a default key or duration when unblocking editing, or inherit your app defaults." : { + }, "Choose how much time they get each day. On the day you add a limit, only time after that counts." : { "comment" : "How it works section of the usage limits guide.", @@ -756,10 +777,25 @@ }, "Edit Limit" : { "comment" : "Title of the editor for an existing Max Daily Limit." + }, + "Edit Protection" : { + }, "Edit Schedule" : { "comment" : "The title of the navigation bar for editing a schedule.", "isCommentAutoGenerated" : true + }, + "Editing is available whenever no apps are blocked." : { + + }, + "Editing is blocked." : { + + }, + "Editing Unblocked" : { + + }, + "Editing will automatically re-block after this time." : { + }, "Email" : { "comment" : "A label for the email address in the \"Email\" section of the contact us view.", @@ -1343,6 +1379,9 @@ "Proceed at your own risk" : { "comment" : "A label with a warning about the potential risks involved in bypassing the Settings.", "isCommentAutoGenerated" : true + }, + "Protects apps, groups, schedules, and keys even when no apps are blocked." : { + }, "QR code or barcode examples" : { "comment" : "A section header explaining that QR codes and barcodes can also be used as keys.", @@ -1368,9 +1407,11 @@ "comment" : "A button that removes a timed unblock duration as the default.", "isCommentAutoGenerated" : true }, - "Removes all blocks immediately without a key. Each use regenerates after 6 months." : { - "comment" : "A detailed explanation of how emergency unblocks work.", - "isCommentAutoGenerated" : true + "Removes all blocks and unblocks editing immediately without a key. Each use regenerates after 6 months." : { + + }, + "Removing domains is blocked." : { + }, "Repeat" : { "comment" : "A section header that indicates that a schedule can repeat on certain weekdays.", @@ -1393,6 +1434,9 @@ "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." : { "comment" : "Error description for a schedule registration error.", "isCommentAutoGenerated" : true + }, + "Scan a global key to unblock editing. Blocked apps stay blocked." : { + }, "Scan QR Code / Barcode" : { "comment" : "The title of the view.", @@ -1606,9 +1650,8 @@ "This limit" : { "comment" : "Names the limit in the delete confirmation: “This limit will be permanently removed.”" }, - "This will immediately remove all app blocks. Each unblock regenerates after 6 months. You have %lld remaining." : { - "comment" : "An explanatory text that appears when the user confirms an emergency unblock.", - "isCommentAutoGenerated" : true + "This will immediately remove all app blocks and unblock editing until you re-block it. Each unblock regenerates after 6 months. You have %lld remaining." : { + }, "Tighten anytime: lowering a limit or adding apps always works. After creating a limit raising or deleting it is allowed once every 7 days." : { "comment" : "Text describing how to change limits anytime.", @@ -1638,8 +1681,7 @@ "isCommentAutoGenerated" : true }, "To make changes to apps, keys, groups, or schedules, all apps must be unblocked." : { - "comment" : "Text describing the requirement to unblock all apps to make changes to apps, keys, groups, or schedules.", - "isCommentAutoGenerated" : true + }, "Too many items selected." : { "comment" : "A warning message displayed when a user has selected too many items to be blocked.", @@ -1656,6 +1698,9 @@ "Unblock" : { "comment" : "A button label that unblocks an app group.", "isCommentAutoGenerated" : true + }, + "Unblock & Continue" : { + }, "Unblock ${group} with ${keyType}, ${duration}" : { @@ -1680,9 +1725,8 @@ "comment" : "Text for a blocked message related to adding or editing schedules.", "isCommentAutoGenerated" : true }, - "Unblock all apps to create schedules." : { - "comment" : "A message displayed below the list of schedules, explaining that they cannot be managed if all apps are blocked.", - "isCommentAutoGenerated" : true + "Unblock all apps to change this setting." : { + }, "Unblock all apps to delete keys." : { "comment" : "Message displayed at the bottom of the screen in a `SafeAreaInset` modifier, when the user is blocked from deleting keys.", @@ -1691,6 +1735,9 @@ "Unblock all apps to edit selection." : { "comment" : "A footer text that appears when \"Select Apps\" is tapped, explaining that unblocking apps is necessary to edit the selection.", "isCommentAutoGenerated" : true + }, + "Unblock All Apps to Edit?" : { + }, "Unblock all apps to remove custom domains." : { "comment" : "A footer text displayed below the list of custom domains, explaining that unblocking all apps is necessary to remove domains from the list.", @@ -1710,6 +1757,12 @@ "Unblock Durations" : { "comment" : "Title of a row that shows the number of unblock durations.", "isCommentAutoGenerated" : true + }, + "Unblock Editing" : { + + }, + "Unblock editing to delete keys." : { + }, "Unblock Group" : { "comment" : "Shortcut title for unblocking a group of apps.", @@ -1750,6 +1803,9 @@ "Unblocks the apps and websites selected in Normal after checking your key. NFC Tag and QR Code / Barcode keys open Normal to scan. A Location key is checked without opening Normal when Background Location is on and a duration is set. With no Key Type or Unblock Duration, Normal uses your defaults." : { "comment" : "Description of the UnblockAllIntent intent.", "isCommentAutoGenerated" : true + }, + "Until manually re-blocked" : { + }, "Until Manually Re-Blocked" : { "comment" : "A label for a section in the timed unblock sheet that indicates the option to unblock indefinitely.", @@ -1815,6 +1871,12 @@ "Welcome to Normal" : { "comment" : "A welcome message displayed at the top of the onboarding screen.", "isCommentAutoGenerated" : true + }, + "When a schedule unblocks all apps, editing becomes available without a key." : { + + }, + "When All Apps Unblocked" : { + }, "When enabled, apps cannot be uninstalled from this device." : { "comment" : "A footer label explaining the purpose of the toggle.", @@ -1839,6 +1901,9 @@ "Why the Apple ID matters" : { "comment" : "A section header explaining the importance of using an Apple ID for the bypass process.", "isCommentAutoGenerated" : true + }, + "With a Key" : { + }, "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." : { @@ -1890,6 +1955,9 @@ "You will need to manually block apps again." : { "comment" : "A message displayed below a button that allows the user to manually unblock apps.", "isCommentAutoGenerated" : true + }, + "You will need to manually block editing again." : { + }, "You'll need a key to unblock later. Without one, you could be permanently locked out." : { "comment" : "A description of the consequences of blocking without a key.", @@ -1918,6 +1986,9 @@ "You're welcome" : { "comment" : "The text on a button that says \"You're welcome\" and is used in an alert.", "isCommentAutoGenerated" : true + }, + "Your apps were unblocked so you could update your app list." : { + }, "Your car, office, mailbox or with a trusted person" : { diff --git a/Normal/Services/BlockActions.swift b/Normal/Services/BlockActions.swift index ea7cf5b..f83a696 100644 --- a/Normal/Services/BlockActions.swift +++ b/Normal/Services/BlockActions.swift @@ -79,6 +79,22 @@ enum BlockActions { playHaptic() } + @discardableResult + static func unblockForAppSelectionEdit( + editAccess: EditProtectionState, + settings: Settings, + screenTimeService: any ScreenTimeProviding, + timedUnblockService: TimedUnblockService + ) throws -> Bool { + guard case .sessionActive = editAccess else { return false } + guard screenTimeService.unblockAll(blockAllPreventsAppDelete: settings.blockAllPreventsAppDelete) else { + throw TimedUnblockStorageError.unavailable + } + timedUnblockService.clearAll() + playHaptic() + return true + } + @discardableResult static func updateMainSelection( from oldSelection: FamilyActivitySelection, @@ -242,12 +258,14 @@ enum BlockActions { screenTimeService: any ScreenTimeProviding, timedUnblockService: TimedUnblockService, scheduleService: ScheduleService, - usageLimitService: UsageLimitService + usageLimitService: UsageLimitService, + editSessionService: EditSessionService? = nil ) { timedUnblockService.discardAll() scheduleService.disableAll(schedules, screenTimeService: screenTimeService) usageLimitService.overrideToday() screenTimeService.removeAllRestrictions() + editSessionService?.grantEmergencyAccess() playHaptic() } diff --git a/Normal/Services/EditSessionService.swift b/Normal/Services/EditSessionService.swift new file mode 100644 index 0000000..9ce7468 --- /dev/null +++ b/Normal/Services/EditSessionService.swift @@ -0,0 +1,181 @@ +import Foundation +import Observation + +struct EditUnlockGrant: Identifiable { + let id = UUID() + let proof: KeyProof + + init?(proof: KeyProof) { + guard proof.coversAllApps else { return nil } + self.proof = proof + } +} + +@MainActor +@Observable +final class EditSessionService { + private static let modeKey = "editSession.mode" + private static let endDateKey = "editSession.endDate" + private static let timedValue = "timed" + private static let permanentValue = "permanent" + + private let defaults: UserDefaults + private let clock: () -> Date + private nonisolated(unsafe) var expirationTask: Task? + + private(set) var state: EditSessionState = .blocked + + init( + defaults: UserDefaults = .standard, + clock: @escaping () -> Date = { .now } + ) { + self.defaults = defaults + self.clock = clock + restoreState() + } + + deinit { + expirationTask?.cancel() + } + + var isActive: Bool { + switch state { + case .blocked: false + case .permanent: true + case .timed(let endDate): endDate > clock() + } + } + + var endDate: Date? { + guard case .timed(let endDate) = state, endDate > clock() else { return nil } + return endDate + } + + var isPermanent: Bool { + state == .permanent + } + + func unblock(for length: UnblockLength, grant _: EditUnlockGrant) { + switch length { + case .timed(let duration): + let endDate = Self.endDate(of: duration, from: clock()) + state = .timed(endDate: endDate) + defaults.set(Self.timedValue, forKey: Self.modeKey) + defaults.set(endDate.timeIntervalSinceReferenceDate, forKey: Self.endDateKey) + scheduleExpiration(at: endDate) + case .permanent: + cancelExpiration() + state = .permanent + defaults.set(Self.permanentValue, forKey: Self.modeKey) + defaults.removeObject(forKey: Self.endDateKey) + } + } + + func grantEmergencyAccess() { + cancelExpiration() + state = .permanent + defaults.set(Self.permanentValue, forKey: Self.modeKey) + defaults.removeObject(forKey: Self.endDateKey) + } + + func block() { + cancelExpiration() + state = .blocked + defaults.removeObject(forKey: Self.modeKey) + defaults.removeObject(forKey: Self.endDateKey) + } + + func refresh() { + switch state { + case .timed(let endDate) where endDate <= clock(): + block() + case .timed(let endDate): + scheduleExpiration(at: endDate) + case .blocked, .permanent: + break + } + } + + func access( + mode: EditProtectionMode, + keys: [Key], + activeShieldCount: @autoclosure () -> Int, + allowWhenNoKeys: Bool = false, + availableKeyTypes: [KeyType] = KeyType.availableOnDevice + ) -> EditProtectionState { + EditProtectionPolicy.state( + mode: mode, + session: state, + keys: keys, + activeShieldCount: activeShieldCount(), + allowWhenNoKeys: allowWhenNoKeys, + now: clock(), + availableKeyTypes: availableKeyTypes + ) + } + + func modeChangeAccess( + from current: EditProtectionMode, + to target: EditProtectionMode, + keys: [Key], + activeShieldCount: @autoclosure () -> Int = 0, + availableKeyTypes: [KeyType] = KeyType.availableOnDevice + ) -> EditProtectionState { + EditProtectionPolicy.modeChangeAccess( + from: current, + to: target, + session: state, + keys: keys, + activeShieldCount: activeShieldCount(), + now: clock(), + availableKeyTypes: availableKeyTypes + ) + } + + private func restoreState() { + switch defaults.string(forKey: Self.modeKey) { + case Self.permanentValue: + state = .permanent + case Self.timedValue: + let timestamp = defaults.double(forKey: Self.endDateKey) + let endDate = Date(timeIntervalSinceReferenceDate: timestamp) + if endDate > clock() { + state = .timed(endDate: endDate) + scheduleExpiration(at: endDate) + } else { + block() + } + default: + state = .blocked + } + } + + private func scheduleExpiration(at endDate: Date) { + cancelExpiration() + let remaining = endDate.timeIntervalSince(clock()) + guard remaining > 0 else { + block() + return + } + expirationTask = Task { [weak self] in + while !Task.isCancelled { + guard let self else { return } + let left = endDate.timeIntervalSince(self.clock()) + guard left > 0 else { break } + try? await Task.sleep(for: .seconds(left)) + } + guard !Task.isCancelled, let self else { return } + self.block() + } + } + + private func cancelExpiration() { + expirationTask?.cancel() + expirationTask = nil + } + + private static func endDate(of duration: TimedUnblockDuration, from start: Date) -> Date { + let end = start.addingTimeInterval(duration.timeInterval).timeIntervalSinceReferenceDate + return Date(timeIntervalSinceReferenceDate: end.rounded(.down)) + } +} diff --git a/Normal/Shared/Components/CustomDomainsEditor.swift b/Normal/Shared/Components/CustomDomainsEditor.swift index 2051693..6360a76 100644 --- a/Normal/Shared/Components/CustomDomainsEditor.swift +++ b/Normal/Shared/Components/CustomDomainsEditor.swift @@ -1,15 +1,19 @@ import SwiftUI struct CustomDomainsEditor: View { + @EditAccess private var editAccess @Binding var domains: [String] var otherItemCount: Int = 0 - var canRemove: Bool = true @State private var input = "" @State private var message: FieldMessage? @State private var messageVersion = 0 + private var canRemove: Bool { + !editAccess.isBlocked + } + private struct FieldMessage: Equatable { var text: String var isError: Bool @@ -31,11 +35,10 @@ struct CustomDomainsEditor: View { } .navigationTitle("Custom Domains") .navigationBarTitleDisplayMode(.inline) - .bottomFooter { - if !canRemove { - FooterMessage(text: BlockedMessage.customDomains) - } - } + .editProtectionBar( + unblockAllMessage: BlockedMessage.customDomains, + blockedLabel: "Removing domains is blocked." + ) .sensoryFeedback(trigger: messageVersion) { _, _ in message == nil ? .impact(weight: .medium) : .warning } @@ -120,6 +123,7 @@ struct CustomDomainsEditor: View { } private func remove(_ domain: String) { + guard canRemove else { return } domains.removeAll { $0 == domain } show(nil) } diff --git a/Normal/Shared/Components/CustomDomainsSubsetSection.swift b/Normal/Shared/Components/CustomDomainsSubsetSection.swift index a1f1068..670c254 100644 --- a/Normal/Shared/Components/CustomDomainsSubsetSection.swift +++ b/Normal/Shared/Components/CustomDomainsSubsetSection.swift @@ -63,7 +63,7 @@ struct CustomDomainsSubsetLink: View { var body: some View { NavigationLink { - CustomDomainsSubsetEditor(available: available, selected: $selected, isEditable: isEditable) + CustomDomainsSubsetEditor(available: available, selected: $selected) } label: { CountRow(title: "Custom Domains", count: effectiveCount) .opacity(isEditable ? 1 : DS.Opacity.dim) @@ -73,9 +73,14 @@ struct CustomDomainsSubsetLink: View { } struct CustomDomainsSubsetEditor: View { + @EditAccess private var editAccess + let available: [String] @Binding var selected: [String] - var isEditable: Bool = true + + private var isEditable: Bool { + !editAccess.isBlocked + } var body: some View { Form { @@ -88,13 +93,10 @@ struct CustomDomainsSubsetEditor: View { CustomDomainSubsetRow(domain: domain, selected: $selected, isEditable: isEditable) } } - } footer: { - if !isEditable { - Text(BlockedMessage.customDomains) - } } } .navigationTitle("Custom Domains") .navigationBarTitleDisplayMode(.inline) + .editProtectionBar(unblockAllMessage: BlockedMessage.customDomains) } } diff --git a/Normal/Shared/Components/EditProtectionBar.swift b/Normal/Shared/Components/EditProtectionBar.swift new file mode 100644 index 0000000..07817e7 --- /dev/null +++ b/Normal/Shared/Components/EditProtectionBar.swift @@ -0,0 +1,255 @@ +import SwiftData +import SwiftUI +import UIKit + +@propertyWrapper +struct EditAccess: DynamicProperty { + @Environment(ScreenTimeService.self) private var screenTimeService + @Environment(EditSessionService.self) private var editSessionService + @Query private var allSettings: [Settings] + @Query private var keys: [Key] + + private let allowWhenNoKeys: Bool + + init(allowWhenNoKeys: Bool = false) { + self.allowWhenNoKeys = allowWhenNoKeys + } + + var wrappedValue: EditProtectionState { + editSessionService.access( + mode: allSettings.unwrapped.editProtectionMode, + keys: keys, + activeShieldCount: screenTimeService.activeShieldCount(), + allowWhenNoKeys: allowWhenNoKeys + ) + } +} + +extension EnvironmentValues { + @Entry var requestEditUnblock: () -> Void = {} +} + +struct EditUnblockHostModifier: ViewModifier { + @Environment(EditSessionService.self) private var editSessionService + @Query private var allSettings: [Settings] + + @State private var authAction: ProtectedAction? + @State private var durationGrant: EditUnlockGrant? + @State private var pendingDurationGrant: EditUnlockGrant? + @State private var isKeySheetPresented = false + + private var settings: Settings { + allSettings.unwrapped + } + + func body(content: Content) -> some View { + content + .environment(\.requestEditUnblock, requestUnblock) + .background { + Color.clear + .keySelect( + action: $authAction, + defaultKeyType: settings.resolvedEditDefaultKeyType, + isKeySheetPresented: $isKeySheetPresented + ) + } + .background { + Color.clear + .sheet(item: $durationGrant) { grant in + EditUnlockDurationSheet(grant: grant) + } + } + .onChange(of: isKeySheetPresented) { _, presented in + guard !presented, let grant = pendingDurationGrant else { return } + pendingDurationGrant = nil + durationGrant = grant + } + } + + private func requestUnblock() { + guard authAction == nil, !isKeySheetPresented, pendingDurationGrant == nil, durationGrant == nil else { return } + authAction = .weaken { proof in + completeUnblock(proof) + } + } + + private func completeUnblock(_ proof: KeyProof) { + guard let grant = EditUnlockGrant(proof: proof) else { return } + if let duration = settings.resolvedEditDefaultDuration { + editSessionService.unblock(for: .timed(duration), grant: grant) + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + } else if isKeySheetPresented { + pendingDurationGrant = grant + } else { + durationGrant = grant + } + } +} + +struct EditProtectionBarModifier: ViewModifier { + @Environment(\.requestEditUnblock) private var requestEditUnblock + @EditAccess private var editState + + let unblockAllMessage: LocalizedStringKey + let blockedLabel: LocalizedStringKey + let fallback: Fallback + + init( + unblockAllMessage: LocalizedStringKey, + blockedLabel: LocalizedStringKey, + allowWhenNoKeys: Bool, + fallback: Fallback + ) { + self.unblockAllMessage = unblockAllMessage + self.blockedLabel = blockedLabel + self.fallback = fallback + _editState = EditAccess(allowWhenNoKeys: allowWhenNoKeys) + } + + func body(content: Content) -> some View { + content + .bottomFooter { + switch editState { + case .sessionActive(let endDate): + ActiveEditSessionBarContent(endDate: endDate) + case .requiresKey: + BlockedKeyBarContent(label: blockedLabel, onUnblock: requestEditUnblock) + case .requiresUnblockAll: + FooterMessage(text: unblockAllMessage) + case .open: + fallback + } + } + } +} + +struct ActiveEditSessionBarModifier: ViewModifier { + @Environment(EditSessionService.self) private var editSessionService + @Query private var allSettings: [Settings] + @Query private var keys: [Key] + + private var activeSessionEndDate: Date?? { + guard + case .sessionActive(let endDate) = editSessionService.access( + mode: allSettings.unwrapped.editProtectionMode, + keys: keys, + activeShieldCount: 0 + ) + else { return nil } + return endDate + } + + func body(content: Content) -> some View { + content + .bottomFooter { + if let endDate = activeSessionEndDate { + ActiveEditSessionBarContent(endDate: endDate) + } + } + } +} + +private struct BlockedKeyBarContent: View { + let label: LocalizedStringKey + let onUnblock: () -> Void + + var body: some View { + AdaptiveStack(spacing: DS.Spacing.md) { + Label(label, systemImage: "lock.fill") + .font(.footnote) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("editProtection.blockedLabel") + + Button("Unblock Editing", action: onUnblock) + .buttonStyle(.borderedProminent) + .controlSize(.small) + .accessibilityIdentifier("editProtection.unblockButton") + } + .dynamicTypeSize(...DynamicTypeSize.accessibility2) + .padding(.horizontal, DS.Spacing.lg) + .padding(.vertical, DS.Spacing.md) + } +} + +private struct ActiveEditSessionBarContent: View { + @Environment(EditSessionService.self) private var editSessionService + let endDate: Date? + + var body: some View { + AdaptiveStack(spacing: DS.Spacing.md) { + HStack(spacing: DS.Spacing.sm) { + Image(systemName: endDate == nil ? "lock.open.fill" : "timer") + .foregroundStyle(.orange) + VStack(alignment: .leading, spacing: DS.Spacing.xs - 2) { + Text("Editing Unblocked") + .font(.footnote.weight(.semibold)) + if let endDate { + Text(timerInterval: .now...max(.now, endDate), countsDown: true) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } else { + Text("Until manually re-blocked") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .accessibilityIdentifier("editProtection.activeLabel") + + Button("Block Now", action: blockEditing) + .buttonStyle(.bordered) + .tint(.orange) + .controlSize(.small) + .accessibilityIdentifier("editProtection.blockButton") + } + .dynamicTypeSize(...DynamicTypeSize.accessibility2) + .padding(.horizontal, DS.Spacing.lg) + .padding(.vertical, DS.Spacing.md) + } + + private func blockEditing() { + editSessionService.block() + UIImpactFeedbackGenerator(style: .medium).impactOccurred() + } +} + +extension View { + func editUnblockHost() -> some View { + modifier(EditUnblockHostModifier()) + } + + func editProtectionBar( + unblockAllMessage: LocalizedStringKey, + blockedLabel: LocalizedStringKey = "Editing is blocked.", + allowWhenNoKeys: Bool = false + ) -> some View { + modifier( + EditProtectionBarModifier( + unblockAllMessage: unblockAllMessage, + blockedLabel: blockedLabel, + allowWhenNoKeys: allowWhenNoKeys, + fallback: EmptyView() + )) + } + + func editProtectionBar( + unblockAllMessage: LocalizedStringKey, + blockedLabel: LocalizedStringKey = "Editing is blocked.", + allowWhenNoKeys: Bool = false, + @ViewBuilder fallback: () -> Fallback + ) -> some View { + modifier( + EditProtectionBarModifier( + unblockAllMessage: unblockAllMessage, + blockedLabel: blockedLabel, + allowWhenNoKeys: allowWhenNoKeys, + fallback: fallback() + )) + } + + func activeEditSessionBar() -> some View { + modifier(ActiveEditSessionBarModifier()) + } +} diff --git a/Normal/Shared/Components/UnblockingDefaultsSection.swift b/Normal/Shared/Components/UnblockingDefaultsSection.swift new file mode 100644 index 0000000..68d535d --- /dev/null +++ b/Normal/Shared/Components/UnblockingDefaultsSection.swift @@ -0,0 +1,117 @@ +import SwiftUI + +struct UnblockingDefaultsSection: View { + @Binding var durationOverride: DefaultOverride + @Binding var keyOverride: DefaultOverride + + let durations: [TimedUnblockDuration] + let availableKeyTypes: [KeyType] + let appDefaultDuration: TimedUnblockDuration? + let appDefaultKeyType: KeyType? + let durationAccessibilityID: String + let keyAccessibilityID: String + var footer: LocalizedStringKey? + + private var appDefaultDurationLabel: String { + appDefaultDuration?.label ?? String(localized: "None") + } + + private var appDefaultKeyLabel: String { + guard let appDefaultKeyType, availableKeyTypes.contains(appDefaultKeyType) else { + return String(localized: "None") + } + return appDefaultKeyType.label + } + + private var durationSelection: Binding> { + Binding( + get: { + if case .value(let duration) = durationOverride, !durations.contains(duration) { + return .none + } + return durationOverride + }, + set: { durationOverride = $0 } + ) + } + + private var keySelection: Binding> { + Binding( + get: { + if case .value(let keyType) = keyOverride, !availableKeyTypes.contains(keyType) { + return .none + } + return keyOverride + }, + set: { keyOverride = $0 } + ) + } + + var body: some View { + Section { + Group { + if #available(iOS 18.0, *) { + Picker("Default Duration", selection: durationSelection) { + durationOptions(appDefault: String(localized: "App Default (\(appDefaultDurationLabel))")) + } currentValueLabel: { + Text(rowLabel(for: durationSelection.wrappedValue) { $0.label }) + } + } else { + Picker("Default Duration", selection: durationSelection) { + durationOptions(appDefault: String(localized: "App Default")) + } + } + } + .adaptivePickerStyle() + .accessibilityIdentifier(durationAccessibilityID) + + Group { + if #available(iOS 18.0, *) { + Picker("Default Key", selection: keySelection) { + keyOptions(appDefault: String(localized: "App Default (\(appDefaultKeyLabel))")) + } currentValueLabel: { + Text(rowLabel(for: keySelection.wrappedValue) { $0.label }) + } + } else { + Picker("Default Key", selection: keySelection) { + keyOptions(appDefault: String(localized: "App Default")) + } + } + } + .adaptivePickerStyle() + .accessibilityIdentifier(keyAccessibilityID) + } header: { + Text("Unblocking") + } footer: { + if let footer { + Text(footer) + } + } + } + + @ViewBuilder + private func durationOptions(appDefault: String) -> some View { + Text(appDefault).tag(DefaultOverride.appDefault) + Text("None").tag(DefaultOverride.none) + ForEach(durations) { duration in + Text(duration.label).tag(DefaultOverride.value(duration)) + } + } + + @ViewBuilder + private func keyOptions(appDefault: String) -> some View { + Text(appDefault).tag(DefaultOverride.appDefault) + Text("None").tag(DefaultOverride.none) + ForEach(availableKeyTypes) { type in + Label(type.label, systemImage: type.icon).tag(DefaultOverride.value(type)) + } + } + + private func rowLabel(for choice: DefaultOverride, value: (Value) -> String) -> String { + switch choice { + case .appDefault: String(localized: "App Default") + case .none: String(localized: "None") + case .value(let chosen): value(chosen) + } + } +} diff --git a/Normal/Views/AppSelect/AppSelectView.swift b/Normal/Views/AppSelect/AppSelectView.swift index 86eb78c..2a9505d 100644 --- a/Normal/Views/AppSelect/AppSelectView.swift +++ b/Normal/Views/AppSelect/AppSelectView.swift @@ -7,14 +7,18 @@ struct AppSelectView: View { @Environment(TimedUnblockService.self) private var timedUnblockService @Environment(ScheduleService.self) private var scheduleService @Environment(\.modelContext) private var modelContext + @EditAccess private var editAccess @Query private var selectedApps: [SelectedApps] @Query private var appGroups: [AppGroup] @Query private var schedules: [BlockSchedule] @Query private var allSettings: [Settings] - @State private var showSelectionChangeAlert = false + @State private var pendingSelectionWarning: SelectionChangeWarning? @State private var showSaveErrorAlert = false + @State private var showReblockAfterEditAlert = false + @State private var shouldPromptReblockAfterPicker = false + @State private var unblockAlert: UnblockAlert? @State private var isFamilyActivityPickerPresented = false @State private var selection = FamilyActivitySelection() @State private var customDomains: [String] = [] @@ -35,7 +39,11 @@ struct AppSelectView: View { customDomainsEnabled ? customDomains : [] } - private var isBlocked: Bool { + private var isEditBlocked: Bool { + editAccess.isBlocked + } + + private var hasActiveShields: Bool { screenTimeService.activeShieldCount() > 0 } @@ -46,17 +54,21 @@ struct AppSelectView: View { private var footerText: Text? { if !isAuthorized { Text("Screen Time permission is required to select apps.") - } else if isBlocked { - Text("Unblock all apps to edit selection.") - } else if mainSelection?.selection.isEmpty ?? true { + } else if !isEditBlocked, hasActiveShields { + Text("Changing your app list will unblock all apps first.") + } else if !isEditBlocked, mainSelection?.selection.isEmpty ?? true { Text("Selecting individual apps is recommended over categories for more granular control.") } else { nil } } - private var selectionChangeWarning: SelectionChangeWarning? { - SelectionChangeWarning(hasGroups: !appGroups.isEmpty, hasSchedules: !schedules.isEmpty) + private var currentSelectionWarning: SelectionChangeWarning? { + SelectionChangeWarning( + hasGroups: !appGroups.isEmpty, + hasSchedules: !schedules.isEmpty, + unblocksActiveShields: hasActiveShields + ) } private var buttonTitle: LocalizedStringKey { @@ -73,7 +85,7 @@ struct AppSelectView: View { ) Section(header: Text("Selection"), footer: footerText) { Button(buttonTitle, action: onUpdateSelectionButton) - .disabled(isBlocked) + .disabled(isEditBlocked) Text(verbatim: selection.selectedTokenCounts) .font(.caption) @@ -84,8 +96,7 @@ struct AppSelectView: View { NavigationLink { CustomDomainsEditor( domains: $customDomains, - otherItemCount: selection.count, - canRemove: !isBlocked + otherItemCount: selection.count ) } label: { CountRow(title: "Custom Domains", count: customDomains.count) @@ -95,24 +106,36 @@ struct AppSelectView: View { } SelectionListView(selection: selection) } + .editProtectionBar(unblockAllMessage: "Unblock all apps to edit selection.") .navigationTitle("App Select") .settingsToolbar() - .alert(selectionChangeWarning?.title ?? "", isPresented: $showSelectionChangeAlert) { + .alert( + pendingSelectionWarning?.title ?? "", + isPresented: Binding( + get: { pendingSelectionWarning != nil }, + set: { if !$0 { pendingSelectionWarning = nil } } + ), + presenting: pendingSelectionWarning + ) { warning in Button("Cancel", role: .cancel) {} - Button("Continue", role: .destructive) { - guard !isBlocked else { return } - isFamilyActivityPickerPresented = true + Button(warning.confirmButtonTitle, role: .destructive) { + confirmSelectionEdit(for: warning) } + } message: { warning in + Text(warning.message) + } + .alert("Block Apps Again?", isPresented: $showReblockAfterEditAlert) { + Button("Not Now", role: .cancel) {} + Button("Block All", action: reblockAfterEdit) } message: { - if let selectionChangeWarning { - Text(selectionChangeWarning.message) - } + Text("Your apps were unblocked so you could update your app list.") } .alert("Couldn't Save Selection", isPresented: $showSaveErrorAlert) { Button("OK", role: .cancel) {} } message: { Text("Couldn't update your selection right now. Please try again.") } + .unblockAlert($unblockAlert) .familyActivityPicker(isPresented: $isFamilyActivityPickerPresented, selection: $selection) .onAppear { if let mainSelection { @@ -120,27 +143,87 @@ struct AppSelectView: View { customDomains = mainSelection.customDomains } } + .onChange(of: isFamilyActivityPickerPresented) { wasPresented, isPresented in + guard wasPresented, !isPresented, shouldPromptReblockAfterPicker else { return } + shouldPromptReblockAfterPicker = false + Task { @MainActor in + await Task.yield() + guard !showSaveErrorAlert, unblockAlert == nil else { return } + guard let currentMain = mainSelection, + currentMain.hasItemsToBlock(customDomainsEnabled: customDomainsEnabled) + else { return } + let domains = customDomainsEnabled ? currentMain.customDomains : [] + guard screenTimeService.blockStatus(selection: currentMain.selection, customDomains: domains) != .all + else { return } + showReblockAfterEditAlert = true + } + } .onChange(of: selection, persistSelection) .onChange(of: customDomains, persistCustomDomains) } } private func onUpdateSelectionButton() { - guard !isBlocked else { return } + guard !isEditBlocked else { return } screenTimeService.ifAuthorized { - guard !isBlocked else { return } - if selectionChangeWarning == nil { - isFamilyActivityPickerPresented = true + guard !isEditBlocked else { return } + if let warning = currentSelectionWarning { + pendingSelectionWarning = warning } else { - showSelectionChangeAlert = true + isFamilyActivityPickerPresented = true } } } + private func confirmSelectionEdit(for warning: SelectionChangeWarning) { + guard !isEditBlocked else { return } + if !warning.unblocksActiveShields, hasActiveShields { + Task { @MainActor in + await Task.yield() + guard !isEditBlocked else { return } + pendingSelectionWarning = SelectionChangeWarning( + hasGroups: !appGroups.isEmpty, + hasSchedules: !schedules.isEmpty, + unblocksActiveShields: hasActiveShields + ) + } + return + } + if warning.unblocksActiveShields, hasActiveShields { + do { + guard + try BlockActions.unblockForAppSelectionEdit( + editAccess: editAccess, + settings: settings, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) + else { return } + shouldPromptReblockAfterPicker = true + } catch { + unblockAlert = .failed(error) + return + } + } + isFamilyActivityPickerPresented = true + } + + private func reblockAfterEdit() { + guard let mainSelection, + mainSelection.hasItemsToBlock(customDomainsEnabled: customDomainsEnabled) + else { return } + BlockActions.blockAll( + mainSelection: mainSelection, + settings: settings, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) + } + private func persistSelection(_: FamilyActivitySelection, _ new: FamilyActivitySelection) { let storedSelection = mainSelection?.selection ?? FamilyActivitySelection() guard new != storedSelection else { return } - guard !isBlocked else { + guard !isEditBlocked else { selection = storedSelection return } @@ -153,7 +236,7 @@ struct AppSelectView: View { private func persistCustomDomains(_: [String], _ new: [String]) { let storedDomains = mainSelection?.customDomains ?? [] guard new != storedDomains else { return } - if isBlocked { + if isEditBlocked { let storedSet = Set(storedDomains.compactMap(DomainNormalizer.normalize)) let newSet = Set(new.compactMap(DomainNormalizer.normalize)) guard storedSet.isSubset(of: newSet) else { @@ -202,13 +285,30 @@ enum SelectionChangeWarning: Equatable { case groups case schedules case groupsAndSchedules + case unblockAll + case unblockAllAndGroups + case unblockAllAndSchedules + case unblockAllAndGroupsAndSchedules - init?(hasGroups: Bool, hasSchedules: Bool) { - switch (hasGroups, hasSchedules) { - case (true, true): self = .groupsAndSchedules - case (true, false): self = .groups - case (false, true): self = .schedules - case (false, false): return nil + init?(hasGroups: Bool, hasSchedules: Bool, unblocksActiveShields: Bool = false) { + switch (unblocksActiveShields, hasGroups, hasSchedules) { + case (false, true, true): self = .groupsAndSchedules + case (false, true, false): self = .groups + case (false, false, true): self = .schedules + case (false, false, false): return nil + case (true, true, true): self = .unblockAllAndGroupsAndSchedules + case (true, true, false): self = .unblockAllAndGroups + case (true, false, true): self = .unblockAllAndSchedules + case (true, false, false): self = .unblockAll + } + } + + var unblocksActiveShields: Bool { + switch self { + case .groups, .schedules, .groupsAndSchedules: + false + case .unblockAll, .unblockAllAndGroups, .unblockAllAndSchedules, .unblockAllAndGroupsAndSchedules: + true } } @@ -217,9 +317,15 @@ enum SelectionChangeWarning: Equatable { case .groups: "Selection may affect existing groups" case .schedules: "Selection may affect existing schedules" case .groupsAndSchedules: "Selection may affect existing groups and schedules" + case .unblockAll, .unblockAllAndGroups, .unblockAllAndSchedules, .unblockAllAndGroupsAndSchedules: + "Unblock All Apps to Edit?" } } + var confirmButtonTitle: LocalizedStringKey { + unblocksActiveShields ? "Unblock & Continue" : "Continue" + } + var message: LocalizedStringKey { switch self { case .groups: @@ -228,6 +334,14 @@ enum SelectionChangeWarning: Equatable { "Schedules that use apps you remove will need updating. Until then, their cards are locked." case .groupsAndSchedules: "Groups and schedules that use apps you remove will need updating. Until then, their cards are locked." + case .unblockAll: + "Changing your app list will unblock all apps first. Remember to block them again after." + case .unblockAllAndGroups: + "Changing your app list will unblock all apps first. Remember to block them again after. Groups that use apps you remove will need updating." + case .unblockAllAndSchedules: + "Changing your app list will unblock all apps first. Remember to block them again after. Schedules that use apps you remove will need updating." + case .unblockAllAndGroupsAndSchedules: + "Changing your app list will unblock all apps first. Remember to block them again after. Groups and schedules that use apps you remove will need updating." } } } diff --git a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift index fd32e1d..4f2df9b 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift @@ -14,6 +14,7 @@ struct KeySelectModifier: ViewModifier { var requestedKeyType: KeyType? var keyGroupID: UUID? var requestID: UUID? + var isKeySheetPresented: Binding? @State private var flow = KeyCheckFlow(nfc: NFCService.shared, qr: QRService.shared) @State private var keepsMinimizedDetent = false @@ -71,8 +72,11 @@ struct KeySelectModifier: ViewModifier { } message: { missingKey in Text(message(for: missingKey)) } - .sheet(item: keySheet, onDismiss: flow.keySheetDismissed) { _ in + .sheet(item: keySheet, onDismiss: handleKeySheetDismissed) { _ in keySelectSheet + .onAppear { + isKeySheetPresented?.wrappedValue = true + } } } @@ -185,6 +189,11 @@ struct KeySelectModifier: ViewModifier { ) } + private func handleKeySheetDismissed() { + isKeySheetPresented?.wrappedValue = false + flow.keySheetDismissed() + } + private func start() { guard let action else { return } let scopedKeys = Key.scoped(keys, toGroup: keyGroupID) @@ -208,7 +217,8 @@ extension View { defaultKeyType: KeyType? = nil, requestedKeyType: KeyType? = nil, keyGroupID: UUID? = nil, - requestID: UUID? = nil + requestID: UUID? = nil, + isKeySheetPresented: Binding? = nil ) -> some View { modifier( KeySelectModifier( @@ -216,7 +226,8 @@ extension View { defaultKeyType: defaultKeyType, requestedKeyType: requestedKeyType, keyGroupID: keyGroupID, - requestID: requestID + requestID: requestID, + isKeySheetPresented: isKeySheetPresented )) } } diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/EditUnlockDurationSheet.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/EditUnlockDurationSheet.swift new file mode 100644 index 0000000..0b41aae --- /dev/null +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/EditUnlockDurationSheet.swift @@ -0,0 +1,26 @@ +import SwiftData +import SwiftUI + +struct EditUnlockDurationSheet: View { + @Environment(EditSessionService.self) private var editSessionService + @Query private var allSettings: [Settings] + + let grant: EditUnlockGrant + + private var settings: Settings { + allSettings.unwrapped + } + + var body: some View { + TimedUnblockSheet( + title: String(localized: "Unblock Editing"), + durations: settings.unblockDurations, + initialDuration: settings.resolvedEditDefaultDuration, + timedFooter: "Editing will automatically re-block after this time.", + permanentFooter: "You will need to manually block editing again.", + onConfirm: { length in + editSessionService.unblock(for: length, grant: grant) + } + ) + } +} diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift index a7fd54f..13c9f62 100644 --- a/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift @@ -5,6 +5,10 @@ struct TimedUnblockSheet: View { let title: String let durations: [TimedUnblockDuration] + let timedHeader: LocalizedStringKey + let timedFooter: LocalizedStringKey + let permanentTitle: LocalizedStringKey + let permanentFooter: LocalizedStringKey let onConfirm: (UnblockLength) throws -> Void @State private var selection: UnblockLength @@ -14,10 +18,18 @@ struct TimedUnblockSheet: View { title: String, durations: [TimedUnblockDuration], initialDuration: TimedUnblockDuration?, + timedHeader: LocalizedStringKey = "Timed Unblock", + timedFooter: LocalizedStringKey = "Apps will automatically re-block after this time, even if you close the app.", + permanentTitle: LocalizedStringKey = "Until Manually Re-Blocked", + permanentFooter: LocalizedStringKey = "You will need to manually block apps again.", onConfirm: @escaping (UnblockLength) throws -> Void ) { self.title = title self.durations = durations + self.timedHeader = timedHeader + self.timedFooter = timedFooter + self.permanentTitle = permanentTitle + self.permanentFooter = permanentFooter self.onConfirm = onConfirm _selection = State(initialValue: (initialDuration ?? durations.first).map(UnblockLength.timed) ?? .permanent) } @@ -36,21 +48,21 @@ struct TimedUnblockSheet: View { .accessibilityIdentifier("timedUnblock.duration.\(duration.seconds)") } } header: { - Text("Timed Unblock") + Text(timedHeader) } footer: { - Text("Apps will automatically re-block after this time, even if you close the app.") + Text(timedFooter) } Section { ChoiceListRow( - title: "Until Manually Re-Blocked", + title: permanentTitle, isSelected: selection == .permanent ) { selection = .permanent } .accessibilityIdentifier("timedUnblock.permanent") } footer: { - Text("You will need to manually block apps again.") + Text(permanentFooter) } if let error { diff --git a/Normal/Views/Groups/GroupFormSheet.swift b/Normal/Views/Groups/GroupFormSheet.swift index bfdecd9..7e507b8 100644 --- a/Normal/Views/Groups/GroupFormSheet.swift +++ b/Normal/Views/Groups/GroupFormSheet.swift @@ -7,6 +7,7 @@ struct GroupFormSheet: View { @Environment(\.modelContext) private var modelContext @Environment(ScreenTimeService.self) private var screenTimeService @Environment(TimedUnblockService.self) private var timedUnblockService + @EditAccess private var editAccess @Query private var allGroups: [AppGroup] @Query private var allSettings: [Settings] @@ -39,51 +40,16 @@ struct GroupFormSheet: View { return KeyType.allCases.filter { type in keys.contains { $0.type == type } } } - private var appDefaultDurationLabel: String { - allSettings.first?.defaultDuration?.label ?? String(localized: "None") - } - - private var appDefaultKeyLabel: String { - guard let keyType = allSettings.first?.defaultKeyType, groupKeyTypes.contains(keyType) else { - return String(localized: "None") - } - return keyType.label - } - - private var durationSelection: Binding> { - Binding( - get: { - if case .value(let duration) = durationOverride, !durations.contains(duration) { - return .none - } - return durationOverride - }, - set: { durationOverride = $0 } - ) - } - - private var keySelection: Binding> { - Binding( - get: { - if case .value(let keyType) = keyOverride, !groupKeyTypes.contains(keyType) { - return .none - } - return keyOverride - }, - set: { keyOverride = $0 } - ) - } - private var isNew: Bool { existing == nil } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var isReadOnly: Bool { - !isNew && isBlocked + !isNew && isEditBlocked } private var customDomainsEnabled: Bool { @@ -167,11 +133,7 @@ struct GroupFormSheet: View { } .navigationTitle(isReadOnly ? "Group" : (isNew ? "New Group" : "Edit Group")) .navigationBarTitleDisplayMode(.inline) - .bottomFooter { - if isBlocked { - FooterMessage(text: BlockedMessage.groups) - } - } + .editProtectionBar(unblockAllMessage: BlockedMessage.groups) .toolbar { if isReadOnly { ToolbarItem(placement: .confirmationAction) { @@ -184,7 +146,7 @@ struct GroupFormSheet: View { ToolbarItem(placement: .confirmationAction) { Button(isNew ? "Save" : "Update", action: save) .fontWeight(.semibold) - .disabled(!canSave || isBlocked) + .disabled(!canSave || isEditBlocked) } } } @@ -202,6 +164,7 @@ struct GroupFormSheet: View { onDelete: deleteGroup ) } + .editUnblockHost() } private var appsReadOnlyRow: some View { @@ -213,9 +176,9 @@ struct GroupFormSheet: View { } private var groupKeyDeleteAction: ((IndexSet) -> Void)? { - guard !isBlocked else { return nil } + guard !isEditBlocked else { return nil } return { offsets in - guard !isBlocked else { return } + guard !isEditBlocked else { return } for index in offsets { modelContext.delete(groupKeys[index]) } @@ -223,65 +186,16 @@ struct GroupFormSheet: View { } private var unblockingSection: some View { - Section("Unblocking") { - Group { - if #available(iOS 18.0, *) { - Picker("Default Duration", selection: durationSelection) { - durationOptions(appDefault: String(localized: "App Default (\(appDefaultDurationLabel))")) - } currentValueLabel: { - Text(rowLabel(for: durationSelection.wrappedValue) { $0.label }) - } - } else { - Picker("Default Duration", selection: durationSelection) { - durationOptions(appDefault: String(localized: "App Default")) - } - } - } - .adaptivePickerStyle() - .accessibilityIdentifier("groupForm.defaultDuration") - - Group { - if #available(iOS 18.0, *) { - Picker("Default Key", selection: keySelection) { - keyOptions(appDefault: String(localized: "App Default (\(appDefaultKeyLabel))")) - } currentValueLabel: { - Text(rowLabel(for: keySelection.wrappedValue) { $0.label }) - } - } else { - Picker("Default Key", selection: keySelection) { - keyOptions(appDefault: String(localized: "App Default")) - } - } - } - .adaptivePickerStyle() - .accessibilityIdentifier("groupForm.defaultKey") - } - } - - @ViewBuilder - private func durationOptions(appDefault: String) -> some View { - Text(appDefault).tag(DefaultOverride.appDefault) - Text("None").tag(DefaultOverride.none) - ForEach(durations) { duration in - Text(duration.label).tag(DefaultOverride.value(duration)) - } - } - - @ViewBuilder - private func keyOptions(appDefault: String) -> some View { - Text(appDefault).tag(DefaultOverride.appDefault) - Text("None").tag(DefaultOverride.none) - ForEach(groupKeyTypes) { type in - Label(type.label, systemImage: type.icon).tag(DefaultOverride.value(type)) - } - } - - private func rowLabel(for choice: DefaultOverride, value: (Value) -> String) -> String { - switch choice { - case .appDefault: String(localized: "App Default") - case .none: String(localized: "None") - case .value(let chosen): value(chosen) - } + UnblockingDefaultsSection( + durationOverride: $durationOverride, + keyOverride: $keyOverride, + durations: durations, + availableKeyTypes: groupKeyTypes, + appDefaultDuration: allSettings.first?.defaultDuration, + appDefaultKeyType: allSettings.first?.defaultKeyType, + durationAccessibilityID: "groupForm.defaultDuration", + keyAccessibilityID: "groupForm.defaultKey" + ) } private var groupKeysSection: some View { @@ -296,7 +210,7 @@ struct GroupFormSheet: View { } label: { Label("Add Key", systemImage: "plus") } - .disabled(isBlocked) + .disabled(isEditBlocked) } } header: { Text("Group Keys (Optional)") @@ -306,7 +220,7 @@ struct GroupFormSheet: View { } private func deleteGroup() { - guard let existing, !isBlocked else { return } + guard let existing, !isEditBlocked else { return } BlockActions.deleteGroup( existing, keys: allKeys, @@ -338,7 +252,7 @@ struct GroupFormSheet: View { } private func save() { - guard !isBlocked else { return } + guard !isEditBlocked else { return } let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return } diff --git a/Normal/Views/Groups/GroupListCardView.swift b/Normal/Views/Groups/GroupListCardView.swift index 8fdd69e..efca122 100644 --- a/Normal/Views/Groups/GroupListCardView.swift +++ b/Normal/Views/Groups/GroupListCardView.swift @@ -6,6 +6,7 @@ struct GroupListCardView: View { @Environment(ScreenTimeService.self) private var screenTimeService @Environment(TimedUnblockService.self) private var timedUnblockService @Environment(\.modelContext) private var modelContext + @EditAccess private var editAccess @Query private var selectedApps: [SelectedApps] @Query private var allSettings: [Settings] @@ -31,8 +32,8 @@ struct GroupListCardView: View { settings.enableCustomDomains ? appGroup.customDomains : [] } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var blockStatus: BlockStatus { @@ -72,16 +73,16 @@ struct GroupListCardView: View { } .opacity(needsSync ? DS.Opacity.dim : 1) .onTapGesture { - if needsSync, !isBlocked { + if needsSync, !isEditBlocked { isReselecting = true } else { isEditing = true } } .editDeleteContextMenu( - isDisabled: isBlocked, + isDisabled: isEditBlocked, onEdit: { - if needsSync, !isBlocked { + if needsSync, !isEditBlocked { isReselecting = true } else { isEditing = true @@ -96,9 +97,9 @@ struct GroupListCardView: View { SelectAppsForGroupSheet( selection: .constant(appGroup.selection), customDomains: .constant(appGroup.customDomains), - saveBlockedMessage: isBlocked ? BlockedMessage.groups : nil + editProtectionMessage: BlockedMessage.groups ) { newSelection, newDomains in - guard !isBlocked else { return false } + guard !isEditBlocked else { return false } appGroup.selection = newSelection appGroup.customDomains = newDomains appGroup.lastUpdated = .now @@ -116,7 +117,7 @@ struct GroupListCardView: View { itemName: appGroup.name, isPresented: $showDeleteConfirmation, onDelete: { - guard !isBlocked else { return } + guard !isEditBlocked else { return } BlockActions.deleteGroup( appGroup, keys: allKeys, diff --git a/Normal/Views/Groups/GroupsView.swift b/Normal/Views/Groups/GroupsView.swift index 11be2e9..a3dcd8b 100644 --- a/Normal/Views/Groups/GroupsView.swift +++ b/Normal/Views/Groups/GroupsView.swift @@ -3,6 +3,7 @@ import SwiftUI struct GroupsView: View { @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess private var editAccess @Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var appGroups: [AppGroup] @Query private var selectedApps: [SelectedApps] @@ -14,22 +15,22 @@ struct GroupsView: View { @State private var durationGrant: UnblockGrant? @State private var unblockAlert: UnblockAlert? + private var settings: Settings { + allSettings.unwrapped + } + private var hasSelection: Bool { - selectedApps.first?.hasItemsToBlock(customDomainsEnabled: allSettings.unwrapped.enableCustomDomains) == true + selectedApps.first?.hasItemsToBlock(customDomainsEnabled: settings.enableCustomDomains) == true } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } var body: some View { NavigationStack { content - .bottomFooter { - if isBlocked, hasSelection || !appGroups.isEmpty { - FooterMessage(text: BlockedMessage.groups) - } - } + .editProtectionBar(unblockAllMessage: BlockedMessage.groups) .navigationTitle("App Groups") .settingsToolbar() .toolbar { @@ -37,7 +38,7 @@ struct GroupsView: View { Button(action: openSheet) { Label("Add Group", systemImage: "plus") } - .disabled(!hasSelection || isBlocked) + .disabled(!hasSelection || isEditBlocked) .sheet(isPresented: $isShowingSheet) { GroupFormSheet() } @@ -62,13 +63,13 @@ struct GroupsView: View { unblockAlert: $unblockAlert ) }, - onMove: isBlocked ? nil : { move(from: $0, to: $1) } + onMove: isEditBlocked ? nil : { move(from: $0, to: $1) } ) // 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( + defaultKeyType: settings.defaultKeyType( for: appGroups.first { $0.id == pendingGroupID } ), keyGroupID: pendingGroupID @@ -81,7 +82,7 @@ struct GroupsView: View { } private func move(from source: IndexSet, to destination: Int) { - guard !isBlocked else { return } + guard !isEditBlocked else { return } _ = SortIndexing.reorder(appGroups, from: source, to: destination, sortIndex: \.sortIndex) } @@ -95,7 +96,7 @@ struct GroupsView: View { } actions: { Button("Create Group", action: openSheet) .buttonStyle(.borderedProminent) - .disabled(isBlocked) + .disabled(isEditBlocked) } } else { ContentUnavailableView { @@ -107,9 +108,9 @@ struct GroupsView: View { } private func openSheet() { - guard !isBlocked else { return } + guard !isEditBlocked else { return } screenTimeService.ifAuthorized { - guard !isBlocked else { return } + guard !isEditBlocked else { return } isShowingSheet = true } } diff --git a/Normal/Views/Groups/SelectAppsForGroupSheet.swift b/Normal/Views/Groups/SelectAppsForGroupSheet.swift index 62ac6aa..42f8cac 100644 --- a/Normal/Views/Groups/SelectAppsForGroupSheet.swift +++ b/Normal/Views/Groups/SelectAppsForGroupSheet.swift @@ -5,6 +5,7 @@ import SwiftUI struct SelectAppsForGroupSheet: View { @Environment(\.dismiss) private var dismiss + @EditAccess private var editAccess @Query private var selectedApps: [SelectedApps] @Query private var allSettings: [Settings] @@ -12,6 +13,7 @@ struct SelectAppsForGroupSheet: View { var customDomains: Binding<[String]>? var saveBlockedMessage: LocalizedStringKey? var saveErrorMessage: String? + var editProtectionMessage: LocalizedStringKey? var onSave: ((FamilyActivitySelection, [String]) -> Bool)? @State private var workingSelection = FamilyActivitySelection() @@ -38,41 +40,69 @@ struct SelectAppsForGroupSheet: View { !sortedCategories.isEmpty || !sortedApps.isEmpty || !sortedDomains.isEmpty || showsDomains } + private var isSaveBlocked: Bool { + saveBlockedMessage != nil || (editProtectionMessage != nil && editAccess.isBlocked) + } + var body: some View { - NavigationStack { + if let editProtectionMessage { + sheetContent(editProtectionMessage: editProtectionMessage) + .editUnblockHost() + } else { + sheetContent(editProtectionMessage: nil) + } + } + + private func sheetContent(editProtectionMessage: LocalizedStringKey?) -> some View { + let bodyContent = VStack(spacing: 0) { content - .bottomFooter { - if let saveBlockedMessage { - FooterMessage(text: saveBlockedMessage) - } else if let saveErrorMessage { - MessageView(message: saveErrorMessage, color: .red) - .padding() - } - } - .navigationTitle("Select Apps") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { dismiss() } - } - ToolbarItem(placement: .confirmationAction) { - Button("Done") { - let filteredDomains = CustomDomains.subset(workingDomains, of: mainDomains) - if let onSave { - guard saveBlockedMessage == nil, onSave(workingSelection, filteredDomains) else { return } - } else { - selection = workingSelection - customDomains?.wrappedValue = filteredDomains + if let saveErrorMessage { + MessageView(message: saveErrorMessage, color: .red) + .padding() + } + } + return NavigationStack { + Group { + if let editProtectionMessage { + bodyContent + .editProtectionBar(unblockAllMessage: editProtectionMessage) { + if let saveBlockedMessage { + FooterMessage(text: saveBlockedMessage) } - dismiss() } - .fontWeight(.semibold) - .disabled( - saveBlockedMessage != nil - || (onSave != nil && workingSelection.isEmpty && (!showsDomains || workingDomains.isEmpty)) - ) + } else { + bodyContent + .bottomFooter { + if let saveBlockedMessage { + FooterMessage(text: saveBlockedMessage) + } + } + } + } + .navigationTitle("Select Apps") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("Done") { + let filteredDomains = CustomDomains.subset(workingDomains, of: mainDomains) + if let onSave { + guard !isSaveBlocked, onSave(workingSelection, filteredDomains) else { return } + } else { + selection = workingSelection + customDomains?.wrappedValue = filteredDomains + } + dismiss() } + .fontWeight(.semibold) + .disabled( + isSaveBlocked + || (onSave != nil && workingSelection.isEmpty && (!showsDomains || workingDomains.isEmpty)) + ) } + } } .onAppear(perform: prepare) } diff --git a/Normal/Views/Home/HomeView.swift b/Normal/Views/Home/HomeView.swift index 6d9f5a5..3cb4434 100644 --- a/Normal/Views/Home/HomeView.swift +++ b/Normal/Views/Home/HomeView.swift @@ -71,6 +71,7 @@ struct HomeView: View { } } } + .activeEditSessionBar() .protectedAction($authAction, defaultKeyType: settings.defaultKeyType) .sheet(item: $durationGrant) { grant in UnblockDurationSheet(grant: grant) { timing in diff --git a/Normal/Views/Key/GroupKeyRow.swift b/Normal/Views/Key/GroupKeyRow.swift index c82a826..edaed0c 100644 --- a/Normal/Views/Key/GroupKeyRow.swift +++ b/Normal/Views/Key/GroupKeyRow.swift @@ -3,13 +3,13 @@ import SwiftUI struct GroupKeyRow: View { @Environment(\.modelContext) private var modelContext - @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess private var editAccess let key: Key @State private var isEditing = false - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } var body: some View { @@ -33,9 +33,12 @@ struct GroupKeyRow: View { } .buttonStyle(.plain) .editDeleteContextMenu( - isDisabled: isBlocked, + isDisabled: isEditBlocked, onEdit: { isEditing = true }, - onDelete: { modelContext.delete(key) } + onDelete: { + guard !isEditBlocked else { return } + modelContext.delete(key) + } ) .sheet(isPresented: $isEditing) { KeyFormSheet(existing: key) diff --git a/Normal/Views/Key/GroupKeysViewer.swift b/Normal/Views/Key/GroupKeysViewer.swift index 8654c23..1d69364 100644 --- a/Normal/Views/Key/GroupKeysViewer.swift +++ b/Normal/Views/Key/GroupKeysViewer.swift @@ -3,15 +3,15 @@ import SwiftUI struct GroupKeysViewer: View { @Environment(\.modelContext) private var modelContext - @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess private var editAccess @Query(filter: #Predicate { $0.groupID != nil }, sort: [SortDescriptor(\Key.sortIndex)]) private var groupKeys: [Key] @Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var groups: [AppGroup] - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var sections: [(group: AppGroup, keys: [Key])] { @@ -28,17 +28,13 @@ struct GroupKeysViewer: View { ForEach(section.keys) { key in GroupKeyRow(key: key) } - .onDelete(perform: isBlocked ? nil : { offsets in delete(offsets, in: section.keys) }) + .onDelete(perform: isEditBlocked ? nil : { offsets in delete(offsets, in: section.keys) }) } } } .navigationTitle("Group Keys") .navigationBarTitleDisplayMode(.inline) - .bottomFooter { - if isBlocked, !sections.isEmpty { - FooterMessage(text: "Unblock all apps to delete keys.") - } - } + .editProtectionBar(unblockAllMessage: "Unblock all apps to delete keys.") .overlay { if sections.isEmpty { ContentUnavailableView( @@ -51,7 +47,7 @@ struct GroupKeysViewer: View { } private func delete(_ offsets: IndexSet, in keys: [Key]) { - guard !isBlocked else { return } + guard !isEditBlocked else { return } for index in offsets { modelContext.delete(keys[index]) } diff --git a/Normal/Views/Key/KeyFormSheet.swift b/Normal/Views/Key/KeyFormSheet.swift index 8339ca1..2df9948 100644 --- a/Normal/Views/Key/KeyFormSheet.swift +++ b/Normal/Views/Key/KeyFormSheet.swift @@ -12,7 +12,7 @@ struct KeyFormSheet: View { @Environment(\.dismiss) private var dismiss @Environment(\.modelContext) private var modelContext @Environment(QRService.self) private var qrService - @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess private var editAccess @Query private var keys: [Key] @@ -35,12 +35,12 @@ struct KeyFormSheet: View { existing == nil } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 && (!isNew || !keys.isEmpty) + private var isEditBlocked: Bool { + editAccess.isBlocked } private var isReadOnly: Bool { - !isNew && isBlocked + !isNew && isEditBlocked } private var isLastKey: Bool { @@ -71,6 +71,7 @@ struct KeyFormSheet: View { init(existing: Key? = nil, groupID: UUID? = nil) { self.existing = existing self.groupID = groupID + _editAccess = EditAccess(allowWhenNoKeys: existing == nil) _name = State(initialValue: existing?.name ?? "") _keyType = State(initialValue: existing?.type ?? KeyType.availableOnDevice.first ?? .qr) _scannedKeyId = State(initialValue: nil) @@ -140,11 +141,7 @@ struct KeyFormSheet: View { } .navigationTitle(navigationTitle) .navigationBarTitleDisplayMode(.inline) - .bottomFooter { - if isBlocked { - FooterMessage(text: BlockedMessage.keys) - } - } + .editProtectionBar(unblockAllMessage: BlockedMessage.keys, allowWhenNoKeys: isNew) .toolbar { if isReadOnly { ToolbarItem(placement: .confirmationAction) { @@ -158,7 +155,7 @@ struct KeyFormSheet: View { Button(isNew ? "Save" : "Update", action: save) .fontWeight(.semibold) .accessibilityIdentifier("key.saveButton") - .disabled(!canSave || isBlocked) + .disabled(!canSave || isEditBlocked) } } } @@ -203,6 +200,7 @@ struct KeyFormSheet: View { Text("Keys cannot be re-assigned once created. Please create a new key instead and delete this one.") } } + .editUnblockHost() } private func attemptDelete() { @@ -214,13 +212,13 @@ struct KeyFormSheet: View { } private func deleteKey() { - guard let existing, !isBlocked, Key.canDelete(existing, in: keys) else { return } + guard let existing, !isEditBlocked, Key.canDelete(existing, in: keys) else { return } modelContext.delete(existing) dismiss() } private func save() { - guard !isBlocked else { return } + guard !isEditBlocked else { return } let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return } diff --git a/Normal/Views/Key/KeyListCardView.swift b/Normal/Views/Key/KeyListCardView.swift index 0de5ecc..129183d 100644 --- a/Normal/Views/Key/KeyListCardView.swift +++ b/Normal/Views/Key/KeyListCardView.swift @@ -3,7 +3,7 @@ import SwiftUI struct KeyListCardView: View { @Environment(\.modelContext) private var modelContext - @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess private var editAccess @Query private var keys: [Key] @@ -13,8 +13,8 @@ struct KeyListCardView: View { let key: Key - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var isLastKey: Bool { @@ -46,7 +46,7 @@ struct KeyListCardView: View { KeyFormSheet(existing: key) } .editDeleteContextMenu( - isDisabled: isBlocked, + isDisabled: isEditBlocked, onEdit: { isEditing = true }, onDelete: attemptDelete ) @@ -55,7 +55,7 @@ struct KeyListCardView: View { itemName: key.name, isPresented: $showDeleteConfirmation, onDelete: { - guard !isBlocked, Key.canDelete(key, in: keys) else { return } + guard !isEditBlocked, Key.canDelete(key, in: keys) else { return } modelContext.delete(key) } ) diff --git a/Normal/Views/Key/KeysView.swift b/Normal/Views/Key/KeysView.swift index 2c98971..3d0ce5f 100644 --- a/Normal/Views/Key/KeysView.swift +++ b/Normal/Views/Key/KeysView.swift @@ -2,7 +2,7 @@ import SwiftData import SwiftUI struct KeysView: View { - @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess(allowWhenNoKeys: true) private var editAccess @Query(filter: #Predicate { $0.groupID == nil }, sort: [SortDescriptor(\Key.sortIndex)]) private var keys: [Key] @@ -11,26 +11,27 @@ struct KeysView: View { @State private var isShowingSheet = false @State private var isShowingGroupKeys = false - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 && (!keys.isEmpty || !groupKeys.isEmpty) + private var isEditBlocked: Bool { + editAccess.isBlocked } var body: some View { NavigationStack { content + .editProtectionBar(unblockAllMessage: BlockedMessage.keys, allowWhenNoKeys: true) .sheet(isPresented: $isShowingGroupKeys) { groupKeysSheet } .navigationTitle("Keys") .settingsToolbar() .toolbar { ToolbarItem(placement: .primaryAction) { Button { - guard !isBlocked else { return } + guard !isEditBlocked else { return } isShowingSheet.toggle() } label: { Label("Add Key", systemImage: "plus") } .accessibilityIdentifier("keys.addButton") - .disabled(isBlocked) + .disabled(isEditBlocked) .sheet(isPresented: $isShowingSheet) { KeyFormSheet() } @@ -42,9 +43,16 @@ struct KeysView: View { private var content: some View { Group { if keys.isEmpty { - KeysEmptyStateView(isAddDisabled: isBlocked) { - guard !isBlocked else { return } - isShowingSheet = true + VStack(spacing: 0) { + KeysEmptyStateView(isAddDisabled: isEditBlocked) { + guard !isEditBlocked else { return } + isShowingSheet = true + } + if !groupKeys.isEmpty { + groupKeysLink + .padding(.horizontal, DS.Spacing.lg) + .padding(.bottom, DS.Spacing.sm) + } } } else { ReorderableListView( @@ -52,25 +60,11 @@ struct KeysView: View { rowContent: { key in KeyListCardView(key: key) }, - onMove: isBlocked ? nil : { move(from: $0, to: $1) }, + onMove: isEditBlocked ? nil : { move(from: $0, to: $1) }, footer: { groupKeysRow } ) } } - .bottomFooter { - if isBlocked || (keys.isEmpty && !groupKeys.isEmpty) { - VStack(spacing: DS.Spacing.sm) { - if keys.isEmpty, !groupKeys.isEmpty { - groupKeysLink - .padding(.horizontal, DS.Spacing.lg) - .padding(.bottom, isBlocked ? 0 : DS.Spacing.sm) - } - if isBlocked { - FooterMessage(text: BlockedMessage.keys) - } - } - } - } } @ViewBuilder @@ -110,10 +104,11 @@ struct KeysView: View { } } } + .editUnblockHost() } private func move(from source: IndexSet, to destination: Int) { - guard !isBlocked else { return } + guard !isEditBlocked else { return } _ = SortIndexing.reorder(keys, from: source, to: destination, sortIndex: \.sortIndex) } } diff --git a/Normal/Views/Key/LocationPickerSheet.swift b/Normal/Views/Key/LocationPickerSheet.swift index 0aaa042..77f138e 100644 --- a/Normal/Views/Key/LocationPickerSheet.swift +++ b/Normal/Views/Key/LocationPickerSheet.swift @@ -7,8 +7,8 @@ struct LocationPickerSheet: View { @Environment(\.dismiss) private var dismiss @Environment(\.modelContext) private var modelContext @Environment(LocationService.self) private var locationService - @Environment(ScreenTimeService.self) private var screenTimeService @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @EditAccess(allowWhenNoKeys: true) private var editState @Query private var keys: [Key] let kind: LocationRadiusKind @@ -23,8 +23,13 @@ struct LocationPickerSheet: View { @State private var inspectedKey: Key? private func deleteDisabledReason(for key: Key) -> LocalizedStringKey? { - if screenTimeService.activeShieldCount() > 0 && !keys.isEmpty { + switch editState { + case .requiresKey: + return "Unblock editing to delete keys." + case .requiresUnblockAll: return "Unblock all apps to delete keys." + case .open, .sessionActive: + break } if groupID != nil, key.groupID != groupID { return "Global keys can be deleted in the Keys tab." diff --git a/Normal/Views/Schedules/ScheduleCardView.swift b/Normal/Views/Schedules/ScheduleCardView.swift index a12f77c..8b8658b 100644 --- a/Normal/Views/Schedules/ScheduleCardView.swift +++ b/Normal/Views/Schedules/ScheduleCardView.swift @@ -7,6 +7,7 @@ struct ScheduleCardView: View { @Environment(ScheduleService.self) private var scheduleService @Environment(ScreenTimeService.self) private var screenTimeService @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @EditAccess private var editAccess @Query private var allSchedules: [BlockSchedule] @Query private var keys: [Key] @@ -31,8 +32,8 @@ struct ScheduleCardView: View { @State private var pendingReselectionError: Error? @State private var reselectionError: String? - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var hasGlobalKey: Bool { @@ -48,17 +49,7 @@ struct ScheduleCardView: View { } private var isLocked: Bool { - isBlocked || !hasGlobalKey || needsSync - } - - private var reselectionBlockedMessage: LocalizedStringKey? { - if isBlocked { - BlockedMessage.schedules - } else if !hasGlobalKey { - "Add a key in the Keys tab to manage schedules." - } else { - nil - } + isEditBlocked || !hasGlobalKey || needsSync } var body: some View { @@ -73,17 +64,17 @@ struct ScheduleCardView: View { } .opacity((schedule.isEnabled && !isLocked) ? 1 : DS.Opacity.dim) .onTapGesture { - if needsSync, !isBlocked, hasGlobalKey { + if needsSync, !isEditBlocked, hasGlobalKey { isReselecting = true - } else if !isLocked || isBlocked { + } else if !isLocked || isEditBlocked { isEditing = true } } .editDeleteContextMenu( - isDisabled: isBlocked || !hasGlobalKey, - isDuplicateDisabled: needsSync || isBlocked || !hasGlobalKey, + isDisabled: isEditBlocked || !hasGlobalKey, + isDuplicateDisabled: needsSync || isEditBlocked || !hasGlobalKey, onEdit: { - if needsSync, !isBlocked, hasGlobalKey { + if needsSync, !isEditBlocked, hasGlobalKey { isReselecting = true } else { isEditing = true @@ -108,10 +99,11 @@ struct ScheduleCardView: View { SelectAppsForGroupSheet( selection: .constant(schedule.selection), customDomains: .constant(schedule.customDomains), - saveBlockedMessage: reselectionBlockedMessage, - saveErrorMessage: reselectionError + saveBlockedMessage: hasGlobalKey ? nil : "Add a key in the Keys tab to manage schedules.", + saveErrorMessage: reselectionError, + editProtectionMessage: BlockedMessage.schedules ) { newSelection, newDomains in - guard !isBlocked, hasGlobalKey else { return false } + guard !isEditBlocked, hasGlobalKey else { return false } reselectionError = nil let previousSelection = schedule.selection let previousDomains = schedule.customDomains @@ -296,7 +288,7 @@ struct ScheduleCardView: View { } private func toggleEnabled() { - guard !isBlocked, hasGlobalKey else { return } + guard !isEditBlocked, hasGlobalKey else { return } do { try scheduleService.toggleEnabled( schedule, @@ -310,7 +302,7 @@ struct ScheduleCardView: View { } private func duplicateSchedule() { - guard !isBlocked, hasGlobalKey, !needsSync else { return } + guard !isEditBlocked, hasGlobalKey, !needsSync else { return } let ordered = allSchedules.sorted { $0.sortIndex < $1.sortIndex } let copy = schedule.duplicate(named: CopyNaming.name(for: schedule.name, existing: allSchedules.map(\.name))) withAnimation { @@ -321,7 +313,7 @@ struct ScheduleCardView: View { } private func deleteSchedule() { - guard !isBlocked, hasGlobalKey else { return } + guard !isEditBlocked, hasGlobalKey else { return } let remaining = allSchedules.filter { $0.id != schedule.id } do { try scheduleService.remove( diff --git a/Normal/Views/Schedules/ScheduleFormSheet.swift b/Normal/Views/Schedules/ScheduleFormSheet.swift index 18eade7..53d9418 100644 --- a/Normal/Views/Schedules/ScheduleFormSheet.swift +++ b/Normal/Views/Schedules/ScheduleFormSheet.swift @@ -8,6 +8,7 @@ struct ScheduleFormSheet: View { @Environment(\.modelContext) private var modelContext @Environment(ScheduleService.self) private var scheduleService @Environment(ScreenTimeService.self) private var screenTimeService + @EditAccess private var editAccess @Query private var allSchedules: [BlockSchedule] @Query private var allSettings: [Settings] @@ -34,12 +35,12 @@ struct ScheduleFormSheet: View { existing == nil } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var isReadOnly: Bool { - !isNew && isBlocked + !isNew && isEditBlocked } private var isDurationTooShort: Bool { @@ -127,10 +128,8 @@ struct ScheduleFormSheet: View { } .navigationTitle(isReadOnly ? "Schedule" : (isNew ? "New Schedule" : "Edit Schedule")) .navigationBarTitleDisplayMode(.inline) - .bottomFooter { - if isBlocked { - FooterMessage(text: BlockedMessage.schedules) - } else if !hasGlobalKey { + .editProtectionBar(unblockAllMessage: BlockedMessage.schedules) { + if !hasGlobalKey { FooterMessage(text: "Add a key in the Keys tab to manage schedules.") } } @@ -146,7 +145,7 @@ struct ScheduleFormSheet: View { ToolbarItem(placement: .confirmationAction) { Button(isNew ? "Save" : "Update", action: save) .fontWeight(.semibold) - .disabled(!canSave || isBlocked || !hasGlobalKey) + .disabled(!canSave || isEditBlocked || !hasGlobalKey) } } } @@ -160,6 +159,7 @@ struct ScheduleFormSheet: View { onDelete: deleteSchedule ) } + .editUnblockHost() } private var deleteSection: some View { @@ -302,7 +302,7 @@ struct ScheduleFormSheet: View { } private func deleteSchedule() { - guard let existing, !isBlocked, hasGlobalKey else { return } + guard let existing, !isEditBlocked, hasGlobalKey else { return } let remaining = allSchedules.filter { $0.id != existing.id } error = nil do { @@ -320,7 +320,7 @@ struct ScheduleFormSheet: View { } private func save() { - guard !isBlocked, hasGlobalKey else { return } + guard !isEditBlocked, hasGlobalKey else { return } let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return } error = nil diff --git a/Normal/Views/Schedules/SchedulesView.swift b/Normal/Views/Schedules/SchedulesView.swift index 88848ee..eaf38e6 100644 --- a/Normal/Views/Schedules/SchedulesView.swift +++ b/Normal/Views/Schedules/SchedulesView.swift @@ -5,6 +5,7 @@ struct SchedulesView: View { @Environment(ScreenTimeService.self) private var screenTimeService @Environment(ScheduleService.self) private var scheduleService @Environment(\.navigationCoordinator) private var navigation + @EditAccess private var editAccess @Query(sort: [SortDescriptor(\BlockSchedule.sortIndex)]) private var schedules: [BlockSchedule] @@ -22,8 +23,8 @@ struct SchedulesView: View { selectedApps.first?.hasItemsToBlock(customDomainsEnabled: settings.enableCustomDomains) == true } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 + private var isEditBlocked: Bool { + editAccess.isBlocked } private var hasGlobalKey: Bool { @@ -31,12 +32,17 @@ struct SchedulesView: View { } private var canAdd: Bool { - hasAppSelection && hasGlobalKey && !isBlocked + hasAppSelection && hasGlobalKey && !isEditBlocked } var body: some View { NavigationStack { content + .editProtectionBar(unblockAllMessage: BlockedMessage.schedules) { + if !schedules.isEmpty, !hasGlobalKey { + FooterMessage(text: "Add a key in the Keys tab to manage schedules.") + } + } .navigationTitle("Schedules") .settingsToolbar() .toolbar { @@ -63,33 +69,18 @@ struct SchedulesView: View { rowContent: { schedule in ScheduleCardView(schedule: schedule) }, - onMove: isBlocked ? nil : { move(from: $0, to: $1) } + onMove: isEditBlocked ? nil : { move(from: $0, to: $1) } ) - .bottomFooter { - if let message = bottomMessage { - FooterMessage(text: message) - } - } } } private func move(from source: IndexSet, to destination: Int) { - guard !isBlocked else { return } + guard !isEditBlocked else { return } let reordered = SortIndexing.reorder(schedules, from: source, to: destination, sortIndex: \.sortIndex) let constraint = selectedApps.first?.effectiveConstraint(customDomainsEnabled: settings.enableCustomDomains) scheduleService.syncAllToSharedStore(reordered, constrainedTo: constraint) } - private var bottomMessage: LocalizedStringKey? { - if isBlocked { - BlockedMessage.schedules - } else if !hasGlobalKey { - "Add a key in the Keys tab to manage schedules." - } else { - nil - } - } - @ViewBuilder private var emptyState: some View { if !hasAppSelection { @@ -107,12 +98,6 @@ struct SchedulesView: View { Button("Go to Keys") { navigation.show(.keys) } .buttonStyle(.borderedProminent) } - } else if isBlocked { - ContentUnavailableView( - "Apps Blocked", - systemImage: "lock.fill", - description: Text("Unblock all apps to create schedules.") - ) } else { ContentUnavailableView( "No Schedules", @@ -123,9 +108,9 @@ struct SchedulesView: View { } private func openSheet() { - guard !isBlocked else { return } + guard !isEditBlocked else { return } screenTimeService.ifAuthorized { - guard !isBlocked else { return } + guard !isEditBlocked else { return } isShowingSheet = true } } diff --git a/Normal/Views/Settings/EditProtectionView.swift b/Normal/Views/Settings/EditProtectionView.swift new file mode 100644 index 0000000..5ed2092 --- /dev/null +++ b/Normal/Views/Settings/EditProtectionView.swift @@ -0,0 +1,128 @@ +import SwiftData +import SwiftUI + +struct EditProtectionView: View { + @Environment(ScreenTimeService.self) private var screenTimeService + @Environment(EditSessionService.self) private var editSessionService + @Query private var keys: [Key] + + let settings: Settings + + @State private var authAction: ProtectedAction? + + private var globalKeyTypes: [KeyType] { + let globalKeys = Key.scoped(keys, toGroup: nil) + return KeyType.allCases.filter { type in globalKeys.contains { $0.type == type } } + } + + var body: some View { + Form { + modeSection + + if settings.editProtectionMode == .requireKey { + UnblockingDefaultsSection( + durationOverride: Bindable(settings).editDurationOverride, + keyOverride: Bindable(settings).editKeyOverride, + durations: settings.unblockDurations, + availableKeyTypes: globalKeyTypes, + appDefaultDuration: settings.defaultDuration, + appDefaultKeyType: settings.defaultKeyType, + durationAccessibilityID: "editProtection.defaultDuration", + keyAccessibilityID: "editProtection.defaultKey", + footer: "Choose a default key or duration when unblocking editing, or inherit your app defaults." + ) + } + } + .navigationTitle("Edit Protection") + .navigationBarTitleDisplayMode(.inline) + .keySelect( + action: $authAction, + defaultKeyType: settings.resolvedEditDefaultKeyType + ) + } + + private var isUnblockAllDisabled: Bool { + editSessionService.modeChangeAccess( + from: settings.editProtectionMode, + to: .unblockAll, + keys: keys, + activeShieldCount: screenTimeService.activeShieldCount() + ) == .requiresUnblockAll + } + + private var modeSection: some View { + Section { + ForEach(EditProtectionMode.allCases) { mode in + modeRow(mode) + } + } header: { + Text("Allow Editing") + } footer: { + Text( + isUnblockAllDisabled + ? String(localized: "Unblock all apps to change this setting.") + : settings.editProtectionMode.footer + ) + } + } + + private func modeRow(_ mode: EditProtectionMode) -> some View { + let isSelected = settings.editProtectionMode == mode + let isDisabled = mode == .unblockAll && isUnblockAllDisabled + return Button { + selectMode(mode) + } label: { + HStack(spacing: DS.Spacing.md) { + VStack(alignment: .leading, spacing: DS.Spacing.xs) { + Text(mode.label) + .foregroundStyle(.primary) + Text(mode.description) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + if isSelected { + Image(systemName: "checkmark") + .foregroundStyle(.tint) + .fontWeight(.semibold) + .accessibilityHidden(true) + } + } + .opacity(isDisabled ? DS.Opacity.dim : 1) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .disabled(isDisabled) + .accessibilityAddTraits(isSelected ? .isSelected : []) + .accessibilityIdentifier("settings.editProtection.\(mode.rawValue)") + } + + private func selectMode(_ mode: EditProtectionMode) { + let current = settings.editProtectionMode + guard mode != current else { return } + + switch editSessionService.modeChangeAccess( + from: current, + to: mode, + keys: keys, + activeShieldCount: screenTimeService.activeShieldCount() + ) { + case .open, .sessionActive: + applyMode(mode) + case .requiresKey: + authAction = .weaken { proof in + guard proof.coversAllApps else { return } + applyMode(mode) + } + case .requiresUnblockAll: + break + } + } + + private func applyMode(_ mode: EditProtectionMode) { + withAnimation { + settings.editProtectionMode = mode + } + editSessionService.block() + } +} diff --git a/Normal/Views/Settings/EmergencyUnblockView.swift b/Normal/Views/Settings/EmergencyUnblockView.swift index 4a00694..2452762 100644 --- a/Normal/Views/Settings/EmergencyUnblockView.swift +++ b/Normal/Views/Settings/EmergencyUnblockView.swift @@ -19,7 +19,7 @@ struct EmergencyUnblockView: View { } header: { Text("Emergency Unblock") } footer: { - Text("Removes all blocks immediately without a key. Each use regenerates after 6 months.") + Text("Removes all blocks and unblocks editing immediately without a key. Each use regenerates after 6 months.") } Section { diff --git a/Normal/Views/Settings/GeneralSettingsView.swift b/Normal/Views/Settings/GeneralSettingsView.swift index 92caa5f..708dbfd 100644 --- a/Normal/Views/Settings/GeneralSettingsView.swift +++ b/Normal/Views/Settings/GeneralSettingsView.swift @@ -5,11 +5,14 @@ struct GeneralSettingsView: View { @Environment(ScreenTimeService.self) private var screenTimeService @Environment(ScheduleService.self) private var scheduleService @Environment(TimedUnblockService.self) private var timedUnblockService + @EditAccess private var editState @Query private var schedules: [BlockSchedule] @Query private var selectedApps: [SelectedApps] let settings: Settings let availableKeyTypes: [KeyType] + @State private var customDomainsAuthAction: ProtectedAction? + private static let defaultPageOptions: [AppTab] = [.home, .groups, .schedules] private static let writeReviewURL = URL(string: "https://apps.apple.com/app/id6768861415?action=write-review")! @@ -26,45 +29,62 @@ struct GeneralSettingsView: View { } #endif } + .keySelect( + action: $customDomainsAuthAction, + defaultKeyType: settings.resolvedEditDefaultKeyType + ) } - private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 - } - - private var cannotDisableCustomDomains: Bool { - settings.enableCustomDomains && isBlocked + private var isCustomDomainsToggleDisabled: Bool { + editState == .requiresUnblockAll && settings.enableCustomDomains } private var customDomainsBinding: Binding { Binding( get: { settings.enableCustomDomains }, set: { enabled in - if !enabled, isBlocked { return } - BlockActions.setCustomDomainsEnabled( - enabled, - settings: settings, - schedules: schedules, - mainSelection: selectedApps.first, - screenTimeService: screenTimeService, - timedUnblockService: timedUnblockService, - scheduleService: scheduleService - ) + if enabled { + setCustomDomainsEnabled(true) + return + } + switch editState { + case .requiresUnblockAll: + return + case .requiresKey: + customDomainsAuthAction = .weaken { proof in + guard proof.coversAllApps else { return } + setCustomDomainsEnabled(false) + } + case .open, .sessionActive: + setCustomDomainsEnabled(false) + } } ) } + private func setCustomDomainsEnabled(_ enabled: Bool) { + BlockActions.setCustomDomainsEnabled( + enabled, + settings: settings, + schedules: schedules, + mainSelection: selectedApps.first, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService, + scheduleService: scheduleService + ) + } + private var websitesSection: some View { Section { Toggle( "Enable Custom Websites", isOn: customDomainsBinding ) - .disabled(cannotDisableCustomDomains) + .disabled(isCustomDomainsToggleDisabled) } header: { Text("Websites") } footer: { - if cannotDisableCustomDomains { + if isCustomDomainsToggleDisabled { Text("Unblock all apps to turn this off.") } } @@ -129,6 +149,13 @@ struct GeneralSettingsView: View { Section { UsageSummaryView() + NavigationLink { + EditProtectionView(settings: settings) + } label: { + LabeledContent("Edit Protection", value: settings.editProtectionMode.shortLabel) + } + .accessibilityIdentifier("settings.editProtectionLink") + AdultContentToggleView(defaultKeyType: settings.defaultKeyType) Toggle( diff --git a/Normal/Views/Settings/SettingsView.swift b/Normal/Views/Settings/SettingsView.swift index 50bb6cc..4f3762e 100644 --- a/Normal/Views/Settings/SettingsView.swift +++ b/Normal/Views/Settings/SettingsView.swift @@ -8,6 +8,7 @@ struct SettingsView: View { @Environment(TimedUnblockService.self) private var timedUnblockService @Environment(EmergencyUnblockService.self) private var emergencyUnblockService @Environment(UsageLimitService.self) private var usageLimitService + @Environment(EditSessionService.self) private var editSessionService @Query private var allSettings: [Settings] @Query private var keys: [Key] @Query private var schedules: [BlockSchedule] @@ -47,14 +48,14 @@ struct SettingsView: View { Button("Cancel", role: .cancel) {} } message: { Text( - "This will immediately remove all app blocks. Each unblock regenerates after 6 months. You have \(settings.emergencyUnblocksAvailable) remaining." + "This will immediately remove all app blocks and unblock editing until you re-block it. 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." + "All app blocks have been removed and editing is unblocked until you block it again. You have \(settings.emergencyUnblocksAvailable) emergency unblock\(settings.emergencyUnblocksAvailable == 1 ? "" : "s") remaining." ) } } @@ -130,7 +131,8 @@ struct SettingsView: View { screenTimeService: screenTimeService, timedUnblockService: timedUnblockService, scheduleService: scheduleService, - usageLimitService: usageLimitService + usageLimitService: usageLimitService, + editSessionService: editSessionService ) showSuccessAlert = true } diff --git a/NormalTests/Models/EditProtectionPolicyTests.swift b/NormalTests/Models/EditProtectionPolicyTests.swift new file mode 100644 index 0000000..d7e3125 --- /dev/null +++ b/NormalTests/Models/EditProtectionPolicyTests.swift @@ -0,0 +1,364 @@ +import Foundation +import Testing + +@testable import Normal + +@MainActor +struct EditProtectionPolicyTests { + private let now = Date(timeIntervalSinceReferenceDate: 800_000_000) + + private var globalKey: Key { + Key(name: "Desk", type: .qr, rawValue: "GLOBAL") + } + + private func groupKey(groupID: UUID = UUID()) -> Key { + Key(name: "Social", type: .qr, rawValue: "GROUP", groupID: groupID) + } + + @Test func requireKeyWithUsableGlobalKeyIgnoresShieldsAndDoesNotEvaluateShieldCount() { + let keys = [globalKey] + var evaluatedShieldCount = false + + let blockedState = EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: keys, + activeShieldCount: { + evaluatedShieldCount = true + return 0 + }(), + now: now + ) + #expect(blockedState == .requiresKey) + #expect(blockedState.isBlocked) + #expect(!evaluatedShieldCount) + + let endDate = now.addingTimeInterval(.minutes(15)) + let activeTimed = EditProtectionPolicy.state( + mode: .requireKey, + session: .timed(endDate: endDate), + keys: keys, + activeShieldCount: { + evaluatedShieldCount = true + return 3 + }(), + now: now + ) + #expect(activeTimed == .sessionActive(endDate: endDate)) + #expect(!activeTimed.isBlocked) + #expect(!evaluatedShieldCount) + + let expiredTimed = EditProtectionPolicy.state( + mode: .requireKey, + session: .timed(endDate: now), + keys: keys, + activeShieldCount: { + evaluatedShieldCount = true + return 0 + }(), + now: now + ) + #expect(expiredTimed == .requiresKey) + #expect(!evaluatedShieldCount) + + let permanent = EditProtectionPolicy.state( + mode: .requireKey, + session: .permanent, + keys: keys, + activeShieldCount: { + evaluatedShieldCount = true + return 2 + }(), + now: now + ) + #expect(permanent == .sessionActive(endDate: nil)) + #expect(!permanent.isBlocked) + #expect(!evaluatedShieldCount) + } + + @Test func requireKeyHonorsActiveSessionEvenWithoutUsableGlobalKey() { + let onlyGroupKey = [groupKey()] + let nfcOnly = [Key(name: "Tag", type: .nfc, rawValue: "NFC")] + let ipadCapabilities: [KeyType] = [.qr, .location] + let endDate = now.addingTimeInterval(.minutes(15)) + var evaluatedShieldCount = false + + let permanentWithGroupKey = EditProtectionPolicy.state( + mode: .requireKey, + session: .permanent, + keys: onlyGroupKey, + activeShieldCount: { + evaluatedShieldCount = true + return 2 + }(), + now: now + ) + #expect(permanentWithGroupKey == .sessionActive(endDate: nil)) + #expect(!evaluatedShieldCount) + + let permanentWithNoKeys = EditProtectionPolicy.state( + mode: .requireKey, + session: .permanent, + keys: [], + activeShieldCount: { + evaluatedShieldCount = true + return 0 + }(), + now: now + ) + #expect(permanentWithNoKeys == .sessionActive(endDate: nil)) + #expect(!evaluatedShieldCount) + + let timedOnIpad = EditProtectionPolicy.state( + mode: .requireKey, + session: .timed(endDate: endDate), + keys: nfcOnly, + activeShieldCount: { + evaluatedShieldCount = true + return 2 + }(), + now: now, + availableKeyTypes: ipadCapabilities + ) + #expect(timedOnIpad == .sessionActive(endDate: endDate)) + #expect(!evaluatedShieldCount) + + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .timed(endDate: now), + keys: onlyGroupKey, + activeShieldCount: 2, + now: now + ) == .requiresUnblockAll) + } + + @Test func requireKeyWithoutUsableGlobalKeyFallsBackToUnblockAllRules() { + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: [], + activeShieldCount: 0, + now: now + ) == .open) + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: [], + activeShieldCount: 2, + allowWhenNoKeys: false, + now: now + ) == .requiresUnblockAll) + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: [], + activeShieldCount: 2, + allowWhenNoKeys: true, + now: now + ) == .open) + + let onlyGroupKey = [groupKey()] + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: onlyGroupKey, + activeShieldCount: 0, + now: now + ) == .open) + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: onlyGroupKey, + activeShieldCount: 1, + allowWhenNoKeys: true, + now: now + ) == .requiresUnblockAll) + } + + @Test func unblockAllModeDependsOnlyOnActiveShieldsAndAllowWhenNoKeys() { + let keys = [globalKey] + + #expect( + EditProtectionPolicy.state( + mode: .unblockAll, + session: .permanent, + keys: keys, + activeShieldCount: 0, + now: now + ) == .open) + #expect( + EditProtectionPolicy.state( + mode: .unblockAll, + session: .permanent, + keys: keys, + activeShieldCount: 1, + now: now + ) == .requiresUnblockAll) + #expect( + EditProtectionPolicy.state( + mode: .unblockAll, + session: .blocked, + keys: [], + activeShieldCount: 1, + allowWhenNoKeys: true, + now: now + ) == .open) + #expect( + EditProtectionPolicy.state( + mode: .unblockAll, + session: .blocked, + keys: [], + activeShieldCount: 1, + allowWhenNoKeys: false, + now: now + ) == .requiresUnblockAll) + } + + @Test func modeChangeAccessRequiresKeyOrUnblockAllWhenDowngradingWithoutAnActiveSession() { + let keys = [globalKey] + let onlyGroupKey = [groupKey()] + var evaluatedShieldCount = false + + let downgrade = EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: keys, + activeShieldCount: { + evaluatedShieldCount = true + return 0 + }(), + now: now + ) + #expect(downgrade == .requiresKey) + #expect(!evaluatedShieldCount) + + let tighten = EditProtectionPolicy.modeChangeAccess( + from: .unblockAll, + to: .requireKey, + session: .blocked, + keys: keys, + activeShieldCount: { + evaluatedShieldCount = true + return 3 + }(), + now: now + ) + #expect(tighten == .open) + #expect(!evaluatedShieldCount) + + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: [], + activeShieldCount: 0, + now: now + ) == .open) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: [], + activeShieldCount: 2, + now: now + ) == .requiresUnblockAll) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: onlyGroupKey, + activeShieldCount: 0, + now: now + ) == .open) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: onlyGroupKey, + activeShieldCount: 2, + now: now + ) == .requiresUnblockAll) + + let endDate = now.addingTimeInterval(.minutes(15)) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .timed(endDate: endDate), + keys: keys, + now: now + ) == .sessionActive(endDate: endDate)) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .timed(endDate: now), + keys: keys, + now: now + ) == .requiresKey) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .permanent, + keys: onlyGroupKey, + activeShieldCount: 2, + now: now + ) == .sessionActive(endDate: nil)) + } + + @Test func unsupportedDeviceKeysFallBackToShieldProtection() { + let nfcOnly = [Key(name: "Tag", type: .nfc, rawValue: "NFC")] + let ipadCapabilities: [KeyType] = [.qr, .location] + + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: nfcOnly, + activeShieldCount: 0, + now: now, + availableKeyTypes: ipadCapabilities + ) == .open) + #expect( + EditProtectionPolicy.state( + mode: .requireKey, + session: .blocked, + keys: nfcOnly, + activeShieldCount: 2, + now: now, + availableKeyTypes: ipadCapabilities + ) == .requiresUnblockAll) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: nfcOnly, + activeShieldCount: 0, + now: now, + availableKeyTypes: ipadCapabilities + ) == .open) + #expect( + EditProtectionPolicy.modeChangeAccess( + from: .requireKey, + to: .unblockAll, + session: .blocked, + keys: nfcOnly, + activeShieldCount: 2, + now: now, + availableKeyTypes: ipadCapabilities + ) == .requiresUnblockAll) + } +} diff --git a/NormalTests/Models/EditProtectionSettingsTests.swift b/NormalTests/Models/EditProtectionSettingsTests.swift new file mode 100644 index 0000000..b0c9015 --- /dev/null +++ b/NormalTests/Models/EditProtectionSettingsTests.swift @@ -0,0 +1,50 @@ +import Foundation +import Testing + +@testable import Normal + +@MainActor +struct EditProtectionSettingsTests { + @Test func editProtectionDefaultsToUnblockAllListsItFirstAndInheritsAppDefaults() { + let settings = Settings() + settings.defaultDuration = .thirtyMinutes + settings.defaultKeyType = .nfc + + #expect(EditProtectionMode.allCases == [.unblockAll, .requireKey]) + #expect(settings.editProtectionMode == .unblockAll) + #expect(settings.editDurationOverride == .appDefault) + #expect(settings.editKeyOverride == .appDefault) + #expect(settings.resolvedEditDefaultDuration == .thirtyMinutes) + #expect(settings.resolvedEditDefaultKeyType == .nfc) + } + + @Test func missingRawValueFallsBackToUnblockAllForUpgradedStores() { + let settings = Settings() + settings.editProtectionRawValue = nil + #expect(settings.editProtectionMode == .unblockAll) + } + + @Test func explicitNoneOverridesAppDefaultsToAsk() { + let settings = Settings() + settings.defaultDuration = .oneHour + settings.defaultKeyType = .qr + + settings.editDurationOverride = .none + settings.editKeyOverride = .none + + #expect(settings.resolvedEditDefaultDuration == nil) + #expect(settings.resolvedEditDefaultKeyType == nil) + } + + @Test func explicitDurationOverrideResolvesAndDropsToAskWhenRemoved() { + let settings = Settings() + settings.defaultDuration = .fifteenMinutes + settings.editDurationOverride = .value(.fourHours) + + #expect(settings.resolvedEditDefaultDuration == .fourHours) + + settings.removeUnblockDuration(.fourHours) + + #expect(settings.resolvedEditDefaultDuration == nil) + } +} diff --git a/NormalTests/Models/SettingsTests.swift b/NormalTests/Models/SettingsTests.swift index c4de23f..a6a5282 100644 --- a/NormalTests/Models/SettingsTests.swift +++ b/NormalTests/Models/SettingsTests.swift @@ -52,5 +52,8 @@ struct SettingsTests { #expect(s.blockAllPreventsAppDelete == false) #expect(s.hasCompletedOnboarding == false) #expect(s.defaultTab == nil) + #expect(s.editProtectionMode == .unblockAll) + #expect(s.editDurationOverride == .appDefault) + #expect(s.editKeyOverride == .appDefault) } } diff --git a/NormalTests/Models/StoreUpgradeTests.swift b/NormalTests/Models/StoreUpgradeTests.swift index e0a523f..a1943bb 100644 --- a/NormalTests/Models/StoreUpgradeTests.swift +++ b/NormalTests/Models/StoreUpgradeTests.swift @@ -401,6 +401,9 @@ struct StoreUpgradeTests { #expect(!settings.skipBlockWithoutKeyConfirmation) #expect(settings.dailyLimitResetMinutes == 0) #expect(settings.unblockDurations == TimedUnblockDuration.presets) + #expect(settings.editProtectionMode == .unblockAll) + #expect(settings.editDurationOverride == .appDefault) + #expect(settings.editKeyOverride == .appDefault) } @Test func version15StoreKeepsDurationsResetTimeAndDailyLimits() throws { @@ -430,6 +433,9 @@ struct StoreUpgradeTests { #expect(settings.skipBlockWithoutKeyConfirmation) #expect(settings.dailyLimitResetMinutes == 240) #expect(settings.blockAllPreventsAppDelete) + #expect(settings.editProtectionMode == .unblockAll) + #expect(settings.editDurationOverride == .appDefault) + #expect(settings.editKeyOverride == .appDefault) let limit = try #require(try container.mainContext.fetch(FetchDescriptor()).first) #expect(limit.id == limitID) @@ -438,4 +444,38 @@ struct StoreUpgradeTests { #expect(limit.lockAnchor == Self.updated) #expect(limit.createdAt == nil) } + + @Test func editProtectionSettingsSurviveStoreReopen() throws { + let url = storeURL() + defer { removeStore(at: url) } + do { + let container = try reopen(at: url) + let settings = Normal.Settings() + settings.editProtectionMode = .requireKey + settings.editDurationOverride = .value(.fourHours) + settings.editKeyOverride = .value(.nfc) + container.mainContext.insert(settings) + try container.mainContext.save() + } + + let container = try reopen(at: url) + let settings = try #require(try container.mainContext.fetch(FetchDescriptor()).first) + #expect(settings.editProtectionMode == .requireKey) + #expect(settings.editDurationOverride == .value(.fourHours)) + #expect(settings.editKeyOverride == .value(.nfc)) + } + + @Test func freshInstallDefaultsToUnblockAllAcrossStoreReopen() throws { + let url = storeURL() + defer { removeStore(at: url) } + do { + let container = try reopen(at: url) + container.mainContext.insert(Normal.Settings()) + try container.mainContext.save() + } + + let container = try reopen(at: url) + let settings = try #require(try container.mainContext.fetch(FetchDescriptor()).first) + #expect(settings.editProtectionMode == .unblockAll) + } } diff --git a/NormalTests/Services/EditSessionServiceTests.swift b/NormalTests/Services/EditSessionServiceTests.swift new file mode 100644 index 0000000..431e054 --- /dev/null +++ b/NormalTests/Services/EditSessionServiceTests.swift @@ -0,0 +1,106 @@ +import Foundation +import Testing + +@testable import Normal + +@MainActor +struct EditSessionServiceTests { + private final class Clock { + var now = Date(timeIntervalSinceReferenceDate: 800_000_000) + } + + private func makeService( + defaults: UserDefaults? = nil, + clock: Clock = Clock() + ) -> (service: EditSessionService, defaults: UserDefaults, clock: Clock) { + let suite = defaults ?? UserDefaults(suiteName: "edit-session-test-\(UUID().uuidString)")! + return (EditSessionService(defaults: suite, clock: { clock.now }), suite, clock) + } + + private func globalGrant() throws -> EditUnlockGrant { + try #require(EditUnlockGrant(proof: KeyProof(keyGroupID: nil))) + } + + @Test func startsBlockedByDefault() { + let (service, _, _) = makeService() + #expect(!service.isActive) + #expect(service.state == .blocked) + #expect(service.endDate == nil) + #expect(!service.isPermanent) + } + + @Test func timedUnblockActivatesPersistsAndExpiresWhenClockAdvances() throws { + let (service, defaults, clock) = makeService() + let start = clock.now + + service.unblock(for: .timed(.fifteenMinutes), grant: try globalGrant()) + + #expect(service.isActive) + #expect(!service.isPermanent) + #expect(service.endDate == start.addingTimeInterval(.minutes(15))) + + let restored = EditSessionService(defaults: defaults, clock: { clock.now }) + #expect(restored.isActive) + #expect(restored.endDate == service.endDate) + + clock.now = start.addingTimeInterval(.minutes(15)) + #expect(!service.isActive) + service.refresh() + #expect(service.state == .blocked) + + let afterExpiry = EditSessionService(defaults: defaults, clock: { clock.now }) + #expect(!afterExpiry.isActive) + #expect(afterExpiry.state == .blocked) + } + + @Test func permanentUnblockPersistsUntilManuallyBlocked() throws { + let (service, defaults, clock) = makeService() + + service.unblock(for: .permanent, grant: try globalGrant()) + + #expect(service.isActive) + #expect(service.isPermanent) + #expect(service.endDate == nil) + + clock.now = clock.now.addingTimeInterval(.days(7)) + let restored = EditSessionService(defaults: defaults, clock: { clock.now }) + #expect(restored.isActive) + #expect(restored.isPermanent) + + restored.block() + #expect(!restored.isActive) + #expect(restored.state == .blocked) + #expect(!EditSessionService(defaults: defaults, clock: { clock.now }).isActive) + } + + @Test func editUnlockGrantRejectsGroupScopedKeyProof() { + #expect(EditUnlockGrant(proof: KeyProof(keyGroupID: UUID())) == nil) + #expect(EditUnlockGrant(proof: KeyProof(keyGroupID: nil)) != nil) + } + + @Test func emergencyAccessUnblocksEditingWithoutAKeyProof() { + let (service, defaults, clock) = makeService() + + service.grantEmergencyAccess() + + #expect(service.isActive) + #expect(service.isPermanent) + #expect(EditSessionService(defaults: defaults, clock: { clock.now }).isActive) + } + + @Test func accessReflectsLiveSessionAndClock() throws { + let (service, _, clock) = makeService() + let keys = [Key(name: "Desk", type: .qr, rawValue: "GLOBAL")] + + #expect(service.access(mode: .requireKey, keys: keys, activeShieldCount: 0) == .requiresKey) + + service.unblock(for: .timed(.fifteenMinutes), grant: try globalGrant()) + #expect( + service.access(mode: .requireKey, keys: keys, activeShieldCount: 3) + == .sessionActive(endDate: clock.now.addingTimeInterval(.minutes(15))) + ) + + clock.now = clock.now.addingTimeInterval(.minutes(15)) + #expect(service.access(mode: .requireKey, keys: keys, activeShieldCount: 0) == .requiresKey) + } +} diff --git a/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift b/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift index fc9d064..174b3b3 100644 --- a/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift +++ b/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift @@ -2084,4 +2084,67 @@ struct EditWhileBlockedEdgeCaseTests { ) return (activity, store, service) } + + @Test func emergencyUnblockGrantsEditSessionAccess() { + let h = BlockingHarness(mainApps: [1]) + let editSession = EditSessionService(defaults: UserDefaults(suiteName: "emg-\(UUID().uuidString)")!) + #expect(!editSession.isActive) + + BlockActions.emergencyUnblock( + schedules: h.schedules, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock, + scheduleService: h.scheduleService, + usageLimitService: h.usageLimits, + editSessionService: editSession + ) + + #expect(editSession.isActive) + #expect(editSession.isPermanent) + } + + @Test func unblockForAppSelectionEditRequiresActiveSessionAndChecksShieldWrite() throws { + let h = BlockingHarness(mainApps: [1, 2]) + let group = h.group([1]) + h.settings.blockAllPreventsAppDelete = true + h.blockAll() + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .thirtyMinutes) + + for disallowed in [EditProtectionState.open, .requiresKey, .requiresUnblockAll] { + let unblocked = try BlockActions.unblockForAppSelectionEdit( + editAccess: disallowed, + settings: h.settings, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock + ) + #expect(!unblocked) + #expect(h.blocked == h.apps(2)) + #expect(h.appDeletionBlocked) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + } + + let failingScreenTime = FakeScreenTimeService() + failingScreenTime.reconcileResult = false + #expect(throws: TimedUnblockStorageError.unavailable) { + try BlockActions.unblockForAppSelectionEdit( + editAccess: .sessionActive(endDate: nil), + settings: h.settings, + screenTimeService: failingScreenTime, + timedUnblockService: h.timedUnblock + ) + } + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + let unblocked = try BlockActions.unblockForAppSelectionEdit( + editAccess: .sessionActive(endDate: h.at(10, 30)), + settings: h.settings, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock + ) + #expect(unblocked) + #expect(h.blocked.isEmpty) + #expect(!h.appDeletionBlocked) + #expect(h.timedUnblock.activeUnblocks.isEmpty) + } } diff --git a/NormalTests/Views/SelectionChangeWarningTests.swift b/NormalTests/Views/SelectionChangeWarningTests.swift index 0b3ab9c..9735dd7 100644 --- a/NormalTests/Views/SelectionChangeWarningTests.swift +++ b/NormalTests/Views/SelectionChangeWarningTests.swift @@ -18,4 +18,18 @@ struct SelectionChangeWarningTests { @Test func warnsAboutGroupsAndSchedules() { #expect(SelectionChangeWarning(hasGroups: true, hasSchedules: true) == .groupsAndSchedules) } + + @Test func warnsAboutUnblockingActiveShieldsAcrossAllCombinations() { + let none = SelectionChangeWarning(hasGroups: false, hasSchedules: false, unblocksActiveShields: true) + let groups = SelectionChangeWarning(hasGroups: true, hasSchedules: false, unblocksActiveShields: true) + let schedules = SelectionChangeWarning(hasGroups: false, hasSchedules: true, unblocksActiveShields: true) + let both = SelectionChangeWarning(hasGroups: true, hasSchedules: true, unblocksActiveShields: true) + + #expect(none == .unblockAll) + #expect(groups == .unblockAllAndGroups) + #expect(schedules == .unblockAllAndSchedules) + #expect(both == .unblockAllAndGroupsAndSchedules) + #expect(none?.unblocksActiveShields == true) + #expect(SelectionChangeWarning.groups.unblocksActiveShields == false) + } } diff --git a/NormalUITests/EditProtectionUITests.swift b/NormalUITests/EditProtectionUITests.swift new file mode 100644 index 0000000..d4b59e2 --- /dev/null +++ b/NormalUITests/EditProtectionUITests.swift @@ -0,0 +1,440 @@ +import XCTest + +final class EditProtectionUITests: XCTestCase { + private let timeout: TimeInterval = 20 + + override func setUpWithError() throws { + continueAfterFailure = false + XCUIDevice.shared.orientation = .portrait + } + + private func launch(_ extra: [String] = []) -> XCUIApplication { + let app = XCUIApplication() + app.launchArguments = ["-uiTestMode", "-uiTestSkipOnboarding"] + extra + app.launch() + return app + } + + private func launchRequireKey(_ extra: [String] = []) -> XCUIApplication { + launch(["-uiTestEditProtection", "requireKey"] + extra) + } + + private func require(_ element: XCUIElement, _ message: String) { + XCTAssertTrue(element.waitForExistence(timeout: timeout), message) + } + + func testEditProtectionDefaultsToUnblockAllAndListsItFirst() { + let app = launch(["-uiTestStartBlocked", "-uiTestSeedSchedule"]) + + app.mainTab("Schedules").tap() + require( + app.staticTexts["Unblock all apps to add or edit schedules."], + "Fresh installs should default to When All Apps Unblocked" + ) + XCTAssertFalse(app.buttons["editProtection.unblockButton"].exists) + + app.buttons["nav.settings"].tap() + let link = app.buttons["settings.editProtectionLink"] + require(link, "General settings should have an Edit Protection drill-down") + link.tap() + + let unblockAllRow = app.buttons["settings.editProtection.unblockAll"] + let requireKeyRow = app.buttons["settings.editProtection.requireKey"] + require(unblockAllRow, "Edit Protection should list When All Apps Unblocked") + require(requireKeyRow, "Edit Protection should list With a Key") + XCTAssertLessThan( + unblockAllRow.frame.minY, + requireKeyRow.frame.minY, + "When All Apps Unblocked must be the first option" + ) + XCTAssertTrue(unblockAllRow.isSelected, "When All Apps Unblocked should be selected by default") + XCTAssertFalse(requireKeyRow.isSelected) + XCTAssertFalse(app.buttons["editProtection.defaultDuration"].exists) + + requireKeyRow.tap() + require( + app.buttons["editProtection.defaultDuration"], + "Switching to With a Key should reveal unblocking defaults without prompting for a key" + ) + + app.navigationBars.buttons.element(boundBy: 0).tap() + require(app.buttons["Close"], "Returning to General settings should show Close") + app.buttons["Close"].tap() + + require(app.buttons["editProtection.unblockButton"], "Schedules should now require a key to unblock editing") + } + + func testEditingWithKeyKeepsAppsBlocked() { + let app = launchRequireKey(["-uiTestStartBlocked", "-uiTestSeedSchedule"]) + + app.mainTab("Schedules").tap() + require(app.buttons["editProtection.unblockButton"], "Schedules should offer key-based edit unblock") + XCTAssertFalse(app.switches["schedule.enabledToggle"].isEnabled, "Schedule toggle should be blocked before key check") + + app.buttons["editProtection.unblockButton"].tap() + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblocking editing should prompt for a global key") + XCTAssertFalse(app.buttons["keySelect.blockWithoutKey"].exists, "Unblocking editing must not offer a bypass") + keyRow.tap() + + let confirm = app.buttons["timedUnblock.confirm"] + require(confirm, "Unblocking editing should present duration choices when no default is set") + confirm.tap() + + require(app.buttons["editProtection.blockButton"], "Active edit session should show Block Now") + XCTAssertTrue(app.switches["schedule.enabledToggle"].isEnabled, "Schedule toggle should unblock during edit session") + + app.mainTab("Home").tap() + require(app.staticTexts["All Selected Apps Blocked"], "Blocked apps must stay blocked during an edit session") + + app.mainTab("Schedules").tap() + app.buttons["editProtection.blockButton"].tap() + require(app.buttons["editProtection.unblockButton"], "Tapping Block Now should immediately re-block editing") + XCTAssertFalse(app.switches["schedule.enabledToggle"].isEnabled, "Schedule toggle should be blocked again") + } + + func testEditProtectionDefaultDurationSkipsDurationSheet() { + let app = launchRequireKey() + + app.buttons["nav.settings"].tap() + let link = app.buttons["settings.editProtectionLink"] + require(link, "General settings should have an Edit Protection drill-down") + link.tap() + + let durationPicker = app.buttons["editProtection.defaultDuration"] + require(durationPicker, "Edit Protection should offer a Default Duration override") + durationPicker.tap() + let fourHours = app.buttons["4 hours"] + require(fourHours, "Default Duration menu should list saved unblock durations") + fourHours.tap() + + app.navigationBars.buttons.element(boundBy: 0).tap() + require(app.buttons["Close"], "Returning to General settings should show Close") + app.buttons["Close"].tap() + + app.mainTab("Keys").tap() + let unblockButton = app.buttons["editProtection.unblockButton"] + require(unblockButton, "Keys tab should require unblocking editing by default") + unblockButton.tap() + + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblocking editing should prompt for a key") + keyRow.tap() + + require(app.buttons["editProtection.blockButton"], "Default duration should start the edit session directly") + XCTAssertFalse(app.buttons["timedUnblock.confirm"].exists, "Default duration should skip the duration sheet") + XCTAssertTrue(app.buttons["keys.addButton"].isEnabled, "Add Key should be enabled while editing is unblocked") + } + + func testDowngradingEditProtectionToUnblockAllRequiresKey() { + let app = launchRequireKey() + + app.buttons["nav.settings"].tap() + let link = app.buttons["settings.editProtectionLink"] + require(link, "General settings should have an Edit Protection drill-down") + link.tap() + + let unblockAllRow = app.buttons["settings.editProtection.unblockAll"] + require(unblockAllRow, "Edit Protection should list When All Apps Unblocked") + unblockAllRow.tap() + + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Downgrading edit protection must require a global key") + XCTAssertFalse(app.buttons["keySelect.blockWithoutKey"].exists, "Downgrading must not offer a bypass") + keyRow.tap() + + XCTAssertTrue( + app.buttons["editProtection.defaultDuration"].waitForNonExistence(timeout: timeout), + "Switching to When All Apps Unblocked should hide key unblocking defaults" + ) + app.navigationBars.buttons.element(boundBy: 0).tap() + require(app.buttons["Close"], "Returning to General settings should show Close") + app.buttons["Close"].tap() + + app.mainTab("Keys").tap() + XCTAssertTrue(app.buttons["keys.addButton"].isEnabled, "Editing should now be open while no apps are blocked") + } + + func testEmergencyUnblockOpensEditingForLostKeyRecovery() { + let app = launchRequireKey(["-uiTestStartBlocked"]) + + app.buttons["nav.settings"].tap() + let emergencyTab = app.tabBars.buttons["Emergency"] + require(emergencyTab, "Settings should have an Emergency tab") + emergencyTab.tap() + + app.buttons["emergency.unblockButton"].tap() + app.alerts.buttons["Unblock All Apps"].tap() + app.alerts.buttons["OK"].tap() + app.buttons["Close"].tap() + + require(app.buttons["editProtection.blockButton"], "Home should show the active edit session after emergency unblock") + app.mainTab("Keys").tap() + require(app.buttons["editProtection.blockButton"], "Emergency unblock should grant an active edit session") + XCTAssertTrue(app.buttons["keys.addButton"].isEnabled, "User should be able to add a replacement key after emergency unblock") + } + + func testUnblockingEditingInsideGroupSheetAllowsNestedSheetsAndReblocksLive() { + let app = launchRequireKey(["-uiTestStartBlocked", "-uiTestSeedGroupKey"]) + app.mainTab("Groups").tap() + + let group = app.staticTexts["Test Group"] + require(group, "Seeded group should render") + group.tap() + + require(app.buttons["Done"], "Blocked group sheet should open read-only") + XCTAssertFalse(app.buttons["Update"].exists, "Read-only group sheet should not show Update") + XCTAssertFalse(app.buttons["Delete Group"].exists, "Read-only group sheet should not show Delete Group") + + let unblockButton = hittableButton(in: app, identifier: "editProtection.unblockButton") + require(unblockButton, "Group sheet should show Unblock Editing bar") + unblockButton.tap() + + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Unblocking editing from inside a sheet should prompt for a global key") + XCTAssertFalse(app.buttons["keySelect.blockWithoutKey"].exists, "Unblocking editing must not offer bypass") + keyRow.tap() + + let confirm = app.buttons["timedUnblock.confirm"] + require(confirm, "Duration sheet should present cleanly over the group sheet") + confirm.tap() + + require(app.buttons["Update"], "Group sheet should flip live to editable after unblocking editing") + let selectApps = app.buttons.matching(NSPredicate(format: "label BEGINSWITH 'Select Apps'")).firstMatch + require(selectApps, "Editable group sheet should show Select Apps") + selectApps.tap() + + let selectAppsNav = app.navigationBars["Select Apps"] + require(selectAppsNav, "Select Apps sheet should present cleanly after edit-protection auth") + selectAppsNav.buttons["Cancel"].tap() + + let blockNow = hittableButton(in: app, identifier: "editProtection.blockButton") + require(blockNow, "Active edit session bar should stay visible inside the group sheet") + blockNow.tap() + + require(app.buttons["Done"], "Tapping Block Now should return the open group sheet to read-only") + XCTAssertFalse(app.buttons["Update"].exists, "Update button should disappear when re-blocked") + app.buttons["Done"].tap() + + require(app.buttons["group.unblockButton"], "Blocked group must remain blocked after editing session") + } + + func testTurningOffCustomWebsitesRequiresKeyAndSnapsBackOnCancel() { + let app = launchRequireKey(["-uiTestCustomDomains", "-uiTestStartBlocked"]) + + app.buttons["nav.settings"].tap() + let toggle = app.switches["Enable Custom Websites"] + for _ in 0..<4 where !toggle.exists || !toggle.isHittable { app.swipeUp() } + require(toggle, "Settings should show Enable Custom Websites") + XCTAssertTrue(toggle.isHittable, "Enable Custom Websites should be scrolled into view") + XCTAssertEqual(toggle.value as? String, "1", "Toggle should start enabled") + + tapSwitch(toggle) + let keyRow = app.buttons["keySelect.row.QR"] + require(keyRow, "Turning off custom websites should require a global key") + XCTAssertFalse(app.buttons["keySelect.blockWithoutKey"].exists, "Turning off custom websites must not offer bypass") + + app.navigationBars.buttons["Cancel"].tap() + requireValue("1", of: toggle, "Cancelling the key prompt should keep Enable Custom Websites on") + + tapSwitch(toggle) + require(keyRow, "Second attempt should prompt for a key again") + keyRow.tap() + requireValue("0", of: toggle, "Verifying a key should turn Enable Custom Websites off") + + app.buttons["Close"].tap() + app.mainTab("App Select").tap() + XCTAssertFalse( + app.buttons["appSelect.customDomainsLink"].waitForExistence(timeout: 3), + "Custom Domains link should disappear after disabling custom websites" + ) + } + + func testGroupKeyOnlyBlockedUserKeepsGroupKeysReachableAndDisablesAddKey() { + let app = launchRequireKey(["-uiTestNoKeys", "-uiTestSeedGroupKey", "-uiTestStartBlocked"]) + + app.mainTab("Keys").tap() + require( + app.staticTexts["Unblock all apps to add or delete keys."], + "Group-key-only user should see unblock-all footer while shielded" + ) + XCTAssertFalse(app.buttons["editProtection.unblockButton"].exists, "Must not offer key edit unblock without a global key") + XCTAssertFalse(app.buttons["keys.addButton"].isEnabled, "Toolbar Add Key must be disabled while blocked") + + let emptyAddButtons = app.buttons.matching(NSPredicate(format: "label == 'Add Key'")) + for index in 0.. XCUIElement { + let query = app.buttons.matching(identifier: identifier) + _ = query.firstMatch.waitForExistence(timeout: timeout) + for index in (0..