The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.
Arc's dialog sheet for every confirmation: one card, its buttons, keys and hover, as in Arc (#224)
Grigoriybc47470fe446
diff --git a/Packages/CraCore/Sources/CraCore/DialogActions.swift b/Packages/CraCore/Sources/CraCore/DialogActions.swiftnew file mode 100644index 0000000..5f6cc66--- /dev/null+++ b/Packages/CraCore/Sources/CraCore/DialogActions.swift@@ -0,0 +1,52 @@+import Foundation++public struct DialogAction: Equatable, Sendable {+ public enum Role: Sendable { case primary, secondary, destructive, cancel }++ public let title: String+ public let role: Role++ public init(_ title: String, role: Role = .primary) {+ self.title = title+ self.role = role+ }++ public static let cancel = DialogAction("Cancel", role: .cancel)+}++public struct DialogActions: Equatable, Sendable {+ public let buttons: [DialogAction]++ public init(_ buttons: [DialogAction]) {+ precondition(!buttons.isEmpty, "A dialog needs at least one button")+ self.buttons = buttons+ }++ public var defaultIndex: Int? {+ buttons.firstIndex { $0.role == .primary || $0.role == .destructive }+ }++ public var cancelIndex: Int? {+ buttons.firstIndex { $0.role == .cancel } ?? (buttons.count == 1 ? 0 : nil)+ }++ public var displayOrder: [Int] {+ let others = buttons.indices.reversed().filter { $0 != defaultIndex }+ return others + (defaultIndex.map { [$0] } ?? [])+ }++ /// Buttons at the card's left edge: secondary choices such as Arc's "Quit, and don’t ask again".+ public var leadingOrder: [Int] { displayOrder.filter { buttons[$0].role == .secondary } }++ /// Buttons at the card's right edge, the default last.+ public var trailingOrder: [Int] { displayOrder.filter { buttons[$0].role != .secondary } }++ public func key(at index: Int) -> String {+ if index == defaultIndex { return "↩" }+ return index == cancelIndex ? "ESC" : ""+ }++ public func isEnabled(at index: Int, input: String?, requiresInput: Bool) -> Bool {+ index != defaultIndex || !requiresInput || !(input ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ }+}diff --git a/Packages/CraCore/Tests/CraCoreTests/DialogActionsTests.swift b/Packages/CraCore/Tests/CraCoreTests/DialogActionsTests.swiftnew file mode 100644index 0000000..5d5550e--- /dev/null+++ b/Packages/CraCore/Tests/CraCoreTests/DialogActionsTests.swift@@ -0,0 +1,70 @@+import CraCore+import Testing++struct DialogActionsTests {+ @Test func destructiveConfirmationKeepsResponseOrderButPutsCancelOnTheLeft() {+ let actions = DialogActions([DialogAction("Delete Folder", role: .destructive), .cancel])+ #expect(actions.buttons[0].title == "Delete Folder")+ #expect(actions.buttons[0].role == .destructive)+ #expect(actions.displayOrder == [1, 0])+ #expect(actions.defaultIndex == 0)+ #expect(actions.cancelIndex == 1)+ #expect(actions.key(at: 0) == "↩")+ #expect(actions.key(at: 1) == "ESC")+ }++ @Test func threeButtonsKeepForceQuitSeparateFromTheDefaultAction() {+ let actions = DialogActions([DialogAction("Try Again"), DialogAction("Force Quit", role: .destructive), .cancel])+ #expect(actions.displayOrder == [2, 1, 0])+ #expect(actions.defaultIndex == 0)+ #expect(actions.cancelIndex == 2)+ #expect(actions.key(at: 1).isEmpty)+ }++ /// Arc 1.172.1's Quit sheet: "Quit, and don’t ask again" at the card's left edge, Cancel and Quit at its right.+ @Test func quitPutsTheSecondaryChoiceAtTheLeftEdge() {+ let actions = DialogActions([DialogAction("Quit"), .cancel, DialogAction("Quit, and don’t ask again", role: .secondary)])+ #expect(actions.leadingOrder == [2])+ #expect(actions.trailingOrder == [1, 0])+ #expect(actions.key(at: 2).isEmpty)+ }++ @Test func singleAcknowledgementAcceptsReturnAndEscape() {+ let actions = DialogActions([DialogAction("OK")])+ #expect(actions.defaultIndex == 0)+ #expect(actions.cancelIndex == 0)+ #expect(actions.displayOrder == [0])+ }++ @Test func cancellationIsExplicitRatherThanGuessedFromTheTitle() {+ let actions = DialogActions([DialogAction("Allow"), DialogAction("Block", role: .cancel)])+ #expect(actions.cancelIndex == 1)+ #expect(actions.buttons[1].title == "Block")+ let secondary = DialogActions([DialogAction("Other", role: .secondary), DialogAction("Close", role: .cancel)])+ #expect(secondary.defaultIndex == nil)+ #expect(secondary.displayOrder == [1, 0])+ #expect(secondary.key(at: 0).isEmpty)+ #expect(DialogActions([DialogAction("Yes"), DialogAction("No", role: .secondary)]).cancelIndex == nil)+ }++ @Test(arguments: [nil, "", " ", "\n\t"] as [String?])+ func emptyInputDisablesOnlyTheDefaultAction(_ input: String?) {+ let actions = DialogActions([DialogAction("Rename"), .cancel])+ #expect(!actions.isEnabled(at: 0, input: input, requiresInput: true))+ #expect(actions.isEnabled(at: 1, input: input, requiresInput: true))+ #expect(actions.isEnabled(at: 0, input: input, requiresInput: false))+ }++ @Test func nonemptyInputEnablesSubmission() {+ let actions = DialogActions([DialogAction("Rename"), .cancel])+ #expect(actions.isEnabled(at: 0, input: " Work ", requiresInput: true))+ }++ @Test func quitWithoutAskingAgainIsNotTheReturnOrEscapeAction() {+ let actions = DialogActions([DialogAction("Quit"), .cancel, DialogAction("Quit, and don’t ask again", role: .secondary)])+ #expect(actions.displayOrder == [2, 1, 0])+ #expect(actions.defaultIndex == 0)+ #expect(actions.cancelIndex == 1)+ #expect(actions.key(at: 2).isEmpty)+ }+}diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swiftindex e08703c..b5458c6 100644--- a/Sources/Cra/App/AppDelegate.swift+++ b/Sources/Cra/App/AppDelegate.swift@@ -329,12 +329,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {}private func confirmQuit() -> Bool {- let alert = NSAlert()- alert.messageText = "Quit Cra?"- alert.informativeText = "All windows and tabs will close. They come back when Cra starts again."- alert.addButton(withTitle: "Quit")- alert.addButton(withTitle: "Cancel")- return alert.runModal() == .alertFirstButtonReturn+ let alert = AppDialog(title: "Quit Cra?",+ actions: [DialogAction("Quit"), .cancel, DialogAction("Quit, and don’t ask again", role: .secondary)],+ icon: .application, buttonSpacing: 45.5)+ switch alert.runModal() {+ case .alertFirstButtonReturn: return true+ case .alertThirdButtonReturn:+ store.settings.warnBeforeQuitting = false+ return true+ default: return false+ }}func openExternalURL(_ url: String) {@@ -1121,7 +1125,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {guard keyFallbackMonitor == nil else { return }keyFallbackMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in// Esc drops a ⌘/⇧-click tab selection before anything else sees it.- if event.keyCode == 53, let ui = self?.main.sidebarUI, !ui.multiSelection.isEmpty {+ if event.keyCode == 53, !(event.window is DialogPanel), let ui = self?.main.sidebarUI, !ui.multiSelection.isEmpty {ui.clearPicks()return nil}@@ -1180,6 +1184,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {}func perform(_ id: String) {+ if let dialog = NSApp.keyWindow as? DialogPanel, ["closeTab", "closeWindow"].contains(id) {+ dialog.close()+ return+ }store.recordCommandUse(id)// An extension's own window (Arc: BrowserExtensionWindowController.closeCurrentItem:)// closes on ⌘W instead of the tab behind it.@@ -1326,21 +1334,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {NSPasteboard.general.setString(s, forType: .string)}- func confirmDeleteSpace(_ space: Space) {+ func confirmDeleteSpace(_ space: Space, in window: NSWindow? = nil) {+ let window = window ?? main?.window ?? AppDialog.parentWindowguard store.spaceOrder.count > 1 else {- let a = NSAlert()- a.messageText = "You need at least one space."- a.runModal()+ let a = AppDialog(title: "You need at least one space.")+ a.runModal(over: window)return}- let a = NSAlert()- // Arc 1.171's copy (WindowsData+CloseItems).- a.messageText = "Delete your \(space.title) Space?"- a.informativeText = "This will archive all the tabs and folders inside it."- a.addButton(withTitle: "Delete")- a.addButton(withTitle: "Cancel")- a.alertStyle = .warning- if a.runModal() == .alertFirstButtonReturn { store.deleteSpace(space.id) }+ let a = AppDialog(title: "Delete your “\(space.title)” Space?",+ message: "This will archive all the tabs and folders inside it.",+ actions: [DialogAction("Delete", role: .destructive), .cancel])+ if a.runModal(over: window) == .alertFirstButtonReturn { store.deleteSpace(space.id) }}// MARK: Windowsdiff --git a/Sources/Cra/App/NewestCopy.swift b/Sources/Cra/App/NewestCopy.swiftindex 9c3602a..222dde8 100644--- a/Sources/Cra/App/NewestCopy.swift+++ b/Sources/Cra/App/NewestCopy.swift@@ -47,7 +47,7 @@ enum NewestCopy {/// A running Cra older than this one that owns our profile is asked to quit, so this/// launch takes over instead of being handed to it. Its SingletonLock names it/// ("host-pid"), which also leaves CRA_DATA_DIR copies on other profiles alone.- static func replaceOlderRunningCopy() {+ @MainActor static func replaceOlderRunningCopy() {guard let other = profileOwner(), let url = other.bundleURL,let theirs = shortVersion(at: url), isOlder(theirs, than: version) else { return }let pid = other.processIdentifier@@ -69,24 +69,21 @@ enum NewestCopy {/// prompt is up. That prompt is centred and its app is in front, so this one floats/// above the centre and stays visible while Cra is not active (the launch may not/// have activated it yet), and it closes by itself (.OK) once the old copy is gone.- private static func stillOpenAlert(_ theirs: String, pid: pid_t) -> NSApplication.ModalResponse {- let alert = NSAlert()- alert.messageText = "Cra \(theirs) is still open"- alert.informativeText = "Quit it to open Cra \(version). If it asked whether to quit, choose Quit."- alert.addButton(withTitle: "Try Again")- alert.addButton(withTitle: "Force Quit")- alert.addButton(withTitle: "Cancel")- alert.layout()- alert.window.hidesOnDeactivate = false+ @MainActor private static func stillOpenAlert(_ theirs: String, pid: pid_t) -> NSApplication.ModalResponse {+ let alert = AppDialog(title: "Cra \(theirs) is still open",+ message: "Quit it to open Cra \(version). If it asked whether to quit, choose Quit.",+ actions: [DialogAction("Try Again"), DialogAction("Force Quit", role: .destructive), .cancel])+ let window = alert.prepareWindow()+ window.hidesOnDeactivate = falseif let screen = NSScreen.main?.visibleFrame {- let size = alert.window.frame.size- alert.window.setFrameOrigin(NSPoint(x: screen.midX - size.width / 2, y: screen.midY + 170))+ let size = window.frame.size+ window.setFrameOrigin(NSPoint(x: screen.midX - size.width / 2, y: screen.midY + 170))}// runModal resets the level, so raise it once the modal session runs.RunLoop.current.perform(inModes: [.modalPanel]) {MainActor.assumeIsolated {- alert.window.level = .floating- alert.window.orderFrontRegardless()+ window.level = .floating+ window.orderFrontRegardless()}}let gone = Timer(timeInterval: 0.2, repeats: true) { _ in@@ -94,7 +91,7 @@ enum NewestCopy {}RunLoop.current.add(gone, forMode: .modalPanel)defer { gone.invalidate() }- return alert.runModal()+ return alert.runModal(over: nil)}private static func profileOwner() -> NSRunningApplication? {diff --git a/Sources/Cra/App/main.swift b/Sources/Cra/App/main.swiftindex 8e65543..7c354cd 100644--- a/Sources/Cra/App/main.swift+++ b/Sources/Cra/App/main.swift@@ -64,9 +64,8 @@ MainActor.assumeIsolated {exit(0)}if !started {- let alert = NSAlert()- alert.messageText = "Cra could not start Chromium"- alert.informativeText = "Chromium Embedded Framework failed to initialize. See \(AppPaths.log.path)."+ let alert = AppDialog(title: "Cra could not start Chromium",+ message: "Chromium Embedded Framework failed to initialize. See \(AppPaths.log.path).")alert.runModal()exit(1)}diff --git a/Sources/Cra/Perf/PerformancePane.swift b/Sources/Cra/Perf/PerformancePane.swiftindex 7dcc6b7..8513bfa 100644--- a/Sources/Cra/Perf/PerformancePane.swift+++ b/Sources/Cra/Perf/PerformancePane.swift@@ -210,11 +210,9 @@ struct PerformancePane: View {}private func confirmClear() {- let alert = NSAlert()- alert.messageText = "Clear the performance recording?"- alert.informativeText = "This session's numbers, the last 24 hours and saved freezes are deleted."- alert.addButton(withTitle: "Clear")- alert.addButton(withTitle: "Cancel")+ let alert = AppDialog(title: "Clear the performance recording?",+ message: "This session's numbers, the last 24 hours and saved freezes are deleted.",+ actions: [DialogAction("Clear", role: .destructive), .cancel])guard alert.runModal() == .alertFirstButtonReturn else { return }PerfRecorder.clear()report = nildiff --git a/Sources/Cra/Services/AppLinkPrompt.swift b/Sources/Cra/Services/AppLinkPrompt.swiftindex f81c95a..7b19b2d 100644--- a/Sources/Cra/Services/AppLinkPrompt.swift+++ b/Sources/Cra/Services/AppLinkPrompt.swift@@ -44,12 +44,10 @@ enum AppLinkPrompt {return true}CraLog.note("page \(page) asks to open \(name) for \(scheme)")- let alert = NSAlert()- alert.messageText = "Open \(name)?"- alert.informativeText = "\(URL(string: browser.currentURL)?.host ?? "This site") wants to open this application."- alert.addButton(withTitle: "Open \(name)")- alert.addButton(withTitle: "Cancel")- alert.beginSheetModal(for: window) { response in+ let alert = AppDialog(title: "Open \(name)?",+ message: "\(URL(string: browser.currentURL)?.host ?? "This site") wants to open this application.",+ actions: [DialogAction("Open \(name)"), .cancel])+ alert.present(over: window) { response inif response == .alertFirstButtonReturn { NSWorkspace.shared.open(target) }}return truediff --git a/Sources/Cra/Services/ArcProfileRebuilder.swift b/Sources/Cra/Services/ArcProfileRebuilder.swiftindex 01bb1c3..1f2145a 100644--- a/Sources/Cra/Services/ArcProfileRebuilder.swift+++ b/Sources/Cra/Services/ArcProfileRebuilder.swift@@ -21,13 +21,11 @@ enum ArcProfileRebuilder {alert("No spaces to move", "Every space named like one of your Arc spaces is already on the right profile, or Arc has it on its Default profile.")return}- let a = NSAlert()- a.messageText = "Move \(moves.count == 1 ? "this space" : "these spaces") to \(moves.count == 1 ? "its" : "their") Arc profile\(moves.count == 1 ? "" : "s")?"- a.informativeText = moves.map { "\($0.spaceTitle) → \($0.profileName)" }.joined(separator: "\n") + "\n\n"+ let message = moves.map { "\($0.spaceTitle) → \($0.profileName)" }.joined(separator: "\n") + "\n\n"+ "Cra brings over the sign-ins, passwords and extensions these Arc profiles have, so the spaces work as they did in Arc. "+ "Sign-ins and passwords you added in Cra since the import stay with Default. macOS asks for your password to unlock Arc's data, then Cra restarts."- a.addButton(withTitle: "Move and Restart")- a.addButton(withTitle: "Cancel")+ let a = AppDialog(title: "Move \(moves.count == 1 ? "this space" : "these spaces") to \(moves.count == 1 ? "its" : "their") Arc profile\(moves.count == 1 ? "" : "s")?",+ message: message, actions: [DialogAction("Move and Restart"), .cancel])guard a.runModal() == .alertFirstButtonReturn else { return }let folders = Set(moves.map(\.folder))@@ -43,11 +41,9 @@ enum ArcProfileRebuilder {case .success(let c): credentials = ccase .failure(let error):CraLog.note("rebuild from Arc: sign-ins not read: \(error.localizedDescription)")- let b = NSAlert()- b.messageText = "Move the spaces without their sign-ins?"- b.informativeText = "\(error.localizedDescription) The spaces would start signed out of every site. Cancel changes nothing."- b.addButton(withTitle: "Move Without Sign-ins")- b.addButton(withTitle: "Cancel")+ let b = AppDialog(title: "Move the spaces without their sign-ins?",+ message: "\(error.localizedDescription) The spaces would start signed out of every site. Cancel changes nothing.",+ actions: [DialogAction("Move Without Sign-ins"), .cancel])guard b.runModal() == .alertFirstButtonReturn else { return }}}@@ -82,9 +78,7 @@ enum ArcProfileRebuilder {}private static func alert(_ title: String, _ text: String) {- let a = NSAlert()- a.messageText = title- a.informativeText = text+ let a = AppDialog(title: title, message: text)a.runModal()}}diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swiftindex 40463f0..abd923c 100644--- a/Sources/Cra/Services/BrowserManager.swift+++ b/Sources/Cra/Services/BrowserManager.swift@@ -1360,12 +1360,10 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {}func browser(_ browser: CraBrowser, requestsPermissionForOrigin origin: String, kinds: UInt, completion: @escaping (Bool) -> Void) {- let alert = NSAlert()- alert.messageText = PermissionPrompt.message(origin: origin, kinds: kinds)- alert.addButton(withTitle: "Allow")- alert.addButton(withTitle: "Block")+ let alert = AppDialog(title: PermissionPrompt.message(origin: origin, kinds: kinds),+ actions: [DialogAction("Allow"), DialogAction("Block", role: .cancel)])guard let window = container.window else { completion(false); return }- alert.beginSheetModal(for: window) { resp in completion(resp == .alertFirstButtonReturn) }+ alert.present(over: window) { resp in completion(resp == .alertFirstButtonReturn) }}func browserDidReceiveFocus(_ browser: CraBrowser) {diff --git a/Sources/Cra/Services/Diagnostics.swift b/Sources/Cra/Services/Diagnostics.swiftindex c9f9f8c..ee98c39 100644--- a/Sources/Cra/Services/Diagnostics.swift+++ b/Sources/Cra/Services/Diagnostics.swift@@ -110,9 +110,7 @@ enum Diagnostics {}try? fm.removeItem(at: staging)guard ditto.terminationStatus == 0, fm.fileExists(atPath: destination.path) else {- let alert = NSAlert()- alert.messageText = "Cra couldn’t save the diagnostics"- alert.informativeText = "Try another folder."+ let alert = AppDialog(title: "Cra couldn’t save the diagnostics", message: "Try another folder.")alert.runModal()return}diff --git a/Sources/Cra/Services/SidebarExport.swift b/Sources/Cra/Services/SidebarExport.swiftindex 693e584..e8b3e36 100644--- a/Sources/Cra/Services/SidebarExport.swift+++ b/Sources/Cra/Services/SidebarExport.swift@@ -67,7 +67,7 @@ enum SidebarExport {try html.write(to: url, atomically: true, encoding: .utf8)NSWorkspace.shared.activateFileViewerSelecting([url])} catch {- NSAlert(error: error).runModal()+ DispatchQueue.main.async { AppDialog(error: error).runModal(over: window ?? AppDialog.parentWindow) }}}if let window { panel.beginSheetModal(for: window, completionHandler: done) } else { done(panel.runModal()) }diff --git a/Sources/Cra/UI/Colors.swift b/Sources/Cra/UI/Colors.swiftnew file mode 100644index 0000000..9e6f172--- /dev/null+++ b/Sources/Cra/UI/Colors.swift@@ -0,0 +1,22 @@+import AppKit+import SwiftUI++extension Color {+ init(hex: String) {+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)+ self.init(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: 1)+ }++ init(_ c: RGB) { self.init(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: 1) }+}++extension NSColor {+ convenience init(hex: String) {+ let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)+ self.init(srgbRed: c.r, green: c.g, blue: c.b, alpha: 1)+ }++ convenience init(_ c: RGB, alpha: CGFloat = 1) {+ self.init(srgbRed: c.r, green: c.g, blue: c.b, alpha: alpha)+ }+}diff --git a/Sources/Cra/UI/ExtensionsMenu.swift b/Sources/Cra/UI/ExtensionsMenu.swiftindex 6221b13..ef7f043 100644--- a/Sources/Cra/UI/ExtensionsMenu.swift+++ b/Sources/Cra/UI/ExtensionsMenu.swift@@ -111,7 +111,7 @@ final class ExtensionsMenu: NSObject, NSMenuDelegate, NSMenuItemValidation {panel.allowedContentTypes = [.image]panel.message = "Choose an icon for \(e.name)'s toolbar button"guard panel.runModal() == .OK, let url = panel.url else { return }- do { try store.setCustomIcon(id, from: url) } catch { NSAlert(error: error).runModal() }+ do { try store.setCustomIcon(id, from: url) } catch { AppDialog(error: error).runModal() }}choose.state = style.imageFile != nil ? .on : .offmenu.addItem(choose)diff --git a/Sources/Cra/UI/Settings/ProfilesPane.swift b/Sources/Cra/UI/Settings/ProfilesPane.swiftindex eafd582..34cf3d1 100644--- a/Sources/Cra/UI/Settings/ProfilesPane.swift+++ b/Sources/Cra/UI/Settings/ProfilesPane.swift@@ -9,9 +9,6 @@ struct ProfilesPane: View {let nav: SettingsNavigationlet actions: SettingsActions@Environment(SidebarStore.self) private var store- @State private var naming: BrowserProfile?- @State private var name = ""- @State private var deleting: BrowserProfile?var body: some View {SettingsCardPane {@@ -21,8 +18,8 @@ struct ProfilesPane: View {ForEach(store.profiles) { p inSettingsCardDivider()row(name: p.name, profileID: p.id) {- Button("Rename…") { name = p.name; naming = p }- Button("Delete…") { deleting = p }+ Button("Rename…") { rename(p) }+ Button("Delete…") { delete(p) }.disabled(!store.spaces(usingProfile: p.id).isEmpty)}}@@ -61,17 +58,6 @@ struct ProfilesPane: View {.id(nav.shown) // read again each time Settings comes up: Chromium's page may have changed themSettingsFootnote("The languages websites show their pages in for each Profile, most wanted first. Change opens Chromium’s language settings for that Profile. Cra itself stays in English.")}- .alert("Rename Profile", isPresented: Binding(get: { naming != nil }, set: { if !$0 { naming = nil } })) {- TextField("Profile name", text: $name)- Button("Rename") { if let p = naming { store.renameProfile(p.id, to: trimmed) } }- Button("Cancel", role: .cancel) {}- }- .alert("Delete “\(deleting?.name ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {- Button("Delete", role: .destructive) { if let p = deleting { store.deleteProfile(p.id) } }- Button("Cancel", role: .cancel) {}- } message: {- Text("Deleting this Profile will permanently remove any cookies, history, preferences, and logins that belong to it.")- }}private enum DownloadChoice: Hashable { case folder, ask, other }@@ -147,7 +133,27 @@ struct ProfilesPane: View {.flatMap(BrowserLanguages.codes(preferencesFile:)) ?? []}- private var trimmed: String { name.trimmingCharacters(in: .whitespaces) }+ private func rename(_ profile: BrowserProfile) {+ guard let window = AppDialog.parentWindow else { return }+ let dialog = AppDialog(title: "Rename your Profile",+ message: "This won’t affect the names of any of the Spaces associated with this Profile.",+ actions: [DialogAction("Save"), .cancel], input: profile.name, placeholder: "Profile name", requiresInput: true,+ icon: .none, width: 496, buttonSpacing: 30, buttonOutset: 0)+ dialog.present(over: window) { response in+ guard response == .alertFirstButtonReturn, let name = dialog.input else { return }+ store.renameProfile(profile.id, to: name.trimmingCharacters(in: .whitespacesAndNewlines))+ }+ }++ private func delete(_ profile: BrowserProfile) {+ guard let window = AppDialog.parentWindow else { return }+ let dialog = AppDialog(title: "Delete “\(profile.name)”?",+ message: "Deleting this Profile will permanently remove any cookies, history, preferences, and logins that belong to it.",+ actions: [DialogAction("Delete Profile", role: .destructive), .cancel])+ dialog.present(over: window) { response in+ if response == .alertFirstButtonReturn { store.deleteProfile(profile.id) }+ }+ }private func row<Trailing: View>(name: String, profileID: UUID?, @ViewBuilder trailing: () -> Trailing) -> some View {let spaces = store.spaces(usingProfile: profileID)diff --git a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swiftindex b9849bd..631c6db 100644--- a/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift+++ b/Sources/Cra/UI/Sidebar/List/SidebarMenus.swift@@ -212,21 +212,19 @@ enum SidebarMenus {copy(lines.joined(separator: "\n"))}menu.addItem(.separator())- add(menu, "Delete Live Folder") { confirmDeleteLiveFolder(item, store: store) }+ let window = list.window+ add(menu, "Delete Live Folder") { confirmDeleteLiveFolder(item, store: store, in: window) }return menu}- /// Arc asks first ("Delete your %@ Live Folder?") and says how to get it back.- static func confirmDeleteLiveFolder(_ item: SidebarItem, store: SidebarStore) {- let alert = NSAlert()- alert.messageText = "Delete your \(item.title ?? "Pull Requests") Live Folder?"- alert.informativeText = "You can add it again with New GitHub Live Folder in the sidebar’s menu or the command bar."- alert.addButton(withTitle: "Delete")- alert.addButton(withTitle: "Cancel")- alert.buttons.first?.hasDestructiveAction = true+ /// Arc asks first ("Delete your %@ Live Folder?") and says how to get it back, in its own words.+ static func confirmDeleteLiveFolder(_ item: SidebarItem, store: SidebarStore, in window: NSWindow? = nil) {+ let alert = AppDialog(title: "Delete your \(item.title ?? "Pull Requests") Live Folder?",+ message: "You can restore this folder at any time by right-clicking the sidebar.",+ actions: [DialogAction("Delete Folder", role: .destructive), .cancel])let id = item.id- if let window = NSApp.keyWindow {- alert.beginSheetModal(for: window) { if $0 == .alertFirstButtonReturn { store.deleteFolder(id) } }+ if let window = window ?? AppDialog.parentWindow {+ alert.present(over: window) { if $0 == .alertFirstButtonReturn { store.deleteFolder(id) } }} else if alert.runModal() == .alertFirstButtonReturn {store.deleteFolder(id)}diff --git a/Sources/Cra/UI/Theme.swift b/Sources/Cra/UI/Theme.swiftindex dbe6fd5..0a24a36 100644--- a/Sources/Cra/UI/Theme.swift+++ b/Sources/Cra/UI/Theme.swift@@ -2,26 +2,6 @@ import AppKitimport Observationimport SwiftUI-extension Color {- init(hex: String) {- let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)- self.init(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: 1)- }-- init(_ c: RGB) { self.init(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: 1) }-}--extension NSColor {- convenience init(hex: String) {- let c = HexColor.components(hex) ?? (0.5, 0.5, 0.5)- self.init(srgbRed: c.r, green: c.g, blue: c.b, alpha: 1)- }-- convenience init(_ c: RGB, alpha: CGFloat = 1) {- self.init(srgbRed: c.r, green: c.g, blue: c.b, alpha: alpha)- }-}-/// Colors derived from a space theme, the way Arc derives a/// semanticColorPalette from the window theme.struct SpacePalette {diff --git a/Sources/Cra/UI/Windows/AppDialog.swift b/Sources/Cra/UI/Windows/AppDialog.swiftnew file mode 100644index 0000000..ba99c01--- /dev/null+++ b/Sources/Cra/UI/Windows/AppDialog.swift@@ -0,0 +1,219 @@+import AppKit+import Observation+import SwiftUI++@MainActor+@Observable+final class AppDialog {+ enum Icon { case mark, application, none }++ let title: String+ let message: String+ let actions: DialogActions+ let icon: Icon+ let width: CGFloat+ let buttonSpacing: CGFloat+ let buttonOutset: CGFloat+ var input: String?+ let placeholder: String+ let requiresInput: Bool+ let suppressionTitle: String?+ var isSuppressed = false+ private var presentedWindow: DialogPanel?+ private var completion: ((NSApplication.ModalResponse) -> Void)?+ private var runningModal = false+ private var result = NSApplication.ModalResponse.abort++ init(title: String, message: String = "", actions: [DialogAction] = [DialogAction("OK")],+ input: String? = nil, placeholder: String = "", requiresInput: Bool = false, suppressionTitle: String? = nil,+ icon: Icon = .mark, width: CGFloat = 450, buttonSpacing: CGFloat = 38, buttonOutset: CGFloat = 10.5) {+ self.title = title+ self.message = message+ self.actions = DialogActions(actions)+ self.icon = icon+ self.width = width+ self.buttonSpacing = buttonSpacing+ self.buttonOutset = buttonOutset+ self.input = input+ self.placeholder = placeholder+ self.requiresInput = requiresInput+ self.suppressionTitle = suppressionTitle+ }++ convenience init(error: Error) {+ let error = error as NSError+ self.init(title: error.localizedDescription, message: error.localizedRecoverySuggestion ?? error.localizedFailureReason ?? "")+ }++ static var parentWindow: NSWindow? {+ let candidates = [NSApp.keyWindow, NSApp.mainWindow].compactMap { $0 } + NSApp.orderedWindows+ for candidate in candidates {+ var window = candidate+ while let parent = window.parent { window = parent }+ if window.isVisible && window.canBecomeMain { return window }+ }+ return nil+ }++ @discardableResult+ func runModal() -> NSApplication.ModalResponse {+ runModal(over: Self.parentWindow)+ }++ @discardableResult+ func runModal(over parent: NSWindow?) -> NSApplication.ModalResponse {+ if let parent, parent.attachedSheet != nil { return .abort }+ let window = prepareWindow(over: parent)+ runningModal = true+ window.show()+ let response = NSApp.runModal(for: window)+ runningModal = false+ window.close()+ return response+ }++ func present(over parent: NSWindow, completion: @escaping (NSApplication.ModalResponse) -> Void) {+ guard parent.attachedSheet == nil else {+ completion(.abort)+ return+ }+ self.completion = completion+ prepareWindow(over: parent).show()+ }++ func prepareWindow(over parent: NSWindow? = nil) -> DialogPanel {+ if let window = presentedWindow { return window }+ result = .abort+ let window = DialogPanel(over: parent, content: AppDialogView(dialog: self))+ window.title = title+ window.onDismiss = { [self] in+ presentedWindow = nil+ let done = completion+ completion = nil+ if runningModal { NSApp.stopModal(withCode: result) }+ done?(result)+ }+ window.handleKey = { [weak self] event in+ guard let self, event.modifierFlags.intersection([.command, .control, .option, .shift]).isEmpty else { return false }+ if event.keyCode == 53 {+ if let index = actions.cancelIndex { select(index) }+ return true+ }+ if event.keyCode == 36 || event.keyCode == 76 {+ if let index = actions.defaultIndex { select(index) }+ return true+ }+ return false+ }+ presentedWindow = window+ return window+ }++ func select(_ index: Int) {+ guard let window = presentedWindow, !window.isDismissing, actions.buttons.indices.contains(index),+ actions.isEnabled(at: index, input: input, requiresInput: requiresInput) else { return }+ result = NSApplication.ModalResponse(rawValue: NSApplication.ModalResponse.alertFirstButtonReturn.rawValue + index)+ window.close()+ }+}++private struct AppDialogView: View {+ @Bindable var dialog: AppDialog+ @FocusState private var inputFocused: Bool++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ DialogScrollContent(width: dialog.width - 77, maximumHeight: max(140, (NSScreen.main?.visibleFrame.height ?? 800) - 250)) {+ details+ }+ // Arc's extra choice ("Quit, and don’t ask again") sits at the card's left edge, the rest at its right.+ HStack(spacing: 7) {+ buttons(dialog.actions.leadingOrder)+ Spacer(minLength: 0)+ buttons(dialog.actions.trailingOrder)+ }+ .fixedSize(horizontal: false, vertical: true)+ .padding(.horizontal, -dialog.buttonOutset)+ .padding(.top, dialog.buttonSpacing)+ }+ .padding(.horizontal, 38.5)+ .padding(.top, 38.5)+ .padding(.bottom, 28)+ .frame(width: dialog.width)+ .fixedSize(horizontal: false, vertical: true)+ .modifier(DialogSurface(cornerRadius: 16))+ .onAppear { inputFocused = dialog.input != nil }+ }++ private var details: some View {+ VStack(alignment: .leading, spacing: 0) {+ if dialog.icon != .none {+ ZStack {+ if dialog.icon == .application {+ Image(nsImage: NSApp.applicationIconImage).resizable()+ } else {+ BrandMark(size: 56)+ }+ }+ // Arc 1.172.1 (7 Nov 2026, Quit and Delete Space sheets against Cra's, card edge to pixel): the app+ // icon shows 50.5 pt across from 43.5 pt in, the title's caps start 120 pt down, the buttons end+ // 26.5 pt from the card's right edge.+ .frame(width: dialog.icon == .mark ? 61 : 62, height: dialog.icon == .mark ? 61 : 62)+ .offset(y: dialog.icon == .application ? 0.75 : 0)+ .padding(.top, dialog.icon == .application ? -1 : 0)+ .accessibilityHidden(true)+ }+ Text(dialog.title)+ .font(.system(size: 17.5, weight: .semibold))+ .foregroundStyle(.white)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.top, dialog.icon == .none ? 0 : dialog.icon == .application ? 18 : 17.5)+ if !dialog.message.isEmpty {+ Text(dialog.message)+ .font(.system(size: 14))+ .lineSpacing(0.7)+ .foregroundStyle(DialogTheme.body)+ .fixedSize(horizontal: false, vertical: true)+ .padding(.top, 16)+ }+ if dialog.input != nil {+ TextField(dialog.placeholder, text: Binding(get: { dialog.input ?? "" }, set: { dialog.input = $0 }))+ .textFieldStyle(.plain)+ .font(.system(size: 14))+ .foregroundStyle(.white)+ .focused($inputFocused)+ .padding(.horizontal, 12)+ .frame(height: 37)+ .background(RoundedRectangle(cornerRadius: 6).fill(Color(hex: "#383E4F")))+ .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Color(hex: "#737884"), lineWidth: 1))+ .padding(.top, 18)+ }+ if let title = dialog.suppressionTitle {+ Toggle(title, isOn: $dialog.isSuppressed)+ .toggleStyle(.checkbox)+ .font(.system(size: 13))+ .foregroundStyle(DialogTheme.body)+ .padding(.top, 18)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .fixedSize(horizontal: false, vertical: true)+ }++ private func buttons(_ order: [Int]) -> some View {+ ForEach(order, id: \.self) { index in+ let action = dialog.actions.buttons[index]+ DialogButton(title: action.title, key: dialog.actions.key(at: index),+ enabled: dialog.actions.isEnabled(at: index, input: dialog.input, requiresInput: dialog.requiresInput),+ style: style(action.role)) { dialog.select(index) }+ }+ }++ private func style(_ role: DialogAction.Role) -> DialogButton.Style {+ switch role {+ case .primary: return .accent+ case .destructive: return .destructive+ case .secondary, .cancel: return .secondary+ }+ }+}diff --git a/Sources/Cra/UI/Windows/DialogComponents.swift b/Sources/Cra/UI/Windows/DialogComponents.swiftnew file mode 100644index 0000000..8fbb77b--- /dev/null+++ b/Sources/Cra/UI/Windows/DialogComponents.swift@@ -0,0 +1,224 @@+import AppKit+import SwiftUI++/// Arc's dialog card (measured against Arc 1.172.1's Quit and Delete Space sheets, 7 Nov 2026: #161C2F).+enum DialogTheme {+ static let card = Color(hex: "#161C2F")+ static let body = Color(hex: "#B8B9C4")+}++/// The card a dialog draws on. The sheet it sits in already has macOS's 1 pt light edge, as Arc's does,+/// so the card draws none of its own.+struct DialogSurface: ViewModifier {+ var cornerRadius: CGFloat = 24++ func body(content: Content) -> some View {+ content+ .background(DialogTheme.card, in: RoundedRectangle(cornerRadius: cornerRadius, style: .continuous))+ .environment(\.colorScheme, .dark)+ }+}++struct DialogButton: View {+ enum Style {+ case secondary, primary, accent, destructive++ /// Arc 1.172.1's Quit sheet under the pointer: 10 % white over Cancel (#302F60 → #454470, its key+ /// badge too), 10 % black over Quit (#3339F1 → #2D33D9).+ var hoverTint: Color { self == .secondary ? .white : .black }+ }+ let title: String+ let key: String+ let enabled: Bool+ let style: Style+ var badge: CGSize?+ let action: () -> Void+ @State private var hovered = false++ init(title: String, key: String, enabled: Bool, primary: Bool, action: @escaping () -> Void) {+ self.init(title: title, key: key, enabled: enabled, style: primary ? .primary : .secondary, action: action)+ }++ init(title: String, key: String, enabled: Bool, style: Style, badge: CGSize? = nil, action: @escaping () -> Void) {+ self.title = title+ self.key = key+ self.enabled = enabled+ self.style = style+ self.badge = badge+ self.action = action+ }++ // Destructive (Delete in Arc's Delete Space and Delete Live Folder sheets): fill #E2492C, no lighter rim,+ // key badge #E55B41 edged #E86D56 as captured; the hex values here render to those on Cra's sheets.+ private var accent: Bool { style == .accent && enabled }+ private var destructive: Bool { style == .destructive && enabled }+ private var primary: Bool { style != .secondary }++ var body: some View {+ Button(action: action) {+ HStack(spacing: 9) {+ Text(title).font(.system(size: 13, weight: .medium))+ .foregroundStyle(accent || destructive ? .white : enabled ? Color(hex: "#EBEBEF") : Color(hex: "#5B5C7F"))+ if !key.isEmpty {+ Text(key).font(.system(size: key == "↩" ? 13 : 11, weight: .bold))+ .foregroundStyle(destructive ? .white : accent ? Color(hex: "#EDEDFF") : enabled ? Color(hex: "#B7B7DD") : Color(hex: "#5F6193"))+ .frame(minWidth: badge?.width ?? 27, maxWidth: badge?.width, minHeight: badge?.height ?? 19, maxHeight: badge?.height)+ .padding(.horizontal, badge != nil || key == "↩" ? 0 : 2)+ .background(RoundedRectangle(cornerRadius: badge == nil ? 5 : 3, style: .continuous)+ .fill(destructive ? Color(hex: "#F74C31") : accent ? Color(hex: "#464DFB") : primary ? Color(hex: enabled ? "#4E4C9A" : "#222469") : Color(hex: "#4E4C77")))+ .overlay(RoundedRectangle(cornerRadius: badge == nil ? 5 : 3, style: .continuous)+ .strokeBorder(destructive ? Color(hex: "#FA624C") : accent ? Color(hex: "#6B71FE") : .clear, lineWidth: 1))+ }+ }+ .padding(.leading, 12.5)+ .padding(.trailing, 12)+ .frame(height: 37)+ .background(+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .fill(destructive ? Color(hex: "#F53516") : accent ? Color(hex: "#3239FB") : primary ? Color(hex: enabled ? "#3B3C8F" : "#1C1D4C") : Color(hex: "#302F60"))+ )+ .overlay(+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ .strokeBorder(destructive ? Color(hex: "#F53516") : accent ? Color(hex: "#5B61FD") : primary ? (enabled ? Color(hex: "#6362A9") : .clear) : Color(hex: "#6362A9"), lineWidth: 1)+ )+ .background(+ RoundedRectangle(cornerRadius: 8, style: .continuous)+ // Arc's default buttons sit on a darker lip, ~1.5 pt below: blue for Quit and Save, a dark+ // red for Delete (#41232A in Arc 1.172.1's Delete Space sheet).+ .fill(style == .accent ? Color(hex: enabled ? "#2C3475" : "#1D2259") : destructive ? Color(hex: "#41232A") : .clear)+ .offset(y: 1.5)+ )+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous)+ .fill(style.hoverTint.opacity(hovered && enabled ? 0.1 : 0))+ .allowsHitTesting(false))+ }+ .buttonStyle(.plain)+ .disabled(!enabled)+ .onHover { hovered = $0 }+ .animation(.easeOut(duration: 0.1), value: hovered)+ .accessibilityLabel(title)+ .fixedSize()+ }+}++struct DialogScrollContent<Content: View>: NSViewRepresentable {+ let width: CGFloat+ let maximumHeight: CGFloat+ let content: () -> Content++ init(width: CGFloat, maximumHeight: CGFloat, @ViewBuilder content: @escaping () -> Content) {+ self.width = width+ self.maximumHeight = maximumHeight+ self.content = content+ }++ func makeNSView(context: Context) -> NSScrollView {+ let scroll = NSScrollView()+ scroll.drawsBackground = false+ scroll.autohidesScrollers = true+ scroll.scrollerStyle = .overlay+ scroll.borderType = .noBorder+ scroll.horizontalScrollElasticity = .none+ scroll.documentView = NSHostingView(rootView: AnyView(content().frame(width: width, alignment: .leading)))+ return scroll+ }++ func updateNSView(_ scroll: NSScrollView, context: Context) {+ guard let host = scroll.documentView as? NSHostingView<AnyView> else { return }+ host.rootView = AnyView(content().frame(width: width, alignment: .leading))+ resize(scroll)+ }++ func sizeThatFits(_ proposal: ProposedViewSize, nsView scroll: NSScrollView, context: Context) -> CGSize? {+ resize(scroll)+ }++ @discardableResult+ private func resize(_ scroll: NSScrollView) -> CGSize {+ guard let host = scroll.documentView else { return .zero }+ let height = host.fittingSize.height+ host.setFrameSize(NSSize(width: width, height: height))+ scroll.hasVerticalScroller = height > maximumHeight+ scroll.contentView.scroll(to: NSPoint(x: 0, y: host.isFlipped ? 0 : max(0, height - maximumHeight)))+ return CGSize(width: width, height: min(height, maximumHeight))+ }+}++final class DialogPanel: NSPanel {+ var onDismiss: (() -> Void)?+ var handleKey: ((NSEvent) -> Bool)?+ private weak var owner: NSWindow?+ private var parentObserver: NSObjectProtocol?+ private(set) var isDismissing = false+ private var isClosed = false++ override var canBecomeKey: Bool { true }++ convenience init<Content: View>(over parent: NSWindow?, content: Content) {+ self.init(contentRect: .zero, styleMask: [.titled], backing: .buffered, defer: false)+ isReleasedWhenClosed = false+ isOpaque = false+ backgroundColor = .clear+ titleVisibility = .hidden+ titlebarAppearsTransparent = true+ hidesOnDeactivate = false+ let host = NSHostingView(rootView: content)+ contentView = host+ setContentSize(host.fittingSize)+ owner = parent+ if let parent {+ parentObserver = NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: parent, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.close() }+ }+ } else {+ center()+ }+ }++ func show() {+ if let owner {+ owner.beginSheet(self) { [weak self] _ in self?.finishClose() }+ } else {+ makeKeyAndOrderFront(nil)+ }+ }++ override func sendEvent(_ event: NSEvent) {+ if event.type == .keyDown, handleKey?(event) == true { return }+ super.sendEvent(event)+ }++ override func close() {+ guard !isClosed, !isDismissing else { return }+ isDismissing = true+ if let parent = sheetParent {+ parent.endSheet(self)+ } else {+ finishClose()+ }+ }++ private func finishClose() {+ guard !isClosed else { return }+ isClosed = true+ let dismissed = onDismiss+ onDismiss = nil+ handleKey = nil+ if let parentObserver { NotificationCenter.default.removeObserver(parentObserver) }+ parentObserver = nil+ orderOut(nil)+ super.close()+ dismissed?()+ }++ @discardableResult+ static func present<Content: View>(over parent: NSWindow, _ content: (@escaping () -> Void) -> Content) -> Bool {+ guard parent.attachedSheet == nil else { return false }+ var panel: DialogPanel?+ let window = DialogPanel(over: parent, content: content { panel?.close() })+ panel = window+ window.onDismiss = { panel = nil }+ window.show()+ return true+ }+}diff --git a/Sources/Cra/UI/Windows/EditPinnedURLDialog.swift b/Sources/Cra/UI/Windows/EditPinnedURLDialog.swiftindex 44cd1c9..3737b98 100644--- a/Sources/Cra/UI/Windows/EditPinnedURLDialog.swift+++ b/Sources/Cra/UI/Windows/EditPinnedURLDialog.swift@@ -10,9 +10,6 @@ struct EditPinnedURLDialog: View {@State private var text: String@FocusState private var focused: Bool- private static let card = Color(hex: "#161C2F")- private static let body = Color(hex: "#B8B9C4")-init(url: String, onSave: @escaping (String) -> Void, onCancel: @escaping () -> Void) {self.onSave = onSaveself.onCancel = onCancel@@ -32,7 +29,7 @@ struct EditPinnedURLDialog: View {Text("This is what opens first when you click this tab or its favicon.").font(.system(size: 14)).lineSpacing(0.8)- .foregroundStyle(Self.body)+ .foregroundStyle(DialogTheme.body).fixedSize(horizontal: false, vertical: true).frame(width: 304, height: 35, alignment: .topLeading).padding(.top, 16)@@ -62,8 +59,7 @@ struct EditPinnedURLDialog: View {Spacer(minLength: 0)}.frame(width: 393, height: 265)- .background(Self.card, in: RoundedRectangle(cornerRadius: 24, style: .continuous))- .environment(\.colorScheme, .dark)+ .modifier(DialogSurface()).onAppear { focused = true }}}diff --git a/Sources/Cra/UI/Windows/LittleWindowController.swift b/Sources/Cra/UI/Windows/LittleWindowController.swiftindex 35e65c4..5f59281 100644--- a/Sources/Cra/UI/Windows/LittleWindowController.swift+++ b/Sources/Cra/UI/Windows/LittleWindowController.swift@@ -856,16 +856,12 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precofunc changeProfile(to id: UUID?) {guard id != state.profileID, let window else { return }if UserDefaults.standard.bool(forKey: Self.bypassProfileDialogKey) { reload(inProfile: id); return }- let alert = NSAlert()- alert.messageText = "Open this page in \(store.profile(id)?.name ?? "Default")?"- alert.informativeText = "Each Profile has different browser data, so this webpage might look a little different."- alert.addButton(withTitle: "Change Profile")- alert.addButton(withTitle: "Cancel")- alert.showsSuppressionButton = true- alert.suppressionButton?.title = "Don’t ask again"- alert.beginSheetModal(for: window) { [weak self, weak alert] resp in+ let alert = AppDialog(title: "Open this page in \(store.profile(id)?.name ?? "Default")?",+ message: "Each Profile has different browser data, so this webpage might look a little different.",+ actions: [DialogAction("Change Profile"), .cancel], suppressionTitle: "Don’t ask again")+ alert.present(over: window) { [weak self, weak alert] resp inguard let self, resp == .alertFirstButtonReturn else { return }- if alert?.suppressionButton?.state == .on { UserDefaults.standard.set(true, forKey: Self.bypassProfileDialogKey) }+ if alert?.isSuppressed == true { UserDefaults.standard.set(true, forKey: Self.bypassProfileDialogKey) }self.reload(inProfile: id)}}@@ -1183,12 +1179,10 @@ final class LittleWindowController: NSWindowController, NSWindowDelegate, @precofunc browser(_ browser: CraBrowser, requestsPermissionForOrigin origin: String, kinds: UInt, completion: @escaping (Bool) -> Void) {// The main window's sheet. A quiet notification deny here would save a block for the// site that its tabs then hit too (#137).- let alert = NSAlert()- alert.messageText = PermissionPrompt.message(origin: origin, kinds: kinds)- alert.addButton(withTitle: "Allow")- alert.addButton(withTitle: "Block")+ let alert = AppDialog(title: PermissionPrompt.message(origin: origin, kinds: kinds),+ actions: [DialogAction("Allow"), DialogAction("Block", role: .cancel)])guard let window else { completion(false); return }- alert.beginSheetModal(for: window) { resp in completion(resp == .alertFirstButtonReturn) }+ alert.present(over: window) { resp in completion(resp == .alertFirstButtonReturn) }}func browserDidReceiveFocus(_ browser: CraBrowser) {}diff --git a/Sources/Cra/UI/Windows/MainWindowController+SpaceMenu.swift b/Sources/Cra/UI/Windows/MainWindowController+SpaceMenu.swiftindex 33fbe4c..8ae6d93 100644--- a/Sources/Cra/UI/Windows/MainWindowController+SpaceMenu.swift+++ b/Sources/Cra/UI/Windows/MainWindowController+SpaceMenu.swift@@ -65,7 +65,7 @@ extension MainWindowController {/// Settings ▸ Profiles ▸ Create Profile…: the same dialog over Settings, no space ticked.func showNewProfileDialog(over window: NSWindow, ticked: Set<UUID> = []) {- DialogOverlayWindow.present(over: window) { close in+ DialogPanel.present(over: window) { close inNewProfileDialog(spaces: profileSpaces, ticked: ticked, onCreate: { [weak self] name, ids inself?.createProfile(name: name, forSpaces: ids)close()@@ -77,7 +77,7 @@ extension MainWindowController {func showChangeProfileDialog(forSpace id: UUID) {guard let window, let space = store.space(id) else { return }let store = self.store- DialogOverlayWindow.present(over: window) { close in+ DialogPanel.present(over: window) { close inChangeProfileDialog(space: space, profiles: store.profiles, spaces: profileSpaces, onChange: { p instore.setProfile(p, forSpace: id)close()diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swiftindex 47cc70e..853c95c 100644--- a/Sources/Cra/UI/Windows/MainWindowController.swift+++ b/Sources/Cra/UI/Windows/MainWindowController.swift@@ -276,7 +276,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserMsidebarActions.editSpaceThemeBeside = { [weak self] s, card in self?.showSpaceStyleEditor(space: s, beside: card) }sidebarActions.newProfile = { [weak self] id in self?.showNewProfileDialog(forSpace: id) }sidebarActions.manageSpaces = { [weak self] in self?.showManageSpaces() }- sidebarActions.deleteSpace = { [weak self] s in self?.app.confirmDeleteSpace(s) }+ sidebarActions.deleteSpace = { [weak self] s in self?.app.confirmDeleteSpace(s, in: self?.window) }sidebarActions.toggleSidebar = { [weak self] in self?.toggleSidebar() }sidebarActions.toggleLibrary = { [weak self] in self?.toggleLibrary() }sidebarActions.showLibrary = { [weak self] page in self?.showLibrary(page) }@@ -1745,7 +1745,7 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM/// pinned URL loads the new one; one navigated away stays where it is.func editPinnedURL(_ id: UUID) {guard let window, let tab = store.item(id)?.tab, store.isPinned(id), tab.liveItemURL == nil else { return }- DialogOverlayWindow.present(over: window) { [weak self] close in+ DialogPanel.present(over: window) { [weak self] close inEditPinnedURLDialog(url: tab.savedURL, onSave: { url inclose()guard let self, let before = self.store.item(id)?.tab, self.store.setPinnedURL(id, to: url),diff --git a/Sources/Cra/UI/Windows/NewProfileDialog.swift b/Sources/Cra/UI/Windows/NewProfileDialog.swiftindex 8a6bd1b..e3e89d5 100644--- a/Sources/Cra/UI/Windows/NewProfileDialog.swift+++ b/Sources/Cra/UI/Windows/NewProfileDialog.swift@@ -14,8 +14,8 @@ struct NewProfileDialog: View {@State private var choosingSpaces = false@FocusState private var focused: Bool- static let card = Color(hex: "#161C2F")- static let body = Color(hex: "#B8B9C4")+ static let card = DialogTheme.card+ static let body = DialogTheme.bodyprivate var trimmed: String { name.trimmingCharacters(in: .whitespaces) }init(spaces: [Space], ticked: Set<UUID>, onCreate: @escaping (String, Set<UUID>) -> Void, onCancel: @escaping () -> Void) {@@ -85,77 +85,11 @@ struct NewProfileDialog: View {}.padding(.horizontal, 38.5).frame(width: 450, height: 426)- .background(Self.card, in: RoundedRectangle(cornerRadius: 24, style: .continuous))- .environment(\.colorScheme, .dark)+ .modifier(DialogSurface()).onAppear { focused = true }}}-/// Arc's dialog button: a label and its key in a small badge. `.accent` is the vivid blue of-/// Edit Pinned URL's Save (measured 1 Nov); disabled it looks like `.primary`.-struct DialogButton: View {- enum Style { case secondary, primary, accent }- let title: String- let key: String- let enabled: Bool- let style: Style- /// The key badge's size where it was measured (Edit Pinned URL); otherwise it fits the key.- var badge: CGSize?- let action: () -> Void-- init(title: String, key: String, enabled: Bool, primary: Bool, action: @escaping () -> Void) {- self.init(title: title, key: key, enabled: enabled, style: primary ? .primary : .secondary, action: action)- }-- init(title: String, key: String, enabled: Bool, style: Style, badge: CGSize? = nil, action: @escaping () -> Void) {- self.title = title- self.key = key- self.enabled = enabled- self.style = style- self.badge = badge- self.action = action- }-- private var accent: Bool { style == .accent && enabled }- private var primary: Bool { style != .secondary }-- var body: some View {- Button(action: action) {- HStack(spacing: 9) {- Text(title).font(.system(size: 13, weight: .medium))- .foregroundStyle(accent ? .white : enabled ? Color(hex: "#EBEBEF") : Color(hex: "#5B5C7F"))- Text(key).font(.system(size: key == "↩" ? 13 : 11, weight: .bold))- .foregroundStyle(accent ? Color(hex: "#EDEDFF") : enabled ? Color(hex: "#B7B7DD") : Color(hex: "#5F6193"))- .frame(minWidth: badge?.width ?? 27, maxWidth: badge?.width, minHeight: badge?.height ?? 19, maxHeight: badge?.height)- .padding(.horizontal, badge != nil || key == "↩" ? 0 : 2)- .background(RoundedRectangle(cornerRadius: badge == nil ? 5 : 3, style: .continuous)- .fill(accent ? Color(hex: "#464DFB") : primary ? Color(hex: enabled ? "#4E4C9A" : "#222469") : Color(hex: "#4E4C77")))- .overlay(RoundedRectangle(cornerRadius: badge == nil ? 5 : 3, style: .continuous)- .strokeBorder(accent ? Color(hex: "#6B71FE") : .clear, lineWidth: 1))- }- .padding(.leading, 12.5)- .padding(.trailing, 12)- .frame(height: 37)- .background(- RoundedRectangle(cornerRadius: 8, style: .continuous)- .fill(accent ? Color(hex: "#3239FB") : primary ? Color(hex: enabled ? "#3B3C8F" : "#1C1D4C") : Color(hex: "#302F60"))- )- .overlay(- RoundedRectangle(cornerRadius: 8, style: .continuous)- .strokeBorder(accent ? Color(hex: "#5B61FD") : primary ? (enabled ? Color(hex: "#6362A9") : .clear) : Color(hex: "#6362A9"), lineWidth: 1)- )- // Arc's Save sits on a darker blue lip, ~1.5 pt below it.- .background(- RoundedRectangle(cornerRadius: 8, style: .continuous)- .fill(style == .accent ? Color(hex: enabled ? "#2C3475" : "#1D2259") : .clear)- .offset(y: 1.5)- )- }- .buttonStyle(.plain)- .disabled(!enabled)- }-}-/// Arc's profile glyph: a lavender smiley in a dashed ring with a green plus badge.struct ProfileAvatar: View {var body: some View {@@ -179,7 +113,7 @@ struct ProfileAvatar: View {Circle().fill(Color(hex: "#5DA642")).frame(width: 17, height: 17)Image(systemName: "plus").font(.system(size: 10, weight: .heavy)).foregroundStyle(.white)}- .overlay(Circle().strokeBorder(Color(hex: "#161C2F"), lineWidth: 1.5))+ .overlay(Circle().strokeBorder(DialogTheme.card, lineWidth: 1.5)).offset(x: 1, y: 1)}.frame(width: 61, height: 61)@@ -194,39 +128,3 @@ struct SmileArc: Shape {return p}}--/// A borderless window over the main window: Arc's dim plus the dialog, and keys for its field.-final class DialogOverlayWindow: NSWindow {- override var canBecomeKey: Bool { true }-- convenience init<Content: View>(over parent: NSWindow, content: Content) {- self.init(contentRect: parent.frame, styleMask: [.borderless], backing: .buffered, defer: false)- isOpaque = false- backgroundColor = .clear- hasShadow = false- let root = ZStack {- // Arc darkens the window to about 35% under its dialogs (sampled on 1 Nov).- Color(white: 0.1).opacity(0.65)- // One shadow for the card: without the group SwiftUI shadows every text and field on it.- content.compositingGroup().shadow(color: .black.opacity(0.35), radius: 24, y: 8)- }- contentView = NSHostingView(rootView: root)- }-- /// Shows a dialog over `parent` (one at a time); `content` gets the closure that dismisses it.- static func present<Content: View>(over parent: NSWindow, _ content: (@escaping () -> Void) -> Content) {- guard parent.childWindows?.contains(where: { $0 is DialogOverlayWindow }) != true else { return }- var overlay: DialogOverlayWindow?- let close = { [weak parent] in- guard let o = overlay else { return }- parent?.removeChildWindow(o)- o.orderOut(nil)- overlay = nil- parent?.makeKey()- }- let o = DialogOverlayWindow(over: parent, content: content(close))- overlay = o- parent.addChildWindow(o, ordered: .above)- o.makeKeyAndOrderFront(nil)- }-}diff --git a/Sources/Cra/UI/Windows/ProfileDialogs.swift b/Sources/Cra/UI/Windows/ProfileDialogs.swiftindex 309a110..59125fa 100644--- a/Sources/Cra/UI/Windows/ProfileDialogs.swift+++ b/Sources/Cra/UI/Windows/ProfileDialogs.swift@@ -48,8 +48,7 @@ struct ProfileSpacesStep: View {}.padding(.horizontal, 38.5).frame(width: 450, height: 506)- .background(NewProfileDialog.card, in: RoundedRectangle(cornerRadius: 24, style: .continuous))- .environment(\.colorScheme, .dark)+ .modifier(DialogSurface())}}@@ -135,7 +134,7 @@ struct ChangeProfileDialog: View {private func showMenu() {// The dialog's own window, which needn't be key (Cra may be in the background).- guard let content = NSApp.windows.last(where: { $0 is DialogOverlayWindow && $0.isVisible })?.contentView else { return }+ guard let content = NSApp.windows.last(where: { $0 is DialogPanel && $0.isVisible })?.contentView else { return }let m = NSMenu()m.autoenablesItems = falseMenuItems.add(m, "Default") { choice = .existing(nil) }@@ -211,8 +210,7 @@ struct ChangeProfileDialog: View {}.padding(.horizontal, 38.5).frame(width: 450, height: 338)- .background(NewProfileDialog.card, in: RoundedRectangle(cornerRadius: 24, style: .continuous))- .environment(\.colorScheme, .dark)+ .modifier(DialogSurface())}}diff --git a/Tests/BrowserManagerSupport/AppServices.swift b/Tests/BrowserManagerSupport/AppServices.swiftindex 2991c9f..345b62c 100644--- a/Tests/BrowserManagerSupport/AppServices.swift+++ b/Tests/BrowserManagerSupport/AppServices.swift@@ -1,6 +1,11 @@import AppKitimport CraCEF+@MainActor final class AppDialog {+ init(title: String, actions: [DialogAction]) {}+ func present(over window: NSWindow, completion: @escaping (NSApplication.ModalResponse) -> Void) { completion(.abort) }+}+// Unrelated shell services required to typecheck the complete production manager.// The tab store deliberately remains observable so stale callbacks can be asserted.struct TestTab { var url: String; var savedTitle = ""; var muted = false; var faviconKey: String?; var themeColor: String?; var activeTabBeforeCreationID: UUID? }diff --git a/Tests/DialogTests.swift b/Tests/DialogTests.swiftnew file mode 100644index 0000000..e3a015a--- /dev/null+++ b/Tests/DialogTests.swift@@ -0,0 +1,224 @@+import AppKit+import SwiftUI++@main+enum DialogTests {+ private static var checks = 0++ @MainActor+ static func main() throws {+ _ = NSApplication.shared+ NSApp.setActivationPolicy(.prohibited)+ for style in [DialogButton.Style.primary, .accent, .destructive] {+ let tint = NSColor(style.hoverTint).usingColorSpace(.sRGB)!+ expect(tint.redComponent == 0 && tint.greenComponent == 0 && tint.blueComponent == 0,+ "primary and destructive buttons darken on hover: \(style)")+ }+ let secondaryHover = NSColor(DialogButton.Style.secondary.hoverTint).usingColorSpace(.sRGB)!+ expect(secondaryHover.redComponent == 1 && secondaryHover.greenComponent == 1 && secondaryHover.blueComponent == 1,+ "secondary buttons brighten on hover")+ if let directory = ProcessInfo.processInfo.environment["CRA_DIALOG_SNAPSHOTS"] { try snapshots(in: directory) }+ let parent = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 900, height: 700),+ styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)+ parent.isReleasedWhenClosed = false+ parent.orderBack(nil)+ parent.resignKey()+ parent.resignMain()+ expect(NSApp.keyWindow == nil && NSApp.mainWindow == nil, "the background-window check has no key or main window")+ expect(AppDialog.parentWindow === parent, "an inactive app still anchors dialogs to its visible browser window")++ let acknowledgement = AppDialog(title: "You need at least one space.")+ acknowledgement.present(over: parent) { _ in }+ let acknowledgementWindow = sheet(over: parent)+ expect(acknowledgementWindow.isSheet && acknowledgementWindow.sheetParent === parent,+ "dialogs use the same native sheet presentation as the Space editor")+ guard let acknowledgementView = acknowledgementWindow.contentView else { fatalError("Dialog content missing") }+ expect(acknowledgementWindow.hasShadow && acknowledgementWindow.animationBehavior == .default,+ "AppKit owns the sheet's shadow and animations")+ expect(acknowledgementView.bounds.width == 450 && acknowledgementView.bounds.height < 400,+ "the panel fits the card rather than covering the browser window")+ let acknowledgementBitmap = bitmap(of: acknowledgementView)+ let face = acknowledgementBitmap.colorAt(x: 15, y: acknowledgementBitmap.pixelsHigh / 2)!.usingColorSpace(.sRGB)!+ let reference = AppDialog(title: "You need at least one space.").prepareWindow()+ let referenceBitmap = bitmap(of: reference.contentView!)+ let referenceFace = referenceBitmap.colorAt(x: 15, y: referenceBitmap.pixelsHigh / 2)!.usingColorSpace(.sRGB)!+ expect(abs(face.redComponent - referenceFace.redComponent) < 0.025 && abs(face.blueComponent - referenceFace.blueComponent) < 0.025,+ "the parent window's dim must not change the card's colors")+ reference.close()+ let buttonPoint = blueButtonCenter(in: acknowledgementBitmap, view: acknowledgementView)+ let hit = acknowledgementView.hitTest(buttonPoint)+ expect(hit != nil, "the sheet content receives pointer events")+ acknowledgementWindow.close()++ for code: UInt16 in [36, 53, 76] {+ let dialog = AppDialog(title: "Delete your “Work” Space?", message: "This will archive all the tabs and folders inside it.",+ actions: [DialogAction("Delete", role: .destructive), .cancel])+ var responses: [NSApplication.ModalResponse] = []+ dialog.present(over: parent) { responses.append($0) }+ let window = sheet(over: parent)+ expect(window.sheetParent === parent, "the panel is attached to its source window")+ expect(window.canBecomeKey, "the dialog can receive keyboard input")+ window.sendEvent(key(code, window: window))+ expect(window.isDismissing, "answering ends the native sheet session")+ expect(responses == [code == 53 ? .alertSecondButtonReturn : .alertFirstButtonReturn], "Return and Escape keep the original response indices")+ expect(parent.attachedSheet == nil, "answering detaches the sheet")+ window.close()+ expect(responses.count == 1, "a completion runs exactly once")+ }++ let rename = AppDialog(title: "Rename your Profile", actions: [DialogAction("Save"), .cancel], input: "", requiresInput: true, icon: .none)+ var renamed: NSApplication.ModalResponse?+ rename.present(over: parent) { renamed = $0 }+ let renameWindow = sheet(over: parent)+ renameWindow.sendEvent(key(36, window: renameWindow))+ expect(renamed == nil && renameWindow.isVisible, "empty names cannot submit")+ rename.input = "Work"+ renameWindow.sendEvent(key(36, window: renameWindow))+ expect(renamed == .alertFirstButtonReturn && rename.input == "Work", "the edited text survives dismissal")++ let profile = AppDialog(title: "Change Profile", actions: [DialogAction("Change Profile"), .cancel], suppressionTitle: "Don’t ask again")+ var suppressed = false+ profile.present(over: parent) { _ in suppressed = profile.isSuppressed }+ profile.isSuppressed = true+ profile.select(0)+ expect(suppressed, "the suppression choice is available in the completion")++ let confirmation = AppDialog(title: "Quit Cra?", actions: [DialogAction("Quit"), .cancel])+ RunLoop.current.perform(inModes: [.modalPanel]) {+ MainActor.assumeIsolated {+ expect(sheet(over: parent).sheetParent === parent, "a synchronous confirmation also uses a native sheet")+ confirmation.select(1)+ }+ }+ expect(confirmation.runModal(over: parent) == .alertSecondButtonReturn, "a synchronous sheet returns Cancel after native dismissal")+ expect(parent.attachedSheet == nil, "the synchronous sheet leaves no attached modal behind")++ let externallyDismissed = AppDialog(title: "Rename your Profile", actions: [DialogAction("Save"), .cancel], input: "Work")+ var externalResponse: NSApplication.ModalResponse?+ externallyDismissed.present(over: parent) { externalResponse = $0 }+ parent.endSheet(sheet(over: parent))+ expect(externalResponse == .abort, "native dismissal without a button cancels the operation")++ var dismissCustom: (() -> Void)?+ expect(DialogPanel.present(over: parent) { close in+ dismissCustom = close+ return Text("Profile settings").frame(width: 450, height: 338)+ }, "custom profile and URL views use the same sheet presenter")+ let customPanel = sheet(over: parent)+ expect(customPanel.contentView?.bounds.size == NSSize(width: 450, height: 338), "custom content keeps its measured size")+ expect(!DialogPanel.present(over: parent) { _ in Text("Duplicate") }, "custom content cannot replace an open sheet")+ dismissCustom?()+ expect(parent.attachedSheet == nil && !customPanel.isVisible, "closing custom content dismisses the native sheet")+ dismissCustom = nil++ let permission = AppDialog(title: "example.com wants to use your camera", actions: [DialogAction("Allow"), DialogAction("Block", role: .cancel)])+ var permissionResponse: NSApplication.ModalResponse?+ permission.present(over: parent) { permissionResponse = $0 }+ let permissionWindow = sheet(over: parent)+ var duplicateResponse: NSApplication.ModalResponse?+ AppDialog(title: "Another request").present(over: parent) { duplicateResponse = $0 }+ expect(duplicateResponse == .abort, "a duplicate request completes without replacing the first")+ expect(sheet(over: parent) === permissionWindow, "the original request stays visible")+ let permissionSize = permissionWindow.frame.size+ parent.setFrame(NSRect(x: -9900, y: -9900, width: 1100, height: 800), display: true)+ expect(permissionWindow.sheetParent === parent && permissionWindow.frame.size == permissionSize,+ "AppKit keeps the card attached without stretching it on parent resize")+ parent.close()+ expect(permissionResponse == .abort && !permissionWindow.isVisible, "closing the parent denies a pending permission")++ let modal = AppDialog(title: "Cra is still open", actions: [DialogAction("Try Again"), DialogAction("Force Quit", role: .destructive), .cancel])+ let modalWindow = modal.prepareWindow()+ modalWindow.setFrameOrigin(NSPoint(x: -10000, y: -10000))+ expect(modalWindow.contentView?.bounds.width == 450 && modalWindow.hasShadow,+ "a standalone panel fits its card and uses the system shadow")+ RunLoop.current.perform(inModes: [.modalPanel]) { MainActor.assumeIsolated { modal.select(1) } }+ expect(modal.runModal(over: nil) == .alertSecondButtonReturn, "a standalone modal returns its selected action")+ expect(!modalWindow.isVisible, "the standalone modal closes after a response")++ let autoClosing = AppDialog(title: "An older Cra is still open")+ let autoClosingWindow = autoClosing.prepareWindow()+ autoClosingWindow.setFrameOrigin(NSPoint(x: -10000, y: -10000))+ RunLoop.current.perform(inModes: [.modalPanel]) { NSApp.stopModal(withCode: .OK) }+ expect(autoClosing.runModal(over: nil) == .OK, "the old-copy timer can stop the modal without a button press")+ expect(!autoClosingWindow.isVisible, "external modal dismissal also removes the window")++ let error = AppDialog(error: NSError(domain: "DialogTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "Could not save", NSLocalizedRecoverySuggestionErrorKey: "Try another folder."]))+ expect(error.title == "Could not save" && error.message == "Try another folder.", "errors keep their description and recovery advice")+ let errorWindow = error.prepareWindow()+ errorWindow.setFrameOrigin(NSPoint(x: -10000, y: -10000))+ RunLoop.current.perform(inModes: [.modalPanel]) { MainActor.assumeIsolated { errorWindow.sendEvent(key(53, window: errorWindow)) } }+ expect(error.runModal(over: nil) == .alertFirstButtonReturn, "Escape acknowledges a one-button error")+ print("Dialogs: \(checks) checks passed")+ }++ @MainActor+ private static func snapshots(in directory: String) throws {+ let examples: [(String, AppDialog)] = [+ ("delete-space", AppDialog(title: "Delete your “Work main” Space?", message: "This will archive all the tabs and folders inside it.",+ actions: [DialogAction("Delete", role: .destructive), .cancel])),+ ("rename-profile", AppDialog(title: "Rename your Profile", message: "This won’t affect the names of any of the Spaces associated with this Profile.",+ actions: [DialogAction("Save"), .cancel], input: "Work", requiresInput: true,+ icon: .none, width: 496, buttonSpacing: 30)),+ ("quit", AppDialog(title: "Quit Cra?", actions: [DialogAction("Quit"), .cancel, DialogAction("Quit, and don’t ask again", role: .secondary)],+ icon: .application, buttonSpacing: 49.5, buttonOutset: 10.5)),+ ("long-message", AppDialog(title: "Move these spaces to their Arc profiles?", message: Array(repeating: "Work → Work Profile", count: 80).joined(separator: "\n"),+ actions: [DialogAction("Move and Restart"), .cancel])),+ ("last-space", AppDialog(title: "You need at least one space."))+ ]+ let folder = URL(fileURLWithPath: directory, isDirectory: true)+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ for (name, dialog) in examples {+ let window = dialog.prepareWindow()+ window.setFrameOrigin(NSPoint(x: -10000, y: -10000))+ guard let view = window.contentView else { fatalError("Dialog content missing") }+ let bitmap = bitmap(of: view)+ guard let png = bitmap.representation(using: .png, properties: [:]) else { fatalError("Dialog PNG missing") }+ try png.write(to: folder.appendingPathComponent(name + ".png"))+ window.close()+ }+ }++ @MainActor+ private static func bitmap(of view: NSView) -> NSBitmapImageRep {+ view.layoutSubtreeIfNeeded()+ guard let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { fatalError("Dialog bitmap missing") }+ view.cacheDisplay(in: view.bounds, to: bitmap)+ return bitmap+ }++ @MainActor+ private static func blueButtonCenter(in bitmap: NSBitmapImageRep, view: NSView) -> NSPoint {+ var minX = bitmap.pixelsWide, maxX = 0, minY = bitmap.pixelsHigh, maxY = 0+ for y in 0..<bitmap.pixelsHigh {+ for x in 0..<bitmap.pixelsWide {+ guard let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.sRGB),+ color.blueComponent > 0.8, color.redComponent < 0.4, color.greenComponent < 0.4 else { continue }+ minX = min(minX, x); maxX = max(maxX, x)+ minY = min(minY, y); maxY = max(maxY, y)+ }+ }+ guard minX < maxX, minY < maxY else { fatalError("The acknowledgement button must remain bright blue above the dim") }+ let x = CGFloat(minX + maxX) / 2 * view.bounds.width / CGFloat(bitmap.pixelsWide)+ let y = CGFloat(minY + maxY) / 2 * view.bounds.height / CGFloat(bitmap.pixelsHigh)+ return NSPoint(x: x, y: view.isFlipped ? y : view.bounds.height - y)+ }++ @MainActor+ private static func sheet(over parent: NSWindow) -> DialogPanel {+ guard let window = parent.attachedSheet as? DialogPanel else {+ fatalError("Native dialog sheet missing")+ }+ return window+ }++ @MainActor+ private static func key(_ code: UInt16, window: NSWindow) -> NSEvent {+ NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 1, windowNumber: window.windowNumber,+ context: nil, characters: code == 53 ? "\u{1b}" : "\r", charactersIgnoringModifiers: "", isARepeat: false, keyCode: code)!+ }++ private static func expect(_ condition: @autoclosure () -> Bool, _ message: String) {+ guard condition() else { fatalError(message) }+ checks += 1+ }+}diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.shindex bf1acef..fcd30ec 100755--- a/Tests/test-browser-manager.sh+++ b/Tests/test-browser-manager.sh@@ -12,7 +12,7 @@ xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} -I "$-Xlinker -rpath -Xlinker "$TEST_DIR" \"$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Sources/Cra/Services/Scheduler.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/PageProbe.swift Sources/Cra/Services/Persistence.swift \Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift Packages/CraCore/Sources/CraCore/PermissionPrompt.swift Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift Packages/CraCore/Sources/CraCore/ProtectedMedia.swift Sources/Cra/Services/WebKit/PageEngines.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \- Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests"+ Packages/CraCore/Sources/CraCore/DialogActions.swift Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests"# A data folder of its own: PageEngines keeps protected-media.json there, not in the real Cra's.CRA_DATA_DIR="$TEST_DIR/data" "$TEST_DIR/lifecycle-tests"[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/lifecycle-tests" "$CRA_TEST_KEEP/"diff --git a/docs/arc-reverse-engineering.md b/docs/arc-reverse-engineering.mdindex edcdacc..d3f547c 100644--- a/docs/arc-reverse-engineering.md+++ b/docs/arc-reverse-engineering.md@@ -3380,3 +3380,25 @@ Read from the arm64 slice's Swift field metadata (`__swift5_fieldmd`, case and f- Cra: BlankWindow (Space.standaloneWindowID, saved in sidebar.json outside spaceOrder), SidebarStore.addBlankWindow /isStandalone, TabTearOff (decision + frame), SpaceListView.dragEnded, AppDelegate.tearOffTab and moveBlankWindow("Move to…", `cra://debug?blankMoveTo=<n>`), BlankWindow.theme (Auto).++## Confirmation dialogs (Arc 1.172.1, 7 Nov 2026, PR #224, offline Arc on a fake home, 2x window captures)+- [O static] Arc has two paths: `AlertClient.runModal` (NSAlert) and its own `Dialogs` module (`DialogView`,+ `DialogButton`, `SuppressionCheckbox`, `TextInputDialogView`, `PermissionRequestDialogView`,+ `NSWindow+DialogSheet.swift` → `Dialogs.SheetWindow`, "Label for the icon to press enter/escape").+- [O] Quit Arc? (shouldWarnBeforeQuitting), Delete your “<name>” Space? and Delete your <name> Live Folder?+ are all the Dialogs card, presented as a real sheet on the browser window: 450 pt wide, centred, no AX+ window of its own, the window dimmed, and macOS 26's sheet animation (fade in while dropping a few points).+ The 1 pt light edge is the sheet's own (20 % white over the card), not a stroke. Card #161C2F, 16 pt+ continuous corners.+- [O] Quit: the app icon 50.5 pt across from 43.5 pt in; "Quit Arc?" caps 120 pt down; buttons 37 pt tall+ (+1.5 pt lip) from 183.5 pt: "Quit, and don’t ask again" at the left edge (27.5 pt in), Cancel `ESC` and+ Quit `↩` at the right, ending 26.5 pt from the card's edge, 7.5 pt apart; card 248 pt tall.+- [O] Delete Space / Delete Live Folder: Arc's logo mark instead of the app icon, title caps at 120 pt, the+ message's at 157 pt, buttons from 208.5 pt; Cancel `ESC` and a red Delete / Delete Folder `↩` (fill+ #E2492C, no lighter rim, lip #41232A, key badge #E55B41 edged #E86D56). Live Folder text: "You can restore+ this folder at any time by right-clicking the sidebar."+- [O] Colours: secondary #302F60 edged #6362A9, its ESC badge #4E4C77; Quit #3339F1. Hover: 10 % white over a+ secondary button, badge included (#302F60 → #454470), 10 % black over the default one (#3339F1 → #2D33D9).+- Cra (#224, STRENCH0): `AppDialog` + `DialogPanel` (a real sheet via beginSheet) replace NSAlert and the+ borderless DialogOverlayWindow; checked against these captures on the same display, within ~1 pt and a few+ levels of colour. Arc's quit capture was taken with its command bar open; that doesn't change the sheet.diff --git a/scripts/test-dialogs.sh b/scripts/test-dialogs.shnew file mode 100755index 0000000..ae43bce--- /dev/null+++ b/scripts/test-dialogs.sh@@ -0,0 +1,12 @@+#!/bin/bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp/}cra-dialog-tests.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} \+ Packages/CraCore/Sources/CraCore/*.swift Packages/CraCore/Sources/CraCore/Perf/*.swift \+ Sources/Cra/UI/Colors.swift Sources/Cra/UI/BrandMark.swift \+ Sources/Cra/UI/Windows/DialogComponents.swift Sources/Cra/UI/Windows/AppDialog.swift \+ Tests/DialogTests.swift -o "$TEST_DIR/dialog-tests"+"$TEST_DIR/dialog-tests"+[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/dialog-tests" "$CRA_TEST_KEEP/"diff --git a/scripts/test.sh b/scripts/test.shindex d0c4080..10b1943 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -22,6 +22,7 @@ if [ "${1:-}" != core ]; thensuite "Extension popup candidate" scripts/test-extension-popup-candidate.shsuite "Extension popup window" scripts/test-extension-popup-window.shsuite "Peek dismiss panel" scripts/test-peek-dim-panel.sh+ suite "Dialogs" scripts/test-dialogs.shsuite "Extension state" scripts/test-extension-state.shsuite "Extension store migration" scripts/test-extension-store-migration.shsuite "Store and importers" scripts/test-store.sh