diff --git a/Phone/Sources/About/AboutLayer.swift b/Phone/Sources/About/AboutLayer.swift index c55866e5..7e578420 100644 --- a/Phone/Sources/About/AboutLayer.swift +++ b/Phone/Sources/About/AboutLayer.swift @@ -17,7 +17,7 @@ final class AboutModel { /// Yab's community: the group chat on X the site's changelog links to (the Mac's Links.community). static let community = URL(string: "https://x.com/i/chat/group_join/g2108389056413618447/Tmr5OvF8Rx")! static let copyright = "© 2026 Serafim Korablev" - static let line = "Yes, another one. A small, quiet browser for your iPhone." + static let line = "Yes, another one. A small, quiet browser for your \(DeviceWord.name)." static var version: String { "Version \(SettingsStore.version()) (\(SettingsStore.build()))" } /// Shown at once, for named states and tests. diff --git a/Phone/Sources/Answers/ChatBackend.swift b/Phone/Sources/Answers/ChatBackend.swift index 8913c440..4d51a762 100644 --- a/Phone/Sources/Answers/ChatBackend.swift +++ b/Phone/Sources/Answers/ChatBackend.swift @@ -15,12 +15,12 @@ struct AskContext: Sendable { var parts: [String] = [] let previous = history.filter { $0.role == .you || $0.role == .answer }.suffix(8) if !previous.isEmpty { - parts.append("Earlier conversation on this iPhone:\n" + previous.map { + parts.append("Earlier conversation on this \(DeviceWord.name):\n" + previous.map { "\($0.role == .you ? "You" : "Assistant"): \(String($0.plain.prefix(2000)))" }.joined(separator: "\n")) } if let page { - parts.append("Page on this iPhone:\nTitle: \(page.title)\nURL: \(page.address)\nPage text:\n\(String(page.text.prefix(12000)))") + parts.append("Page on this \(DeviceWord.name):\nTitle: \(page.title)\nURL: \(page.address)\nPage text:\n\(String(page.text.prefix(12000)))") } guard !parts.isEmpty else { return question } parts.insert("Question: " + question, at: 0) @@ -63,8 +63,8 @@ final class Answerers { case unavailable, interrupted var errorDescription: String? { switch self { - case .unavailable: "Apple Intelligence isn't available on this iPhone. Enable it in Settings, then ask again. This question stayed on this iPhone." - case .interrupted: "This iPhone couldn't answer. Ask again, or choose Your Mac for public page questions in Settings. This question stayed on this iPhone." + case .unavailable: "Apple Intelligence isn't available on this \(DeviceWord.name). Enable it in Settings, then ask again. This question stayed on this \(DeviceWord.name)." + case .interrupted: "This \(DeviceWord.name) couldn't answer. Ask again, or choose Your Mac for public page questions in Settings. This question stayed on this \(DeviceWord.name)." } } } diff --git a/Phone/Sources/Answers/OnDeviceModel.swift b/Phone/Sources/Answers/OnDeviceModel.swift index 92c75916..579302b0 100644 --- a/Phone/Sources/Answers/OnDeviceModel.swift +++ b/Phone/Sources/Answers/OnDeviceModel.swift @@ -20,7 +20,7 @@ final class OnDeviceModel: ChatBackend { func answer(_ context: AskContext) async throws -> String { let session = LanguageModelSession(instructions: """ - You answer questions about the web page a person has open in Yab, a browser on their iPhone. \ + You answer questions about the web page a person has open in Yab, a browser on their \(DeviceWord.name). \ Answer from the page's words in two or three plain sentences, in the language of the question. \ No headings, lists or markup. If the page doesn't say, say so in one sentence. """) diff --git a/Phone/Sources/App/AppActions.swift b/Phone/Sources/App/AppActions.swift index 5ec02ea6..d7878f27 100644 --- a/Phone/Sources/App/AppActions.swift +++ b/Phone/Sources/App/AppActions.swift @@ -61,7 +61,7 @@ extension AppModel { Motion.nowGone.run { saved = self.tasks.markLiveSeen(snapshot) if !saved { - self.say("Couldn’t save read status on this iPhone", glyph: .macbook) + self.say("Couldn’t save read status on this \(DeviceWord.name)", glyph: .macbook) } } return saved diff --git a/Phone/Sources/App/AppModel.swift b/Phone/Sources/App/AppModel.swift index dee2e907..d4bf3c56 100644 --- a/Phone/Sources/App/AppModel.swift +++ b/Phone/Sources/App/AppModel.swift @@ -160,6 +160,7 @@ final class AppModel { return self.browser.tab(tab.id) } pages.onOpenLink = { [weak self] url, source, opening in self?.openHeldLink(url, from: source, as: opening) } + pages.canOpenLinkBeside = { [weak self] source in self?.canOpenLinkBeside(source) ?? false } pages.onCloseWindowFrom = { [weak self] id, source in guard let self, self.browser.tab(id) != nil else { return } // A background completion never takes focus from another page. diff --git a/Phone/Sources/App/BrowserKeys.swift b/Phone/Sources/App/BrowserKeys.swift index 16b08c19..1b011742 100644 --- a/Phone/Sources/App/BrowserKeys.swift +++ b/Phone/Sources/App/BrowserKeys.swift @@ -8,19 +8,36 @@ let keysLog = Logger(subsystem: "dev.serafim.fast.iphone", category: "keys") /// an iPad lists them, and ⌘W is the tab's: the system's Close Window, which /// closes a single-window app outright, is taken out of the menu. enum BrowserKey: Hashable, Sendable { - case newTab, openLocation, closeTab, reopenTab + case newTab, newPrivateTab, openLocation, closeTab, reopenTab case reload, back, forward, find - case nextTab, previousTab, toggleSidebar + case nextTab, previousTab, toggleSidebar, settings + /// The Mac's ⇧⌘S: tabs in the sidebar or across the top; Safari's ⇧⌘\ for All Tabs. + case toggleTabsInSidebar, allTabs + /// The Mac's View and File keys for the page. + case zoomIn, zoomOut, actualSize, stop, reader, copyLink, print /// ⌘1 to ⌘8 the tab at that place, ⌘9 the last one. case tab(Int) - static let all: [BrowserKey] = [.newTab, .openLocation, .closeTab, .reopenTab, - .reload, .back, .forward, .find, .nextTab, .previousTab, .toggleSidebar] + static let all: [BrowserKey] = [.newTab, .newPrivateTab, .openLocation, .closeTab, .reopenTab, + .reload, .back, .forward, .find, .nextTab, .previousTab, .toggleSidebar, .settings, + .toggleTabsInSidebar, .allTabs, + .zoomIn, .zoomOut, .actualSize, .stop, .reader, .copyLink, .print] + (1...9).map { .tab($0) } var title: String { switch self { case .newTab: "New Tab" + case .newPrivateTab: "New Private Tab" + case .settings: "Settings…" + case .toggleTabsInSidebar: "Show Tabs in Sidebar" + case .allTabs: "Show All Tabs" + case .zoomIn: "Zoom In" + case .zoomOut: "Zoom Out" + case .actualSize: "Actual Size" + case .stop: "Stop Loading" + case .reader: "Show Reader" + case .copyLink: "Copy Link" + case .print: "Print…" case .openLocation: "Open Location" case .closeTab: "Close Tab" case .reopenTab: "Reopen Closed Tab" @@ -40,6 +57,18 @@ enum BrowserKey: Hashable, Sendable { switch self { case .newTab, .reopenTab: "t" case .openLocation: "l" + case .newPrivateTab: "n" + case .settings: "," + case .toggleTabsInSidebar: "s" + case .allTabs: "\\" + // ⌘= is ⌘+ on the keyboard, as Safari's Zoom In. + case .zoomIn: "=" + case .zoomOut: "-" + case .actualSize: "0" + case .stop: "." + case .reader: "r" + case .copyLink: "c" + case .print: "p" case .closeTab: "w" case .reload: "r" case .back: "[" @@ -53,7 +82,7 @@ enum BrowserKey: Hashable, Sendable { var modifiers: UIKeyModifierFlags { switch self { - case .reopenTab: [.command, .shift] + case .reopenTab, .newPrivateTab, .toggleTabsInSidebar, .allTabs, .reader, .copyLink: [.command, .shift] case .nextTab: .control case .previousTab: [.control, .shift] default: .command @@ -89,6 +118,10 @@ enum BrowserKey: Hashable, Sendable { static let viewMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.view") static let historyMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.history") static let tabsMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.switch") + static let settingsMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.settings") + static let pageMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.page") + static let printMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.print") + static let copyMenu = UIMenu.Identifier("dev.serafim.fast.iphone.keys.copy") /// File holds the tabs, View Reload, History Back and Forward, Window /// the tab switching, Edit Find on Page: where Safari keeps them. @@ -106,19 +139,34 @@ enum BrowserKey: Hashable, Sendable { // The system's Find would reach only a focused web view, not the tab in front. builder.remove(menu: .find) - let tabs = inline(filesMenu, [.newTab, .openLocation, .closeTab, .reopenTab]) + // Settings where the Mac keeps it, in the app's own menu under About. + let settings = inline(settingsMenu, [.settings]) + if builder.menu(for: .preferences) != nil { builder.replace(menu: .preferences, with: settings) } + else if builder.menu(for: .about) != nil { builder.insertSibling(settings, afterMenu: .about) } + else if builder.menu(for: .application) != nil { builder.insertChild(settings, atStartOfMenu: .application) } + + let tabs = inline(filesMenu, [.newTab, .newPrivateTab, .openLocation, .closeTab, .reopenTab]) if builder.menu(for: .file) != nil { builder.insertChild(tabs, atStartOfMenu: .file) } else { builder.insertSibling(UIMenu(title: "File", children: [tabs]), afterMenu: .application) } + let printing = inline(printMenu, [.print]) + if builder.menu(for: .file) != nil { builder.insertChild(printing, atEndOfMenu: .file) } + let find = inline(findMenu, [.find]) - if builder.menu(for: .edit) != nil { builder.insertChild(find, atEndOfMenu: .edit) } + if builder.menu(for: .edit) != nil { + builder.insertChild(inline(copyMenu, [.copyLink]), atEndOfMenu: .edit) + builder.insertChild(find, atEndOfMenu: .edit) + } else { builder.insertSibling(UIMenu(title: "Edit", children: [find]), afterMenu: .file) } - let reload = inline(viewMenu, [.reload, .toggleSidebar]) - if builder.menu(for: .view) != nil { builder.insertChild(reload, atStartOfMenu: .view) } + let reload = inline(viewMenu, [.reload, .stop, .toggleSidebar, .toggleTabsInSidebar, .allTabs]) + if builder.menu(for: .view) != nil { + builder.insertChild(reload, atStartOfMenu: .view) + builder.insertChild(inline(pageMenu, [.reader, .zoomIn, .zoomOut, .actualSize]), atEndOfMenu: .view) + } var history: [BrowserKey] = [.back, .forward] - if builder.menu(for: .view) == nil { history.insert(contentsOf: [.reload, .toggleSidebar], at: 0) } + if builder.menu(for: .view) == nil { history.insert(contentsOf: [.reload, .toggleSidebar, .toggleTabsInSidebar, .allTabs], at: 0) } let historyTop = UIMenu(title: "History", identifier: historyMenu, children: history.map(\.command)) let after: UIMenu.Identifier = builder.menu(for: .view) != nil ? .view : .edit builder.insertSibling(historyTop, afterMenu: after) @@ -135,12 +183,24 @@ extension AppModel { /// puts it away. func mayUse(_ key: BrowserKey) -> Bool { if privateContentBlocked || privateLock.presentsPrompt { return false } + // Always ours, Settings up or not: a ⌘, we turn down goes to the + // system's own Settings item, which leaves Yab for the Settings app. + if key == .settings { return true } if surfaces.settings || surfaces.join || surfaces.chat != nil { return false } if surfaces.coversChrome { return key == .closeTab && surfaces.field != nil } + return offers(key) + } + + /// Whether the key has something to do for the browser as it is, with + /// nothing over it: the field asks this of the commands it offers. + func offers(_ key: BrowserKey) -> Bool { let tab = browser.tab switch key { - case .newTab: return true - case .toggleSidebar: return workspace.tabletControls + case .newTab, .newPrivateTab, .settings: return true + case .toggleSidebar, .toggleTabsInSidebar: return workspace.tabletControls + case .allTabs, .zoomIn, .zoomOut, .actualSize, .copyLink, .print: return tab != nil + case .stop: return tab != nil && currentPageState.isLoading + case .reader: return tab != nil && (currentPageState.readerAvailable || currentPageState.readerEnabled) case .openLocation, .reload, .find: return tab != nil case .closeTab: return tab != nil case .reopenTab: return backStack.closed != nil @@ -155,7 +215,21 @@ extension AppModel { guard mayUse(key) else { return } switch key { case .newTab: openNewTab() + case .newPrivateTab: openNewTab(privately: true) + case .settings: + // Taken but idle while something covers the browser (mayUse). + guard !surfaces.settings, !surfaces.join, surfaces.chat == nil, !surfaces.coversChrome else { return } + openSettingsFromSpaces(at: nil) case .toggleSidebar: workspace.sidebarShown.toggle() + case .toggleTabsInSidebar: workspace.preferences.tabsInSidebar.toggle() + case .allTabs: TabStack.of(self).openGallery() + case .zoomIn: pageMenuZoom(1) + case .zoomOut: pageMenuZoom(-1) + case .actualSize: pageMenuZoom(0) + case .stop: if let id = browser.tab?.id { pages.stop(id) } + case .reader: pageMenuReader() + case .copyLink: if let tab = browser.tab { copyLink(of: tab) } + case .print: printPage() case .openLocation: Motion.fieldOpen.run { surfaces.openField(.address) } case .closeTab: if surfaces.field != nil { field.close(); return } @@ -186,3 +260,51 @@ extension AppModel { if let closed { backStack.offer(closed) } } } + +extension BrowserKey { + /// Kept out of the field: a tab by place, the field itself, Find (the + /// field's own On This Page row) and Settings (its own row). + var commandable: Bool { + switch self { + case .tab, .nextTab, .previousTab, .openLocation, .find, .settings: false + default: true + } + } + + /// Other words the field knows a command by. + var aliases: [String] { + switch self { + case .newPrivateTab: ["private", "incognito"] + case .reopenTab: ["reopen", "undo close"] + case .reload: ["refresh"] + case .zoomIn: ["bigger", "larger"] + case .zoomOut: ["smaller"] + case .actualSize: ["reset zoom", "100%"] + case .reader: ["reader", "reading mode"] + case .copyLink: ["copy address", "copy url"] + case .toggleSidebar: ["sidebar", "hide sidebar"] + case .toggleTabsInSidebar: ["tab bar", "vertical tabs"] + case .allTabs: ["tabs", "tab overview"] + default: [] + } + } + + /// The keys as the menu writes them: ⇧⌘R. + var shortcut: String { + var marks = "" + if modifiers.contains(.control) { marks += "⌃" } + if modifiers.contains(.alternate) { marks += "⌥" } + if modifiers.contains(.shift) { marks += "⇧" } + if modifiers.contains(.command) { marks += "⌘" } + let key = switch input { case "\t": "⇥"; case "=": "+"; default: input.uppercased() } + return marks + key + } +} + +extension AppModel { + /// The menu actions the field offers now (Words.commandRows). + var commandCandidates: [CommandCandidate] { + BrowserKey.all.filter { $0.commandable && offers($0) } + .map { CommandCandidate(token: $0.token, title: $0.title, aliases: $0.aliases, shortcut: $0.shortcut) } + } +} diff --git a/Phone/Sources/App/BrowserWorkspace.swift b/Phone/Sources/App/BrowserWorkspace.swift index d6761624..f9a5f644 100644 --- a/Phone/Sources/App/BrowserWorkspace.swift +++ b/Phone/Sources/App/BrowserWorkspace.swift @@ -60,6 +60,9 @@ final class BrowserWorkspace { private(set) var secondFocused = false private(set) var expanded = false var paneFrame = CGRect.zero + /// The iPad's downloads button in sight, by its id, in the window: + /// where a file flies to (TabletDownloadFlights). + @ObservationIgnored var downloadsLandings: [String: CGRect] = [:] var windowSize = CGSize.zero var tabletControls = false var regularWidth = false @@ -83,6 +86,8 @@ final class BrowserWorkspace { } /// All Tabs lays three cards whole across an unfolded Duo on its side. var galleryAcross: Bool { unfolded && windowSize.width > windowSize.height } + /// The iPad's page card, where All Tabs' cards leave from and land. + var galleryPageFrame: CGRect? { tabletControls && !paneFrame.isEmpty ? paneFrame : nil } /// What the system reserves from a surface this wide at the window's left: /// the column beside a page reaches only that edge. func sides(ofSurface width: CGFloat) -> ChromeGeometry.Sides { diff --git a/Phone/Sources/App/BrowserWorkspaceView.swift b/Phone/Sources/App/BrowserWorkspaceView.swift index 5ba59c51..a109fe78 100644 --- a/Phone/Sources/App/BrowserWorkspaceView.swift +++ b/Phone/Sources/App/BrowserWorkspaceView.swift @@ -95,10 +95,10 @@ struct BrowserWorkspaceView: View { Menu { Button { app.field.openSpaces() } label: { menuLabel("Show Tabs", .yabSidebar) } if !app.pageIsPrivate, let current = app.browser.tab, !current.isMail { - Button { app.newTabBeside() } label: { menuLabel("Open Beside", .yabSplitPlus) } + Button { app.newTabBeside() } label: { menuLabel("Split View", .yabSplitPlus) } if app.workspace.paired { - Button { app.workspace.fullSpread() } label: { menuLabel("Full Spread", .yabSplitSlash) } - Button { app.closeWorkspacePage() } label: { menuLabel("Close Page", .yabTabX) } + Button { app.workspace.fullSpread() } label: { menuLabel("Separate Split View", .yabSplitSlash) } + Button { app.closeWorkspacePage() } label: { menuLabel("Close Split", .yabTabX) } } } } label: { diff --git a/Phone/Sources/App/PrivateLock.swift b/Phone/Sources/App/PrivateLock.swift index a4339eba..6b8416a8 100644 --- a/Phone/Sources/App/PrivateLock.swift +++ b/Phone/Sources/App/PrivateLock.swift @@ -193,7 +193,7 @@ final class PrivateLock { phase = .failed("Private is still locked.") case .unavailable: retireAttempt() - phase = .failed("Set a device passcode in iPhone Settings to unlock Private.") + phase = .failed("Set a device passcode in \(DeviceWord.name) Settings to unlock Private.") case .failed: retireAttempt() Haptics.play(.error, reason: Haptics.Reason.unlockFailed) diff --git a/Phone/Sources/App/PrivateLockView.swift b/Phone/Sources/App/PrivateLockView.swift index cb2bb308..95c659c2 100644 --- a/Phone/Sources/App/PrivateLockView.swift +++ b/Phone/Sources/App/PrivateLockView.swift @@ -44,9 +44,9 @@ struct PrivateLockView: View { private var message: String { switch app.privateLock.phase { - case .authenticating: "Unlocking with your iPhone." + case .authenticating: "Unlocking with your \(DeviceWord.name)." case let .failed(message): message - default: "Unlock with Face ID, Touch ID or your device passcode. Your private tabs stay on this iPhone." + default: "Unlock with Face ID, Touch ID or your device passcode. Your private tabs stay on this \(DeviceWord.name)." } } } diff --git a/Phone/Sources/App/TabClearCoordinator.swift b/Phone/Sources/App/TabClearCoordinator.swift index 7bdda37a..e5c9948e 100644 --- a/Phone/Sources/App/TabClearCoordinator.swift +++ b/Phone/Sources/App/TabClearCoordinator.swift @@ -254,7 +254,7 @@ final class TabClearCoordinator { } } persist() - message = "Cleared \(ids.count) on this iPhone" + (unknown > 0 ? " · other tabs protected" : "") + message = "Cleared \(ids.count) on this \(DeviceWord.name)" + (unknown > 0 ? " · other tabs protected" : "") // Offer Undo after the durable public write, rather than displaying an // unusable Undo during that await; its six seconds start once its // toast is on screen (seen). diff --git a/Phone/Sources/App/TabletChrome.swift b/Phone/Sources/App/TabletChrome.swift new file mode 100644 index 00000000..a38e14f3 --- /dev/null +++ b/Phone/Sources/App/TabletChrome.swift @@ -0,0 +1,489 @@ +import SwiftUI + +/// Where the Mac's controls stand in the iPad workspace, from the same two +/// choices the Mac offers: tabs in the sidebar or across the top +/// (Sources/Fast/TabBar), and the address in the sidebar or as a band over +/// the page card (Show Address Bar, Sources/Fast/AddressBar). +struct TabletChromePlan: Equatable { + /// Tabs across the top: the Mac's tab bar, the sidebar off. + let strip: Bool + /// The sidebar on screen beside the page. + let sidebarInView: Bool + let addressBars: Bool + /// Two pages side by side: each keeps its own band, its own Back and + /// its own close, as the Mac's split does. + var split = false + + /// The address as a plate in the sidebar, under its header. + var plate: Bool { sidebarInView && !addressBars && !split } + /// Back, Forward and Reload in the sidebar's header, beside its door. + var headerNav: Bool { plate } + /// The address as a band across the top of the page card. + var band: Bool { !plate } + /// The band holds Back, Forward and Reload, unless the tab bar has them. + var bandNav: Bool { band && !strip } + /// The band holds the sidebar's door and the tab buttons when neither + /// the sidebar nor the tab bar is there to hold them. + var bandWorkspace: Bool { !strip && !sidebarInView } +} + +extension Metrics.Tablet { + /// The Mac's sidebar header (Metrics.strip) and its doors (SideBar). + static let header: CGFloat = 52 + static let door: CGFloat = 36 + static let doorRadius: CGFloat = 10 + /// The Mac's address plate in the sidebar (SiteControls). + static let plate: CGFloat = 36 + static let plateRadius: CGFloat = 10 + static let plateFont: CGFloat = 12.5 + /// The Mac's tab bar: its row, a tab, a pin (Design.swift Density). + static let strip: CGFloat = 46 + static let stripTab: CGFloat = 34 + static let stripTabWidth: CGFloat = 186 + static let stripPin: CGFloat = 36 + static let stripGap: CGFloat = 2 +} + +/// A door of the Mac's chrome: a mark on a plate that shows under a +/// pointer or a press, a finger's target around it. +struct TabletDoor: View { + let title: String + let mark: Image + let id: String + var size: CGFloat = 15 + let action: () -> Void + + init(_ title: String, mac: MacGlyph, id: String, size: CGFloat = 15, action: @escaping () -> Void) { + self.title = title; self.mark = Image(mac.rawValue); self.id = id; self.size = size; self.action = action + } + init(_ title: String, asset: String, id: String, size: CGFloat = 17, action: @escaping () -> Void) { + self.title = title; self.mark = Image(asset); self.id = id; self.size = size; self.action = action + } + + var body: some View { + Button(action: action) { + mark.renderingMode(.template).resizable().scaledToFit().frame(width: size, height: size) + .frame(width: Metrics.Tablet.door, height: Metrics.Tablet.door) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + .contentShape(Rectangle()) + } + .buttonStyle(TabletDoorPress()) + .accessibilityLabel(title) + .accessibilityIdentifier(id) + } +} + +/// The Mac's door under a finger: its plate, briefly. +struct TabletDoorPress: ButtonStyle { + @Environment(\.isEnabled) private var enabled + func makeBody(configuration: Configuration) -> some View { + configuration.label + .foregroundStyle(enabled ? Ink.primary : Ink.secondary.opacity(0.5)) + .background(Ink.primary.opacity(configuration.isPressed ? 0.1 : 0), + in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + } +} + +/// Back, Forward and Reload (Stop while loading) for a tab: the focused +/// page's unless one is named. +struct TabletNavigationDoors: View { + @Environment(AppModel.self) private var app + var tab: Tab? = nil + private var target: Tab? { tab ?? app.browser.tab } + private var focused: Bool { target?.id == app.browser.tab?.id } + private var state: WebPool.PageState { target.flatMap { app.chrome.pageStates[$0.id] } ?? .idle } + private var canGoBack: Bool { + guard let target else { return false } + return focused ? app.backStack.route(for: target) != .nowhere + : state.canGoBack || state.readerEnabled || app.backStack.opener(of: target.id) != nil + } + + var body: some View { + HStack(spacing: 0) { + TabletDoor("Back", mac: .yabBack, id: id("tablet.back")) { act { app.goBack() } } + .disabled(!canGoBack) + TabletDoor("Forward", mac: .yabForward, id: id("tablet.forward")) { act { app.pageMenuForward() } } + .disabled(!state.canGoForward) + TabletDoor(state.isLoading ? "Stop" : "Reload", mac: state.isLoading ? .yabStop : .yabReload, id: id("tablet.reload"), size: 16) { + guard let target else { return } + if state.isLoading { app.pages.stop(target.id) } else { app.pages.reload(target.id) } + } + .disabled(target == nil) + } + } + + private func id(_ base: String) -> String { + guard let tab, !focused else { return base } + return base + "." + tab.id + } + + /// Another pane's door takes that pane first: navigation reads the + /// pool's active page in this same touch. + private func act(_ action: () -> Void) { + if let target, !focused { + app.browser.select(target.id) + _ = app.pages.activate(target) + } + action() + } +} + +/// The door that shows or hides the sidebar, with the layout's choices on +/// its hold. From the tab bar it brings the tabs back into the sidebar. +struct TabletSidebarDoor: View { + @Environment(AppModel.self) private var app + private var preferences: TabletLayoutPreferences { app.workspace.preferences } + var body: some View { + TabletDoor("Sidebar", asset: "TabletSidebar", id: "tablet.sidebar", size: 18) { + if !preferences.tabsInSidebar { + preferences.tabsInSidebar = true + preferences.sidebarShown = true + } else { + app.workspace.sidebarShown.toggle() + } + } + .accessibilityValue(preferences.tabsInSidebar && app.workspace.sidebarShown ? "shown" : "hidden") + .contextMenu { + Toggle("Show Tabs in Sidebar", isOn: Binding(get: { app.workspace.preferences.tabsInSidebar }, + set: { app.workspace.preferences.tabsInSidebar = $0 })) + Toggle("Show Address Bar", isOn: Binding(get: { app.workspace.preferences.addressBars }, + set: { app.workspace.preferences.addressBars = $0 })) + Toggle("Frame Page with Sidebar", isOn: Binding(get: { app.workspace.preferences.framed }, + set: { app.workspace.preferences.framed = $0 })) + } + } +} + +/// The sidebar's head, as the Mac's column has it: the door on the left, +/// Back, Forward and Reload against the right while the address is a plate. +struct TabletSidebarHeader: View { + let plan: TabletChromePlan + var body: some View { + HStack(spacing: 0) { + TabletSidebarDoor() + TabletAllTabsDoor() + Spacer(minLength: 0) + if plan.headerNav { TabletNavigationDoors() } + } + .padding(.horizontal, Metrics.Tablet.inset - 4) + .frame(height: Metrics.Tablet.header) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("tablet.sidebar.header") + } +} + +/// Opens and closes Site Controls in its popover from wherever it stands. +struct TabletSiteControlsDoor: View { + @Environment(AppModel.self) private var app + var size: CGFloat = 15 + private var open: Binding { + Binding(get: { app.surfaces.menu == .plate }, set: { open in + if !open { app.surfaces.closeMenu(); app.pageMenu.reset() } + }) + } + var body: some View { + TabletDoor("Site Controls", mac: .sliderHorizontal2Square, id: "tablet.siteControls", size: size) { + if app.surfaces.menu == .plate { app.surfaces.closeMenu(); app.pageMenu.reset() } + else { app.openPageMenu(); app.pageMenu.shown = true; app.pageMenu.page = .site } + } + .disabled(app.browser.tab == nil) + .popover(isPresented: open, arrowEdge: .top) { + TabletSiteControls().environment(app).presentationCompactAdaptation(.popover) + } + } +} + +/// The address in the sidebar, as the Mac's column shows it with Show +/// Address Bar off: the site in a plate, a tap away from the field. +struct TabletAddressPlate: View { + @Environment(AppModel.self) private var app + private var host: String { app.browser.tab.map { $0.addressHost.isEmpty ? $0.address : $0.addressHost } ?? "" } + + var body: some View { + HStack(spacing: 0) { + Button { app.surfaces.openField(.address) } label: { + HStack(spacing: 8) { + if app.pages.connection(app.browser.tab?.id ?? "", fallback: app.browser.tab?.navigationURL).secure == false, + app.browser.tab != nil { + TabletGlyph("TabletUnlock", size: 12, color: .red) + } + Text(host.isEmpty ? "Search or enter address" : host) + .font(.system(size: Metrics.Tablet.plateFont, weight: .medium)) + .foregroundStyle(host.isEmpty ? Ink.secondary : Ink.primary) + .lineLimit(1).truncationMode(.middle) + Spacer(minLength: 0) + } + .padding(.leading, 12) + .frame(maxHeight: .infinity) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Search or enter address") + .accessibilityValue(app.browser.tab?.address ?? "") + .accessibilityIdentifier("tablet.address") + TabletSiteControlsDoor(size: 14) + } + .frame(height: Metrics.Tablet.plate) + .background(Ink.primary.opacity(0.055), in: RoundedRectangle(cornerRadius: Metrics.Tablet.plateRadius, style: .continuous)) + .hoverEffect(.highlight) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("tablet.addressPlate") + } +} + +/// The tab buttons for when nothing else holds them: downloads, New Tab +/// (its hold has the rest) and All Tabs. +struct TabletWorkspaceDoors: View { + @Environment(AppModel.self) private var app + var body: some View { + HStack(spacing: 0) { + if app.showsToolbarDownloads(sidebarShown: false) { + TabletDownloadsButton(active: true, id: "tablet.downloads") + } + TabletNewTabMenu(id: "tablet.newTab") + TabletAllTabsDoor() + } + } +} + +/// All Tabs: every tab of the space as cards. +struct TabletAllTabsDoor: View { + @Environment(AppModel.self) private var app + var body: some View { + TabletDoor("All Tabs", mac: .yabTabs, id: "tablet.tabs", size: 17) { TabStack.of(app).openGallery() } + .disabled(app.browser.space.allTabs.isEmpty) + } +} + +/// New Tab on a tap; on a hold the other ways in and the split. +struct TabletNewTabMenu: View { + @Environment(AppModel.self) private var app + let id: String + var spaces: (() -> Void)? = nil + var body: some View { + Menu { + Button { app.openNewTab() } label: { Label("New Tab", image: MacGlyph.yabTabPlus.rawValue) } + .accessibilityIdentifier("tablet.menu.newTab") + Button { app.openNewTab(privately: true) } label: { Label("New Private Tab", image: MacGlyph.incognito.rawValue) } + .accessibilityIdentifier("tablet.menu.newPrivateTab") + Button { TabStack.of(app).openGallery() } label: { Label("All Tabs", image: MacGlyph.yabTabs.rawValue) } + .accessibilityIdentifier("tablet.menu.allTabs") + if app.workspace.canSplit, !app.pageIsPrivate, app.browser.tab != nil, app.browser.tab?.isMail != true { + Divider() + Button("Split View") { app.newTabBeside() } + .accessibilityIdentifier("tablet.menu.splitView") + if app.workspace.paired { + Button("Separate Split View") { app.workspace.fullSpread() } + Button("Close Split") { app.closeWorkspacePage() } + } + } + if let spaces { + Divider() + Button("Spaces and Chats", action: spaces) + .accessibilityIdentifier("tablet.menu.spaces") + } + } label: { + Glyph(.plusMedium, size: 17) + .frame(width: Metrics.Tablet.door, height: Metrics.Tablet.door) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + .contentShape(Rectangle()) + } primaryAction: { + app.openNewTab() + } + .buttonStyle(.plain) + .accessibilityLabel("New Tab") + .accessibilityIdentifier(id) + } +} + +/// The address band over a page card (Show Address Bar on, the sidebar +/// away, or the tab bar): the site in the middle, its controls at the ends. +/// In a split, one over each pane, the focused one in full. +struct TabletPageBand: View { + @Environment(AppModel.self) private var app + let tab: Tab + let plan: TabletChromePlan + let split: Bool + private var focused: Bool { app.browser.tab?.id == tab.id } + private var leading: Bool { !split || tab.id == app.workspace.first } + private var side: CGFloat { + // Both ends as wide as the wider, so the site stays centered. + let leading = (plan.bandWorkspace ? 1 : 0) + (plan.bandNav ? 3 : 0) + let trailing = 1 + (split ? 2 : 0) + (plan.bandWorkspace ? 2 + (app.showsToolbarDownloads(sidebarShown: false) ? 1 : 0) : 0) + return Metrics.Tablet.door * CGFloat(max(leading, trailing)) + } + + var body: some View { + HStack(spacing: 0) { + HStack(spacing: 0) { + // One door, at the window's leading edge: on the first page of a split. + if plan.bandWorkspace, leading { TabletSidebarDoor() } + if plan.bandNav { TabletNavigationDoors(tab: tab) } + } + .frame(width: side, alignment: .leading) + Button { + if !focused { app.browser.select(tab.id); _ = app.pages.activate(tab) } + app.surfaces.openField(.address) + } label: { + Text(tab.addressHost.isEmpty ? tab.address : tab.addressHost) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(focused ? Ink.primary : Ink.secondary) + .lineLimit(1).truncationMode(.middle) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Search or enter address").accessibilityValue(tab.address) + .accessibilityIdentifier(focused ? "tablet.address" : "tablet.address.\(tab.id)") + HStack(spacing: 0) { + if focused { TabletSiteControlsDoor() } + if split && focused { splitMenu } + if split { + Button { app.closeWorkspacePage(tab.id) } label: { + Glyph(.crossSmall, size: 15).frame(width: Metrics.Tablet.door, height: Metrics.Tablet.door) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight).contentShape(Rectangle()) + } + .buttonStyle(TabletDoorPress()) + .accessibilityLabel("Close Split").accessibilityIdentifier("tablet.close.\(tab.id)") + } + if plan.bandWorkspace && focused { TabletWorkspaceDoors() } + } + .frame(width: side, alignment: .trailing) + } + .padding(.horizontal, 4) + .frame(height: Metrics.Tablet.paneBar) + .background(Ink.surface.opacity(0.92)) + .overlay(alignment: .bottom) { Rectangle().fill(Ink.primary.opacity(0.08)).frame(height: 1) } + .accessibilityElement(children: .contain) + .accessibilityIdentifier("tablet.addressBar.\(tab.id)") + .accessibilityValue(focused ? "active" : "inactive") + } +} + +extension TabletPageBand { + /// The split's own choices, on its focused page. + var splitMenu: some View { + Menu { + Button("Split View") { app.newTabBeside() } + Button("Separate Split View") { app.workspace.fullSpread() } + Button("Close Split") { app.closeWorkspacePage(tab.id) } + } label: { + TabletGlyph("TabletSplitView", size: 16) + .frame(width: Metrics.Tablet.door, height: Metrics.Tablet.door) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("Split View").accessibilityIdentifier("tablet.paneMenu") + } +} + +/// The Mac's tab bar, for Show Tabs in Sidebar off: Back, Forward and +/// Reload, the space, its pins, its tabs, +, then downloads and All Tabs. +struct TabletTabStrip: View { + @Environment(AppModel.self) private var app + private var space: Space { app.browser.space } + private var tabs: [Tab] { + space.keptTabs + space.today.filter { space.isPrivate || !$0.isPrivate } + } + + var body: some View { + HStack(spacing: 6) { + HStack(spacing: 0) { + TabletSidebarDoor() + TabletNavigationDoors() + } + spaceMenu + ScrollViewReader { scroll in + ScrollView(.horizontal) { + HStack(spacing: Metrics.Tablet.stripGap) { + ForEach(app.sync.pins(in: space)) { pin($0) } + ForEach(tabs) { tab($0).id($0.id) } + } + .padding(.horizontal, 2) + } + .scrollIndicators(.hidden) + .onChange(of: app.browser.tab?.id, initial: true) { _, id in + guard let id else { return } + Motion.space.run { scroll.scrollTo(id, anchor: .center) } + } + } + TabletNewTabMenu(id: "tablet.newTab") + TabletDownloadsButton(active: true, id: "tablet.downloads") + TabletAllTabsDoor() + } + .padding(.horizontal, 8) + .frame(height: Metrics.Tablet.strip) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("tablet.strip") + } + + private var spaceMenu: some View { + Menu { + ForEach(app.browser.spaces.filter { !$0.isPrivate }) { item in + Button { Motion.space.run { app.workspace.fullSpread(); app.browser.showSpace(item.id) } } label: { + Text(item.emoji.isEmpty ? item.name : "\(item.emoji) \(item.name)") + } + } + } label: { + HStack(spacing: 6) { + if !space.emoji.isEmpty { Text(space.emoji).font(.system(size: 15)) } + Text(space.name).font(.system(size: 12.5, weight: .medium)).lineLimit(1) + } + .foregroundStyle(Ink.primary) + .padding(.horizontal, 10) + .frame(height: Metrics.Tablet.stripTab) + .background(Ink.primary.opacity(0.055), in: Capsule()) + .contentShape(.hoverEffect, Capsule()) + .hoverEffect(.highlight) + } + .buttonStyle(.plain) + .accessibilityLabel("Space") + .accessibilityValue(space.name) + .accessibilityIdentifier("tablet.strip.space") + } + + private func select(_ tab: Tab) { app.chooseFromSpacePage(tab.id, in: space.id) } + + private func pin(_ tab: Tab) -> some View { + Button { select(tab) } label: { + Favicon(icon: tab.icon, host: tab.addressHost, size: 17, url: tab.navigationURL, isPrivate: tab.isPrivate, mark: tab.customMark) + .frame(width: Metrics.Tablet.stripPin, height: Metrics.Tablet.stripTab) + .background(Ink.primary.opacity(tab.id == space.current ? 0.09 : 0.04), + in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + } + .buttonStyle(.plain) + .accessibilityLabel(tab.short) + .accessibilityAddTraits(tab.id == space.current ? .isSelected : []) + .accessibilityIdentifier("tablet.pin.\(tab.id)") + .modifier(TabHold(tab: tab, list: .pins)) + } + + private func tab(_ tab: Tab) -> some View { + let current = tab.id == space.current + return Button { select(tab) } label: { + HStack(spacing: 8) { + Favicon(icon: tab.icon, host: tab.addressHost, size: 15, url: tab.navigationURL, isPrivate: tab.isPrivate, mark: tab.customMark) + Text(tab.short).font(.system(size: 12.5)).lineLimit(1).truncationMode(.tail) + Spacer(minLength: 0) + } + .foregroundStyle(Ink.primary) + .padding(.horizontal, 10) + .frame(width: Metrics.Tablet.stripTabWidth, height: Metrics.Tablet.stripTab) + .background(Ink.primary.opacity(current ? 0.09 : 0), in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityIdentifier("tablet.tab.\(tab.id)") + .accessibilityAddTraits(current ? .isSelected : []) + .modifier(TabHold(tab: tab, list: tab.place == .kept ? .kept : .today)) + } +} diff --git a/Phone/Sources/App/TabletDownloads.swift b/Phone/Sources/App/TabletDownloads.swift new file mode 100644 index 00000000..f727d28f --- /dev/null +++ b/Phone/Sources/App/TabletDownloads.swift @@ -0,0 +1,233 @@ +import SwiftUI + +/// The Mac's downloads button (Hoard) for the iPad: in the sidebar's foot +/// always, in the toolbar while the sidebar is away and there is something +/// to show. Its popover holds the first file's question, then the list. +/// The phone keeps these in its plate (ChromeLayer), which the iPad's +/// toolbar layout never mounts. +struct TabletDownloadsButton: View { + @Environment(AppModel.self) private var app + /// Only the button on screen presents, so two never stand at once. + let active: Bool + let id: String + @State private var open = false + @State private var frame = CGRect.zero + + private typealias M = Metrics.Tablet + private var isPrivate: Bool { app.pageIsPrivate } + private var question: DownloadAsk? { app.downloads.asking(isPrivate: isPrivate) } + private var running: [DownloadEntry] { app.downloads.list(isPrivate: isPrivate).filter(\.isRunning) } + /// The last file in, as the Mac's button keeps its icon: until the list + /// or the file opens. + private var waiting: DownloadEntry? { + app.downloads.waiting.flatMap(app.downloads.entry).flatMap { $0.isPrivate == isPrivate && $0.isDone ? $0 : nil } + } + + var body: some View { + let running = running + Button { open.toggle() } label: { + ZStack { + if let waiting { + Glyph(mac: DownloadMark.of(waiting.name), size: 19) + .transition(.scale(scale: 0.4).combined(with: .opacity)) + } else { + Glyph(mac: .yabDownload, size: 17) + } + if !running.isEmpty { ring(DownloadWords.overall(running)) } + } + .frame(width: Metrics.touch, height: Metrics.touch) + .overlay(alignment: .topTrailing) { + if question != nil { + Circle().fill(Ink.unread) + .frame(width: M.downloadDot, height: M.downloadDot) + .offset(x: -M.downloadDotInset, y: M.downloadDotInset) + } + } + // Each arrival, the button gives a little, as the Mac's does. + .keyframeAnimator(initialValue: CGFloat(1), trigger: app.downloads.bumps) { content, scale in + content.scaleEffect(scale) + } keyframes: { _ in + SpringKeyframe(Motion.reduced ? 1 : M.downloadBump, duration: 0.1) + SpringKeyframe(1, duration: 0.3) + } + .animation(Motion.downloadAsk.current, value: waiting?.id) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame = $0; land() } + .onChange(of: active, initial: true) { _, _ in land() } + .onDisappear { app.workspace.downloadsLandings[id] = nil } + .accessibilityLabel("Downloads") + .accessibilityValue(question != nil ? "Asking" : !running.isEmpty ? "Downloading" : waiting.map { "Downloaded \($0.name)" } ?? "") + .accessibilityIdentifier(id) + .popover(isPresented: Binding(get: { active && open }, set: { open = $0 }), arrowEdge: .bottom) { + TabletDownloadsPanel().environment(app).presentationCompactAdaptation(.popover) + } + // A site's first file asks at once, from wherever the button is. + .onChange(of: question?.id, initial: true) { _, id in if id != nil { open = true } } + .onChange(of: active) { _, shown in open = shown && question != nil } + .onChange(of: open) { _, shown in if shown { app.downloads.seen() } } + } + + /// A file in the air lands on the button on screen. + private func land() { app.workspace.downloadsLandings[id] = active && !frame.isEmpty ? frame : nil } + + /// The Mac's badge: the progress round the mark, a track where it + /// doesn't know the size yet. + private func ring(_ percent: Int?) -> some View { + ZStack { + Circle().stroke(Ink.primary.opacity(0.15), lineWidth: M.downloadRingLine) + Circle().trim(from: 0, to: CGFloat(percent ?? 0) / 100) + .stroke(Ink.primary, style: StrokeStyle(lineWidth: M.downloadRingLine, lineCap: .round)) + .rotationEffect(.degrees(-90)) + } + .frame(width: M.downloadRing, height: M.downloadRing) + .accessibilityHidden(true) + } +} + +/// Files thrown at the downloads button, as the Mac's are (HoardSkyView): +/// a dark disc with a white arrow lifts off where the link was held, then +/// flies an arc into the button, smaller as it comes in, and the button +/// gives. Over everything, touching nothing. +struct TabletDownloadFlights: View { + @Environment(AppModel.self) private var app + + var body: some View { + ZStack(alignment: .topLeading) { + ForEach(app.downloads.flights) { flight in + TabletDownloadFlight(flight: flight) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .ignoresSafeArea() + .allowsHitTesting(false) + .accessibilityHidden(true) + .onAppear { app.downloads.flies = true } + .onDisappear { app.downloads.flies = false } + } +} + +private struct TabletDownloadFlight: View { + @Environment(AppModel.self) private var app + let flight: DownloadStore.Flight + @State private var lifted = false + @State private var travel: CGFloat = 0 + @State private var landing: CGPoint? + + private typealias M = Metrics.Tablet + + var body: some View { + let rise = CGPoint(x: flight.from.x, y: flight.from.y - M.downloadRise) + TabletDownloadDisc() + .scaleEffect(lifted ? 1 : 0.4) + .opacity(lifted ? 1 : 0) + .modifier(TabletFlightPose(start: rise, end: landing ?? rise, travel: travel, + landingScale: M.downloadRing / M.downloadDisc, fadesWhereItRose: landing == nil)) + .offset(y: lifted ? 0 : M.downloadRise) + .onAppear(perform: fly) + } + + private func fly() { + let id = flight.id, downloads = app.downloads + guard !Motion.disabled, !Motion.reduced else { downloads.landed(id); return } + withAnimation(.easeOut(duration: M.downloadLift)) { lifted = true } completion: { + // Where it lands is asked once it has lifted off. + landing = app.workspace.downloadsLandings.values.first.map { CGPoint(x: $0.midX, y: $0.midY) } + withAnimation(.timingCurve(0.45, 0, 0.2, 1, duration: M.downloadArc)) { travel = 1 } completion: { + downloads.landed(id) + } + } + } +} + +/// Along the arc: down to a low button it rises first and falls in, up to +/// a high one it goes along and then up (the Mac's HoardSkyView.arc); down +/// to the badge's size past halfway, gone in its last moment. +private struct TabletFlightPose: ViewModifier, Animatable { + let start: CGPoint + let end: CGPoint + var travel: CGFloat + let landingScale: CGFloat + let fadesWhereItRose: Bool + + var animatableData: CGFloat { + get { travel } + set { travel = newValue } + } + + func body(content: Content) -> some View { + let t = travel + let control = Self.control(from: start, to: end) + let u = 1 - t + let x = u * u * start.x + 2 * u * t * control.x + t * t * end.x + let y = u * u * start.y + 2 * u * t * control.y + t * t * end.y + let shrink = t < 0.55 ? 1 : 1 + (landingScale - 1) * (t - 0.55) / 0.45 + let fade: CGFloat = fadesWhereItRose ? 1 - t : (t < 0.94 ? 1 : 1 - (t - 0.94) / 0.06) + return content + .scaleEffect(shrink) + .opacity(Double(max(0, fade))) + .position(x: x, y: y) + } + + static func control(from start: CGPoint, to end: CGPoint) -> CGPoint { + end.y < start.y - 40 + ? CGPoint(x: start.x + (end.x - start.x) * 0.7, y: start.y - 10) + : CGPoint(x: (start.x + end.x) / 2, y: min(start.y, end.y) - Metrics.Tablet.downloadArcHeight) + } +} + +/// The Mac's thrown file: near black, a white arrow, a teal glow. +private struct TabletDownloadDisc: View { + var body: some View { + let side = Metrics.Tablet.downloadDisc + let k = side / 19 + Circle() + .fill(Color(red: 13 / 255, green: 26 / 255, blue: 20 / 255)) + .overlay { + Path { path in + path.move(to: CGPoint(x: 9.5 * k, y: 5 * k)) + path.addLine(to: CGPoint(x: 9.5 * k, y: 13.4 * k)) + path.move(to: CGPoint(x: 6 * k, y: 10.2 * k)) + path.addLine(to: CGPoint(x: 9.5 * k, y: 13.6 * k)) + path.addLine(to: CGPoint(x: 13 * k, y: 10.2 * k)) + } + .stroke(.white, style: StrokeStyle(lineWidth: 1.7 * k, lineCap: .round, lineJoin: .round)) + } + .frame(width: side, height: side) + .shadow(color: Color(red: 90 / 255, green: 190 / 255, blue: 170 / 255).opacity(0.55), radius: 5) + } +} + +/// The popover's body: the question while one waits, else every file. +struct TabletDownloadsPanel: View { + @Environment(AppModel.self) private var app + @Environment(\.colorScheme) private var scheme + + var body: some View { + let isPrivate = app.pageIsPrivate + Group { + if let question = app.downloads.asking(isPrivate: isPrivate) { + DownloadAskCard(ask: question) + .id(question.id) + .frame(height: Metrics.DownloadAsk.height) + .padding(Metrics.Tablet.downloadsInset) + } else { + ScrollView { + VStack(alignment: .leading, spacing: 0) { + Text("Downloads").font(.system(size: 13, weight: .semibold)) + .padding(.horizontal, Metrics.PageMenu.inset + 6).padding(.vertical, 10) + DownloadsBody(ink: PageMenuInk(dark: isPrivate || scheme == .dark), host: nil, isPrivate: isPrivate) + } + .padding(.top, Metrics.Tablet.downloadsInset) + } + .scrollBounceBehavior(.basedOnSize) + .frame(maxHeight: Metrics.Tablet.downloadsHeight) + } + } + .frame(width: Metrics.Tablet.downloadsWidth) + .animation(Motion.downloadAsk.current, value: app.downloads.asking(isPrivate: isPrivate)?.id) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("tablet.downloads") + } +} diff --git a/Phone/Sources/App/TabletLayoutPreferences.swift b/Phone/Sources/App/TabletLayoutPreferences.swift index 6e1f0a4e..bb89534c 100644 --- a/Phone/Sources/App/TabletLayoutPreferences.swift +++ b/Phone/Sources/App/TabletLayoutPreferences.swift @@ -8,12 +8,53 @@ extension Metrics { static let sidebarMinimum: CGFloat = 220 static let sidebarMaximum: CGFloat = 360 static let toolbar: CGFloat = 44 + /// The Mac's 36-point address band, centered in the 44-point row. + static let addressHeight: CGFloat = 36 + static let rim: CGFloat = 8 static let paneBar: CGFloat = 44 static let row: CGFloat = 44 + /// The Mac's row ground, inside the finger's row. + static let rowGround: CGFloat = 36 + static let clearLine: CGFloat = 28 + /// The spaces not in front, in the foot: the Mac's dimmed marks. + static let dimmedSpace: Double = 0.45 + /// The Mac's two-finger paging (SpacePaging): the row at half the + /// travel, a 0.15 give past the ends, and a let-go speed (points a + /// second) that keeps going. + static let spacePull: CGFloat = 0.5 + static let spaceGive: CGFloat = 0.15 + static let spaceFling: CGFloat = 300 static let splitGap: CGFloat = 8 static let resizeTarget: CGFloat = 20 static let inset: CGFloat = 10 static let pin: CGFloat = 48 + static let downloadsWidth: CGFloat = 340 + static let downloadsHeight: CGFloat = 480 + static let downloadsInset: CGFloat = 8 + static let downloadDot: CGFloat = 7 + static let downloadDotInset: CGFloat = 9 + /// The Mac's Hoard: the badge's ring round the button's mark, the + /// disc a file is thrown as, its lift, its arc and how far it rises. + static let downloadRing: CGFloat = 26 + static let downloadRingLine: CGFloat = 2 + static let downloadDisc: CGFloat = 24 + static let downloadLift: Double = 0.11 + static let downloadArc: Double = 0.56 + static let downloadRise: CGFloat = 6 + static let downloadArcHeight: CGFloat = 90 + static let downloadBump: CGFloat = 1.18 + static let pinGap: CGFloat = 7 + static let pinMinWidth: CGFloat = 47 + static let pinMaxColumns = 4 + + /// The Mac's SideBar.pinColumns: as many as fit, four at most, then + /// only as many as keep the rows even, the row filling the width. + static func pinColumns(_ count: Int, width: CGFloat) -> Int { + guard count > 0 else { return 1 } + let fits = min(pinMaxColumns, max(1, Int((width + pinGap) / (pinMinWidth + pinGap)))) + let rows = (count + fits - 1) / fits + return (count + rows - 1) / rows + } static let pairInset: CGFloat = 4 static let pairGap: CGFloat = 4 static let pairRadius: CGFloat = 5 @@ -29,7 +70,11 @@ extension Metrics { final class TabletLayoutPreferences { @ObservationIgnored private let defaults: UserDefaults? var sidebarShown: Bool { didSet { save(sidebarShown, "ipadSidebarShown") } } - var addressBars: Bool { didSet { save(addressBars, "ipadAddressBars") } } + /// The Mac's Show Address Bar: a band over the page card; off, the + /// address is a plate in the sidebar, as the Mac's default. + var addressBars: Bool { didSet { save(addressBars, "ipadAddressBar") } } + /// The Mac's Show Tabs in Sidebar: off, the tabs go across the top. + var tabsInSidebar: Bool { didSet { save(tabsInSidebar, "ipadTabsInSidebar") } } var framed: Bool { didSet { save(framed, "ipadPageFrame") } } private(set) var sidebarWidth: CGFloat private(set) var splitFraction: CGFloat @@ -40,7 +85,9 @@ final class TabletLayoutPreferences { defaults?.object(forKey: key) == nil ? fallback : defaults!.bool(forKey: key) } sidebarShown = flag("ipadSidebarShown", true) - addressBars = flag("ipadAddressBars", true) + // A new key: the old one defaulted to the band the Mac keeps off. + addressBars = flag("ipadAddressBar", false) + tabsInSidebar = flag("ipadTabsInSidebar", true) framed = flag("ipadPageFrame", true) let width = defaults?.object(forKey: "ipadSidebarWidth") as? Double ?? Double(Metrics.Tablet.sidebar) sidebarWidth = Self.width(CGFloat(width)) diff --git a/Phone/Sources/App/TabletOmnibox.swift b/Phone/Sources/App/TabletOmnibox.swift index e14956cc..67480a74 100644 --- a/Phone/Sources/App/TabletOmnibox.swift +++ b/Phone/Sources/App/TabletOmnibox.swift @@ -277,6 +277,7 @@ struct TabletOmnibox: View { case .ask: "Ask" case .task: "Send" case .settings: "Open Settings" + case .command: "Do" case .findOnPage: "Find" } } diff --git a/Phone/Sources/App/TabletSidebar.swift b/Phone/Sources/App/TabletSidebar.swift index 4a3993fe..58a7ffe9 100644 --- a/Phone/Sources/App/TabletSidebar.swift +++ b/Phone/Sources/App/TabletSidebar.swift @@ -1,46 +1,35 @@ import SwiftUI -/// The Mac's sidebar order, with iPad touch targets and the existing tab menus. +/// The Mac's column: its header (the door, and Back, Forward and Reload +/// while the address is a plate), the address plate, then each space's +/// page of pins and tabs side by side, sliding as the Mac's do when the +/// space changes (docs/space-switching.md), and the foot. struct TabletSidebar: View { @Environment(AppModel.self) private var app @Environment(\.colorScheme) private var scheme let width: CGFloat + /// On screen: the sidebar stays in the tree, faded, while it is away. + var shown = true + var plan = TabletChromePlan(strip: false, sidebarInView: true, addressBars: false) @State private var browseSpaces = false + @GestureState private var drag: CGFloat = 0 private var space: Space { app.browser.space } - private var shownPins: [Tab] { app.sync.pins(in: space) } + /// The pages side by side: every ordinary space, and a private one only while it is in front. + private var pages: [Space] { app.browser.spaces.filter { !$0.isPrivate || $0.id == space.id } } private var pair: [Tab.ID] { app.workspace.paired ? [app.workspace.first, app.workspace.second].compactMap { $0 } : [] } var body: some View { VStack(spacing: 0) { - ScrollView { - VStack(alignment: .leading, spacing: 0) { - if !shownPins.isEmpty { - LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 7), count: 4), spacing: 7) { - ForEach(shownPins) { tab in - Button { select(tab) } label: { - mark(tab, size: 24).frame(maxWidth: .infinity).frame(height: Metrics.Tablet.pin) - .background(Ink.surface.opacity(tab.id == space.current ? 0.95 : 0.5), in: RoundedRectangle(cornerRadius: 10)) - } - .buttonStyle(.plain).accessibilityLabel(tab.short) - .accessibilityIdentifier("tablet.pin.\(tab.id)") - .modifier(TabHold(tab: tab, list: .pins)) - } - }.padding(.bottom, 12) - } - ForEach(space.kept) { kept($0, depth: 0) } - if !space.today.isEmpty { - HStack(spacing: 10) { - Rectangle().fill(Ink.primary.opacity(0.12)).frame(height: 0.5) - Button("Clear") { Task { @MainActor in await app.tabClear.clear(in: space.id) } } - .font(.system(size: 12)).foregroundStyle(Ink.secondary) - .frame(minHeight: Metrics.touch) - .accessibilityIdentifier("tablet.clear") - }.padding(.horizontal, 8) - } - if pair.count == 2 { pairRow } - ForEach(space.today.filter { (space.isPrivate || !$0.isPrivate) && !pair.contains($0.id) }) { row($0) } - }.padding(.horizontal, Metrics.Tablet.inset).padding(.top, 8) + // Away, its doors go: the band holds the same ones (TabletPageBand). + if shown { TabletSidebarHeader(plan: plan).transition(.identity) } else { Color.clear.frame(height: Metrics.Tablet.header) } + if plan.plate { + TabletAddressPlate() + .padding(.horizontal, Metrics.Tablet.inset) + .padding(.bottom, 8) + // Gone at once: the band takes the address as the sidebar leaves. + .transition(.identity) } + pager footer } .frame(width: width) @@ -48,35 +37,142 @@ struct TabletSidebar: View { .accessibilityIdentifier("tablet.sidebar.content") } + // MARK: - the pages + + private var pager: some View { + let index = CGFloat(pages.firstIndex { $0.id == space.id } ?? 0) + return HStack(spacing: 0) { + ForEach(pages) { page in + self.page(page) + .frame(width: width) + .accessibilityHidden(page.id != space.id) + } + } + .frame(width: width, alignment: .leading) + .offset(x: -index * width + drag) + .animation(Motion.space.current, value: index) + .clipped() + .contentShape(Rectangle()) + // A sideways swipe pages the spaces as two fingers do on the Mac + // (SpacePaging): half the finger's travel, a page at most, resisting + // past the ends; let go moving it keeps on, held it settles nearest. + .simultaneousGesture( + DragGesture(minimumDistance: 24) + .updating($drag) { value, state, _ in + guard abs(value.translation.width) > abs(value.translation.height) * 1.5 else { return } + state = Self.paged(value.translation.width, index: Int(index), count: pages.count, width: width) + } + .onEnded { value in + guard abs(value.translation.width) > abs(value.translation.height) * 1.5 else { return } + let moved = Self.paged(value.translation.width, index: Int(index), count: pages.count, width: width) + let speed = value.velocity.width * Metrics.Tablet.spacePull + let step: Int + if abs(speed) > Metrics.Tablet.spaceFling { step = speed < 0 ? 1 : -1 } + else { step = abs(moved) > width / 2 ? (moved < 0 ? 1 : -1) : 0 } + let next = Int(index) + step + guard step != 0, pages.indices.contains(next) else { return } + show(pages[next]) + } + ) + } + + /// The pages' offset for a finger's travel: the Mac's half, one page at + /// most, a little give past the first and the last. + static func paged(_ travel: CGFloat, index: Int, count: Int, width: CGFloat) -> CGFloat { + let moved = min(width, max(-width, travel * Metrics.Tablet.spacePull)) + let pastEnd = (index == 0 && moved > 0) || (index >= count - 1 && moved < 0) + return pastEnd ? moved * Metrics.Tablet.spaceGive : moved + } + + private func page(_ space: Space) -> some View { + let pins = app.sync.pins(in: space) + let front = space.id == self.space.id + return ScrollView { + VStack(alignment: .leading, spacing: 0) { + if !pins.isEmpty { + let columns = Metrics.Tablet.pinColumns(pins.count, width: width - 2 * Metrics.Tablet.inset) + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: Metrics.Tablet.pinGap), count: columns), + spacing: Metrics.Tablet.pinGap) { + ForEach(pins) { tab in + Button { select(tab, in: space) } label: { + mark(tab, size: 24).frame(maxWidth: .infinity).frame(height: Metrics.Tablet.pin) + .background(Ink.surface.opacity(tab.id == space.current ? 0.95 : 0.5), + in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + } + .buttonStyle(.plain).accessibilityLabel(tab.short) + .accessibilityIdentifier("tablet.pin.\(tab.id)") + .modifier(TabHold(tab: tab, list: .pins)) + } + }.padding(.bottom, 12) + } + ForEach(space.kept) { kept($0, in: space, depth: 0) } + if !space.today.isEmpty { clearLine(space) } + if front, pair.count == 2 { pairRow(space) } + ForEach(space.today.filter { (space.isPrivate || !$0.isPrivate) && !(front && pair.contains($0.id)) }) { row($0, in: space) } + } + .padding(.horizontal, Metrics.Tablet.inset).padding(.top, 4) + } + .scrollIndicators(.hidden) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("tablet.sidebar.page.\(space.id)") + } + private func mark(_ tab: Tab, size: CGFloat = 17) -> some View { Favicon(icon: tab.icon, host: tab.addressHost, size: size, url: tab.navigationURL, isPrivate: tab.isPrivate, mark: tab.customMark) } - private func select(_ tab: Tab) { app.chooseFromSpacePage(tab.id, in: space.id) } + private func select(_ tab: Tab, in space: Space) { app.chooseFromSpacePage(tab.id, in: space.id) } + private func show(_ space: Space) { + guard space.id != self.space.id else { return } + Motion.space.run { app.workspace.fullSpread(); app.browser.showSpace(space.id) } + } + + /// The Mac's line between kept tabs and Today: thin, Clear at its end. + private func clearLine(_ space: Space) -> some View { + HStack(spacing: 10) { + Rectangle().fill(Ink.primary.opacity(0.12)).frame(height: 0.5) + Button("Clear") { Task { @MainActor in await app.tabClear.clear(in: space.id) } } + .font(.system(size: 11)).foregroundStyle(Ink.secondary) + .frame(minWidth: Metrics.touch, minHeight: Metrics.Tablet.clearLine) + .contentShape(Rectangle()) + .hoverEffect(.highlight) + .accessibilityIdentifier("tablet.clear") + } + .padding(.horizontal, 8) + } - private func row(_ tab: Tab, depth: Int = 0) -> some View { - Button { select(tab) } label: { + /// A tab's row: the Mac's 36-point ground inside a finger's 44. + private func row(_ tab: Tab, in space: Space, depth: Int = 0) -> some View { + let current = tab.id == space.current + return Button { select(tab, in: space) } label: { HStack(spacing: 10) { mark(tab) Text(tab.short).font(.system(size: 13.5)).lineLimit(1).truncationMode(.tail) Spacer(minLength: 0) } .foregroundStyle(Ink.primary) - .padding(.horizontal, 10).frame(minHeight: Metrics.Tablet.row) - .background(Ink.surface.opacity(tab.id == space.current ? 0.85 : 0), in: RoundedRectangle(cornerRadius: 8)) + .padding(.horizontal, 10) + .frame(height: Metrics.Tablet.rowGround) + .background(Ink.surface.opacity(current ? 0.85 : 0), + in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) .padding(.leading, CGFloat(depth) * 16) + .frame(minHeight: Metrics.Tablet.row) .contentShape(Rectangle()) } .buttonStyle(.plain).accessibilityIdentifier("tablet.tab.\(tab.id)") - .accessibilityAddTraits(tab.id == space.current ? .isSelected : []) + .accessibilityAddTraits(current ? .isSelected : []) .modifier(TabHold(tab: tab, list: tab.place == .kept ? .kept : .today)) } - private var pairRow: some View { + private func pairRow(_ space: Space) -> some View { HStack(spacing: Metrics.Tablet.pairGap) { ForEach(pair, id: \.self) { id in if let tab = app.browser.tab(id) { - Button { select(tab) } label: { + Button { select(tab, in: space) } label: { HStack(spacing: Metrics.Tablet.pairPadding) { mark(tab, size: Metrics.Tablet.pairIcon) Text(tab.short).font(.system(size: 12.5)).lineLimit(1).truncationMode(.tail) @@ -85,9 +181,10 @@ struct TabletSidebar: View { .foregroundStyle(Ink.primary) .padding(.horizontal, Metrics.Tablet.pairPadding) .frame(maxWidth: .infinity) - .frame(height: Metrics.Tablet.row - 2 * Metrics.Tablet.pairInset) + .frame(height: Metrics.Tablet.rowGround - 2 * Metrics.Tablet.pairInset) .background(Ink.primary.opacity(0.07), in: RoundedRectangle(cornerRadius: Metrics.Tablet.pairRadius)) - .padding(.vertical, Metrics.Tablet.pairInset) + // The Mac's chip, a finger's height to touch. + .frame(height: Metrics.Tablet.row) .contentShape(Rectangle()) } .buttonStyle(.plain) @@ -99,13 +196,14 @@ struct TabletSidebar: View { } } .padding(.horizontal, Metrics.Tablet.pairInset) - .background(Ink.surface.opacity(0.85), in: RoundedRectangle(cornerRadius: 8)) + .background(Ink.surface.opacity(0.85), in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous) + .inset(by: (Metrics.Tablet.row - Metrics.Tablet.rowGround) / 2)) .accessibilityElement(children: .contain).accessibilityIdentifier("tablet.split.row") } - private func kept(_ item: KeptItem, depth: Int) -> AnyView { + private func kept(_ item: KeptItem, in space: Space, depth: Int) -> AnyView { switch item { - case let .tab(tab): return AnyView(row(tab, depth: depth)) + case let .tab(tab): return AnyView(row(tab, in: space, depth: depth)) case let .folder(folder): return AnyView(VStack(spacing: 0) { Button { (folder.open ? Motion.folderShut : Motion.folderOpen).run { app.browser.setFolder(folder.id, open: !folder.open, in: space.id) } } label: { @@ -121,56 +219,63 @@ struct TabletSidebar: View { .contentShape(Rectangle()) } .buttonStyle(.plain).accessibilityIdentifier("tablet.folder.\(folder.id)") - if folder.open { ForEach(folder.items) { kept($0, depth: depth + 1) } } + if folder.open { ForEach(folder.items) { kept($0, in: space, depth: depth + 1) } } }) } } + // MARK: - the foot + + /// The Mac's foot: downloads, the spaces in the middle (the one in front + /// in its color, the rest dimmed), and +. private var footer: some View { HStack(spacing: 2) { - Button { app.openSettingsFromSpaces(at: nil) } label: { - Glyph(SettingsFieldRow.glyph, size: 17).frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) - } - .frame(width: Metrics.touch, height: Metrics.touch).accessibilityLabel("Settings") - .contextMenu { - Button("Spaces and Chats") { browseSpaces = true } + TabletDownloadsButton(active: shown, id: "tablet.downloads.sidebar") + ScrollViewReader { scroll in + ScrollView(.horizontal) { + HStack(spacing: 2) { + ForEach(app.browser.spaces.filter { !$0.isPrivate }) { item in spaceButton(item).id(item.id) } + } + .frame(minWidth: max(0, width - 2 * (Metrics.touch + 2) - 12)) } + .scrollIndicators(.hidden) + .onChange(of: space.id, initial: true) { _, id in Motion.space.run { scroll.scrollTo(id, anchor: .center) } } + } + TabletNewTabMenu(id: "tablet.sidebar.newTab", spaces: { browseSpaces = true }) .popover(isPresented: $browseSpaces) { SpacePagesCard(content: NewTabContent.make(for: app), width: Metrics.Workspace.sidebar, maxHeight: TabletWorkspaceGeometry.sheetHeight, fullness: 1, headerInset: SpacePagesCard.capsuleTop) .environment(app).presentationCompactAdaptation(.popover) } - .accessibilityIdentifier("tablet.settings") - ScrollView(.horizontal) { - HStack(spacing: 2) { - ForEach(app.browser.spaces.filter { !$0.isPrivate }) { item in - Button { app.workspace.fullSpread(); app.browser.showSpace(item.id) } label: { - Group { - if item.emoji.isEmpty { Image(systemName: "circle.fill").font(.system(size: 10)) } - else { Text(item.emoji).font(.system(size: 17)) } - } - .frame(width: Metrics.touch, height: Metrics.touch) - .background(Ink.surface.opacity(item.id == space.id ? 0.8 : 0), in: RoundedRectangle(cornerRadius: 8)) - .contentShape(Rectangle()) - } - .buttonStyle(.plain).accessibilityLabel(item.name) - .accessibilityAddTraits(item.id == space.id ? .isSelected : []) - .accessibilityIdentifier("tablet.space.\(item.id)") - } - } - }.scrollIndicators(.hidden) - Button { app.openNewTab() } label: { - Glyph(.plusMedium, size: 18).frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) - } - .frame(width: Metrics.touch, height: Metrics.touch).accessibilityLabel("New Tab") - .accessibilityIdentifier("tablet.sidebar.newTab") } - .buttonStyle(.plain).foregroundStyle(Ink.primary) - .padding(.horizontal, 4).padding(.vertical, 6) + .foregroundStyle(Ink.primary) + .padding(.horizontal, 6).padding(.vertical, 6) .background(alignment: .top) { Rectangle().fill(Ink.primary.opacity(0.1)).frame(height: 0.5) } .onChange(of: app.browser.tab?.id) { _, _ in browseSpaces = false } .onChange(of: app.surfaces.chat) { _, _ in browseSpaces = false } .onChange(of: app.surfaces.settings) { _, shown in if shown { browseSpaces = false } } } + + private func spaceButton(_ item: Space) -> some View { + let current = item.id == space.id + return Button { show(item) } label: { + Group { + if item.emoji.isEmpty { Image(systemName: "circle.fill").font(.system(size: 9)) } + else { Text(item.emoji).font(.system(size: 17)) } + } + .saturation(current ? 1 : 0) + .opacity(current ? 1 : Metrics.Tablet.dimmedSpace) + .frame(width: Metrics.Tablet.door, height: Metrics.Tablet.door) + .background(Ink.surface.opacity(current ? 0.8 : 0), + in: RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .contentShape(.hoverEffect, RoundedRectangle(cornerRadius: Metrics.Tablet.doorRadius, style: .continuous)) + .hoverEffect(.highlight) + .frame(width: Metrics.touch, height: Metrics.touch) + .contentShape(Rectangle()) + } + .buttonStyle(.plain).accessibilityLabel(item.name) + .accessibilityAddTraits(current ? .isSelected : []) + .accessibilityIdentifier("tablet.space.\(item.id)") + } } diff --git a/Phone/Sources/App/TabletWorkspaceView.swift b/Phone/Sources/App/TabletWorkspaceView.swift index f5593b12..af7641cb 100644 --- a/Phone/Sources/App/TabletWorkspaceView.swift +++ b/Phone/Sources/App/TabletWorkspaceView.swift @@ -17,24 +17,33 @@ struct TabletWorkspaceGeometry: Equatable { let framed: Bool var sidebarExtent: CGFloat = Metrics.Tablet.sidebar var paired = false + /// Tabs across the top (the Mac's tab bar) instead of in the sidebar. + var strip = false static func usesToolbar(size: CGSize, regular: Bool, idiom: UIUserInterfaceIdiom, verticalBar: Bool = false) -> Bool { !verticalBar && idiom == .pad && regular && min(size.width, size.height) >= minimumSide } - var top: CGFloat { statusBar + Self.toolbar } + /// The workspace's top: under the status bar, and under the tab bar + /// when there is one. The sidebar starts here; the page card a rim lower. + var top: CGFloat { statusBar + (strip ? Metrics.Tablet.strip : 0) } var sidebarWidth: CGFloat { - guard sidebar else { return 0 } + guard sidebar, !strip else { return 0 } let width = min(Metrics.Tablet.sidebarMaximum, max(Metrics.Tablet.sidebarMinimum, sidebarExtent)) let reserved = paired && size.width > size.height ? Metrics.Workspace.minimumPane * 2 + Metrics.Tablet.splitGap : Metrics.Workspace.minimumPane return size.width - width - (framed ? 16 : 0) >= reserved ? width : 0 } - var rim: CGFloat { sidebarWidth > 0 && framed ? 8 : 0 } + /// The Mac's card: in from every edge while framed, the sidebar or not. + var rim: CGFloat { framed ? Metrics.Tablet.rim : 0 } var page: CGRect { CGRect(x: sidebarWidth + rim, y: top + rim, width: max(1, size.width - sidebarWidth - rim * 2), height: max(1, size.height - top - rim * 2)) } + static func conversation(in size: CGSize, expanded: Bool, chat: Bool) -> CGFloat { + let column = Metrics.Workspace.conversation + return expanded && chat && size.width >= column + Metrics.Workspace.minimumPane ? column : 0 + } func searchHeight(keyboard: CGFloat) -> CGFloat { max(44, min(292, size.height - max(0, keyboard) - top - 40)) } } @@ -42,10 +51,21 @@ struct TabletWorkspaceView: View { @Environment(AppModel.self) private var app let size: CGSize private var preferences: TabletLayoutPreferences { app.workspace.preferences } + /// A chat's column stands beside the workspace, as the phone's wide + /// layout and the Mac's chat panel do, never over its toolbar or page. + private var conversation: CGFloat { + TabletWorkspaceGeometry.conversation(in: size, expanded: app.workspace.expanded, + chat: app.chatSheet.shown && !app.field.shown) + } private var geometry: TabletWorkspaceGeometry { - TabletWorkspaceGeometry(size: size, statusBar: SettingsLayer.statusBar, + TabletWorkspaceGeometry(size: CGSize(width: size.width - conversation, height: size.height), statusBar: SettingsLayer.statusBar, sidebar: preferences.sidebarShown, framed: preferences.framed, - sidebarExtent: preferences.sidebarWidth, paired: app.workspace.paired) + sidebarExtent: preferences.sidebarWidth, paired: app.workspace.paired, + strip: !preferences.tabsInSidebar) + } + private func plan(_ g: TabletWorkspaceGeometry) -> TabletChromePlan { + TabletChromePlan(strip: g.strip, sidebarInView: g.sidebarWidth > 0, addressBars: preferences.addressBars, + split: layout(g).split) } private var covered: Bool { FirstLaunch.shows(app) || app.surfaces.settings || app.surfaces.join || app.surfaces.chat != nil @@ -63,17 +83,17 @@ struct TabletWorkspaceView: View { ZStack(alignment: .topLeading) { Ink.ground.ignoresSafeArea() SpacePagesBackground(spaces: app.browser.spaces, pages: app.browser.spaces.map(\.id), position: CGFloat(app.browser.spaceIndex)) - .frame(width: size.width, height: size.height - g.top).offset(y: g.top) + .frame(width: g.size.width, height: size.height - g.top).offset(y: g.top) pages(in: g) .frame(width: g.page.width, height: g.page.height) .padding(.leading, g.page.minX).padding(.top, g.page.minY) .accessibilityHidden(covered || gallery) // Keep the outgoing sidebar at its full width while it travels. // Removing the conditional view first made its rows vanish at once. - TabletSidebar(width: preferences.sidebarWidth) + TabletSidebar(width: preferences.sidebarWidth, shown: g.sidebarWidth > 0, plan: plan(g)) .frame(height: size.height - g.top) .offset(x: Motion.reduced || g.sidebarWidth > 0 ? 0 : -preferences.sidebarWidth, y: g.top) - .opacity(g.sidebarWidth > 0 ? 1 : 0) + .opacity(g.sidebarWidth > 0 ? (gallery ? app.surfaces.chromeOpacity : 1) : 0) .allowsHitTesting(g.sidebarWidth > 0 && !covered && !gallery) .accessibilityHidden(g.sidebarWidth == 0 || covered || gallery) TabletResizeHandle(label: "Sidebar Width", identifier: "tablet.sidebar.resize", value: preferences.sidebarWidth) { width, save in @@ -84,20 +104,18 @@ struct TabletWorkspaceView: View { .opacity(g.sidebarWidth > 0 ? 1 : 0) .allowsHitTesting(g.sidebarWidth > 0 && !covered && !gallery) .accessibilityHidden(g.sidebarWidth == 0 || covered || gallery) - if !FirstLaunch.shows(app), !gallery { - Group { - if !layout(g).split && preferences.addressBars { - TabletSingleToolbar(sidebarShown: g.sidebarWidth > 0) - } else { - TabletToolbar(sidebarShown: g.sidebarWidth > 0) - } - } + if g.strip, !FirstLaunch.shows(app) { + TabletTabStrip() + .frame(width: g.size.width) .padding(.top, g.statusBar) .environment(\.colorScheme, app.pageIsPrivate ? .dark : AppAppearance.current) - .allowsHitTesting(!covered).accessibilityHidden(covered) + // All Tabs fades it with the page's bar, so it is back as the card lands. + .opacity(gallery ? app.surfaces.chromeOpacity : 1) + .allowsHitTesting(!covered && !gallery).accessibilityHidden(covered || gallery) } + // No phone chrome under All Tabs: the sidebar is the iPad's, and the + // phone's plate faded in over the page as All Tabs closed. TabGalleryLayer() - if gallery { ChromeLayer() } if app.field.shown { TabletOmnibox(geometry: g) } WorkspaceChatsLayer() TasksLayer() @@ -106,11 +124,15 @@ struct TabletWorkspaceView: View { AboutLayer() ReaderCardLayer() ToastLayer() + TabletDownloadFlights() AssistantApprovalLayer() if app.showsDesignSheet { DesignSheet() } } .frame(width: size.width, height: size.height) .animation(Motion.tabletSidebar.current, value: preferences.sidebarShown) + .animation(Motion.tabletSidebar.current, value: preferences.tabsInSidebar) + .animation(Motion.tabletSidebar.current, value: preferences.addressBars) + .animation(Motion.tabletSidebar.current, value: conversation) .environment(\.colorScheme, app.pageIsPrivate ? .dark : AppAppearance.current) .onChange(of: app.field.revision, initial: true) { _, _ in if app.field.shown, app.field.mode == .newTab, app.field.resting { @@ -124,6 +146,7 @@ struct TabletWorkspaceView: View { .onChange(of: g, initial: true) { _, _ in updateFrame() } .onChange(of: preferences.splitFraction) { _, _ in updateFrame() } .onChange(of: preferences.addressBars) { _, _ in updateFrame() } + .onChange(of: preferences.tabsInSidebar) { _, _ in updateFrame() } .onChange(of: app.workspace.paired) { _, _ in updateFrame() } .onChange(of: app.workspace.secondFocused) { _, _ in updateFrame() } .onChange(of: gallery) { _, _ in updateFrame() } @@ -133,13 +156,14 @@ struct TabletWorkspaceView: View { let g = geometry TabStack.of(app).screen = size var pane = layout(g).pane(app.workspace.secondFocused) - if preferences.addressBars && layout(g).split { pane.origin.y += Metrics.Tablet.paneBar; pane.size.height -= Metrics.Tablet.paneBar } + if plan(g).band { pane.origin.y += Metrics.Tablet.paneBar; pane.size.height -= Metrics.Tablet.paneBar } app.workspace.paneFrame = pane.offsetBy(dx: g.page.minX, dy: g.page.minY) } private func pages(in g: TabletWorkspaceGeometry) -> some View { let plan = layout(g) - let paneBars = preferences.addressBars && plan.split + let chrome = self.plan(g) + let paneBars = chrome.band let ids = plan.split ? [app.workspace.first, app.workspace.second].compactMap { $0 } : [app.browser.tab?.id].compactMap { $0 } return ZStack(alignment: .topLeading) { // In the page's own corners: square, it stood white past a round screen's. @@ -150,7 +174,7 @@ struct TabletWorkspaceView: View { let frame = plan.pane(second) let focused = id == app.browser.tab?.id VStack(spacing: 0) { - if paneBars { TabletPaneBar(tab: tab) } + if paneBars { TabletPageBand(tab: tab, plan: chrome, split: plan.split) } ZStack { if focused { BackRevealLayer() } TabletDocumentView(tab: tab, app: app, interactive: !covered && !gallery) @@ -194,224 +218,7 @@ struct TabletWorkspaceView: View { } } -private struct TabletSingleToolbar: View { - @Environment(AppModel.self) private var app - let sidebarShown: Bool - private var siteOpen: Binding { - Binding(get: { app.surfaces.menu == .plate }, set: { open in - if !open { app.surfaces.closeMenu(); app.pageMenu.reset() } - }) - } - - var body: some View { - HStack(spacing: 16) { - HStack(spacing: 0) { - tool("Sidebar", asset: "TabletSidebar", id: "tablet.sidebar") { - app.workspace.sidebarShown.toggle() - } - .accessibilityValue(sidebarShown ? "shown" : "hidden") - .contextMenu { - Toggle("Frame Page with Sidebar", isOn: Binding(get: { app.workspace.preferences.framed }, - set: { app.workspace.preferences.framed = $0 })) - } - macTool("Back", .yabBack, id: "tablet.back") { app.goBack() } - .disabled(app.backStack.route(for: app.browser.tab) == .nowhere) - macTool("Forward", .yabForward, id: "tablet.forward") { app.pageMenuForward() } - .disabled(!app.currentPageState.canGoForward) - } - .frame(width: 132) - Spacer(minLength: 0) - HStack(spacing: 0) { - macTool(app.currentPageState.isLoading ? "Stop" : "Reload", app.currentPageState.isLoading ? .yabStop : .yabReload, id: "tablet.reload") { - guard let id = app.browser.tab?.id else { return } - if app.currentPageState.isLoading { app.pages.stop(id) } else { app.pages.reload(id) } - } - Button { app.surfaces.openField(.address) } label: { - Text(app.browser.tab?.address ?? "Search or enter address") - .font(.system(size: Metrics.Chrome.labelFont)) - .foregroundStyle(Ink.primary).lineLimit(1).truncationMode(.middle) - .frame(maxWidth: .infinity, minHeight: Metrics.touch) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .accessibilityLabel("Search or enter address") - .accessibilityValue(app.browser.tab?.address ?? "") - .accessibilityIdentifier("tablet.address") - macTool("Site Controls", .sliderHorizontal2Square, id: "tablet.siteControls") { - if app.surfaces.menu == .plate { app.surfaces.closeMenu(); app.pageMenu.reset() } - else { app.openPageMenu(); app.pageMenu.shown = true; app.pageMenu.page = .site } - } - .popover(isPresented: siteOpen, arrowEdge: .top) { - TabletSiteControls().environment(app) - .presentationCompactAdaptation(.popover) - } - } - .frame(maxWidth: 540) - .background(Ink.primary.opacity(0.055), in: Capsule()) - .accessibilityElement(children: .contain).accessibilityIdentifier("tablet.singleAddressBar") - Spacer(minLength: 0) - HStack(spacing: 0) { - if app.workspace.canSplit { Menu { - Button("Open Beside") { app.newTabBeside() } - if app.workspace.paired { - Button("Separate Split") { app.workspace.fullSpread() } - Button("Close Page") { app.closeWorkspacePage() } - } - } label: { TabletGlyph("TabletSplitView").frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) } - .accessibilityLabel("Split View").accessibilityIdentifier("workspace.menu") - .disabled(app.pageIsPrivate || app.browser.tab == nil || app.browser.tab?.isMail == true) - } - tool("New Tab", asset: "TabletPlus", id: "tablet.newTab") { app.openNewTab() } - macTool("All Tabs", .yabTabs, id: "tablet.tabs") { TabStack.of(app).openGallery() } - } - .frame(width: app.workspace.canSplit ? 132 : 88) - } - .padding(.horizontal, 12) - .frame(height: TabletWorkspaceGeometry.toolbar) - .accessibilityElement(children: .contain) - .accessibilityIdentifier("tablet.toolbar") - } - - private func tool(_ title: String, asset: String, id: String, action: @escaping () -> Void) -> some View { - Button(action: action) { TabletGlyph(asset).frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) } - .buttonStyle(.plain).accessibilityLabel(title).accessibilityIdentifier(id) - } - private func macTool(_ title: String, _ glyph: MacGlyph, id: String, action: @escaping () -> Void) -> some View { - Button(action: action) { Glyph(mac: glyph).frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) } - .buttonStyle(.plain).accessibilityLabel(title).accessibilityIdentifier(id) - } -} - -private struct TabletToolbar: View { - @Environment(AppModel.self) private var app - let sidebarShown: Bool - var body: some View { - HStack(spacing: 4) { - Button { app.workspace.sidebarShown.toggle() } label: { - TabletGlyph("TabletSidebar").frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) - } - .frame(width: Metrics.touch, height: Metrics.touch) - .accessibilityLabel("Sidebar").accessibilityValue(sidebarShown ? "shown" : "hidden") - .accessibilityIdentifier("tablet.sidebar") - .contextMenu { - Toggle("Frame Page with Sidebar", isOn: Binding(get: { app.workspace.preferences.framed }, - set: { app.workspace.preferences.framed = $0 })) - } - Text(app.browser.space.name).font(.system(size: 13, weight: .medium)).foregroundStyle(Ink.secondary).lineLimit(1) - Spacer(minLength: 0) - if !app.workspace.preferences.addressBars { - Button { app.surfaces.openField(.address) } label: { - TabletGlyph("TabletFind").frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) - } - .frame(width: Metrics.touch, height: Metrics.touch) - .accessibilityLabel("Search or enter address").accessibilityValue(app.browser.tab?.address ?? "") - .accessibilityIdentifier("tablet.address") - } - if app.workspace.canSplit { - Menu { - Button("Open Beside") { app.newTabBeside() } - if app.workspace.paired { - Button("Separate Split") { app.workspace.fullSpread() } - Button("Close Page") { app.closeWorkspacePage() } - } - } label: { TabletGlyph("TabletSplitView").frame(width: Metrics.touch, height: Metrics.touch) } - .accessibilityLabel("Split View").accessibilityIdentifier("workspace.menu") - .disabled(app.pageIsPrivate || app.browser.tab == nil || app.browser.tab?.isMail == true) - } - Button { app.openNewTab() } label: { - TabletGlyph("TabletPlus").frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) - } - .frame(width: Metrics.touch, height: Metrics.touch).accessibilityLabel("New Tab").accessibilityIdentifier("tablet.newTab") - Button { TabStack.of(app).openGallery() } label: { - Glyph(mac: .yabTabs).frame(width: Metrics.touch, height: Metrics.touch).contentShape(Rectangle()) - } - .frame(width: Metrics.touch, height: Metrics.touch).accessibilityLabel("All Tabs").accessibilityIdentifier("tablet.tabs") - } - .buttonStyle(.plain).foregroundStyle(Ink.primary).padding(.horizontal, 8) - .frame(height: TabletWorkspaceGeometry.toolbar) - .accessibilityElement(children: .contain).accessibilityIdentifier("tablet.toolbar") - } -} - -private struct TabletPaneBar: View { - @Environment(AppModel.self) private var app - let tab: Tab - private var focused: Bool { app.browser.tab?.id == tab.id } - private var state: WebPool.PageState { app.chrome.pageStates[tab.id] ?? .idle } - private var canGoBack: Bool { - focused ? app.backStack.route(for: tab) != .nowhere - : state.canGoBack || state.readerEnabled || app.backStack.opener(of: tab.id) != nil - } - private func act(_ action: () -> Void) { - if !focused { - app.browser.select(tab.id) - // Navigation reads the pool's active page in this same touch. - // SwiftUI updates its document host on the following render. - _ = app.pages.activate(tab) - } - action() - } - private var siteOpen: Binding { - Binding(get: { focused && app.surfaces.menu == .plate }, set: { open in - if !open && focused { app.surfaces.closeMenu(); app.pageMenu.reset() } - }) - } - var body: some View { - HStack(spacing: 0) { - tool("Back", .yabBack, "tablet.back") { app.goBack() } - .disabled(!canGoBack) - tool("Forward", .yabForward, "tablet.forward") { app.pageMenuForward() } - .disabled(!state.canGoForward) - if focused { - tool(state.isLoading ? "Stop" : "Reload", state.isLoading ? .yabStop : .yabReload, "tablet.reload") { - if state.isLoading { app.pages.stop(tab.id) } else { app.pages.reload(tab.id) } - } - } - Button { act { app.surfaces.openField(.address) } } label: { - Text(tab.address).font(.system(size: 12.5)).lineLimit(1).truncationMode(.middle) - .foregroundStyle(focused ? Ink.primary : Ink.secondary) - .frame(maxWidth: .infinity, minHeight: Metrics.Tablet.paneBar).contentShape(Rectangle()) - } - .accessibilityLabel("Search or enter address").accessibilityValue(tab.address) - .accessibilityIdentifier(focused ? "tablet.address" : "tablet.address.\(tab.id)") - if focused { - tool("Site Controls", .sliderHorizontal2Square, "tablet.siteControls") { - if app.surfaces.menu == .plate { app.surfaces.closeMenu(); app.pageMenu.reset() } - else { app.openPageMenu(); app.pageMenu.shown = true; app.pageMenu.page = .site } - } - .popover(isPresented: siteOpen, arrowEdge: .top) { - TabletSiteControls().environment(app).presentationCompactAdaptation(.popover) - } - Menu { - Button("Open Beside") { app.newTabBeside() } - Button("Separate Split") { app.workspace.fullSpread() } - Button("Close Page") { app.closeWorkspacePage(tab.id) } - } label: { - TabletGlyph("TabletSplitView", size: 16) - .frame(width: Metrics.touch, height: Metrics.Tablet.paneBar).contentShape(Rectangle()) - } - .accessibilityLabel("Split View").accessibilityIdentifier("tablet.paneMenu") - } - Button { app.closeWorkspacePage(tab.id) } label: { - Glyph(.crossSmall, size: 15) - .frame(width: Metrics.touch, height: Metrics.Tablet.paneBar).contentShape(Rectangle()) - } - .accessibilityLabel("Close Page").accessibilityIdentifier("tablet.close.\(tab.id)") - } - .buttonStyle(.plain).foregroundStyle(Ink.primary).padding(.horizontal, 4) - .frame(height: Metrics.Tablet.paneBar).background(Ink.surface.opacity(0.92)) - .accessibilityElement(children: .contain).accessibilityIdentifier("tablet.addressBar.\(tab.id)") - .accessibilityValue(focused ? "active" : "inactive") - } - private func tool(_ title: String, _ glyph: MacGlyph, _ id: String, action: @escaping () -> Void) -> some View { - Button { act(action) } label: { - Glyph(mac: glyph, size: 15, color: focused ? Ink.primary : Ink.secondary).frame(width: Metrics.touch, height: Metrics.Tablet.paneBar).contentShape(Rectangle()) - } - .accessibilityLabel(title).accessibilityIdentifier(focused ? id : id + "." + tab.id) - } -} - -private struct TabletGlyph: View { +struct TabletGlyph: View { let asset: String var size: CGFloat = 20 var color: Color? = nil @@ -422,8 +229,9 @@ private struct TabletGlyph: View { } } -private struct TabletSiteControls: View { +struct TabletSiteControls: View { @Environment(AppModel.self) private var app + @Environment(\.colorScheme) private var scheme @State private var contentHeight: CGFloat = 280 // The desktop panel's 280-point width, 8-point inset, 28-point row marks, @@ -440,6 +248,7 @@ private struct TabletSiteControls: View { ScrollView { Group { if app.pageMenu.page == .certificate, let tab = app.browser.tab { certificate(tab) } + else if app.pageMenu.page == .downloads { downloads } else { main } } .padding(8) @@ -504,10 +313,17 @@ private struct TabletSiteControls: View { Button("Forget Permission") { app.forgetPermission(kind) } } label: { row(kind.title, subtitle: decision.word, - asset: kind == .camera ? "TabletCamera" : MacGlyph.mic.rawValue, on: decision == .allowed) + asset: kind.tabletAsset, on: decision == .allowed) } .accessibilityIdentifier("site.permission.\(kind.rawValue).decision") } + let here = app.downloads.list(isPrivate: app.pageIsPrivate, host: app.siteHost(of: tab)).count + if here > 0 { + Button { app.openSiteDownloads() } label: { + row("Downloaded Here", subtitle: here == 1 ? "1 file" : "\(here) files", asset: MacGlyph.yabDownload.rawValue) + } + .buttonStyle(.plain).accessibilityIdentifier("site.downloads.here") + } } } if let tab = app.browser.tab { @@ -527,6 +343,10 @@ private struct TabletSiteControls: View { .buttonStyle(.plain).accessibilityIdentifier("site.connection") Spacer(minLength: 0) Menu { + // The popover goes first: the panel and the sheet stand in its place. + Button("Print…") { app.surfaces.closeMenu(); app.pageMenu.reset(); app.printPage() } + Button("Save as PDF") { app.surfaces.closeMenu(); app.pageMenu.reset(); app.savePageAsPDF() } + Divider() Button("Clear Cookies and Site Data…", role: .destructive) { app.pageMenu.confirmClear = true } Button("Yab Settings…") { app.pageMenuYabSettings() } } label: { smallFace("TabletMore") } @@ -536,6 +356,22 @@ private struct TabletSiteControls: View { } } + /// Downloaded Here, or every file: the phone's Downloads page in the popover. + private var downloads: some View { + VStack(alignment: .leading, spacing: 8) { + Button { app.pageMenu.page = .site } label: { + HStack(spacing: 8) { + Glyph(mac: .yabBack, size: 14) + Text("Site Controls").font(.system(size: 12.5, weight: .medium)) + Spacer(minLength: 0) + }.frame(minHeight: Metrics.touch).contentShape(Rectangle()) + } + .buttonStyle(.plain).padding(.horizontal, 6).accessibilityIdentifier("site.downloads.back") + DownloadsBody(ink: PageMenuInk(dark: app.pageIsPrivate || scheme == .dark), + host: app.pageMenu.downloadsHost, isPrivate: app.pageIsPrivate) + } + } + private func row(_ title: String, subtitle: String, asset: String, on: Bool = false) -> some View { HStack(spacing: 10) { TabletGlyph(asset, size: 15, color: on ? Ink.surface : Ink.secondary) @@ -599,3 +435,22 @@ private struct TabletSiteControls: View { .font(.system(size: 12.5)).frame(minHeight: Metrics.touch) } } + +extension SiteSettings.Permission { + /// Site Controls' mark for the permission, in the popover's asset names. + var tabletAsset: String { + switch self { + case .camera: "TabletCamera" + case .microphone: MacGlyph.mic.rawValue + case .downloads: MacGlyph.yabDownload.rawValue + } + } +} + +extension AppModel { + /// The Mac's rule: the toolbar's downloads button only from the first + /// file, and only while the sidebar's foot, which always has one, is away. + func showsToolbarDownloads(sidebarShown: Bool) -> Bool { + !sidebarShown && (downloads.asking(isPrivate: pageIsPrivate) != nil || !downloads.list(isPrivate: pageIsPrivate).isEmpty) + } +} diff --git a/Phone/Sources/Chats/AttachTray.swift b/Phone/Sources/Chats/AttachTray.swift index fccf1fbc..d9c5083a 100644 --- a/Phone/Sources/Chats/AttachTray.swift +++ b/Phone/Sources/Chats/AttachTray.swift @@ -308,7 +308,7 @@ private struct AttachMainPage: View { private func camera() { guard UIImagePickerController.isSourceTypeAvailable(.camera) else { app.closeAttachTray() - app.say("No camera on this iPhone", glyph: .camera1) + app.say("No camera on this \(DeviceWord.name)", glyph: .camera1) return } app.attachTrayHandOver { $0.attachCamera = true } diff --git a/Phone/Sources/Chats/ChatCard.swift b/Phone/Sources/Chats/ChatCard.swift index 71108a17..034ed1d9 100644 --- a/Phone/Sources/Chats/ChatCard.swift +++ b/Phone/Sources/Chats/ChatCard.swift @@ -109,7 +109,7 @@ private struct AnswerHead: View { .foregroundStyle(Ink.primary) .lineLimit(1) .fixedSize() - Text(chat.by == .iphone ? "on this iPhone" : "on your Mac") + Text(chat.by == .iphone ? "on this \(DeviceWord.name)" : "on your Mac") .font(.system(size: Metrics.Chat.wherePill, weight: .medium)) .foregroundStyle(ChatInk.gray(0.62)) .padding(.vertical, 5) @@ -778,12 +778,12 @@ enum ChatWords { if chat.messages.contains(where: { $0.role == .typing && $0.by != .iphone }) { return "Thinking" } if let wait = chat.messages.last(where: { $0.role == .wait }) { return MacWords.waitsFor(wait.mac?.name ?? "your Mac") } if !app.isFixture { - if chat.by == .iphone { return "Apple Intelligence \u{00B7} on this iPhone" } + if chat.by == .iphone { return "Apple Intelligence \u{00B7} on this \(DeviceWord.name)" } return chat.macAgentName.map { "\($0) \u{00B7} on your Mac" } ?? "On your Mac" } if fresh { return "Claude Opus \u{00B7} on your Mac" } let claude = chat.messages.contains { $0.by == .claude || $0.role == .pick } - return claude ? "Claude Opus \u{00B7} on your Mac" : "Apple Intelligence \u{00B7} on this iPhone" + return claude ? "Claude Opus \u{00B7} on your Mac" : "Apple Intelligence \u{00B7} on this \(DeviceWord.name)" } /// The row's second line, and whether it needs you. diff --git a/Phone/Sources/Chats/ChatDetails.swift b/Phone/Sources/Chats/ChatDetails.swift index 1d34e44f..2245c2f7 100644 --- a/Phone/Sources/Chats/ChatDetails.swift +++ b/Phone/Sources/Chats/ChatDetails.swift @@ -107,7 +107,7 @@ struct ChatDetails: View { .accessibilityIdentifier("chat.info.line") HStack(spacing: 6) { Glyph(onMac ? .macbook : .phone, size: 15, color: Ink.primary) - Text(onMac ? "on your Mac" : "on this iPhone") + Text(onMac ? "on your Mac" : "on this \(DeviceWord.name)") .font(.system(size: 14, weight: .medium)) .foregroundStyle(Ink.primary) } diff --git a/Phone/Sources/Chats/ChatFlow.swift b/Phone/Sources/Chats/ChatFlow.swift index 0d749ac3..2a6e2443 100644 --- a/Phone/Sources/Chats/ChatFlow.swift +++ b/Phone/Sources/Chats/ChatFlow.swift @@ -742,7 +742,7 @@ extension AppModel { /// What Delete Chat asks first: where the chat goes from. func deleteQuestion(_ id: Chat.ID) -> (title: String, detail: String?) { if canControl(id) { return ("Delete this chat on your Mac too?", nil) } - if LocalChatProfile.isRemoteID(id) { return ("Delete this chat from this iPhone?", "It stays on \(macName).") } + if LocalChatProfile.isRemoteID(id) { return ("Delete this chat from this \(DeviceWord.name)?", "It stays on \(macName).") } return ("Delete this chat?", nil) } diff --git a/Phone/Sources/Chats/TurnsView.swift b/Phone/Sources/Chats/TurnsView.swift index f75cbdbd..e3290cd0 100644 --- a/Phone/Sources/Chats/TurnsView.swift +++ b/Phone/Sources/Chats/TurnsView.swift @@ -692,7 +692,7 @@ struct TaskTurnsView: View { private var waitRow: some View { switch status { case .code: - needs(.key1, "Waiting for the code \(codeSender) sent to this iPhone") + needs(.key1, "Waiting for the code \(codeSender) sent to this \(DeviceWord.name)") case .yes: needs(.creditCard1, "Waiting for you: \((def.yes ?? "your yes").replacingOccurrences(of: "?", with: ""))") case .failed: diff --git a/Phone/Sources/Chrome/ChromeLayer.swift b/Phone/Sources/Chrome/ChromeLayer.swift index 2b989a3c..738588c4 100644 --- a/Phone/Sources/Chrome/ChromeLayer.swift +++ b/Phone/Sources/Chrome/ChromeLayer.swift @@ -219,7 +219,8 @@ private struct ChromeLayerContent: View { let menuOpen = app.surfaces.menu == .plate let layout = ChromeGeometry(size: geo.size, folded: sourceFolded, hasNow: app.nowItem != nil, chipWidth: app.nowItem?.chipWidth(screen: geo.size.width), verticalControls: app.workspace.verticalControls, leadingRail: app.workspace.leadingRail) - let question = app.downloads.asking(isPrivate: app.pageIsPrivate) + // The iPad's toolbar layout asks from its downloads button (TabletDownloads). + let question = app.workspace.tabletControls ? nil : app.downloads.asking(isPrivate: app.pageIsPrivate) ZStack(alignment: .topLeading) { if let question { let card = DownloadAskCard.frame(in: ChromeGeometry(size: geo.size, folded: false, hasNow: true)) diff --git a/Phone/Sources/Chrome/PageMenu.swift b/Phone/Sources/Chrome/PageMenu.swift index 72ae42d2..33100fca 100644 --- a/Phone/Sources/Chrome/PageMenu.swift +++ b/Phone/Sources/Chrome/PageMenu.swift @@ -712,7 +712,7 @@ struct PageMenuMorph: View, Animatable { private func listRow(_ row: ListRow) -> some View { switch row { case .beside, .fullSpread, .closePage: - let title = row == .beside ? "Open Beside" : row == .fullSpread ? "Full Spread" : "Close Page" + let title = row == .beside ? "Split View" : row == .fullSpread ? "Separate Split View" : "Close Split" Button { closeThen { switch row { diff --git a/Phone/Sources/Chrome/PlateMarks.swift b/Phone/Sources/Chrome/PlateMarks.swift index dbc4f340..c992fbb9 100644 --- a/Phone/Sources/Chrome/PlateMarks.swift +++ b/Phone/Sources/Chrome/PlateMarks.swift @@ -58,10 +58,11 @@ struct ReloadMark: View { var body: some View { ZStack { - Glyph(.plateReload, size: size, color: color) + // The Mac's marks, as the iPad's and the Mac's own Reload and Stop. + Glyph(mac: .yabReload, size: size, color: color) .scaleEffect(showingStop ? Self.shrunk : 1) .opacity(showingStop ? 0 : 1) - Glyph(.crossMedium, size: stopSize, color: color) + Glyph(mac: .yabStop, size: stopSize, color: color) .scaleEffect(showingStop ? 1 : Self.shrunk) .opacity(showingStop ? 1 : 0) } diff --git a/Phone/Sources/Design/DeviceWord.swift b/Phone/Sources/Design/DeviceWord.swift new file mode 100644 index 00000000..bcc6bd23 --- /dev/null +++ b/Phone/Sources/Design/DeviceWord.swift @@ -0,0 +1,5 @@ +import UIKit + +enum DeviceWord { + static var name: String { UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone" } +} diff --git a/Phone/Sources/Design/Metrics.swift b/Phone/Sources/Design/Metrics.swift index 40d0f373..d4969bb8 100644 --- a/Phone/Sources/Design/Metrics.swift +++ b/Phone/Sources/Design/Metrics.swift @@ -613,6 +613,8 @@ enum Metrics { enum Settings { static let top: CGFloat = 60 + /// The iPad's card: its head this far in from the card's top, as from its sides. + static let cardTop: CGFloat = 12 static let titleFont: CGFloat = 28 static let groupRadius: CGFloat = 16 /// A page's row as tall as the root's, its icon the root's tile. diff --git a/Phone/Sources/Extensions/ExtensionHost.swift b/Phone/Sources/Extensions/ExtensionHost.swift index 1b562718..1f660854 100644 --- a/Phone/Sources/Extensions/ExtensionHost.swift +++ b/Phone/Sources/Extensions/ExtensionHost.swift @@ -483,7 +483,7 @@ final class ExtensionHost: NSObject { let (name, reach, verdict) = try await preview(id) // One that can't work on an iPhone isn't offered: why, and OK. if verdict.kind == .blocked { - let sheet = UIAlertController(title: "“\(name)” doesn't work on iPhone yet", message: verdict.reason, preferredStyle: .alert) + let sheet = UIAlertController(title: "“\(name)” doesn't work on \(DeviceWord.name) yet", message: verdict.reason, preferredStyle: .alert) sheet.view.accessibilityIdentifier = "extensions.blocked" sheet.addAction(UIAlertAction(title: "OK", style: .cancel)) Self.top()?.present(sheet, animated: !Motion.disabled) @@ -578,7 +578,7 @@ extension ExtensionHost: WKWebExtensionControllerDelegate { } note("native message \(applicationIdentifier ?? "")") // No other app on an iPhone answers a browser extension. - throw NSError(domain: "Yab", code: 1, userInfo: [NSLocalizedDescriptionKey: "Native messaging is not available on iPhone"]) + throw NSError(domain: "Yab", code: 1, userInfo: [NSLocalizedDescriptionKey: "Native messaging is not available on \(DeviceWord.name)"]) } } diff --git a/Phone/Sources/Extensions/ExtensionShim.swift b/Phone/Sources/Extensions/ExtensionShim.swift index b75d777a..090f9b7b 100644 --- a/Phone/Sources/Extensions/ExtensionShim.swift +++ b/Phone/Sources/Extensions/ExtensionShim.swift @@ -327,7 +327,7 @@ enum ExtensionShim { return ["openPanelOnActionClick": false] default: ExtensionHost.shared.log(id, "missing " + api) - throw Unsupported(what: "\(api) is not available on iPhone") + throw Unsupported(what: "\(api) is not available on \(DeviceWord.name)") } } diff --git a/Phone/Sources/Field/FieldActions.swift b/Phone/Sources/Field/FieldActions.swift index e2c2e07e..dd508342 100644 --- a/Phone/Sources/Field/FieldActions.swift +++ b/Phone/Sources/Field/FieldActions.swift @@ -65,6 +65,8 @@ extension AppModel { row.subtitle = "Search \(name) · " + (field.place.replacesTab && field.pageIsToday ? "in this tab" : "new tab") return row } + // Yab's own menu actions, as the Mac's field finds them. + rows = Words.withCommands(rows, typed: field.words, commands: commandCandidates) // The engine's completions, under the search for the words themselves. let phrases = SearchSuggest.shared.phrases(for: field.words) if !phrases.isEmpty { @@ -180,6 +182,13 @@ extension AppModel { startTask(for: words) case .settings: Motion.sheetGrow.run { surfaces.openSettings() } + case let .command(token): + guard let key = BrowserKey(token: token) else { return } + closeFieldAfterChoice() + // Once the field is gone: the keys stay the field's while it is up. + DispatchQueue.main.asyncAfter(deadline: .now() + (Motion.disabled ? 0 : Motion.fieldClose.duration)) { [weak self] in + self?.use(key) + } case .findOnPage: let id = browser.tab?.id closeFieldAfterChoice() @@ -393,7 +402,7 @@ extension AppModel { // On iPad it is a popover, and UIKit throws without an anchor // (register 1142), as PageDownload's share does. sheet.popoverPresentationController?.sourceView = root.view - sheet.popoverPresentationController?.sourceRect = CGRect(x: root.view.bounds.midX, y: root.view.bounds.maxY - 44, width: 1, height: 1) + sheet.popoverPresentationController?.sourceRect = Self.shareAnchor(in: root.view) root.present(sheet, animated: !Motion.disabled) } } @@ -401,10 +410,22 @@ extension AppModel { static func topController() -> UIViewController? { let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first var top = scene?.windows.first { $0.isKeyWindow }?.rootViewController ?? scene?.windows.first?.rootViewController - while let next = top?.presentedViewController { top = next } + // A popover on its way out (Site Controls closing for Share) can't present. + while let next = top?.presentedViewController, !next.isBeingDismissed { top = next } return top } + /// Where a share sheet's popover points on iPad: under the toolbar, where + /// Site Controls and the downloads button are, or over the phone's plate. + static func shareAnchor(in view: UIView) -> CGRect { + let traits = view.traitCollection + if TabletWorkspaceGeometry.usesToolbar(size: view.bounds.size, regular: traits.horizontalSizeClass == .regular, + idiom: traits.userInterfaceIdiom) { + return CGRect(x: view.bounds.midX, y: view.safeAreaInsets.top + TabletWorkspaceGeometry.toolbar, width: 1, height: 1) + } + return CGRect(x: view.bounds.midX, y: view.bounds.maxY - 44, width: 1, height: 1) + } + /// The screen the app draws on. var screenSize: CGSize { if workspace.tabletControls, field.shown { return workspace.windowSize } diff --git a/Phone/Sources/Field/NewTabSpaces.swift b/Phone/Sources/Field/NewTabSpaces.swift index ebe4eebd..1643c718 100644 --- a/Phone/Sources/Field/NewTabSpaces.swift +++ b/Phone/Sources/Field/NewTabSpaces.swift @@ -925,7 +925,7 @@ private struct SpacePage: View { let mineFolded = !macs.isEmpty && folded.contains(Self.mine) if (!space.kept.isEmpty && filter == .everything) || !today.isEmpty || !macs.isEmpty { TodayLine(clear: !today.isEmpty && !mineFolded, spaceID: space.id, isPrivate: false, separator: !space.kept.isEmpty, - label: macs.isEmpty ? nil : "This iPhone", folded: mineFolded, fold: { toggle(Self.mine) }, + label: macs.isEmpty ? nil : "This \(DeviceWord.name)", folded: mineFolded, fold: { toggle(Self.mine) }, action: { Haptics.play(.rigid, reason: Haptics.Reason.clear) Task { @MainActor in await app.tabClear.clear(in: space.id) } @@ -1197,6 +1197,9 @@ private struct MacTabRow: View { Section { item("Open Here", .yabTabsPlus) { app.openFromMac(row.tab, in: space) } item("Copy Link", .link) { app.copyLink(of: tab) } + if !tab.isMail, tab.navigationURL != nil { + item("Duplicate Tab", .yabTabPlus) { app.duplicate(tab) } + } item("Share", .yabShare) { app.share(tab) } } Section { @@ -1689,7 +1692,7 @@ struct TabHold: ViewModifier { let column = ColumnState.of(app) Section { if app.workspace.canSplit, !tab.isPrivate, !tab.isMail, tab.id != app.browser.tab?.id, app.browser.space.tab(tab.id) != nil { - item("Open Beside", .yabSplitPlus) { app.openTabBeside(tab) } + item("Split View", .yabSplitPlus) { app.openTabBeside(tab) } } item("Copy Link", .link) { app.copyLink(of: tab) } item("Share", .yabShare) { app.share(tab) } @@ -1702,18 +1705,18 @@ struct TabHold: ViewModifier { if !tab.isPrivate { Section { if list != .today, !tab.isMail, let space = app.browser.space(holding: tab.id) { - item("Rename…", .pencil) { app.tabEdits.begin(.tab(space.id, tab)) } + item("Rename Tab…", .pencil) { app.tabEdits.begin(.tab(space.id, tab)) } } MoveToFolderMenu(tab: tab) if list == .pins { - if !tab.isMail { item("Unpin", .pinSlash) { column.unpin(tab.id) } } + if !tab.isMail { item("Unpin Tab", .pinSlash) { column.unpin(tab.id) } } } else { - item("Pin", .pin) { column.pin(tab.id) } + item("Pin Tab", .pin) { column.pin(tab.id) } } if list == .today { - item("Keep", .yabAnchor) { column.keep(tab.id) } + item("Keep Tab", .yabAnchor) { column.keep(tab.id) } } else if list != .pins { - item("Unkeep", .anchor) { column.unkeep(tab.id) } + item("Don't Keep Tab", .anchor) { column.unkeep(tab.id) } } let home = app.browser.space(holding: tab.id)?.id let others = app.browser.spaces.filter { !$0.isPrivate && $0.id != home } diff --git a/Phone/Sources/Field/PinHold.swift b/Phone/Sources/Field/PinHold.swift index 7744970d..28b1d074 100644 --- a/Phone/Sources/Field/PinHold.swift +++ b/Phone/Sources/Field/PinHold.swift @@ -75,7 +75,7 @@ struct PinHold: UIViewControllerRepresentable { } var page: [UIMenuElement] = [] if app.workspace.canSplit, !tab.isPrivate, !tab.isMail, tab.id != app.browser.tab?.id, app.browser.space.tab(tab.id) != nil { - page.append(item("Open Beside", .yabSplitPlus) { app.openTabBeside(tab) }) + page.append(item("Split View", .yabSplitPlus) { app.openTabBeside(tab) }) } page.append(item("Copy Link", .link) { app.copyLink(of: tab) }) page.append(item("Share", .yabShare) { app.share(tab) }) @@ -88,10 +88,10 @@ struct PinHold: UIViewControllerRepresentable { if !tab.isPrivate { var own: [UIMenuElement] = [] if !tab.isMail, let space = app.browser.space(holding: tab.id) { - own.append(item("Rename…", .pencil) { app.tabEdits.begin(.tab(space.id, tab)) }) + own.append(item("Rename Tab…", .pencil) { app.tabEdits.begin(.tab(space.id, tab)) }) if let folderMenu = TabEdits.folderMenu(tab, app: app) { own.append(folderMenu) } } - if !tab.isMail { own.append(item("Unpin", .pinSlash) { column.unpin(tab.id) }) } + if !tab.isMail { own.append(item("Unpin Tab", .pinSlash) { column.unpin(tab.id) }) } let home = app.browser.space(holding: tab.id)?.id let others = app.browser.spaces.filter { !$0.isPrivate && $0.id != home } if !others.isEmpty { diff --git a/Phone/Sources/Field/PrivatePageViews.swift b/Phone/Sources/Field/PrivatePageViews.swift index 18764ce6..3f95eec0 100644 --- a/Phone/Sources/Field/PrivatePageViews.swift +++ b/Phone/Sources/Field/PrivatePageViews.swift @@ -53,7 +53,7 @@ struct PrivateEmptyPage: View { .font(.system(size: M.title, weight: .semibold)) .foregroundStyle(Color.white) .padding(.top, M.titleGap) - Text("What you open here stays on this iPhone,\nwith no history or sync.") + Text("What you open here stays on this \(DeviceWord.name),\nwith no history or sync.") .font(.system(size: M.note)) .foregroundStyle(Color.white.opacity(M.noteInk)) .multilineTextAlignment(.center) diff --git a/Phone/Sources/Field/SearchEngine.swift b/Phone/Sources/Field/SearchEngine.swift index cf3f8c3b..01121eda 100644 --- a/Phone/Sources/Field/SearchEngine.swift +++ b/Phone/Sources/Field/SearchEngine.swift @@ -83,7 +83,7 @@ enum SearchEngine: String, CaseIterable, Identifiable, Sendable { var fallbackNote: String? { guard let requested else { return nil } if SearchEngine(rawValue: requested) == nil { - return "This search engine isn't supported on this iPhone. Searches use Google; choose an engine below." + return "This search engine isn't supported on this \(DeviceWord.name). Searches use Google; choose an engine below." } if requested == SearchEngine.custom.rawValue && !SearchEngine.accepts(customTemplate) { return "Your Mac's custom search address isn't valid. Searches use Google; choose an engine below." diff --git a/Phone/Sources/History/HistoryPage.swift b/Phone/Sources/History/HistoryPage.swift index 64e30431..24bd9b46 100644 --- a/Phone/Sources/History/HistoryPage.swift +++ b/Phone/Sources/History/HistoryPage.swift @@ -97,7 +97,7 @@ struct HistoryPage: View { } Button("Cancel", role: .cancel) {} } message: { - Text("Pages go from History on this iPhone. History on your Mac stays as it is.") + Text("Pages go from History on this \(DeviceWord.name). History on your Mac stays as it is.") } } @@ -122,7 +122,7 @@ struct HistoryPage: View { Text("No History") .font(.headline) .foregroundStyle(SettingsInk.text) - Text("Pages you open on this iPhone and on your Mac show here.") + Text("Pages you open on this \(DeviceWord.name) and on your Mac show here.") .font(.footnote) .foregroundStyle(SettingsInk.footer) .multilineTextAlignment(.center) diff --git a/Phone/Sources/Join/JoinLayer.swift b/Phone/Sources/Join/JoinLayer.swift index 19ae5258..0e314f1a 100644 --- a/Phone/Sources/Join/JoinLayer.swift +++ b/Phone/Sources/Join/JoinLayer.swift @@ -37,7 +37,7 @@ struct JoinContent: View { .accessibilityIdentifier("join.retry") } if sync.phase == .on, sync.keySharingUnavailable { - Text("Connected on this iPhone. iCloud Keychain could not share the key. You can still join another device with a code.") + Text("Connected on this \(DeviceWord.name). iCloud Keychain could not share the key. You can still join another device with a code.") .font(.footnote) .foregroundStyle(SettingsInk.footer) .fixedSize(horizontal: false, vertical: true) @@ -80,7 +80,7 @@ private struct CodeSections: View { JoinSection(nil, foot: "Or on your Mac choose Add a Device, and scan the code it shows.") { JoinRow(.camera1, "Scan QR", id: "join.scan") { app.sync.showScanner(true) } } - JoinSection(nil, foot: "A Mac on the same Apple ID shares the key through iCloud Keychain, and this iPhone joins by itself.") { + JoinSection(nil, foot: "A Mac on the same Apple ID shares the key through iCloud Keychain, and this \(DeviceWord.name) joins by itself.") { JoinRow(.key1, "Use the Recovery Key", id: "join.recovery") { app.sync.showRecovery(true) } } } @@ -133,7 +133,7 @@ private struct ScanSections: View { .glassPlate(RoundedRectangle(cornerRadius: Metrics.Sync.fieldHeight / 2, style: .continuous)) } JoinSection(nil, foot: nil) { - JoinRow(.macbook, "Show This iPhone’s Code", id: "join.back") { app.sync.showScanner(false) } + JoinRow(.macbook, "Show This \(DeviceWord.name)’s Code", id: "join.back") { app.sync.showScanner(false) } } } } @@ -145,7 +145,7 @@ private struct InviteSections: View { let check: String var body: some View { - JoinSection("Check Your Mac", foot: "Your Mac asks whether this iPhone shows these digits. If they match, choose Let In there.") { + JoinSection("Check Your Mac", foot: "Your Mac asks whether this \(DeviceWord.name) shows these digits. If they match, choose Let In there.") { VStack(spacing: Metrics.Sync.codeWordsGap) { Text(check.map(String.init).joined(separator: " ")) .font(.system(.largeTitle, design: .rounded).weight(.semibold).monospacedDigit()) @@ -163,7 +163,7 @@ private struct InviteSections: View { .padding(.bottom, Metrics.Sync.codeBottom) } JoinSection(nil, foot: nil) { - JoinRow(.macbook, "Show This iPhone’s Code", id: "join.back") { app.sync.showScanner(false) } + JoinRow(.macbook, "Show This \(DeviceWord.name)’s Code", id: "join.back") { app.sync.showScanner(false) } } } } @@ -245,7 +245,7 @@ private struct RefusedSections: View { let why: String var body: some View { - JoinSection(nil, foot: "Joining again takes a code from your Mac or the Recovery Key. What is on this iPhone stays as it is.") { + JoinSection(nil, foot: "Joining again takes a code from your Mac or the Recovery Key. What is on this \(DeviceWord.name) stays as it is.") { HStack(spacing: Metrics.Sync.rowGap) { JoinIcon(.macbook) Text(why) @@ -281,7 +281,7 @@ private struct InSyncSections: View { @Environment(AppModel.self) private var app var body: some View { - JoinSection(nil, foot: "Tabs, chats and tasks sync end to end encrypted: Yab can’t read them. To take this iPhone out, remove it in Settings › Sync on your Mac.") { + JoinSection(nil, foot: "Tabs, chats and tasks sync end to end encrypted: Yab can’t read them. To take this \(DeviceWord.name) out, remove it in Settings › Sync on your Mac.") { HStack(spacing: Metrics.Sync.rowGap) { JoinIcon(.macbook) Text("In sync with \(app.macName)") diff --git a/Phone/Sources/Join/JoinScanner.swift b/Phone/Sources/Join/JoinScanner.swift index b6aa153b..c4dda7a6 100644 --- a/Phone/Sources/Join/JoinScanner.swift +++ b/Phone/Sources/Join/JoinScanner.swift @@ -30,7 +30,7 @@ struct JoinScanArea: View { case .refused: words("Yab can’t use the camera. Allow it in iOS Settings › Apps › Yab, or type the code below.") case .unsupported: - words("This iPhone’s camera can’t scan here. Type the code your Mac shows below.") + words("This \(DeviceWord.name)’s camera can’t scan here. Type the code your Mac shows below.") } } .task { diff --git a/Phone/Sources/Page/DownloadStore.swift b/Phone/Sources/Page/DownloadStore.swift index f9683781..5742571e 100644 --- a/Phone/Sources/Page/DownloadStore.swift +++ b/Phone/Sources/Page/DownloadStore.swift @@ -1,3 +1,4 @@ +import CoreGraphics import Foundation import Observation @@ -56,6 +57,24 @@ final class DownloadStore { private(set) var asks: [DownloadAsk] = [] /// The one the Now line says Open or Failed about, for a moment. private(set) var flash: UUID? + /// Files thrown at the iPad's downloads button from where they were + /// pressed, until they land (TabletDownloadFlights). + private(set) var flights: [Flight] = [] + /// The last file in: its icon stands on the iPad's button until the list + /// opens or the file does, with no timer (the Mac's Hoard `waiting`). + private(set) var waiting: UUID? + /// Counts arrivals: the iPad's button gives a little each time. + private(set) var bumps = 0 + /// Something on screen flies files (the iPad's TabletDownloadFlights); + /// the phone's Now line says it instead. + @ObservationIgnored var flies = false + + struct Flight: Identifiable, Equatable { + let id: UUID + /// In the window. + let from: CGPoint + let name: String + } struct Control { var stop: (@MainActor () -> Void)? @@ -155,8 +174,10 @@ final class DownloadStore { // MARK: - a transfer /// A transfer starts, or starts again under a failed row (same `id`). - func begin(_ id: UUID, name: String, host: String, total: Int64?, isPrivate: Bool, control: Control) { + /// `from`: where it was pressed, in the window, when that is fresh. + func begin(_ id: UUID, name: String, host: String, total: Int64?, isPrivate: Bool, control: Control, from: CGPoint? = nil) { controls[id] = control + if let from, flies { flights.append(Flight(id: id, from: from, name: name)) } else { bumps += 1 } let entry = DownloadEntry(id: id, name: name, host: SiteSettings.key(host) ?? host, size: total ?? 0, date: Date(), state: .running(received: 0, total: total), isPrivate: isPrivate) if let at = entries.firstIndex(where: { $0.id == id }) { entries[at] = entry } else { entries.insert(entry, at: 0) } @@ -195,6 +216,7 @@ final class DownloadStore { entry.state = .done entries[at] = entry controls[id] = nil + waiting = id save() say(id) return true @@ -227,6 +249,8 @@ final class DownloadStore { controls[id] = nil entries.removeAll { $0.id == id } if flash == id { clearFlash() } + if waiting == id { waiting = nil } + flights.removeAll { $0.id == id } withdraw(id) } @@ -246,7 +270,10 @@ final class DownloadStore { controls[entry.id] = nil } asks.filter(\.isPrivate).forEach { answer($0.id, false) } + let gone = Set(entries.filter(\.isPrivate).map(\.id)) entries.removeAll(where: \.isPrivate) + flights.removeAll { gone.contains($0.id) } + if let waiting, gone.contains(waiting) { self.waiting = nil } try? FileManager.default.removeItem(at: privateFolder) } @@ -272,6 +299,18 @@ final class DownloadStore { /// Open pressed: it has said what it had to. func flashTaken() { clearFlash() } + /// A file flown in has reached the button. + func landed(_ id: UUID) { + flights.removeAll { $0.id == id } + bumps += 1 + } + + /// The list opened, or the file did: the button is itself again. + func seen(_ id: UUID? = nil) { + guard let waiting, id == nil || id == waiting else { return } + self.waiting = nil + } + func leave() { away = true } func comeBack() { @@ -318,6 +357,7 @@ final class DownloadStore { if entry.state == .failed { controls[entry.id] = Control(stop: nil, retry: {}) } } self.flash = flash + waiting = flash.flatMap(entry).flatMap { $0.isDone ? $0.id : nil } } func pretend(ask: DownloadAsk) { asks = [ask] } diff --git a/Phone/Sources/Page/Downloads+App.swift b/Phone/Sources/Page/Downloads+App.swift index 96f400d9..af557d2c 100644 --- a/Phone/Sources/Page/Downloads+App.swift +++ b/Phone/Sources/Page/Downloads+App.swift @@ -16,6 +16,14 @@ extension AppModel { guard let self else { answer(false); return } self.askDownload(question, answer: answer) } + // A document a tab opened (a PDF) is whole: it shows in the system's + // viewer while that tab, or the page that opened it, is still in front. + pages.onViewDownload = { [weak self] tab, entry in + guard let self, let file = downloads.entry(entry), + browser.tab?.id == tab || browser.tab(tab) == nil else { return } + downloads.flashTaken() + openDownload(file) + } pages.onImageSaved = { [weak self] outcome in switch outcome { case .saved: self?.say("Saved to Photos", glyph: .checkCircle2) @@ -97,6 +105,7 @@ extension AppModel { func openDownload(_ file: DownloadEntry) { guard let url = downloads.url(of: file) else { return } + downloads.seen(file.id) FilePreview.show(url) } @@ -107,7 +116,7 @@ extension AppModel { guard let root = Self.topController() else { return } let sheet = UIActivityViewController(activityItems: [url], applicationActivities: nil) sheet.popoverPresentationController?.sourceView = root.view - sheet.popoverPresentationController?.sourceRect = CGRect(x: root.view.bounds.midX, y: root.view.bounds.maxY - 44, width: 1, height: 1) + sheet.popoverPresentationController?.sourceRect = Self.shareAnchor(in: root.view) root.present(sheet, animated: !Motion.disabled) } } diff --git a/Phone/Sources/Page/PageBrowserFeedback.swift b/Phone/Sources/Page/PageBrowserFeedback.swift index 72c17269..7538b0cb 100644 --- a/Phone/Sources/Page/PageBrowserFeedback.swift +++ b/Phone/Sources/Page/PageBrowserFeedback.swift @@ -51,7 +51,7 @@ struct PageLoadFailure: Equatable, Sendable { } var explanation: String { switch kind { - case .offline: "\(site) will open when this iPhone is back online." + case .offline: "\(site) will open when this \(DeviceWord.name) is back online." case .connection: "\(site) didn't respond. It may be down for a moment." case .timeout: "\(site) took too long to respond. Try again." case .secureConnection: "A secure connection to this website couldn't be established." diff --git a/Phone/Sources/Page/PageDocument.swift b/Phone/Sources/Page/PageDocument.swift new file mode 100644 index 00000000..e636c3e6 --- /dev/null +++ b/Phone/Sources/Page/PageDocument.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Files a tab opens that are documents rather than pages: a PDF, a Word, +/// Excel, PowerPoint, Pages, Numbers or Keynote file, rich text. Each opens +/// in the system's viewer (QuickLook), which saves and shares it, as a file +/// in Files would; WebKit's own view of them has no way to keep the file. +/// Pictures, video, sound and text stay pages. +nonisolated enum PageDocument { + /// As the Mac's PDFDesk reads a PDF: what servers really send, not only + /// application/pdf. + static let types: Set = [ + "application/pdf", "application/x-pdf", "text/pdf", "text/x-pdf", "application/acrobat", "applications/vnd.pdf", "application/vnd.pdf", + "application/msword", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "application/vnd.apple.pages", "application/vnd.apple.numbers", "application/vnd.apple.keynote", + "application/x-iwork-pages-sffpages", "application/x-iwork-numbers-sffnumbers", "application/x-iwork-keynote-sffkey", + "application/rtf", "text/rtf", + ] + + static func opensInViewer(_ mimeType: String?) -> Bool { + guard let type = mimeType?.split(separator: ";").first?.trimmingCharacters(in: .whitespaces).lowercased() else { return false } + return types.contains(type) + } +} diff --git a/Phone/Sources/Page/PageDownload.swift b/Phone/Sources/Page/PageDownload.swift index 3ac049f9..bce93e61 100644 --- a/Phone/Sources/Page/PageDownload.swift +++ b/Phone/Sources/Page/PageDownload.swift @@ -28,6 +28,12 @@ final class PageDownload: NSObject, WKDownloadDelegate { private let download: WKDownload private let downloads: DownloadStore private let approved: Bool + /// Where the person pressed for it, in the window: it flies from there. + private let from: CGPoint? + /// A document the tab was opening (a PDF): it opens in the system's + /// viewer once it is whole, and the site isn't asked first. + private let opens: Bool + private let viewed: @MainActor (UUID) -> Void /// May the site send this? Answered at once, or by the card. private let ask: @MainActor (DownloadAsk, @escaping @MainActor (Bool) -> Void) -> Void private let retry: @MainActor (UUID, WKWebsiteDataStore?, URLRequest) -> Bool @@ -44,12 +50,14 @@ final class PageDownload: NSObject, WKDownloadDelegate { private var backgroundTask = UIBackgroundTaskIdentifier.invalid /// `entry`: the failed row a Retry starts again under, already asked about. - init(download: WKDownload, source: Source, store: DownloadStore, entry: UUID? = nil, + init(download: WKDownload, source: Source, store: DownloadStore, entry: UUID? = nil, from: CGPoint? = nil, opens: Bool = false, ask: @escaping @MainActor (DownloadAsk, @escaping @MainActor (Bool) -> Void) -> Void, - retry: @escaping @MainActor (UUID, WKWebsiteDataStore?, URLRequest) -> Bool, ended: @escaping @MainActor (UUID) -> Void) { + retry: @escaping @MainActor (UUID, WKWebsiteDataStore?, URLRequest) -> Bool, ended: @escaping @MainActor (UUID) -> Void, + viewed: @escaping @MainActor (UUID) -> Void = { _ in }) { id = entry ?? UUID() self.download = download; self.source = source; downloads = store - approved = entry != nil + approved = entry != nil || opens + self.from = from; self.opens = opens; self.viewed = viewed self.ask = ask; self.retry = retry; self.ended = ended self.store = download.webView?.configuration.websiteDataStore directory = FileManager.default.temporaryDirectory.appendingPathComponent("yab-download-\(UUID())", isDirectory: true) @@ -158,7 +166,7 @@ final class PageDownload: NSObject, WKDownloadDelegate { phase = .transferring destination = target downloads.begin(id, name: name, host: source.host, total: total, isPrivate: source.isPrivate, - control: .init(stop: { [weak self] in self?.cancel() }, retry: nil)) + control: .init(stop: { [weak self] in self?.cancel() }, retry: nil), from: opens ? nil : from) if away { away = false; leave() } answerDestination(target) } catch { showFailure() } @@ -186,6 +194,7 @@ final class PageDownload: NSObject, WKDownloadDelegate { phase = moved ? .ready : .failed Haptics.play(moved ? .success : .error, reason: moved ? Haptics.Reason.downloadReady : Haptics.Reason.downloadFailed) finish() + if moved, opens { viewed(id) } } func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) { guard self.download === download, !cancelling, !removed else { return } diff --git a/Phone/Sources/Page/PageImage.swift b/Phone/Sources/Page/PageImage.swift index e2f79144..f6ba5cc5 100644 --- a/Phone/Sources/Page/PageImage.swift +++ b/Phone/Sources/Page/PageImage.swift @@ -83,7 +83,7 @@ enum PageImage { guard (try? data.write(to: file)) != nil, let root = AppModel.topController() else { return } let sheet = UIActivityViewController(activityItems: [file], applicationActivities: nil) sheet.popoverPresentationController?.sourceView = root.view - sheet.popoverPresentationController?.sourceRect = CGRect(x: root.view.bounds.midX, y: root.view.bounds.maxY - 44, width: 1, height: 1) + sheet.popoverPresentationController?.sourceRect = AppModel.shareAnchor(in: root.view) sheet.completionWithItemsHandler = { _, _, _, _ in try? FileManager.default.removeItem(at: folder) } root.present(sheet, animated: !Motion.disabled) } diff --git a/Phone/Sources/Page/PageLinkMenu.swift b/Phone/Sources/Page/PageLinkMenu.swift index 685b0910..01736a80 100644 --- a/Phone/Sources/Page/PageLinkMenu.swift +++ b/Phone/Sources/Page/PageLinkMenu.swift @@ -15,13 +15,35 @@ enum PageLinkMenu { case front /// After the tab it came from; the page stays in front. case background + /// Beside the page it came from, the two in a split (iPad). + case beside } static let newTab = "Open in New Tab" static let backgroundTab = "Open in Background Tab" static let download = "Download Linked File" + static let beside = "Open in Split View" + /// How long a held link's place stays where a download flies from: the + /// menu stays up while the person reads it. + static let heldFreshness: TimeInterval = 30 - static func configuration(for url: URL, from source: WKWebView, canDownload: Bool, image: [UIMenuElement] = [], + /// Where the finger is holding, in the window: the menu's own + /// interaction, on the web view or its content (a level or two down). + static func pressPoint(in view: UIView) -> CGPoint? { + var level = [view] + for _ in 0..<3 { + for each in level { + if let menu = each.interactions.lazy.compactMap({ $0 as? UIContextMenuInteraction }).first { + let at = menu.location(in: nil) + return at.x.isFinite && at.y.isFinite ? at : nil + } + } + level = level.flatMap(\.subviews) + } + return nil + } + + static func configuration(for url: URL, from source: WKWebView, canDownload: Bool, image: [UIMenuElement] = [], beside: Bool = false, open: @escaping @MainActor (Opening) -> Void, download: @escaping @MainActor () -> Void) -> UIContextMenuConfiguration { // Formed here, both providers are the main actor's; UIKit asks there. @@ -29,13 +51,13 @@ enum PageLinkMenu { guard let source else { return nil } return LinkPreviewController(url: url, configuration: source.configuration.copy() as! WKWebViewConfiguration) }, actionProvider: { suggested in - menu(suggested, canDownload: canDownload, image: image, open: open, download: download, + menu(suggested, canDownload: canDownload, image: image, beside: beside, open: open, download: download, copy: { UIPasteboard.general.url = url }) }) } /// Ours first, as groups of their own, then the system's for the link. - static func menu(_ suggested: [UIMenuElement], canDownload: Bool = false, image: [UIMenuElement] = [], + static func menu(_ suggested: [UIMenuElement], canDownload: Bool = false, image: [UIMenuElement] = [], beside: Bool = false, open: @escaping @MainActor (Opening) -> Void, download: @escaping @MainActor () -> Void = {}, copy: @escaping @MainActor () -> Void = {}) -> UIMenu { @@ -44,7 +66,13 @@ enum PageLinkMenu { let background = UIAction(title: backgroundTab, image: UIImage.menuGlyph(MacGlyph.yabTabDown)) { _ in open(.background) } background.accessibilityIdentifier = "link.backgroundTab" - var groups: [UIMenuElement] = [UIMenu(options: .displayInline, children: [front, background])] + var opens = [front, background] + if beside { + let split = UIAction(title: Self.beside, image: UIImage.menuGlyph(MacGlyph.yabSplitPlus)) { _ in open(.beside) } + split.accessibilityIdentifier = "link.beside" + opens.append(split) + } + var groups: [UIMenuElement] = [UIMenu(options: .displayInline, children: opens)] if canDownload { let file = UIAction(title: Self.download, image: UIImage.menuGlyph(MacGlyph.yabDownload)) { _ in download() } file.accessibilityIdentifier = "link.download" @@ -103,11 +131,25 @@ extension AppModel { browser.openBehind(tab, after: source, in: space.id) Haptics.play(.soft, reason: Haptics.Reason.backgroundTab) say("Opened in Background", glyph: .squareBehindSquare1) + case .beside: + guard canOpenLinkBeside(source) else { return } + workspace.openBeside(current: source, other: tab.id) + browser.openBehind(tab, after: source, in: space.id) + browser.select(tab.id) } profile?.capture(browser) } } +extension AppModel { + /// The Mac's Open in Split View: a wide iPad, an ordinary page. + func canOpenLinkBeside(_ source: Tab.ID) -> Bool { + guard workspace.canSplit, let tab = browser.tab(source), !tab.isPrivate, !tab.isMail, + let space = browser.space(holding: source), !space.isPrivate else { return false } + return true + } +} + extension Haptics.Reason { static let backgroundTab = "background tab" // soft: Open in Background Tab, with its toast } diff --git a/Phone/Sources/Page/PagePrint.swift b/Phone/Sources/Page/PagePrint.swift new file mode 100644 index 00000000..fd2754be --- /dev/null +++ b/Phone/Sources/Page/PagePrint.swift @@ -0,0 +1,58 @@ +import UIKit +import WebKit +import os + +private let printLog = Logger(subsystem: "dev.serafim.fast.iphone", category: "print") + +/// The Mac's Duplicate Tab, Print… and Save as PDF for a page. +extension AppModel { + /// The tab's page again, in a new tab of its space, in front. + func duplicate(_ tab: Tab) { + guard let url = tab.navigationURL else { return } + openHeldLink(url, from: tab.id, as: .front) + } + + /// Print…: the system's print panel with the page as WebKit lays it out for paper. + func printPage() { + guard let tab = browser.tab, let view = pages.liveView(tab.id) else { return } + let info = UIPrintInfo.printInfo() + info.jobName = tab.title + info.outputType = .general + let controller = UIPrintInteractionController.shared + controller.printInfo = info + controller.printFormatter = view.viewPrintFormatter() + controller.present(animated: !Motion.disabled) + } + + /// Save as PDF: the whole page as one PDF, handed to the share sheet + /// (Save to Files and the rest), named for the page. + func savePageAsPDF() { + guard let tab = browser.tab, let view = pages.liveView(tab.id) else { return } + view.createPDF { [weak self] result in + guard let self else { return } + switch result { + case let .success(data): + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("yab-pdf-\(UUID())", isDirectory: true) + let name = PageDownload.filename(tab.title.isEmpty ? "Page" : tab.title) + let file = folder.appendingPathComponent((name as NSString).pathExtension.lowercased() == "pdf" ? name : name + ".pdf") + do { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try data.write(to: file) + } catch { + printLog.error("save as PDF: \(error.localizedDescription, privacy: .public)") + self.say("Couldn’t save this page", glyph: .exclamationCircle) + return + } + guard let root = Self.topController() else { return } + let sheet = UIActivityViewController(activityItems: [file], applicationActivities: nil) + sheet.popoverPresentationController?.sourceView = root.view + sheet.popoverPresentationController?.sourceRect = Self.shareAnchor(in: root.view) + sheet.completionWithItemsHandler = { _, _, _, _ in try? FileManager.default.removeItem(at: folder) } + root.present(sheet, animated: !Motion.disabled) + case let .failure(error): + printLog.error("save as PDF: \(error.localizedDescription, privacy: .public)") + self.say("Couldn’t save this page", glyph: .exclamationCircle) + } + } + } +} diff --git a/Phone/Sources/Page/SiteSettings.swift b/Phone/Sources/Page/SiteSettings.swift index db9f6815..a205bb04 100644 --- a/Phone/Sources/Page/SiteSettings.swift +++ b/Phone/Sources/Page/SiteSettings.swift @@ -1,5 +1,6 @@ import Foundation import Observation +import UIKit import WebKit /// What Yab remembers about a site, as the Mac's Site Controls do: its page @@ -50,6 +51,9 @@ final class SiteSettings { struct Site: Codable, Equatable, Sendable { var zoom: Double = 1 var desktop = false + /// Request Mobile Website, said on an iPad, where every site is + /// asked for as a desktop one otherwise; nil for nothing said. + var mobile: Bool? var permissions: [Permission: Decision] = [:] /// Block Ads and Trackers for this site, said here; nil follows /// the Mac's sites and the switch in Settings (Shield). @@ -58,7 +62,9 @@ final class SiteSettings { /// "pt") are translated as they load (Page/PageTranslation). var translates: String? - var isEmpty: Bool { abs(zoom - 1) < 0.001 && !desktop && permissions.isEmpty && blocksAds == nil && translates == nil } + var isEmpty: Bool { + abs(zoom - 1) < 0.001 && !desktop && mobile == nil && permissions.isEmpty && blocksAds == nil && translates == nil + } } /// The prototype's steps: 10 % at a time up to 200 %, then larger. @@ -69,9 +75,14 @@ final class SiteSettings { private let defaults: UserDefaults? private static let key = "yab.siteSettings" + /// Safari's default: an iPad asks every site for its desktop version, an + /// iPhone for its mobile one. A site's own choice turns it the other way. + var prefersDesktop: Bool + /// `defaults` nil: nothing outlives the app (test worlds). - init(defaults: UserDefaults? = .standard) { + init(defaults: UserDefaults? = .standard, prefersDesktop: Bool? = nil) { self.defaults = defaults + self.prefersDesktop = prefersDesktop ?? (UIDevice.current.userInterfaceIdiom == .pad) if let data = defaults?.data(forKey: Self.key), let saved = try? JSONDecoder().decode([String: Site].self, from: data) { sites = saved @@ -124,10 +135,28 @@ final class SiteSettings { // MARK: - desktop site - func desktop(_ host: String?, isPrivate: Bool) -> Bool { site(host, isPrivate: isPrivate).desktop } + func desktop(_ host: String?, isPrivate: Bool) -> Bool { + let site = site(host, isPrivate: isPrivate) + return prefersDesktop ? site.mobile != true : site.desktop + } func setDesktop(_ desktop: Bool, for host: String?, isPrivate: Bool) { - edit(host, isPrivate: isPrivate) { $0.desktop = desktop } + edit(host, isPrivate: isPrivate) { site in + if prefersDesktop { + site.mobile = desktop ? nil : true + if !desktop { site.desktop = false } + } else { + site.desktop = desktop + } + } + } + + /// What WebKit is asked for. An iPad left alone gets Safari's own + /// choice, `.recommended`: desktop at full width, mobile in a narrow window. + func contentMode(_ host: String?, isPrivate: Bool) -> WKWebpagePreferences.ContentMode { + let site = site(host, isPrivate: isPrivate) + if prefersDesktop { return site.mobile == true ? .mobile : site.desktop ? .desktop : .recommended } + return site.desktop ? .desktop : .mobile } // MARK: - the ad blocker diff --git a/Phone/Sources/Page/WebPool+Site.swift b/Phone/Sources/Page/WebPool+Site.swift index 0e8caf7f..3dd4a56a 100644 --- a/Phone/Sources/Page/WebPool+Site.swift +++ b/Phone/Sources/Page/WebPool+Site.swift @@ -26,6 +26,17 @@ extension WebPool { return siteSettings.desktop(site.host, isPrivate: site.isPrivate) } + func contentMode(_ id: Tab.ID, url: URL?) -> WKWebpagePreferences.ContentMode { + guard let siteSettings else { return Self.defaultContentMode } + let site = site(id, url: url) + return siteSettings.contentMode(site.host, isPrivate: site.isPrivate) + } + + /// Before any site is known, as Safari: desktop on an iPad, mobile on an iPhone. + static var defaultContentMode: WKWebpagePreferences.ContentMode { + UIDevice.current.userInterfaceIdiom == .pad ? .recommended : .mobile + } + // MARK: - find on page /// iOS's find bar over the page, with `text` in it if given. diff --git a/Phone/Sources/Page/WebPool.swift b/Phone/Sources/Page/WebPool.swift index 4b7b10e6..6d36dfae 100644 --- a/Phone/Sources/Page/WebPool.swift +++ b/Phone/Sources/Page/WebPool.swift @@ -89,8 +89,13 @@ final class WebPool: NSObject { let origin: DownloadOrigin let document: UUID? let navigation: WKNavigation? + /// A document the tab was opening, for the system's viewer (PageDocument). + var opens = false } private var downloadConversions: [Tab.ID: DownloadConversion] = [:] + /// Where a link was last held, in the window, and when (uptime): Download + /// Linked File flies from there. + private var heldLink: (tab: Tab.ID, at: CGPoint, time: TimeInterval)? /// Tabs whose main frame was just sent on to an app's link and refused. private var appLinks: Set = [] /// When the person last touched each tab's page (uptime), as Yab's own @@ -104,6 +109,8 @@ final class WebPool: NSObject { let downloads: DownloadStore /// A site wants to send a file: nil lets it (tests of the transfer itself). var onDownloadAsk: (@MainActor (DownloadAsk, @escaping @MainActor (Bool) -> Void) -> Void)? + /// A document a tab opened is whole (PageDocument): the system's viewer shows it. + var onViewDownload: (@MainActor (Tab.ID, UUID) -> Void)? private var pageInteractionsEnabled = true /// Yab is in the background (or inactive on its way there). private var appAway = false @@ -180,6 +187,8 @@ final class WebPool: NSObject { var onImageSaved: (@MainActor (PageImage.Outcome) -> Void)? /// Open in New Tab or Open in Background Tab on a held link (PageLinkMenu). var onOpenLink: ((URL, Tab.ID, PageLinkMenu.Opening) -> Void)? + /// Whether a link held on this page may open beside it, in a split. + var canOpenLinkBeside: ((Tab.ID) -> Bool)? /// The ad blocker: each page's lists, for the site it is heading to. var shield: Shield? @@ -219,7 +228,7 @@ final class WebPool: NSObject { // WebKit's player offers Picture in Picture, inline video too, and a // playing video goes on in it with Yab away (PagePlayback). configuration.allowsPictureInPictureMediaPlayback = true - configuration.defaultWebpagePreferences.preferredContentMode = .mobile + configuration.defaultWebpagePreferences.preferredContentMode = Self.defaultContentMode // Every page zooms with two fingers, paying no mind to a page's // user-scalable=no or maximum-scale: Google Images' // viewer says both, so its picture could not be pinched larger. @@ -2094,7 +2103,7 @@ extension WebPool: WKNavigationDelegate { let policy = await decidePolicy(webView, for: action) // Request Desktop Site, remembered per site (SiteSettings). if policy == .allow, action.targetFrame?.isMainFrame == true, let id = tabsByView[ObjectIdentifier(webView)] { - preferences.preferredContentMode = desktop(id, url: action.request.url) ? .desktop : .mobile + preferences.preferredContentMode = contentMode(id, url: action.request.url) // And the blocker, on or off for where it is going. fitShield(webView.configuration.userContentController, for: id, url: action.request.url) } @@ -2159,14 +2168,20 @@ extension WebPool: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor response: WKNavigationResponse) async -> WKNavigationResponsePolicy { let attachment = (response.response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Disposition")? .trimmingCharacters(in: .whitespacesAndNewlines).lowercased().hasPrefix("attachment") == true - guard attachment || !response.canShowMIMEType else { return .allow } + // A PDF or another document opens as a file, in the system's viewer, + // which saves and shares it; WebKit's own view of it has neither. + let opens = !attachment && response.isForMainFrame && PageDocument.opensInViewer(response.response.mimeType) + guard attachment || opens || !response.canShowMIMEType else { return .allow } guard !fixturesEnabled, response.isForMainFrame, let id = tabsByView[ObjectIdentifier(webView)], canInteract(id, in: webView), downloadOrigins[id] != nil else { + // A tab out of sight never opens the viewer over another: it shows + // the document as WebKit does. + if opens { return .allow } if response.isForMainFrame, let id = tabsByView[ObjectIdentifier(webView)] { restoreDownloadSource(id, in: webView) } return .cancel } if let origin = downloadOrigins[id] { - downloadConversions[id] = DownloadConversion(origin: origin, document: documents[id], navigation: activeNavigations[id]) + downloadConversions[id] = DownloadConversion(origin: origin, document: documents[id], navigation: activeNavigations[id], opens: opens) } return .download } @@ -2204,30 +2219,52 @@ extension WebPool: WKNavigationDelegate { download.originalRequest?.url == conversion.origin.requestURL, download.originatingFrame.request.url == conversion.origin.frameURL, download.originatingFrame.isMainFrame, download.webView === view, - let origin = restoreDownloadSource(id, in: view) else { download.cancel(nil); return } + case let fresh = committedURLs[id] == nil, + let origin = fresh ? releaseFreshSource(id, in: view) : restoreDownloadSource(id, in: view) else { download.cancel(nil); return } downloadConversions[id] = nil - presentDownload(download, tab: id, in: view, origin: origin) + presentDownload(download, tab: id, in: view, origin: origin, opens: conversion.opens) + // A page's new window that was only ever this file has nothing to + // show: it goes, as window.close() would, back to its opener. + if fresh, let opener = popupOpeners.removeValue(forKey: id) { + onCloseWindowFrom?(id, opener) + forget(id) + } + } + + /// A tab that had shown nothing yet when its first load became a file: + /// no page to put back, only the load to end. + private func releaseFreshSource(_ id: Tab.ID, in view: WKWebView) -> DownloadOrigin? { + guard live[id] === view, committedURLs[id] == nil, let origin = downloadOrigins[id], + origin.store == ObjectIdentifier(view.configuration.websiteDataStore), + origin.privateSession == (privateTabs.contains(id) ? privateSession : nil) else { return nil } + downloadOrigins[id] = nil + if let active = activeNavigations.removeValue(forKey: id) { retiredNavigations.add(active) } + requestedURLs[id] = nil; actionTypes[id] = nil; pendingIndex[id] = nil + endRefresh(id, in: view) + publishState(id) + return origin } - private func presentDownload(_ download: WKDownload, tab id: Tab.ID, in view: WKWebView, origin: DownloadOrigin) { + private func presentDownload(_ download: WKDownload, tab id: Tab.ID, in view: WKWebView, origin: DownloadOrigin, opens: Bool) { guard canInteract(id, in: view) else { download.cancel(nil); return } - adopt(download, tab: id, page: origin.url) + adopt(download, tab: id, page: committedURLs[id] == nil ? nil : origin.url, opens: opens) } /// The WKDownload is ours from here. Its source goes by the page it came /// from, as the page said it then: its tab may be long gone by Retry. - private func adopt(_ download: WKDownload, tab id: Tab.ID, page: URL?, entry: UUID? = nil) { + private func adopt(_ download: WKDownload, tab id: Tab.ID, page: URL?, entry: UUID? = nil, from: CGPoint? = nil, opens: Bool = false) { let site = siteOf?(id, page) - let source = PageDownload.Source(tab: id, host: site?.host ?? page?.host() ?? "", + let source = PageDownload.Source(tab: id, host: site?.host ?? page?.host() ?? download.originalRequest?.url?.host() ?? "", isPrivate: site?.isPrivate ?? privateTabs.contains(id)) - let job = PageDownload(download: download, source: source, store: downloads, entry: entry, + let job = PageDownload(download: download, source: source, store: downloads, entry: entry, from: from, opens: opens, ask: { [weak self] question, answer in guard let ask = self?.onDownloadAsk else { answer(true); return } ask(question, answer) }, retry: { [weak self] entry, store, request in self?.retryDownload(entry, store, request, page: page, tab: id) ?? false - }, ended: { [weak self] token in self?.transfers[token] = nil }) + }, ended: { [weak self] token in self?.transfers[token] = nil }, + viewed: { [weak self] entry in self?.onViewDownload?(id, entry) }) transfers[job.id] = job if appAway { job.leave() } } @@ -2237,8 +2274,10 @@ extension WebPool: WKNavigationDelegate { func downloadLinked(_ url: URL, from id: Tab.ID) { guard let view = live[id], canInteract(id, in: view), allowsDownloadOf(url) else { return } let page = committedURLs[id] ?? view.url + let held = heldLink.flatMap { $0.tab == id && ProcessInfo.processInfo.systemUptime - $0.time < PageLinkMenu.heldFreshness ? $0.at : nil } + heldLink = nil view.startDownload(using: URLRequest(url: url)) { [weak self] download in - self?.adopt(download, tab: id, page: page) + self?.adopt(download, tab: id, page: page, from: held) } } @@ -2333,6 +2372,7 @@ extension WebPool: WKUIDelegate { completionHandler: @escaping @MainActor (UIContextMenuConfiguration?) -> Void) { guard let url = elementInfo.linkURL, opensAsTab(url), let id = tabsByView[ObjectIdentifier(webView)], canInteract(id, in: webView) else { completionHandler(nil); return } + if let at = PageLinkMenu.pressPoint(in: webView) { heldLink = (id, at, ProcessInfo.processInfo.systemUptime) } Task { @MainActor [weak self, weak webView] in guard let self, let webView, self.live[id] === webView else { completionHandler(nil); return } let held = await PageImage.held(in: webView) @@ -2340,6 +2380,7 @@ extension WebPool: WKUIDelegate { PageImage.actions(held, in: webView) { [weak self] outcome in self?.onImageSaved?(outcome) } } ?? [] completionHandler(PageLinkMenu.configuration(for: url, from: webView, canDownload: self.allowsDownloadOf(url), image: image, + beside: self.canOpenLinkBeside?(id) == true, open: { [weak self, weak webView] opening in guard let self, let webView, self.live[id] === webView else { return } self.onOpenLink?(url, id, opening) diff --git a/Phone/Sources/Reports/CrashReports.swift b/Phone/Sources/Reports/CrashReports.swift index 5c037239..8da9fe92 100644 --- a/Phone/Sources/Reports/CrashReports.swift +++ b/Phone/Sources/Reports/CrashReports.swift @@ -255,7 +255,7 @@ final class CrashReports { @MainActor enum CrashQuestion { static let title = "Share saved crash reports?" - static let message = "iOS saved crash reports from an earlier Yab session. They include what crashed and why, the versions of Yab and iOS and the iPhone model, never pages or anything you typed. Sharing them helps fix problems. You can turn on automatic sending in Settings › About." + static let message = "iOS saved crash reports from an earlier Yab session. They include what crashed and why, the versions of Yab and iOS and the \(DeviceWord.name) model, never pages or anything you typed. Sharing them helps fix problems. You can turn on automatic sending in Settings › About." static let yes = "Send" static let no = "Don’t Send" diff --git a/Phone/Sources/Settings/SettingsContent.swift b/Phone/Sources/Settings/SettingsContent.swift index 1e0b0c21..830567c8 100644 --- a/Phone/Sources/Settings/SettingsContent.swift +++ b/Phone/Sources/Settings/SettingsContent.swift @@ -184,7 +184,7 @@ struct SettingsContent { /// With no Mac yet, the agent has nowhere to run: it says so, as /// Everything else does. var agentValue: String { context.hasMac ? "\(store.agent.name) · on your Mac" : "Needs your Mac" } - var pageAnswersValue: String { store.pageAnswers == .iPhone ? "This iPhone" : "Your Mac" } + var pageAnswersValue: String { store.pageAnswers == .iPhone ? "This \(DeviceWord.name)" : "Your Mac" } var everythingElseValue: String { context.hasMac ? store.agent.name : "Needs your Mac" } var defaultBrowserValue: String { switch context.yabIsDefaultBrowser { @@ -193,7 +193,7 @@ struct SettingsContent { case nil: "" } } - var todayValue: String { "This iPhone’s own" } + var todayValue: String { "This \(DeviceWord.name)’s own" } var faceIDValue: String { store.faceIDForYes ? "On" : "Off" } var lockScreenValue: String { Self.words(store.lockScreen) } var privateTabsValue: String { "Not kept" } @@ -275,8 +275,8 @@ struct SettingsContent { mac, row("agent", .face, "Agent", agentValue, .page(.agent)), ], footer: context.hasMac - ? "Tasks run in Yab on your Mac, with your sign-ins. The iPhone sends codes and the yes signed by Face ID." - : "Join Yab on your Mac and tasks run there, with your sign-ins. The iPhone sends codes and the yes signed by Face ID."), + ? "Tasks run in Yab on your Mac, with your sign-ins. The \(DeviceWord.name) sends codes and the yes signed by Face ID." + : "Join Yab on your Mac and tasks run there, with your sign-ins. The \(DeviceWord.name) sends codes and the yes signed by Face ID."), SettingsSectionModel(id: "answers", title: "Answers", rows: [ row("aboutPage", .glyph(.sparkle), "About a page", pageAnswersValue, .page(.aboutPage)), row("everythingElse", .face, "Everything else", everythingElseValue, .page(.everythingElse)), @@ -284,7 +284,7 @@ struct SettingsContent { SettingsSectionModel(id: "tabs", title: "Tabs", rows: [ row("defaultBrowser", .glyph(.globe), "Default Browser", defaultBrowserValue, .page(.defaultBrowser)), row("today", .glyph(.squareBehindSquare1), "Today", todayValue, .page(.today)), - ], footer: "Spaces, pins and kept tabs are the same on your Mac; Today is this iPhone’s own. Mail stays in Yab on your Mac."), + ], footer: "Spaces, pins and kept tabs are the same on your Mac; Today is this \(DeviceWord.name)’s own. Mail stays in Yab on your Mac."), SettingsSectionModel(id: "privacy", title: "Privacy", rows: [ row("faceID", .glyph(.faceId), "Face ID for Pay and Post", faceIDValue, .page(.faceID)), row("lockScreen", .glyph(.lock), "Lock Screen Details", lockScreenValue, .page(.lockScreen)), @@ -321,7 +321,7 @@ struct SettingsContent { return [SettingsSectionModel(id: "search", title: "Search Engine", rows: store.searchEngines.map { engine in let name = engine == .custom ? store.customSearchSelection.name : engine.title return choice("search.engine.\(engine.rawValue)", name, selection.engine == engine) { store.chooseSearchEngine(engine) } - }, footer: selection.fallbackNote ?? "Type a web address to open a page, or words to search \(selection.name). This choice is kept on this iPhone; your Mac's setting is unchanged."), + }, footer: selection.fallbackNote ?? "Type a web address to open a page, or words to search \(selection.name). This choice is kept on this \(DeviceWord.name); your Mac's setting is unchanged."), SettingsSectionModel(id: "search.return", title: "Return", rows: [ SettingsRowModel(id: "search.guessesFromWords", icon: .glyph(.sparkle), title: "Guess from Your Words", value: nil, kind: .toggle(Binding(get: { store.guessesFromWords }, set: { store.guessesFromWords = $0 }))), @@ -374,7 +374,7 @@ struct SettingsContent { let history = SettingsSectionModel(id: "sync.history", title: nil, rows: [ SettingsRowModel(id: "sync.history", icon: .glyph(.history), title: "History", value: nil, kind: .toggle(Binding(get: { store.syncHistory }, set: { store.syncHistory = $0 }))), - ], footer: "Pages you open on this iPhone go to History on your Mac for two weeks. Private tabs never do.") + ], footer: "Pages you open on this \(DeviceWord.name) go to History on your Mac for two weeks. Private tabs never do.") // The Recovery Key's page stays reachable (Settings' search finds // it); out of sync it says to join first. let recovery = SettingsSectionModel(id: "sync.recovery", title: nil, rows: [ @@ -383,9 +383,9 @@ struct SettingsContent { guard context.inSync else { return [devices, history, recovery] } return [devices, history, recovery, SettingsSectionModel(id: "sync.off", title: nil, rows: [ - SettingsRowModel(id: "sync.off", icon: nil, title: "Turn Off Sync on This iPhone", value: nil, + SettingsRowModel(id: "sync.off", icon: nil, title: "Turn Off Sync on This \(DeviceWord.name)", value: nil, kind: .action(askSyncOff), danger: true), - ], footer: "Your Mac and your other devices go on syncing. What is on this iPhone stays as it is.")] + ], footer: "Your Mac and your other devices go on syncing. What is on this \(DeviceWord.name) stays as it is.")] case .recoveryKey: guard let key = context.recoveryKey else { return [SettingsSectionModel(id: "recovery", title: nil, rows: [ @@ -403,12 +403,12 @@ struct SettingsContent { return [SettingsSectionModel(id: "passwords", title: nil, rows: [ SettingsRowModel(id: "passwords.provider", icon: .glyph(.key1), title: "Passwords and Passkeys", value: "Managed by iOS", kind: .info), SettingsRowModel(id: "passwords.settings", icon: nil, title: "Open iOS Settings", value: nil, kind: .action(openSystemSettings)), - ], footer: "Use your configured iOS AutoFill provider on supported sign-in fields. Passwords are not stored in a Yab vault on this iPhone.")] + ], footer: "Use your configured iOS AutoFill provider on supported sign-in fields. Passwords are not stored in a Yab vault on this \(DeviceWord.name).")] case .autofill: return [SettingsSectionModel(id: "autofill", title: nil, rows: [ SettingsRowModel(id: "autofill.provider", icon: .glyph(.creditCard1), title: "AutoFill", value: "Managed by iOS", kind: .info), SettingsRowModel(id: "autofill.settings", icon: nil, title: "Open iOS Settings", value: nil, kind: .action(openSystemSettings)), - ], footer: "Use the iOS keyboard's offered information on supported fields. A saved profile for filling whole forms is not available on this iPhone yet.")] + ], footer: "Use the iOS keyboard's offered information on supported fields. A saved profile for filling whole forms is not available on this \(DeviceWord.name) yet.")] case .privacy: // The blocker first, as on the Mac: one switch; the site that // breaks is turned off in its own Site Settings. @@ -429,7 +429,7 @@ struct SettingsContent { SettingsSectionModel(id: "privacy.data", title: nil, rows: [ SettingsRowModel(id: "privacy.clearData", icon: nil, title: "Clear History and Website Data", value: nil, kind: .action(askClearData)), - ], footer: "History, cookies and other website data on this iPhone. Your tabs and what syncs with your Mac stay.")] + ], footer: "History, cookies and other website data on this \(DeviceWord.name). Your tabs and what syncs with your Mac stay.")] case .extensions: let host = ExtensionHost.shared let rows = host.installed.map { item in @@ -466,9 +466,9 @@ struct SettingsContent { case .aboutPage: return [ SettingsSectionModel(id: "aboutPage", title: nil, rows: [ - choice("aboutPage.iPhone", "This iPhone", store.pageAnswers == .iPhone) { store.pageAnswers = .iPhone }, + choice("aboutPage.iPhone", "This \(DeviceWord.name)", store.pageAnswers == .iPhone) { store.pageAnswers = .iPhone }, choice("aboutPage.mac", "Your Mac", store.pageAnswers == .mac) { store.pageAnswers = .mac }, - ], footer: "On this iPhone, a question about a page is answered at once, and the page stays here. On your Mac, \(store.agent.name) answers with your sign-ins."), + ], footer: "On this \(DeviceWord.name), a question about a page is answered at once, and the page stays here. On your Mac, \(store.agent.name) answers with your sign-ins."), ] case .everythingElse: return [ @@ -497,18 +497,18 @@ struct SettingsContent { SettingsRowModel(id: "today.state", icon: .glyph(.squareBehindSquare1), title: "Today", value: todayValue, kind: .info), SettingsRowModel(id: "today.autoClear", icon: .glyph(.broom), title: "Clear after 12 hours", value: nil, kind: .toggle(Binding(get: { store.autoClearToday }, set: { store.autoClearToday = $0 }))), - ], footer: "Clear removes only inactive tabs created on this iPhone with verified safe pages. The page in front, pins, kept tabs, drafts, media, tasks, shared and unverified pages stay. Undo is available for 6 seconds. Automatic Clear checks actual activity after 12 hours when Yab returns or you change spaces; it does not clear unknown Mac tabs."), + ], footer: "Clear removes only inactive tabs created on this \(DeviceWord.name) with verified safe pages. The page in front, pins, kept tabs, drafts, media, tasks, shared and unverified pages stay. Undo is available for 6 seconds. Automatic Clear checks actual activity after 12 hours when Yab returns or you change spaces; it does not clear unknown Mac tabs."), SettingsSectionModel(id: "today.mac", title: nil, rows: [ SettingsRowModel(id: "today.macTabs", icon: .glyph(.macbook), title: "Your Mac’s Tabs", value: nil, kind: .toggle(Binding(get: { store.macTabs }, set: { store.macTabs = $0 }))), - ], footer: "See what is open on \(context.macName) and open it here. Your Today stays this iPhone’s own."), + ], footer: "See what is open on \(context.macName) and open it here. Your Today stays this \(DeviceWord.name)’s own."), ] case .faceID: return [ SettingsSectionModel(id: "faceID", title: nil, rows: [ SettingsRowModel(id: "faceID.toggle", icon: .glyph(.faceId), title: "Face ID for Pay and Post", value: nil, kind: .toggle(Binding(get: { store.faceIDForYes }, set: { store.faceIDForYes = $0 }))), - ], footer: "Paying, posting and canceling wait for your yes, signed on this iPhone. Your Mac checks the signature, then presses the site’s own button; Claude can’t press it. Off, the yes takes your passcode."), + ], footer: "Paying, posting and canceling wait for your yes, signed on this \(DeviceWord.name). Your Mac checks the signature, then presses the site’s own button; Claude can’t press it. Off, the yes takes your passcode."), ] case .lockScreen: return [ @@ -520,7 +520,7 @@ struct SettingsContent { return [ SettingsSectionModel(id: "privateTabs", title: nil, rows: [ SettingsRowModel(id: "privateTabs.state", icon: .glyph(.incognito), title: "Private Tabs", value: privateTabsValue, kind: .info), - ], footer: "Private tabs stay in memory on this iPhone, with no history or sync."), + ], footer: "Private tabs stay in memory on this \(DeviceWord.name), with no history or sync."), ] case .notifications: return [ @@ -532,7 +532,7 @@ struct SettingsContent { var sections = [ SettingsSectionModel(id: "appearance", title: nil, rows: SettingsStore.Appearance.allCases.map { look in choice("appearance.\(look.rawValue)", Self.words(look), store.appearance == look) { store.appearance = look } - }, footer: "System follows your \(context.isPad ? "iPad" : "iPhone"), light by day and dark at night if it is set so."), + }, footer: "System follows your \(DeviceWord.name), light by day and dark at night if it is set so."), SettingsSectionModel(id: "websites", title: "Websites", rows: [ SettingsRowModel(id: "appearance.darkenWebsites", icon: .glyph(.moon), title: "Darken Websites", value: nil, kind: .toggle(Binding(get: { store.darkenWebsites }, set: { store.darkenWebsites = $0 }))), @@ -543,7 +543,9 @@ struct SettingsContent { sections.append(SettingsSectionModel(id: "appearance.browser", title: "Browser", rows: [ SettingsRowModel(id: "appearance.sidebar", icon: nil, title: "Show Sidebar", value: nil, kind: .toggle(Binding(get: { layout.sidebarShown }, set: { layout.sidebarShown = $0 }))), - SettingsRowModel(id: "appearance.addressBars", icon: nil, title: "Show Address Bars", value: nil, + SettingsRowModel(id: "appearance.tabsInSidebar", icon: nil, title: "Show Tabs in Sidebar", value: nil, + kind: .toggle(Binding(get: { layout.tabsInSidebar }, set: { layout.tabsInSidebar = $0 }))), + SettingsRowModel(id: "appearance.addressBars", icon: nil, title: "Show Address Bar", value: nil, kind: .toggle(Binding(get: { layout.addressBars }, set: { layout.addressBars = $0 }))), SettingsRowModel(id: "appearance.pageFrame", icon: nil, title: "Frame Page with Sidebar", value: nil, kind: .toggle(Binding(get: { layout.framed }, set: { layout.framed = $0 }))), @@ -583,8 +585,8 @@ struct SettingsContent { // MARK: - what Yab sends /// The Mac's words for its switches, with iOS and the iPhone in them. - nonisolated static let crashesFooter = "What crashed and why, where Yab stopped responding, the versions of Yab and iOS and the iPhone model. Never pages or anything you typed. When off, Yab asks after a new crash." - nonisolated static let activityFooter = "A random ID for this installation counts the days Yab is active on this iPhone. No pages, searches or browsing history." + nonisolated static let crashesFooter = "What crashed and why, where Yab stopped responding, the versions of Yab and iOS and the \(DeviceWord.name) model. Never pages or anything you typed. When off, Yab asks after a new crash." + nonisolated static let activityFooter = "A random ID for this installation counts the days Yab is active on this \(DeviceWord.name). No pages, searches or browsing history." /// Privacy says what goes at all, and where it is turned off. nonisolated static let sentFooter = "Yab sends no pages, searches or browsing history. A daily count with a random ID for this installation, and crash reports only if you say yes: both in About." @@ -594,7 +596,7 @@ struct SettingsContent { nonisolated static func footer(_ lock: SettingsStore.LockScreen) -> String { switch lock { case .afterFaceID: - "A locked iPhone shows a task by its name, never an amount or who it goes to. After Face ID, the Lock Screen and the Dynamic Island show them; its buttons work after Face ID too." + "A locked \(DeviceWord.name) shows a task by its name, never an amount or who it goes to. After Face ID, the Lock Screen and the Dynamic Island show them; its buttons work after Face ID too." case .never: "The Lock Screen and the Dynamic Island show a task by its name only, never an amount or who it goes to, even after Face ID. Open Yab to see them." } diff --git a/Phone/Sources/Settings/SettingsIndex.swift b/Phone/Sources/Settings/SettingsIndex.swift index 703b52a0..38c4443e 100644 --- a/Phone/Sources/Settings/SettingsIndex.swift +++ b/Phone/Sources/Settings/SettingsIndex.swift @@ -163,7 +163,7 @@ enum SettingsIndex { case .search: "Search the web, or ask a question from the address field." case .spaces: "Sets of tabs, each with its pins, its color and whose sign-ins." case .sync: "Your spaces, tabs and chats on your devices, encrypted so only they can read them." - case .ai: "Answers on this iPhone, and Claude or ChatGPT on your Mac." + case .ai: "Answers on this \(DeviceWord.name), and Claude or ChatGPT on your Mac." case .passwords: "Passwords and passkeys from your configured iOS provider." case .autofill: "Information offered by iOS on supported webpage fields." case .privacy: "Ads and trackers, private tabs, approval and Lock Screen details." diff --git a/Phone/Sources/Settings/SettingsLayer.swift b/Phone/Sources/Settings/SettingsLayer.swift index e77b0563..b2719075 100644 --- a/Phone/Sources/Settings/SettingsLayer.swift +++ b/Phone/Sources/Settings/SettingsLayer.swift @@ -27,9 +27,12 @@ struct SettingsLayer: View { Color.black .opacity(Metrics.Settings.dim * ui.sheet.presence(height: size.height)) .frame(width: geo.size.width, height: geo.size.height) - .allowsHitTesting(false) + // On iPad the sheet is a card: a tap beside it closes it, as a form sheet does. + .contentShape(Rectangle()) + .onTapGesture { if tablet, !ui.join.presented { app.surfaces.closeSettings() } } + .allowsHitTesting(tablet) .accessibilityHidden(true) - SettingsViewport(app: app, size: size, top: tablet ? 0 : SettingsLayer.statusBar, keyboardOffset: origin.y, column: column) + SettingsViewport(app: app, size: size, top: tablet ? Metrics.Settings.cardTop : SettingsLayer.statusBar, keyboardOffset: origin.y, column: column) .frame(width: size.width, height: size.height) .clipShape(RoundedRectangle(cornerRadius: tablet ? 22 : 0)) // Corners while it moves; at rest none, the screen's own glass rounds it. diff --git a/Phone/Sources/Settings/SettingsSpacesView.swift b/Phone/Sources/Settings/SettingsSpacesView.swift index b9386241..9b0544cc 100644 --- a/Phone/Sources/Settings/SettingsSpacesView.swift +++ b/Phone/Sources/Settings/SettingsSpacesView.swift @@ -107,7 +107,7 @@ struct SettingsSpacePage: View { } Button("Cancel", role: .cancel) {} } message: { - Text("Its tabs close on this iPhone and on your other devices.") + Text("Its tabs close on this \(DeviceWord.name) and on your other devices.") } .accessibilityIdentifier("settings.space.page") } diff --git a/Phone/Sources/Settings/SettingsStore.swift b/Phone/Sources/Settings/SettingsStore.swift index d3f69e0b..6d3bcbbb 100644 --- a/Phone/Sources/Settings/SettingsStore.swift +++ b/Phone/Sources/Settings/SettingsStore.swift @@ -415,7 +415,7 @@ final class SettingsStore { /// branch draws it, these are its words and glyph. enum SettingsFieldRow { static let title = "Settings" - static let subtitle = "Yab on this iPhone" + static let subtitle = "Yab on this \(DeviceWord.name)" static let glyph = GlyphName.settingsGear1 static let key = "go" } diff --git a/Phone/Sources/Settings/SettingsSync.swift b/Phone/Sources/Settings/SettingsSync.swift index 73e2d0ec..a8a72885 100644 --- a/Phone/Sources/Settings/SettingsSync.swift +++ b/Phone/Sources/Settings/SettingsSync.swift @@ -28,7 +28,7 @@ struct SettingsDevice: Equatable, Sendable, Identifiable { let said = mac.flatMap { $0.state.isUp ? nil : MacWords.state($0.state, now: now) } return SettingsDevice(id: device.id, name: device.name.isEmpty ? (device.isPhone ? "iPhone" : "Mac") : device.name, isPhone: device.isPhone, isThis: here, - words: here ? "This iPhone" : said ?? words(lastSeen: device.lastSeen, now: now)) + words: here ? "This \(DeviceWord.name)" : said ?? words(lastSeen: device.lastSeen, now: now)) }.sorted { ($0.isThis ? 0 : 1) < ($1.isThis ? 0 : 1) } } @@ -50,13 +50,13 @@ struct SyncOffConfirmation: ViewModifier { func body(content: Content) -> some View { if asks { - content.confirmationDialog("Turn Off Sync on This iPhone?", isPresented: Binding( + content.confirmationDialog("Turn Off Sync on This \(DeviceWord.name)?", isPresented: Binding( get: { SettingsUI.shared.confirmSyncOff }, set: { SettingsUI.shared.confirmSyncOff = $0 }), titleVisibility: .visible) { Button("Turn Off Sync", role: .destructive) { app.sync.turnOff() } Button("Cancel", role: .cancel) {} } message: { - Text("This iPhone forgets the sync key and leaves your account. Its tabs and chats stay here; joining again takes a code from your Mac or the Recovery Key.") + Text("This \(DeviceWord.name) forgets the sync key and leaves your account. Its tabs and chats stay here; joining again takes a code from your Mac or the Recovery Key.") } } else { content diff --git a/Phone/Sources/Sync/PhoneSync.swift b/Phone/Sources/Sync/PhoneSync.swift index b9289557..28c2d183 100644 --- a/Phone/Sources/Sync/PhoneSync.swift +++ b/Phone/Sources/Sync/PhoneSync.swift @@ -1087,7 +1087,7 @@ public nonisolated final class PhoneSync: @unchecked Sendable { public var errorDescription: String? { switch self { case .ownerUnavailable: "This chat's Mac isn't available in your Sync account. Wait for Sync or start a new chat." - case .accessRefused: "This iPhone no longer has access to this Sync account. Rejoin Sync before sending more." + case .accessRefused: "This \(DeviceWord.name) no longer has access to this Sync account. Rejoin Sync before sending more." } } } diff --git a/Phone/Sources/Sync/SyncBridge.swift b/Phone/Sources/Sync/SyncBridge.swift index faf4867d..9e859e7b 100644 --- a/Phone/Sources/Sync/SyncBridge.swift +++ b/Phone/Sources/Sync/SyncBridge.swift @@ -545,7 +545,7 @@ final class SyncBridge { guard let setup else { return false } switch setup.keys.keep(seal, share: share) { case .localFailure: - joinError = "This iPhone could not save the Sync key. Unlock it and try again." + joinError = "This \(DeviceWord.name) could not save the Sync key. Unlock it and try again." Haptics.play(.error, reason: "sync key not saved") return false case .localOnly: @@ -882,7 +882,7 @@ final class SyncBridge { return true } catch { log.error("sync didn't start: \(String(describing: error), privacy: .public)") - joinError = "Sync could not start on this iPhone. Unlock it and try again. Your saved data is unchanged." + joinError = "Sync could not start on this \(DeviceWord.name). Unlock it and try again. Your saved data is unchanged." phase = .off Motion.sheetRise.run { showsJoin = true } return false @@ -996,7 +996,7 @@ final class SyncBridge { prepareAssistantNotifications() reconcileAssistantApprovals() case let .refused(why): - let words = why.replacingOccurrences(of: "This Mac", with: "This iPhone") + let words = why.replacingOccurrences(of: "This Mac", with: "This \(DeviceWord.name)") folderArtwork.reset() phase = .refused(words) Motion.sheetRise.run { showsJoin = true } @@ -2047,7 +2047,7 @@ final class SyncBridge { case .syncChanged: "Sync changed while this question was being prepared. Ask again." case .unsupportedAgent: ChatAgent.unsupported case .chatNotReady: "Your Mac hasn't synced this chat yet. Wait for sync before sending more." - case .privateConversation: "Private conversations stay on this iPhone. Ask about a public page to use your Mac." + case .privateConversation: "Private conversations stay on this \(DeviceWord.name). Ask about a public page to use your Mac." } } } @@ -2476,7 +2476,7 @@ final class SyncBridge { app?.tasks.arrived = nil SettingsUI.shared.recoveryShown = nil probe?.say("state", "turned off") - app?.say("Sync Is Off on This iPhone", glyph: .arrowRotateClockwise) + app?.say("Sync Is Off on This \(DeviceWord.name)", glyph: .arrowRotateClockwise) } /// The journal, key, token and id let go: what Join Again and Turn Off share. @@ -2506,7 +2506,7 @@ final class SyncBridge { func openJoinLink(_ url: URL) -> Bool { guard url.scheme?.lowercased() == "yab", url.host?.lowercased() == "join" else { return false } if phase == .on { - app?.say("This iPhone Is in Sync Already", glyph: .macbook) + app?.say("This \(DeviceWord.name) Is in Sync Already", glyph: .macbook) } else { joinWithInvite(url.absoluteString) } @@ -2552,7 +2552,7 @@ final class SyncBridge { switch failure { case .server(409): self.joinError = "That code was used already. On your Mac, choose Add a Device for a new one." case .expired: self.joinError = "That code ran out. On your Mac, choose Add a Device for a new one." - default: self.joinError = "Your Mac couldn't let this iPhone in. Try again with a new code." + default: self.joinError = "Your Mac couldn't let this \(DeviceWord.name) in. Try again with a new code." } } } diff --git a/Phone/Sources/Tabs/TabGalleryLayer.swift b/Phone/Sources/Tabs/TabGalleryLayer.swift index f1b2ffe8..56df6024 100644 --- a/Phone/Sources/Tabs/TabGalleryLayer.swift +++ b/Phone/Sources/Tabs/TabGalleryLayer.swift @@ -52,7 +52,7 @@ struct TabGalleryLayer: View { let layout = TabGalleryLayout(screen: size, count: tabs.count, verticalControls: app.workspace.galleryVerticalControls, leadingRail: app.workspace.leadingRail, circle: app.workspace.statusColumn ? stack.stackGeometry.circle : nil, - across: app.workspace.galleryAcross) + across: app.workspace.galleryAcross, pageFrame: app.workspace.galleryPageFrame) let poses = tabs.enumerated().map { i, tab in stack.pose(i, of: tab, in: g, layout: layout) } let dark = TabGalleryGround.isDark(app) let at = g.phase == .open @@ -101,6 +101,9 @@ struct TabGalleryLayer: View { Rectangle().opacity(Double(g.bar)) } } + // On iPad the sidebar and toolbar stay under it, coming and + // going with the bar's own fade as the card leaves and lands. + .opacity(app.workspace.tabletControls ? 1 - app.surfaces.chromeOpacity : 1) .contentShape(Rectangle()) .onTapGesture { stack.chooseFront() } .accessibilityHidden(true) @@ -307,7 +310,8 @@ struct TabGalleryLayer: View { .frame(width: rect.width, height: rect.height) .glassEffect(isPrivate ? GlassTone.privateTab.glass(for: .dark) : .regular, in: Circle()) .glassEffectTransition(.identity) - .opacity(app.surfaces.chromeOpacity) + // The iPad has no stack on its page: its All Tabs is in the sidebar. + .opacity(app.workspace.tabletControls ? 0 : app.surfaces.chromeOpacity) .position(x: rect.midX, y: rect.midY + offset) .allowsHitTesting(false) .accessibilityHidden(true) diff --git a/Phone/Sources/Tabs/TabGalleryLayout.swift b/Phone/Sources/Tabs/TabGalleryLayout.swift index c2757b57..59cd7805 100644 --- a/Phone/Sources/Tabs/TabGalleryLayout.swift +++ b/Phone/Sources/Tabs/TabGalleryLayout.swift @@ -19,6 +19,10 @@ struct TabGalleryLayout: Equatable { var circle: CGRect? = nil /// Three cards whole across an unfolded Duo, side by side, none over another. var across = false + /// Where the page stands when it isn't the whole window: the iPad's + /// page card, beside its sidebar and under its toolbar. Cards grow out + /// of it and back into it, so the workspace never jumps when they go. + var pageFrame: CGRect? = nil private typealias G = Metrics.TabGallery @@ -30,10 +34,11 @@ struct TabGalleryLayout: Equatable { /// The page as a card shows it whole: the whole screen, the bar floating /// over its foot as it does over the live page. - var page: CGRect { CGRect(x: 0, y: 0, width: screen.width, height: screen.height) } + var page: CGRect { pageFrame ?? CGRect(x: 0, y: 0, width: screen.width, height: screen.height) } - /// The share of a page's picture above its content area. - var contentTop: CGFloat { screen.height > 0 ? Metrics.statusBar / screen.height : 0 } + /// The share of a page's picture above its content area: none where the + /// page starts under a toolbar rather than under the status bar. + var contentTop: CGFloat { pageFrame != nil ? 0 : screen.height > 0 ? Metrics.statusBar / screen.height : 0 } /// How wide a card's kept picture is, in points (TabPictures): as wide as /// the widest card at rest, the tab in front's beside the focus. @@ -283,8 +288,10 @@ enum TabGalleryMotion { /// Nothing lay on the chosen card: the circle rises with its cards. var rises: Bool - init(count: Int, chosen: Int) { - let after = (0.. String { task.map { "Your Mac is signing in to \(site) for \($0)" } ?? "Your Mac is signing in to \(site)" diff --git a/Phone/Sources/VirtualMac/VirtualMac.swift b/Phone/Sources/VirtualMac/VirtualMac.swift index 571de6e2..7b6ddbb1 100644 --- a/Phone/Sources/VirtualMac/VirtualMac.swift +++ b/Phone/Sources/VirtualMac/VirtualMac.swift @@ -74,7 +74,7 @@ final class VirtualMac: TaskBackend { if let job = jobs[order.id], job.phase != .done, job.phase != .stopped { return } let job = Job(id: order.id, words: order.words, step: order.step) jobs[order.id] = job - note("from iPhone · \(order.words)") + note("from \(DeviceWord.name) · \(order.words)") start(job) } @@ -106,7 +106,7 @@ final class VirtualMac: TaskBackend { private var pendingYes: [TaskRun.ID: SignedYes] = [:] func notNow(_ id: TaskRun.ID) { - note("The yes waits on the iPhone") + note("The yes waits on the \(DeviceWord.name)") } func retry(_ id: TaskRun.ID) { @@ -123,7 +123,7 @@ final class VirtualMac: TaskBackend { job.answer?.resume(returning: nil) job.answer = nil job.phase = .stopped - note("Stopped from the iPhone") + note("Stopped from the \(DeviceWord.name)") emit(.stopped(id)) } @@ -292,7 +292,7 @@ final class VirtualMac: TaskBackend { if step.needs == .code, !job.codeGiven { job.phase = .needsCode let request = script.code ?? CodeRequest(sender: def.name, icon: step.icon, site: def.name) - note("Waiting for the code from the iPhone") + note("Waiting for the code from the \(DeviceWord.name)") emit(.needsCode(job.id, request)) guard case let .code(code)? = await answer(job) else { return } if let expected = script.expectedCode, code.filter(\.isNumber) != expected { @@ -302,14 +302,14 @@ final class VirtualMac: TaskBackend { } job.codeGiven = true job.phase = .working - note("\(step.done) with the code from your iPhone") + note("\(step.done) with the code from your \(DeviceWord.name)") continue // the same step, signed in now } if step.needs == .yes, !job.yesGiven { job.phase = .needsYes let request = script.yes ?? YesRequest(kind: .pay, icon: step.icon, title: def.yes ?? "Go on?", subtitle: def.name, facts: [], button: "Approve with Face ID", waiting: "Waiting for you") - note("Asked on the iPhone: you’ve been away \(self.script.idleMinutes) min") + note("Asked on the \(DeviceWord.name): you’ve been away \(self.script.idleMinutes) min") emit(.needsYes(job.id, request)) let given: SignedYes? if let early = pendingYes.removeValue(forKey: job.id) { @@ -323,13 +323,13 @@ final class VirtualMac: TaskBackend { job.phase = .failed job.runner = nil note("The signature didn’t check out") - emit(.failed(job.id, TaskFailure(line: "The yes didn’t check out · nothing was paid", long: "Your Mac couldn’t check the signature from this iPhone, so it pressed nothing.", + emit(.failed(job.id, TaskFailure(line: "The yes didn’t check out · nothing was paid", long: "Your Mac couldn’t check the signature from this \(DeviceWord.name), so it pressed nothing.", lockTitle: "Nothing was paid", lockLine: "The yes didn’t check out. Retry from Yab."))) return } job.yesGiven = true job.phase = .paying - note("Checked the Face ID signature from the iPhone") + note("Checked the Face ID signature from the \(DeviceWord.name)") emit(.paying(job.id)) guard await pause(payPause) else { return } finish(job, def) diff --git a/Phone/Sources/Welcome/FirstRun.swift b/Phone/Sources/Welcome/FirstRun.swift index 569be9e2..aefad2e7 100644 --- a/Phone/Sources/Welcome/FirstRun.swift +++ b/Phone/Sources/Welcome/FirstRun.swift @@ -1766,7 +1766,7 @@ private struct PrivateField: View { /// means, in chips. private struct PrivateAround: View { private var run: FirstRun { .shared } - static let chips = [["Stays on this iPhone", "Gone when closed"], ["Hidden from the agent", "Never synced"]] + static let chips = [["Stays on this \(DeviceWord.name)", "Gone when closed"], ["Hidden from the agent", "Never synced"]] var body: some View { let night = run.incognito diff --git a/Phone/Sources/Words/CommandRows.swift b/Phone/Sources/Words/CommandRows.swift new file mode 100644 index 00000000..5e2496cf --- /dev/null +++ b/Phone/Sources/Words/CommandRows.swift @@ -0,0 +1,47 @@ +import Foundation + +/// The Mac's commands in the field (Sources/Fast/Query.swift's Command): a +/// menu action found by its name or another word for it. Its name typed +/// whole leads every other row; begun, it stands under the first. +struct CommandCandidate: Equatable, Sendable { + /// What runs it (BrowserKey's token). + let token: String + let title: String + var aliases: [String] = [] + /// The keys that do it, for the row's end ("⇧⌘R"). + var shortcut = "" +} + +extension Words { + static func commandRows(_ typed: String, commands: [CommandCandidate]) -> (exact: [WordRow], begun: [WordRow]) { + let text = name(typed) + guard !text.isEmpty else { return ([], []) } + var exact: [WordRow] = [], begun: [WordRow] = [] + for command in commands { + let names = [name(command.title)] + command.aliases.map(name) + let row = WordRow(action: .command(command.token), icon: .settings, title: command.title.replacingOccurrences(of: "…", with: ""), + subtitle: command.shortcut.isEmpty ? "Yab" : "Yab · \(command.shortcut)", key: .go, group: .yab) + if names.contains(text) { exact.append(row) } + else if text.count >= 3, names.contains(where: { begins($0, text) }) { begun.append(row) } + } + return (exact, Array(begun.prefix(2))) + } + + /// The rows with the commands among them: whole names first, begun ones second. + static func withCommands(_ rows: [WordRow], typed: String, commands: [CommandCandidate]) -> [WordRow] { + let found = commandRows(typed, commands: commands) + var rows = rows + rows.insert(contentsOf: found.begun, at: min(1, rows.count)) + rows.insert(contentsOf: found.exact, at: 0) + return rows + } + + private static func name(_ text: String) -> String { + text.replacingOccurrences(of: "…", with: "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + } + + /// The name, or one of its words, begins with the words typed. + private static func begins(_ name: String, _ text: String) -> Bool { + name.hasPrefix(text) || name.split(separator: " ").contains { $0.hasPrefix(text) } + } +} diff --git a/Phone/Sources/Words/WordRows.swift b/Phone/Sources/Words/WordRows.swift index d92c414a..4df0318d 100644 --- a/Phone/Sources/Words/WordRows.swift +++ b/Phone/Sources/Words/WordRows.swift @@ -20,6 +20,8 @@ struct WordRow: Equatable, Identifiable, Sendable { case findOnPage /// A page from History or a bookmark of the Mac's, opened as a site is. case place(url: String) + /// One of Yab's menu actions (BrowserKey's token). + case command(String) } /// What the row's icon is: a site's favicon, or one of the field's glyphs. @@ -63,6 +65,7 @@ struct WordRow: Equatable, Identifiable, Sendable { case .settings: "settings" case .findOnPage: "find" case let .place(url): "place:" + url + case let .command(token): "command:" + token } } } @@ -157,7 +160,7 @@ extension Words { rows = Array((found + begun + strong + [search] + asked + weak).prefix(4)) } if wantsSettings(text) { - rows.insert(WordRow(action: .settings, icon: .settings, title: "Settings", subtitle: "Yab on this iPhone", key: .go, group: .yab), at: 0) + rows.insert(WordRow(action: .settings, icon: .settings, title: "Settings", subtitle: "Yab on this \(DeviceWord.name)", key: .go, group: .yab), at: 0) } return rows } diff --git a/Phone/Tests/BrowserBasicsTests.swift b/Phone/Tests/BrowserBasicsTests.swift index b541a703..5fbfa531 100644 --- a/Phone/Tests/BrowserBasicsTests.swift +++ b/Phone/Tests/BrowserBasicsTests.swift @@ -220,6 +220,17 @@ final class BrowserBasicsTests: XCTestCase { XCTAssertTrue(menu.children.last === system, "the system's actions stay under ours") } + /// The Mac's Open in Split View, offered where a split can stand. + func testTheMenuOffersSplitViewOnlyWhenAsked() throws { + let plain = try XCTUnwrap(PageLinkMenu.menu([]) { _ in }.children.first as? UIMenu) + XCTAssertFalse(plain.children.map(\.accessibilityIdentifier).contains("link.beside")) + var opened: PageLinkMenu.Opening? + let wide = try XCTUnwrap(PageLinkMenu.menu([], beside: true) { opened = $0 }.children.first as? UIMenu) + XCTAssertEqual(wide.children.compactMap { ($0 as? UIAction)?.title }.last, PageLinkMenu.beside) + XCTAssertEqual(wide.children.last?.accessibilityIdentifier, "link.beside") + _ = opened + } + func testOnlyWebLinksOfThePageInFrontGetTheMenu() async throws { let pages = pool(), page = tab("menu.links") _ = try await ready(pages, page) diff --git a/Phone/Tests/BrowserKeysTests.swift b/Phone/Tests/BrowserKeysTests.swift index 46d19c98..ccccf5d1 100644 --- a/Phone/Tests/BrowserKeysTests.swift +++ b/Phone/Tests/BrowserKeysTests.swift @@ -98,6 +98,60 @@ final class BrowserKeysTests: XCTestCase { XCTAssertFalse(try press(.toggleSidebar), "compact phone and Duo retain their keys") } + func testCommandCommaOpensSettingsAsOnTheMac() throws { + XCTAssertEqual(BrowserKey.settings.input, ",") + XCTAssertEqual(BrowserKey.settings.modifiers, .command) + XCTAssertTrue(try press(.settings)) + XCTAssertTrue(app.surfaces.settings) + XCTAssertTrue(try press(.settings), "still ours with Settings up, never the system's Settings app") + XCTAssertTrue(app.surfaces.settings, "and Settings stays as it is") + } + + func testShiftCommandNOpensAPrivateNewTab() throws { + XCTAssertEqual(BrowserKey.newPrivateTab.input, "n") + XCTAssertEqual(BrowserKey.newPrivateTab.modifiers, [.command, .shift]) + XCTAssertTrue(try press(.newPrivateTab)) + XCTAssertEqual(app.surfaces.field, .newTab) + XCTAssertTrue(app.field.isPrivate) + } + + func testPageKeysFollowTheMacsViewMenu() throws { + XCTAssertEqual(BrowserKey.zoomIn.input, "=") + XCTAssertEqual(BrowserKey.reader.modifiers, [.command, .shift]) + XCTAssertEqual(app.mayUse(.stop), app.currentPageState.isLoading, "Stop only while the page loads") + XCTAssertFalse(app.mayUse(.reader), "no reader for this page") + XCTAssertTrue(try press(.zoomIn)) + XCTAssertEqual(app.pageZoom, 1.1, accuracy: 0.001) + XCTAssertTrue(try press(.actualSize)) + XCTAssertEqual(app.pageZoom, 1, accuracy: 0.001) + XCTAssertTrue(try press(.zoomOut)) + XCTAssertEqual(app.pageZoom, 0.9, accuracy: 0.001) + app.pageMenuZoom(0) + } + + func testOpenInSplitViewPairsTheLinkBesideItsPage() throws { + app.workspace.resize(expanded: true) + app.workspace.windowSize = CGSize(width: 1376, height: 1032) + let source = try XCTUnwrap(app.browser.tab?.id) + XCTAssertTrue(app.canOpenLinkBeside(source)) + app.openHeldLink(URL(string: "https://example.com/beside")!, from: source, as: .beside) + XCTAssertTrue(app.workspace.paired) + XCTAssertEqual(app.workspace.first, source) + XCTAssertEqual(app.browser.tab?.navigationURL?.absoluteString, "https://example.com/beside") + app.workspace.windowSize = CGSize(width: 800, height: 1100) + XCTAssertFalse(app.canOpenLinkBeside(source), "no split in a narrow window") + } + + func testDuplicateTabOpensTheSamePageInFront() throws { + let tab = Tab(id: "web", title: "Example", site: "Example", icon: "globe", url: "https://example.com/a") + app.browser.open(tab, deduplicate: false) + let before = app.browser.space.allTabs.count + app.duplicate(tab) + XCTAssertEqual(app.browser.space.allTabs.count, before + 1) + XCTAssertNotEqual(app.browser.tab?.id, "web") + XCTAssertEqual(app.browser.tab?.navigationURL, tab.navigationURL) + } + func testCommandLOpensTheAddress() throws { XCTAssertTrue(try press(.openLocation)) XCTAssertEqual(app.surfaces.field, .address) @@ -180,7 +234,11 @@ final class BrowserKeysTests: XCTestCase { ] for show in cover { show() - for key in BrowserKey.all { XCTAssertFalse(try press(key), key.title) } + // ⌘, alone is still taken, so the system's Settings item never gets it, and does nothing. + for key in BrowserKey.all where key != .settings { XCTAssertFalse(try press(key), key.title) } + let settingsWereUp = app.surfaces.settings + XCTAssertTrue(try press(.settings)) + XCTAssertEqual(app.surfaces.settings, settingsWereUp) XCTAssertNil(app.surfaces.field) XCTAssertEqual(app.browser.tab?.id, "second") XCTAssertEqual(ids.count, 3) diff --git a/Phone/Tests/CommandRowsTests.swift b/Phone/Tests/CommandRowsTests.swift new file mode 100644 index 00000000..5d504e19 --- /dev/null +++ b/Phone/Tests/CommandRowsTests.swift @@ -0,0 +1,40 @@ +import XCTest +@testable import YabPhone + +/// The Mac's commands in the field: a whole name leads, a begun one follows the first row. +final class CommandRowsTests: XCTestCase { + private let commands = [ + CommandCandidate(token: "zoomIn", title: "Zoom In", aliases: ["bigger"], shortcut: "⌘+"), + CommandCandidate(token: "reader", title: "Show Reader", aliases: ["reader"], shortcut: "⇧⌘R"), + CommandCandidate(token: "print", title: "Print…", shortcut: "⌘P"), + ] + + func testAWholeNameLeadsEveryOtherRow() { + let search = WordRow(action: .search, icon: .magnifier, title: "print", subtitle: "", key: .search, group: .web) + let rows = Words.withCommands([search], typed: "Print", commands: commands) + XCTAssertEqual(rows.first?.action, .command("print")) + XCTAssertEqual(rows.first?.title, "Print") + XCTAssertEqual(rows.first?.subtitle, "Yab · ⌘P") + XCTAssertEqual(rows.last, search) + } + + func testAnAliasCountsAsTheName() { + XCTAssertEqual(Words.commandRows("reader", commands: commands).exact.map(\.action), [.command("reader")]) + XCTAssertEqual(Words.commandRows("bigger", commands: commands).exact.map(\.action), [.command("zoomIn")]) + } + + func testABegunNameStandsUnderTheFirstRow() { + let first = WordRow(action: .tab(id: "a"), icon: .globe, title: "Zoo", subtitle: "", key: .go, group: .tabs) + let rows = Words.withCommands([first], typed: "zoo", commands: commands) + XCTAssertEqual(rows.map(\.action), [.tab(id: "a"), .command("zoomIn")]) + XCTAssertTrue(Words.commandRows("zo", commands: commands).begun.isEmpty, "two letters find nothing") + XCTAssertTrue(Words.commandRows("weather", commands: commands).begun.isEmpty) + } + + func testShortcutsReadAsTheMenuWritesThem() { + XCTAssertEqual(BrowserKey.reader.shortcut, "⇧⌘R") + XCTAssertEqual(BrowserKey.zoomIn.shortcut, "⌘+") + XCTAssertFalse(BrowserKey.tab(3).commandable) + XCTAssertEqual(Set(BrowserKey.all.map(\.title)).count, BrowserKey.all.count) + } +} diff --git a/Phone/Tests/DownloadStoreTests.swift b/Phone/Tests/DownloadStoreTests.swift index 867fbc43..e59d080b 100644 --- a/Phone/Tests/DownloadStoreTests.swift +++ b/Phone/Tests/DownloadStoreTests.swift @@ -105,6 +105,64 @@ final class DownloadStoreTests: XCTestCase { XCTAssertEqual(first.entries.map(\.name), ["open.pdf"]) } + /// The iPad's button: a file pressed for flies from where it was held, + /// only where something draws the flight; one with no place only bumps. + func testAFileFliesFromWhereItWasHeldOnlyWhereFlightsAreDrawn() { + let store = store() + let at = CGPoint(x: 120, y: 340) + store.begin(UUID(), name: "a.pdf", host: "acme.com", total: nil, isPrivate: false, control: .init(), from: at) + XCTAssertTrue(store.flights.isEmpty, "the phone's Now line says it instead") + XCTAssertEqual(store.bumps, 1) + store.flies = true + let thrown = UUID() + store.begin(thrown, name: "b.pdf", host: "acme.com", total: nil, isPrivate: false, control: .init(), from: at) + XCTAssertEqual(store.flights, [DownloadStore.Flight(id: thrown, from: at, name: "b.pdf")]) + XCTAssertEqual(store.bumps, 1, "no bump until it lands") + store.landed(thrown) + XCTAssertTrue(store.flights.isEmpty) + XCTAssertEqual(store.bumps, 2) + store.begin(UUID(), name: "c.pdf", host: "acme.com", total: nil, isPrivate: false, control: .init()) + XCTAssertTrue(store.flights.isEmpty, "no place held: the button only gives") + XCTAssertEqual(store.bumps, 3) + } + + /// The last file's icon waits on the button, with no timer, until the + /// list or the file opens, or the file goes. + func testTheLastFileWaitsUntilSeen() throws { + let store = store() + let first = try finished(store, "one.pdf") + XCTAssertEqual(store.waiting, first) + let second = try finished(store, "two.pdf") + XCTAssertEqual(store.waiting, second, "the newest one") + store.seen(first) + XCTAssertEqual(store.waiting, second, "opening another file leaves it") + store.seen(second) + XCTAssertNil(store.waiting) + let third = try finished(store, "three.pdf") + store.seen() + XCTAssertNil(store.waiting, "the list opened") + let fourth = try finished(store, "four.pdf") + store.delete(fourth) + XCTAssertNil(store.waiting) + _ = third + let secret = try finished(store, "secret.pdf", isPrivate: true) + XCTAssertEqual(store.waiting, secret) + store.forgetPrivate() + XCTAssertNil(store.waiting, "gone with the private tabs") + } + + /// Documents open as files; pages, pictures and text stay pages. + func testWhichTypesOpenInTheViewer() { + for type in ["application/pdf", "Application/PDF; charset=binary", "text/pdf", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.apple.keynote"] { + XCTAssertTrue(PageDocument.opensInViewer(type), type) + } + for type in ["text/html", "image/png", "video/mp4", "text/plain", "application/json", ""] { + XCTAssertFalse(PageDocument.opensInViewer(type), type) + } + XCTAssertFalse(PageDocument.opensInViewer(nil)) + } + func testALaunchClearsWhatAKilledPrivateSessionLeft() throws { try FileManager.default.createDirectory(at: privateFolder, withIntermediateDirectories: true) try Data("x".utf8).write(to: privateFolder.appendingPathComponent("left.pdf")) diff --git a/Phone/Tests/PageDownloadTests.swift b/Phone/Tests/PageDownloadTests.swift index 6392f760..c37a43e0 100644 --- a/Phone/Tests/PageDownloadTests.swift +++ b/Phone/Tests/PageDownloadTests.swift @@ -78,6 +78,11 @@ final class PageDownloadTests: XCTestCase { XCTAssertNil(window.rootViewController?.presentedViewController, "nothing covers the page: no alert, no share sheet") return try XCTUnwrap(store.entries.first) } + /// WKWebView.url can still name the file for a moment after it is whole, + /// then reads the source again with no navigation: wait that moment out. + private func settles(_ view: WKWebView, at url: URL) async throws { + try await require({ view.url == url }, "the source's address did not come back") + } private func bytes(_ entry: DownloadEntry) throws -> Data { try Data(contentsOf: try XCTUnwrap(store.url(of: entry))) } private func failed() async throws -> DownloadEntry { try await require { self.store.entries.first?.state == .failed && self.pages.transfers.isEmpty } @@ -130,7 +135,7 @@ final class PageDownloadTests: XCTestCase { XCTAssertEqual(file.name, "Owned.txt") XCTAssertEqual(file.host, "127.0.0.1") XCTAssertEqual(file.size, Int64(DownloadSite.bytes.count)) - XCTAssertEqual(view.url, site.url("/second")); XCTAssertTrue(view.configuration.websiteDataStore === store) + try await settles(view, at: site.url("/second")); XCTAssertTrue(view.configuration.websiteDataStore === store) XCTAssertEqual(pages.front, source.id) XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), before.entries.map(\.url)) XCTAssertEqual(pages.navigationState(for: source.id)?.index, before.index) @@ -238,7 +243,7 @@ final class PageDownloadTests: XCTestCase { XCTAssertTrue(request.header.contains("private-only=owned")); XCTAssertFalse(request.header.contains("public-only=owned")) XCTAssertTrue(view.configuration.websiteDataStore === store); XCTAssertFalse(store.isPersistent) XCTAssertFalse(store === publicView.configuration.websiteDataStore) - XCTAssertEqual(view.url, site.url("/page")); XCTAssertEqual(pages.front, privateTab.id); XCTAssertTrue(exported.isEmpty) + try await settles(view, at: site.url("/page")); XCTAssertEqual(pages.front, privateTab.id); XCTAssertTrue(exported.isEmpty) // The private tabs close: their file goes. let url = try XCTUnwrap(self.store.url(of: file)) pages.setPageInteractionsEnabled(false); pages.renewPrivateStore() @@ -260,7 +265,7 @@ final class PageDownloadTests: XCTestCase { XCTAssertEqual(before.entries.map(\.url), [site.url("/page").absoluteString, destination.absoluteString]) try await click(view) _ = try await completed() - XCTAssertEqual(view.url, destination) + try await settles(view, at: destination) XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), before.entries.map(\.url)) XCTAssertEqual(pages.navigationState(for: source.id)?.index, before.index) } @@ -271,7 +276,7 @@ final class PageDownloadTests: XCTestCase { let _: Any = try await view.evaluateJavaScript("const a=document.createElement('a');a.href=URL.createObjectURL(new Blob(['Owned blob café+tea'],{type:'text/plain'}));a.download='Blob.txt';document.body.appendChild(a);a.click();true") let file = try await completed() XCTAssertEqual(String(data: try bytes(file), encoding: .utf8), "Owned blob café+tea") - XCTAssertEqual(view.url, site.url("/page")); XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), before.entries.map(\.url)) + try await settles(view, at: site.url("/page")); XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), before.entries.map(\.url)) } func testATransferOutlivesItsPageItsTabAndAViewGone() async throws { @@ -318,7 +323,7 @@ final class PageDownloadTests: XCTestCase { let broken = try await failed() XCTAssertEqual(store.flash, broken.id, "the line says Failed for a moment") XCTAssertEqual(store.nowItem(isPrivate: false)?.subtitle, "Failed") - XCTAssertEqual(view.url, site.url("/page")) + try await settles(view, at: site.url("/page")) XCTAssertNil(broken.file) XCTAssertTrue(store.canRetry(broken.id)) site.allowFiles(); store.retry(broken.id) @@ -327,7 +332,7 @@ final class PageDownloadTests: XCTestCase { XCTAssertEqual(store.entries.count, 1) XCTAssertEqual(site.requests.filter { $0.target == "/file" }.count, 2) XCTAssertEqual(try bytes(file), DownloadSite.bytes) - XCTAssertEqual(view.url, site.url("/page")); XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), [site.url("/page").absoluteString]) + try await settles(view, at: site.url("/page")); XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), [site.url("/page").absoluteString]) let _: Any = try await view.evaluateJavaScript("document.getElementById('touch').click();true") let action = try await view.evaluateJavaScript("document.getElementById('result').textContent") as? String XCTAssertEqual(action, "Page action 1") @@ -376,10 +381,45 @@ final class PageDownloadTests: XCTestCase { XCTAssertEqual(file.host, "127.0.0.1", "the site is the page's") XCTAssertEqual(try bytes(file), DownloadSite.bytes) XCTAssertTrue(try XCTUnwrap(site.requests.last { $0.target == "/file" }).header.contains("linked=owned")) - XCTAssertEqual(view.url, site.url("/page")) + try await settles(view, at: site.url("/page")) + XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), before.entries.map(\.url)) + } + + /// A PDF the page opens inline is a file for the system's viewer: kept + /// in Downloads without asking, handed to the viewer once whole, and the + /// page it came from stays as it was. + func testAPDFOpensAsAFileForTheViewerAndKeepsTheSource() async throws { + var asked = 0, viewed: [(Tab.ID, UUID)] = [] + pages.onDownloadAsk = { _, answer in asked += 1; answer(true) } + pages.onViewDownload = { viewed.append(($0, $1)) } + let source = tab("download.pdf"), view = try await ready(source) + let before = try XCTUnwrap(pages.navigationState(for: source.id)) + try await click(view, "pdf") + let file = try await completed() + XCTAssertEqual(asked, 0, "viewing a document is not the site sending a file") + XCTAssertEqual(file.name, "doc.pdf") + XCTAssertEqual(try bytes(file), DownloadSite.pdf) + try await require { viewed.count == 1 } + XCTAssertEqual(viewed.first?.0, source.id) + XCTAssertEqual(viewed.first?.1, file.id) + try await settles(view, at: site.url("/page")) XCTAssertEqual(pages.navigationState(for: source.id)?.entries.map(\.url), before.entries.map(\.url)) } + /// A tab whose first load is a PDF had no page to put back: the file + /// still opens, rather than being dropped. + func testAPDFAsATabsFirstLoadStillOpens() async throws { + var viewed: [UUID] = [] + pages.onViewDownload = { viewed.append($1) } + let fresh = tab("download.pdf.fresh", "/doc.pdf") + show(pages.activate(fresh)) + let file = try await completed() + XCTAssertEqual(file.name, "doc.pdf") + XCTAssertEqual(file.host, "127.0.0.1", "the site is the file's own") + try await require { viewed == [file.id] } + try await require { !self.pages.state(for: fresh.id).isLoading } + } + func testNativeRequestDownloadReportsItsAPIFrameWithoutNavigatingTheActualDocument() async throws { var publicStore: WKWebsiteDataStore? for privately in [false, true] { @@ -434,7 +474,7 @@ final class PageDownloadTests: XCTestCase { try await require { self.site.requests.filter { $0.target == "/file" }.count == 2 } XCTAssertTrue(pages.transfers.isEmpty) XCTAssertTrue(store.entries.isEmpty) - XCTAssertEqual(view.url, site.url("/page")); XCTAssertEqual(pages.front, selected.id) + try await settles(view, at: site.url("/page")); XCTAssertEqual(pages.front, selected.id) } // MARK: - with Yab in the background @@ -459,7 +499,7 @@ final class PageDownloadTests: XCTestCase { pages.appDidBecomeActive() try await require { self.store.flash == job.id } XCTAssertEqual(store.nowItem(isPrivate: false)?.subtitle, "Open") - XCTAssertEqual(view.url, site.url("/page")) + try await settles(view, at: site.url("/page")) } func testComingBackWhileItStillGoesKeepsTheLine() async throws { @@ -490,6 +530,8 @@ final class PageDownloadTests: XCTestCase { private final class DownloadSite: @unchecked Sendable { struct Request { let target: String; let header: String } static let bytes = Data("Owned actual download café+tea\n".utf8) + /// A PDF the page shows inline, no attachment: one empty page. + static let pdf = Data("%PDF-1.4\n1 0 obj<>endobj 2 0 obj<>endobj 3 0 obj<>endobj\ntrailer<>\n%%EOF\n".utf8) private let listener: NWListener private let queue = DispatchQueue(label: "owned.download.site") private var connections: [ObjectIdentifier:NWConnection] = [:] @@ -545,6 +587,12 @@ private final class DownloadSite: @unchecked Sendable { } let target = header.components(separatedBy: " ").dropFirst().first ?? "/" self.received.append(Request(target: target, header: header)) + if target == "/doc.pdf" { + let body = Self.pdf + let headers = Data("HTTP/1.1 200 OK\r\nContent-Type: application/pdf\r\nContent-Length: \(body.count)\r\nConnection: close\r\n\r\n".utf8) + self.send(headers + body, connection) + return + } if target == "/file" { let body = Self.bytes let headers = Data("HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Disposition: attachment; filename=\"Owned.txt\"\r\nContent-Length: \(body.count)\r\nConnection: close\r\n\r\n".utf8) @@ -554,7 +602,7 @@ private final class DownloadSite: @unchecked Sendable { } else { self.send(headers + (self.fails ? Data(body.prefix(2)) : body), connection) } return } - let body = "Owned download source

Owned actual source

Actual fragmentDownload actual fileReady" + let body = "Owned download source

Owned actual source

Actual fragmentDownload actual fileActual PDFReady" let response = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \(body.utf8.count)\r\nConnection: close\r\n\r\n\(body)" self.send(Data(response.utf8), connection) } diff --git a/Phone/Tests/PageMenuTests.swift b/Phone/Tests/PageMenuTests.swift index 3d5efb4a..8b285017 100644 --- a/Phone/Tests/PageMenuTests.swift +++ b/Phone/Tests/PageMenuTests.swift @@ -61,6 +61,7 @@ final class PageMenuTests: XCTestCase { } func testRequestDesktopSiteTogglesForTheSite() throws { + app.siteSettings.prefersDesktop = false XCTAssertFalse(app.pageIsDesktop) app.pageMenuDesktop() XCTAssertTrue(app.pageIsDesktop) @@ -70,6 +71,25 @@ final class PageMenuTests: XCTestCase { XCTAssertFalse(app.siteSettings.desktop("figma.com", isPrivate: false)) } + /// As Safari on iPad: desktop sites unless a site is asked for as a mobile one. + func testAnIPadAsksForDesktopSitesUnlessTold() throws { + let settings = SiteSettings(defaults: nil, prefersDesktop: true) + XCTAssertTrue(settings.desktop("google.com", isPrivate: false)) + XCTAssertEqual(settings.contentMode("google.com", isPrivate: false), .recommended) + settings.setDesktop(false, for: "google.com", isPrivate: false) + XCTAssertFalse(settings.desktop("google.com", isPrivate: false)) + XCTAssertEqual(settings.contentMode("google.com", isPrivate: false), .mobile) + XCTAssertTrue(settings.desktop("figma.com", isPrivate: false), "only that site") + settings.setDesktop(true, for: "google.com", isPrivate: false) + XCTAssertTrue(settings.desktop("google.com", isPrivate: false)) + XCTAssertTrue(settings.site("google.com", isPrivate: false).isEmpty, "back to the default, nothing kept") + + let phone = SiteSettings(defaults: nil, prefersDesktop: false) + XCTAssertEqual(phone.contentMode("google.com", isPrivate: false), .mobile) + phone.setDesktop(true, for: "google.com", isPrivate: false) + XCTAssertEqual(phone.contentMode("google.com", isPrivate: false), .desktop) + } + func testWhatASiteAskedForIsSaidInAWordAndForgotten() { let settings = SiteSettings(defaults: nil) XCTAssertEqual(settings.asked([.camera], host: "meet.example", isPrivate: false), .prompt, "first time: iOS asks") diff --git a/Phone/Tests/SettingsStoreTests.swift b/Phone/Tests/SettingsStoreTests.swift index 04b0d5e2..35faff53 100644 --- a/Phone/Tests/SettingsStoreTests.swift +++ b/Phone/Tests/SettingsStoreTests.swift @@ -143,7 +143,7 @@ final class SettingsStoreTests: XCTestCase { XCTAssertFalse(SettingsStore.wantsSettings(words), words) } XCTAssertEqual(SettingsFieldRow.title, "Settings") - XCTAssertEqual(SettingsFieldRow.subtitle, "Yab on this iPhone") + XCTAssertEqual(SettingsFieldRow.subtitle, "Yab on this \(DeviceWord.name)") } func testVersionIsTheBundles() { @@ -172,10 +172,10 @@ final class SettingsContentTests: XCTestCase { XCTAssertEqual(rows, [ "MacBook Pro | Online", "Agent | Claude · on your Mac", - "About a page | This iPhone", + "About a page | This \(DeviceWord.name)", "Everything else | Claude", "Default Browser | Yab", - "Today | This iPhone’s own", + "Today | This \(DeviceWord.name)’s own", "Face ID for Pay and Post | On", "Lock Screen Details | After Face ID", "Private Tabs | Not kept", @@ -183,8 +183,8 @@ final class SettingsContentTests: XCTestCase { "Appearance | System", "About Yab | 0.0.1", ]) - XCTAssertEqual(root[0].footer, "Tasks run in Yab on your Mac, with your sign-ins. The iPhone sends codes and the yes signed by Face ID.") - XCTAssertEqual(root[2].footer, "Spaces, pins and kept tabs are the same on your Mac; Today is this iPhone’s own. Mail stays in Yab on your Mac.") + XCTAssertEqual(root[0].footer, "Tasks run in Yab on your Mac, with your sign-ins. The \(DeviceWord.name) sends codes and the yes signed by Face ID.") + XCTAssertEqual(root[2].footer, "Spaces, pins and kept tabs are the same on your Mac; Today is this \(DeviceWord.name)’s own. Mail stays in Yab on your Mac.") XCTAssertNil(root[1].footer) } diff --git a/Phone/Tests/SyncBridgeTests.swift b/Phone/Tests/SyncBridgeTests.swift index c7d30318..10e0935a 100644 --- a/Phone/Tests/SyncBridgeTests.swift +++ b/Phone/Tests/SyncBridgeTests.swift @@ -266,7 +266,7 @@ final class SyncBridgeTests: XCTestCase { let keys = SyncKeychain.testing(folder: folder.appendingPathComponent("keys")) let id = keys.deviceID server.revoke(id) - let told = await until { app.sync.phase == .refused("This iPhone was removed from Sync.") } + let told = await until { app.sync.phase == .refused("This \(DeviceWord.name) was removed from Sync.") } XCTAssertTrue(told, "\(app.sync.phase)") XCTAssertTrue(app.sync.showsJoin) app.sync.joinAgain() @@ -925,7 +925,7 @@ final class SyncBridgeTests: XCTestCase { func testJoinAgainAfterRemovalAddsNoSpaceAndLosesNoTab() async throws { try await leavesAndJoinsAgain { app, server in server.revoke(SyncKeychain.testing(folder: self.folder.appendingPathComponent("keys")).deviceID) - let told = await self.until { app.sync.phase == .refused("This iPhone was removed from Sync.") } + let told = await self.until { app.sync.phase == .refused("This \(DeviceWord.name) was removed from Sync.") } XCTAssertTrue(told, "\(app.sync.phase)") app.sync.joinAgain() } diff --git a/Phone/Tests/SyncDevicesTests.swift b/Phone/Tests/SyncDevicesTests.swift index d7ddd37b..b9ade3fd 100644 --- a/Phone/Tests/SyncDevicesTests.swift +++ b/Phone/Tests/SyncDevicesTests.swift @@ -23,7 +23,7 @@ final class SyncDevicesTests: PhoneLinkTestCase { SyncDevice(id: "phone", name: "Mira’s iPhone", model: "iPhone18,1", lastSeen: now), ], own: "phone", now: now) XCTAssertEqual(words.map(\.id), ["phone", "mac", "old"], "this iPhone first") - XCTAssertEqual(words[0].words, "This iPhone") + XCTAssertEqual(words[0].words, "This \(DeviceWord.name)") XCTAssertTrue(words[0].isPhone && words[0].isThis) XCTAssertEqual(words[1].words, "Syncing now") XCTAssertFalse(words[1].isPhone) @@ -45,14 +45,14 @@ final class SyncDevicesTests: PhoneLinkTestCase { XCTAssertEqual(sections.map(\.id), ["sync", "sync.history", "sync.recovery", "sync.off"]) XCTAssertEqual(sections[0].title, "Devices") XCTAssertEqual(sections[0].rows.map(\.id), ["sync.device.phone", "sync.device.mac", "sync"]) - XCTAssertEqual(sections[0].rows[0].value, "This iPhone") + XCTAssertEqual(sections[0].rows[0].value, "This \(DeviceWord.name)") XCTAssertEqual(sections[0].rows[1].value, "Syncing now") guard case .glyph(.phone)? = sections[0].rows[0].icon, case .glyph(.macbook)? = sections[0].rows[1].icon else { return XCTFail("an iPhone's and a Mac's glyph") } guard case .page(.recoveryKey) = sections[2].rows[0].kind else { return XCTFail("the Recovery Key's page") } let off = sections[3].rows[0] - XCTAssertEqual(off.title, "Turn Off Sync on This iPhone") + XCTAssertEqual(off.title, "Turn Off Sync on This \(DeviceWord.name)") XCTAssertTrue(off.danger) guard case .action = off.kind else { return XCTFail("an action, asked first") } // Not in sync (a test world): the Mac's row as before, and no Turn Off. @@ -96,7 +96,7 @@ final class SyncDevicesTests: PhoneLinkTestCase { let listed = await until { Set(app.sync.devices.map(\.name)) == ["MacBook Pro", "Test iPhone"] } XCTAssertTrue(listed, "\(app.sync.devices)") let words = SettingsDevice.list(app.sync.devices, own: app.sync.ownDevice, now: Date()) - XCTAssertEqual(words.first?.words, "This iPhone") + XCTAssertEqual(words.first?.words, "This \(DeviceWord.name)") XCTAssertEqual(words.first?.isPhone, true) } diff --git a/Phone/Tests/TabStackTests.swift b/Phone/Tests/TabStackTests.swift index 45407b66..edbdf236 100644 --- a/Phone/Tests/TabStackTests.swift +++ b/Phone/Tests/TabStackTests.swift @@ -647,6 +647,13 @@ final class TabStackTests: XCTestCase { XCTAssertNil(alone.front) XCTAssertTrue(alone.rises) XCTAssertEqual(alone.seated, []) + // The iPad has no circle: nothing flies, sits or rises; the others fade in place. + for chosen in 0..<6 { + let flat = Closing(count: 6, chosen: chosen, stack: false) + XCTAssertEqual(flat.roles, (0..<6).map { $0 == chosen ? Role.chosen : .other }) + XCTAssertEqual(flat.seated, []) + XCTAssertFalse(flat.rises) + } // The stack's cards are what TabRecency shows after the chosen tab comes first. for count in 1...6 { for chosen in 0.. b.bounds.width } + // Each page of a split keeps its band either way; the address setting + // leaves the panes as they are, the tab bar takes height from them. let withBars = app.workspace.paneFrame.height app.workspace.preferences.addressBars = false - try await until { app.workspace.paneFrame.height > withBars + 40 } + try await until { app.workspace.paneFrame.height == withBars } + app.workspace.preferences.tabsInSidebar = false + try await until { app.workspace.paneFrame.height < withBars - 40 } + app.workspace.preferences.tabsInSidebar = true + try await until { app.workspace.paneFrame.height == withBars } app.browser.select(first.id) app.reconcileWorkspace() app.workspace.preferences.resizeSidebar(to: 360) diff --git a/Phone/Tests/TabletWorkspaceTests.swift b/Phone/Tests/TabletWorkspaceTests.swift index ab11021e..69ad492f 100644 --- a/Phone/Tests/TabletWorkspaceTests.swift +++ b/Phone/Tests/TabletWorkspaceTests.swift @@ -22,11 +22,70 @@ final class TabletWorkspaceTests: XCTestCase { func testSearchAndFrameRespectKeyboardAndSidebarBounds() { let size = CGSize(width: 1024, height: 768) let open = TabletWorkspaceGeometry(size: size, statusBar: 24, sidebar: true, framed: true) - XCTAssertEqual(open.page, CGRect(x: 272, y: 76, width: 744, height: 684)) + XCTAssertEqual(open.page, CGRect(x: 272, y: 32, width: 744, height: 728)) XCTAssertLessThanOrEqual(open.top + 24 + open.searchHeight(keyboard: 350), size.height - 350) + // Framed, the page keeps its card with the sidebar away, as on the Mac. let closed = TabletWorkspaceGeometry(size: size, statusBar: 24, sidebar: false, framed: true) - XCTAssertEqual(closed.rim, 0) - XCTAssertEqual(closed.page.width, size.width) + XCTAssertEqual(closed.rim, 8) + XCTAssertEqual(closed.page, CGRect(x: 8, y: 32, width: 1008, height: 728)) + let bare = TabletWorkspaceGeometry(size: size, statusBar: 24, sidebar: false, framed: false) + XCTAssertEqual(bare.rim, 0) + XCTAssertEqual(bare.page.width, size.width) + } + + /// The Mac's rule: a row fills the width, rows stay even, four across at most. + func testPinColumnsFollowTheMacsSidebar() { + let wide: CGFloat = 264 - 2 * Metrics.Tablet.inset + XCTAssertEqual(Metrics.Tablet.pinColumns(1, width: wide), 1) + XCTAssertEqual(Metrics.Tablet.pinColumns(3, width: wide), 3) + XCTAssertEqual(Metrics.Tablet.pinColumns(4, width: wide), 4) + XCTAssertEqual(Metrics.Tablet.pinColumns(5, width: wide), 3) + XCTAssertEqual(Metrics.Tablet.pinColumns(6, width: wide), 3) + XCTAssertEqual(Metrics.Tablet.pinColumns(8, width: wide), 4) + let narrow: CGFloat = 200 + XCTAssertEqual(Metrics.Tablet.pinColumns(4, width: narrow), 2) + XCTAssertEqual(Metrics.Tablet.pinColumns(3, width: narrow), 3) + XCTAssertEqual(Metrics.Tablet.pinColumns(0, width: narrow), 1) + } + + /// The Mac's two layouts: tabs in the sidebar with the address as a plate + /// there, or the band over the card; tabs across the top in a 46-point bar. + func testChromePlanFollowsTheMacsLayouts() { + let column = TabletChromePlan(strip: false, sidebarInView: true, addressBars: false) + XCTAssertTrue(column.plate); XCTAssertTrue(column.headerNav); XCTAssertFalse(column.band) + let bar = TabletChromePlan(strip: false, sidebarInView: true, addressBars: true) + XCTAssertFalse(bar.plate); XCTAssertTrue(bar.band); XCTAssertTrue(bar.bandNav); XCTAssertFalse(bar.bandWorkspace) + let away = TabletChromePlan(strip: false, sidebarInView: false, addressBars: false) + XCTAssertTrue(away.band); XCTAssertTrue(away.bandNav); XCTAssertTrue(away.bandWorkspace, "nothing else holds the door and the tab buttons") + let split = TabletChromePlan(strip: false, sidebarInView: true, addressBars: false, split: true) + XCTAssertFalse(split.plate, "each page of a split keeps its own band") + XCTAssertTrue(split.bandNav); XCTAssertFalse(split.headerNav) + let strip = TabletChromePlan(strip: true, sidebarInView: false, addressBars: false) + XCTAssertTrue(strip.band); XCTAssertFalse(strip.bandNav); XCTAssertFalse(strip.bandWorkspace) + let g = TabletWorkspaceGeometry(size: CGSize(width: 1024, height: 768), statusBar: 24, sidebar: true, framed: true, strip: true) + XCTAssertEqual(g.sidebarWidth, 0, "the tab bar takes the sidebar's place") + XCTAssertEqual(g.top, 24 + Metrics.Tablet.strip) + } + + func testSidebarSpacesPageAsTheMacsDo() { + XCTAssertEqual(TabletSidebar.paged(-100, index: 1, count: 3, width: 264), -50, "half the finger's travel") + XCTAssertEqual(TabletSidebar.paged(-900, index: 1, count: 3, width: 264), -264, "a page at most") + XCTAssertEqual(TabletSidebar.paged(100, index: 0, count: 3, width: 264), 7.5, accuracy: 0.001, "give past the first") + XCTAssertEqual(TabletSidebar.paged(-100, index: 2, count: 3, width: 264), -7.5, accuracy: 0.001, "and past the last") + } + + /// A chat stands beside the workspace: the page and toolbar narrow, never sit under it. + func testChatColumnNarrowsTheWorkspace() { + let wide = CGSize(width: 1376, height: 1032) + XCTAssertEqual(TabletWorkspaceGeometry.conversation(in: wide, expanded: true, chat: true), Metrics.Workspace.conversation) + XCTAssertEqual(TabletWorkspaceGeometry.conversation(in: wide, expanded: true, chat: false), 0) + XCTAssertEqual(TabletWorkspaceGeometry.conversation(in: wide, expanded: false, chat: true), 0) + XCTAssertEqual(TabletWorkspaceGeometry.conversation(in: CGSize(width: 600, height: 900), expanded: true, chat: true), 0) + } + + func testEachSitePermissionHasItsOwnMark() { + XCTAssertEqual(SiteSettings.Permission.downloads.tabletAsset, MacGlyph.yabDownload.rawValue) + XCTAssertEqual(Set(SiteSettings.Permission.allCases.map(\.tabletAsset)).count, SiteSettings.Permission.allCases.count) } func testTabletSearchClosesWithoutLandingInThePhonePlate() async throws { diff --git a/Phone/Tests/TaskDeskLifetimeTests.swift b/Phone/Tests/TaskDeskLifetimeTests.swift index 9dcb10cc..67e4abcd 100644 --- a/Phone/Tests/TaskDeskLifetimeTests.swift +++ b/Phone/Tests/TaskDeskLifetimeTests.swift @@ -82,7 +82,7 @@ final class TaskDeskLifetimeTests: XCTestCase { XCTAssertFalse(desk.signing) XCTAssertNil(desk.faceID) XCTAssertEqual(desk.virtualMac?.diary, before) - XCTAssertFalse(desk.virtualMac?.diary.contains("Checked the Face ID signature from the iPhone") ?? true) + XCTAssertFalse(desk.virtualMac?.diary.contains("Checked the Face ID signature from the \(DeviceWord.name)") ?? true) XCTAssertEqual(pending.tasks.run("lisbon")?.status, .yes) } diff --git a/Phone/Tests/TasksDeskTests.swift b/Phone/Tests/TasksDeskTests.swift index 2a949914..f4fe582a 100644 --- a/Phone/Tests/TasksDeskTests.swift +++ b/Phone/Tests/TasksDeskTests.swift @@ -161,7 +161,7 @@ final class TasksDeskTests: XCTestCase { XCTAssertEqual(running.icon, "google") XCTAssertEqual(running.buttons.map(\.label), ["Stop"]) let code = try XCTUnwrap(state(.code, 2)) - XCTAssertEqual(code.title, "TAP sent a code to this iPhone") + XCTAssertEqual(code.title, "TAP sent a code to this \(DeviceWord.name)") XCTAssertEqual(code.line, "Your Mac is signing in to flytap.com") XCTAssertEqual(code.buttons.map(\.label), ["Enter Code"]) XCTAssertEqual(code.word, "Code") @@ -401,7 +401,7 @@ final class TasksDeskTests: XCTestCase { _ = await (first, second) await wait("done") { app.tasks.run("lisbon")?.status == .done } XCTAssertEqual(signer.signs, 1, "a system panel leaves faceID nil while it authenticates") - XCTAssertEqual(desk.virtualMac?.diary.filter { $0 == "Checked the Face ID signature from the iPhone" }.count, 1) + XCTAssertEqual(desk.virtualMac?.diary.filter { $0 == "Checked the Face ID signature from the \(DeviceWord.name)" }.count, 1) } func testStoppingDuringFaceIDDoesNotDeliverTheYes() async throws { @@ -418,7 +418,7 @@ final class TasksDeskTests: XCTestCase { await approval.value XCTAssertEqual(app.tasks.run("lisbon")?.status, .stopped) XCTAssertNil(desk.faceID) - XCTAssertFalse(desk.virtualMac?.diary.contains("Checked the Face ID signature from the iPhone") ?? true) + XCTAssertFalse(desk.virtualMac?.diary.contains("Checked the Face ID signature from the \(DeviceWord.name)") ?? true) } func testReviewAfterNotNowCanStillSignTheYes() async throws { diff --git a/Phone/Tests/TasksVirtualMacTests.swift b/Phone/Tests/TasksVirtualMacTests.swift index b9cf72ea..11ace31c 100644 --- a/Phone/Tests/TasksVirtualMacTests.swift +++ b/Phone/Tests/TasksVirtualMacTests.swift @@ -49,7 +49,7 @@ final class TasksVirtualMacTests: XCTestCase { mac.send(TaskOrder(id: "lisbon", words: "book the tap 18:35 to lisbon, window seat")) await wait("the code") { if case .needsCode = $0 { true } else { false } } guard case let .needsCode(_, code)? = events.last else { return XCTFail("the code comes last: \(events)") } - XCTAssertEqual(code.title, "TAP sent a code to this iPhone") + XCTAssertEqual(code.title, "TAP sent a code to this \(DeviceWord.name)") XCTAssertEqual(code.line(task: "Lisbon flights"), "Your Mac is signing in to flytap.com for Lisbon flights") mac.giveCode("lisbon", code: "482 913") await wait("the yes") { if case .needsYes = $0 { true } else { false } } @@ -75,8 +75,8 @@ final class TasksVirtualMacTests: XCTestCase { } } XCTAssertEqual(order, ["taken", "step 0", "step 1", "step 2", "code", "step 2", "step 3", "yes", "paying", "done"]) - XCTAssertTrue(mac.diary.contains("Signed in to flytap.com with the code from your iPhone"), "\(mac.diary)") - XCTAssertTrue(mac.diary.contains("Checked the Face ID signature from the iPhone"), "\(mac.diary)") + XCTAssertTrue(mac.diary.contains("Signed in to flytap.com with the code from your \(DeviceWord.name)"), "\(mac.diary)") + XCTAssertTrue(mac.diary.contains("Checked the Face ID signature from the \(DeviceWord.name)"), "\(mac.diary)") } func testAWrongCodeIsAskedForAgain() async throws { diff --git a/Phone/Tests/WordsTests.swift b/Phone/Tests/WordsTests.swift index fc25b7d9..c7359e21 100644 --- a/Phone/Tests/WordsTests.swift +++ b/Phone/Tests/WordsTests.swift @@ -182,7 +182,7 @@ final class WordsTests: XCTestCase { func testSettingsComesFirst() { let rows = Words.rows(for: "sett", in: .newTab, tabs: tabs, sites: NewTabContent.miraSites) XCTAssertEqual(describe(rows), [ - "Settings | Yab on this iPhone | go", + "Settings | Yab on this \(DeviceWord.name) | go", "sett | Search Google · new tab | search", "sett | Ask Claude | go", ]) diff --git a/Phone/UITests/AtlasSupport.swift b/Phone/UITests/AtlasSupport.swift index 645ce6cd..70754fe0 100644 --- a/Phone/UITests/AtlasSupport.swift +++ b/Phone/UITests/AtlasSupport.swift @@ -1,3 +1,4 @@ +import UIKit import XCTest /// What the atlas, accessibility, perf and film tests share: the app launched @@ -26,6 +27,7 @@ enum Atlas { static var world: String { environment["YAB_WORLD"].flatMap { $0.isEmpty ? nil : $0 } ?? "mira" } static var model: String { environment["YAB_MODEL"].flatMap { $0.isEmpty ? nil : $0 } ?? "pro" } + static var deviceWord: String { UIDevice.current.userInterfaceIdiom == .pad ? "iPad" : "iPhone" } /// A fresh folder for ready markers, so an old marker never counts. static func readyFolder() -> URL { diff --git a/Phone/UITests/BrowserWorkspaceUITests.swift b/Phone/UITests/BrowserWorkspaceUITests.swift index 722b2cdd..6abcc323 100644 --- a/Phone/UITests/BrowserWorkspaceUITests.swift +++ b/Phone/UITests/BrowserWorkspaceUITests.swift @@ -96,7 +96,7 @@ final class BrowserWorkspaceUITests: XCTestCase { XCTAssertTrue(wait { draft.exists && (draft.value as? String) == "Second page draft" }) try picture("pair-history-restored") app.buttons["workspace.menu"].tap() - app.buttons["Full Spread"].tap() + app.buttons["Separate Split View"].tap() XCTAssertTrue(wait { !self.app.buttons["workspace.companion"].exists }) XCTAssertEqual(draft.value as? String, "Second page draft") try picture("full-spread") @@ -264,7 +264,7 @@ final class BrowserWorkspaceUITests: XCTestCase { XCUIDevice.shared.orientation = .landscapeLeft XCTAssertTrue(app.buttons["workspace.menu"].waitForExistence(timeout: 10)) app.buttons["workspace.menu"].tap() - app.buttons["Open Beside"].tap() + app.buttons["Split View"].tap() let close = app.buttons["field.close"] XCTAssertTrue(close.waitForExistence(timeout: 10)) try picture("beside-new-tab") @@ -274,7 +274,7 @@ final class BrowserWorkspaceUITests: XCTestCase { XCTAssertTrue(wait { !close.exists && self.app.buttons["workspace.companion"].exists }) try picture("beside-selected") app.buttons["workspace.menu"].tap() - app.buttons["Close Page"].tap() + app.buttons["Close Split"].tap() XCTAssertTrue(wait { !self.app.buttons["workspace.companion"].exists }) XCTAssertTrue(app.buttons["chrome.plate"].exists) } diff --git a/Phone/UITests/ChatsTests.swift b/Phone/UITests/ChatsTests.swift index 5421d82d..92380732 100644 --- a/Phone/UITests/ChatsTests.swift +++ b/Phone/UITests/ChatsTests.swift @@ -57,7 +57,7 @@ final class ChatsTests: XCTestCase { let head = element(app, "chat.answerHead") XCTAssertTrue(head.waitForExistence(timeout: 15), "no answer") XCTAssertTrue(head.staticTexts["Apple Intelligence"].exists) - XCTAssertTrue(element(app, "chat.where").label.contains("on this iPhone")) + XCTAssertTrue(element(app, "chat.where").label.contains("on this \(Atlas.deviceWord)")) XCTAssertTrue(app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH %@", "Anna wants")).firstMatch.exists) // The answer stands 8 from the screen's edges, at its own height. let sheet = element(app, "chat.sheet") @@ -100,7 +100,7 @@ final class ChatsTests: XCTestCase { let sheet = element(app, "chat.sheet") XCTAssertTrue(waitFor(abs(sheet.frame.minY) < 2 && abs(sheet.frame.minX) < 1), "chat at \(sheet.frame)") // Who answers is said with the name (and in Chat Info), not under it. - XCTAssertEqual(title.value as? String, "Apple Intelligence \u{00B7} on this iPhone") + XCTAssertEqual(title.value as? String, "Apple Intelligence \u{00B7} on this \(Atlas.deviceWord)") XCTAssertFalse(element(app, "chat.line").exists) // The text field itself: its window-frame probe shares the identifier. diff --git a/Phone/UITests/ExtensionsUITests.swift b/Phone/UITests/ExtensionsUITests.swift index 0082a7be..d9272f40 100644 --- a/Phone/UITests/ExtensionsUITests.swift +++ b/Phone/UITests/ExtensionsUITests.swift @@ -81,7 +81,7 @@ final class ExtensionsUITests: XCTestCase { let alert = app.alerts.firstMatch XCTAssertTrue(alert.waitForExistence(timeout: 60)) record(app, "Loom isn't offered") - XCTAssertTrue(alert.label.contains("doesn't work on iPhone"), alert.label) + XCTAssertTrue(alert.label.contains("doesn't work on \(Atlas.deviceWord)"), alert.label) XCTAssertFalse(alert.buttons["Add"].exists, "no way to add it") alert.buttons["OK"].tap() } diff --git a/Phone/UITests/SpaceRowSwipeTests.swift b/Phone/UITests/SpaceRowSwipeTests.swift index cbcaba0b..cd642ebb 100644 --- a/Phone/UITests/SpaceRowSwipeTests.swift +++ b/Phone/UITests/SpaceRowSwipeTests.swift @@ -158,10 +158,10 @@ final class SpaceRowSwipeTests: XCTestCase { try save("pinned") pin.press(forDuration: 1) try save("pin-hold") - XCTAssertTrue(app.buttons["Unpin"].waitForExistence(timeout: 3)) + XCTAssertTrue(app.buttons["Unpin Tab"].waitForExistence(timeout: 3)) XCTAssertTrue(app.descendants(matching: .any).matching(NSPredicate(format: "label == 'Launch notes'")).firstMatch.exists, "the held pin must own its menu") - app.buttons["Unpin"].tap() + app.buttons["Unpin Tab"].tap() try save("after-unpin") XCTAssertTrue(row.waitForExistence(timeout: 4)) XCTAssertFalse(pin.exists) @@ -197,7 +197,7 @@ final class SpaceRowSwipeTests: XCTestCase { app.terminate(); launch() row.press(forDuration: 1) XCTAssertTrue(app.buttons["Copy Link"].waitForExistence(timeout: 3)) - XCTAssertTrue(app.buttons["Pin"].exists) + XCTAssertTrue(app.buttons["Pin Tab"].exists) try save("tab-hold") } diff --git a/Phone/UITests/SyncTests.swift b/Phone/UITests/SyncTests.swift index e2f0c863..63db9459 100644 --- a/Phone/UITests/SyncTests.swift +++ b/Phone/UITests/SyncTests.swift @@ -150,7 +150,7 @@ final class SyncTests: XCTestCase { let app = launch(["-YabState", "join.5", "-YabNoAnim", "YES"]) let words = element(app, "join.words") XCTAssertTrue(words.waitForExistence(timeout: 15)) - XCTAssertEqual(words.label, "This iPhone was removed from Sync.") + XCTAssertEqual(words.label, "This \(Atlas.deviceWord) was removed from Sync.") element(app, "join.again").tap() XCTAssertTrue(element(app, "join.code").waitForExistence(timeout: 5), "joining again starts with a new code") } diff --git a/Phone/UITests/TabFolderEditingUITests.swift b/Phone/UITests/TabFolderEditingUITests.swift index 877777bb..049b7815 100644 --- a/Phone/UITests/TabFolderEditingUITests.swift +++ b/Phone/UITests/TabFolderEditingUITests.swift @@ -29,9 +29,9 @@ final class TabFolderEditingUITests: XCTestCase { extra: ["-settings.appearance", dark ? "dark" : "light"])) let mode = dark ? "dark" : "light" try picture(mode + "-column") - hold("newtab.pin.edit-pin", expecting: "Rename…") + hold("newtab.pin.edit-pin", expecting: "Rename Tab…") try picture(mode + "-pin-menu") - button("Rename…").tap() + button("Rename Tab…").tap() XCTAssertTrue(app.alerts["Rename Tab"].waitForExistence(timeout: 10)) try picture(mode + "-rename-alert") let text = app.alerts.textFields.firstMatch @@ -40,8 +40,8 @@ final class TabFolderEditingUITests: XCTestCase { if button("Select All").waitForExistence(timeout: 2) { button("Select All").tap() } text.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 60) + "My reference") app.alerts.buttons["Save"].tap() - hold("newtab.pin.edit-pin", expecting: "Rename…") - button("Rename…").tap() + hold("newtab.pin.edit-pin", expecting: "Rename Tab…") + button("Rename Tab…").tap() XCTAssertTrue(app.alerts.buttons["Reset"].waitForExistence(timeout: 10)) app.alerts.buttons["Reset"].tap() hold("newtab.tab.edit-tab", expecting: "Move to Folder") diff --git a/Phone/UITests/TabletArcSplitUITests.swift b/Phone/UITests/TabletArcSplitUITests.swift index 381343c0..1c784cdd 100644 --- a/Phone/UITests/TabletArcSplitUITests.swift +++ b/Phone/UITests/TabletArcSplitUITests.swift @@ -82,8 +82,8 @@ final class TabletArcSplitUITests: XCTestCase { app.buttons["field.close"].tap() XCTAssertTrue(pane("secondary").buttons["tablet.address"].exists) app.buttons["tablet.paneMenu"].tap() - app.buttons["Separate Split"].tap() - XCTAssertTrue(wait { self.element("tablet.singleAddressBar").exists }) + app.buttons["Separate Split View"].tap() + XCTAssertTrue(wait { self.element("tablet.addressPlate").exists }) } func testInactiveNavigationActsOnItsOwnHistory() throws { @@ -116,7 +116,7 @@ final class TabletArcSplitUITests: XCTestCase { XCTAssertTrue(app.staticTexts["Next workspace document"].waitForExistence(timeout: 10)) let closed = survivor == "primary" ? "secondary" : "primary" app.buttons["tablet.close.workspace-" + closed].tap() - XCTAssertTrue(wait { self.element("tablet.singleAddressBar").exists }) + XCTAssertTrue(wait { self.element("tablet.addressPlate").exists }) XCTAssertFalse(element("tablet.split.row").exists) XCTAssertFalse(pane(closed).exists) app.buttons["tablet.back"].tap() @@ -134,7 +134,7 @@ final class TabletArcSplitUITests: XCTestCase { dismissKeyboard() chip("secondary").tap() app.buttons["tablet.close.workspace-secondary"].tap() - XCTAssertTrue(wait { self.element("tablet.singleAddressBar").exists }) + XCTAssertTrue(wait { self.element("tablet.addressPlate").exists }) XCTAssertEqual(app.textFields["Draft"].value as? String, "Left survives") try picture("06-closed-active") } diff --git a/Phone/UITests/TabletChromeUITests.swift b/Phone/UITests/TabletChromeUITests.swift index 91896100..761208ba 100644 --- a/Phone/UITests/TabletChromeUITests.swift +++ b/Phone/UITests/TabletChromeUITests.swift @@ -31,13 +31,16 @@ final class TabletChromeUITests: XCTestCase { } private func wait(_ check: @escaping () -> Bool) -> Bool { TransitionCatalog.wait(15, check) } - func testSinglePageUsesTheOriginalCapsuleAboveTheDocument() throws { + /// The Mac's column: the address a plate in the sidebar under its + /// header, no band over the page. + func testSinglePageKeepsTheAddressInTheSidebarAsTheMacDoes() throws { launch("page.1") try picture("single-page") - let capsule = element("tablet.singleAddressBar") - XCTAssertTrue(capsule.exists, "a single page keeps its original top toolbar capsule") + let plate = element("tablet.addressPlate") + XCTAssertTrue(plate.exists, "the address is the sidebar's plate") let pane = app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "tablet.pane.")).firstMatch - XCTAssertLessThanOrEqual(capsule.frame.maxY, pane.frame.minY) + XCTAssertLessThanOrEqual(plate.frame.maxX, pane.frame.minX) + XCTAssertTrue(element("tablet.sidebar.header").exists) XCTAssertFalse(app.descendants(matching: .any).matching(NSPredicate(format: "identifier BEGINSWITH %@", "tablet.addressBar.")).firstMatch.exists) app.buttons["tablet.siteControls"].tap() XCTAssertTrue(element("site.settings").waitForExistence(timeout: 10)) @@ -47,7 +50,7 @@ final class TabletChromeUITests: XCTestCase { XCTAssertTrue(app.textFields["field.input"].waitForExistence(timeout: 10)) } - func testSeparatingTheSplitRestoresTheOriginalToolbarWithoutLosingTheDraft() throws { + func testSeparatingTheSplitRestoresTheSidebarAddressWithoutLosingTheDraft() throws { launch("workspace.form") let secondary = element("tablet.pane.workspace-secondary") let draft = secondary.textFields["Draft"] @@ -56,9 +59,9 @@ final class TabletChromeUITests: XCTestCase { try picture("split-sidebar") draft.tap(); draft.typeText("Preserved draft") if app.keyboards.buttons["Hide keyboard"].firstMatch.exists { app.keyboards.buttons["Hide keyboard"].firstMatch.tap() } - app.buttons["workspace.menu"].tap() - app.buttons["Separate Split"].tap() - XCTAssertTrue(wait { self.element("tablet.singleAddressBar").exists }) + app.buttons["tablet.paneMenu"].tap() + app.buttons["Separate Split View"].tap() + XCTAssertTrue(wait { self.element("tablet.addressPlate").exists }) XCTAssertFalse(element("tablet.addressBar.workspace-secondary").exists) XCTAssertFalse(element("tablet.split.row").exists) XCTAssertEqual(app.textFields["Draft"].value as? String, "Preserved draft") @@ -80,6 +83,8 @@ final class TabletChromeUITests: XCTestCase { let end = Date().timeIntervalSince1970 let shown = index % 2 == 1 XCTAssertEqual(toggle.value as? String, shown ? "shown" : "hidden") + // The address moves between the sidebar's plate and the band as it goes. + XCTAssertTrue(wait { self.app.buttons.matching(identifier: "tablet.address").count == 1 }) XCTAssertEqual(app.buttons["tablet.address"].value as? String, address) marks.append(["start": start, "end": end, "shown": shown]) } diff --git a/Phone/UITests/TabletLayoutUITests.swift b/Phone/UITests/TabletLayoutUITests.swift index 9dfe57d0..165accfe 100644 --- a/Phone/UITests/TabletLayoutUITests.swift +++ b/Phone/UITests/TabletLayoutUITests.swift @@ -97,22 +97,38 @@ final class TabletLayoutUITests: XCTestCase { try picture("06-pair-from-deck") } - func testExistingAppearanceCanHideAddressBarsAndSearchRemainsAvailable() throws { + /// The Mac's Show Address Bar: off, the address is the sidebar's plate; + /// on, a band over the page. Search is a tap or ⌘L away in both. + func testShowAddressBarMovesTheAddressAndSearchRemainsAvailable() throws { launch("page.1") - element("tablet.settings").tap() + let plate = element("tablet.addressPlate").waitForExistence(timeout: 10) + if !plate { try picture("07-before-settings") } + XCTAssertTrue(plate, "off, as the Mac: the address is the sidebar's plate") + // By touch: the simulator builds the menu on a first key, which can + // reach the system's own Settings item instead (⌘, has unit tests). let appearance = app.buttons["settings.row.appearance"] + app.buttons["tablet.siteControls"].tap() + XCTAssertTrue(element("site.more").waitForExistence(timeout: 10)); element("site.more").tap() + app.buttons["Yab Settings…"].tap() XCTAssertTrue(appearance.waitForExistence(timeout: 15)); appearance.tap() + // The iPad's rows stand at the page's foot: scrolled to, they load. let bars = app.switches["settings.row.appearance.addressBars"] - if !bars.isHittable { app.swipeUp() } - XCTAssertTrue(bars.waitForExistence(timeout: 10)) + // Dragged by the page's margin: a drag started on a row could press it, + // and one of them opens the iOS Settings app. + let corner = app.buttons["settings.back"].coordinate(withNormalizedOffset: .zero) + for _ in 0..<4 where !(bars.waitForExistence(timeout: 2) && bars.isHittable) { + corner.withOffset(CGVector(dx: -6, dy: 520)).press(forDuration: 0.05, thenDragTo: corner.withOffset(CGVector(dx: -6, dy: 140))) + } + if !bars.isHittable { try picture("07-settings-no-switch") } + XCTAssertTrue(bars.isHittable) try picture("07-current-settings-with-tablet-rows") - XCTAssertEqual(bars.value as? String, "1"); bars.tap() + XCTAssertEqual(bars.value as? String, "0"); bars.tap() app.buttons["settings.back"].tap() XCTAssertTrue(app.buttons["settings.close"].waitForExistence(timeout: 10)) app.buttons["settings.close"].tap() XCTAssertTrue(app.buttons["tablet.address"].waitForExistence(timeout: 10)) - XCTAssertTrue(wait { !self.element("tablet.addressBar.work-figma-onb").exists }) - try picture("08-address-bars-hidden") + XCTAssertTrue(wait { self.element("tablet.addressBar.work-figma-onb").exists && !self.element("tablet.addressPlate").exists }) + try picture("08-address-bar-shown") app.buttons["tablet.address"].tap() XCTAssertTrue(app.textFields["field.input"].waitForExistence(timeout: 10)) app.buttons["field.close"].tap() @@ -125,9 +141,48 @@ final class TabletLayoutUITests: XCTestCase { try picture("09-hidden-bars-command-L") } + /// A site's first file asks from the sidebar's downloads button, and is answerable. + func testFirstDownloadAsksFromTheDownloadsButton() throws { + launch("downloads.ask") + XCTAssertEqual(app.buttons["tablet.downloads.sidebar"].value as? String, "Asking") + let download = app.buttons["download.ask.download"] + XCTAssertTrue(download.waitForExistence(timeout: 15)) + XCTAssertTrue(download.isHittable) + try picture("12-download-ask") + download.tap() + XCTAssertTrue(wait { !download.exists }) + } + + func testDownloadsButtonListsFiles() throws { + launch("downloads.now") + app.buttons["tablet.downloads.sidebar"].tap() + XCTAssertTrue(element("downloads.page").waitForExistence(timeout: 10)) + try picture("13-downloads-list") + } + + /// All Tabs: a tap on any card takes that tab, the gallery goes, the workspace returns. + func testAllTabsCardsOpenTheirTab() throws { + launch("page.1") + app.buttons["tablet.tabs"].tap() + XCTAssertTrue(element("tabs.gallery").waitForExistence(timeout: 10)) + try picture("14-all-tabs") + let cards = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH 'tabs.card.'")) + XCTAssertTrue(cards.firstMatch.waitForExistence(timeout: 10)) + let card = (0.. self.app.frame.width }) XCTAssertFalse(element("tablet.addressBar.workspace-primary").exists) - XCTAssertFalse(app.buttons["workspace.menu"].exists) + XCTAssertFalse(app.buttons["tablet.paneMenu"].exists) try picture("ipad-split-portrait") XCUIDevice.shared.orientation = .landscapeLeft try picture("ipad-split-restoring-landscape") - XCTAssertTrue(wait { self.element("tablet.addressBar.workspace-primary").exists && self.app.buttons["workspace.menu"].isHittable }) + XCTAssertTrue(wait { self.element("tablet.addressBar.workspace-primary").exists && self.app.buttons["tablet.paneMenu"].isHittable }) XCTAssertEqual(draft.value as? String, "Second document stays") try picture("ipad-split-restored-landscape") focusCompanion(address: "firstdocument.com") @@ -192,8 +196,8 @@ final class TabletWorkspaceUITests: XCTestCase { focusCompanion(address: "seconddocument.com") draft = element("tablet.pane.workspace-secondary").textFields["Draft"] XCTAssertTrue(wait { (draft.value as? String) == "Second document stays" }) - app.buttons["workspace.menu"].tap() - app.buttons["Separate Split"].tap() + app.buttons["tablet.paneMenu"].tap() + app.buttons["Separate Split View"].tap() XCTAssertTrue(wait { !self.element("tablet.addressBar.workspace-primary").exists }) XCTAssertEqual(draft.value as? String, "Second document stays") try picture("ipad-full-spread") @@ -273,7 +277,7 @@ final class TabletWorkspaceUITests: XCTestCase { for state in ["page.1", "field.1", "site.1", "site.3", "settings.1", "welcome.5", "welcome.11", "stack.gallery"] { launch(state) if Atlas.model != "ipad" { XCTAssertFalse(app.buttons["tablet.address"].exists) } - if state.hasPrefix("welcome") { XCTAssertFalse(app.buttons["workspace.menu"].exists) } + if state.hasPrefix("welcome") { XCTAssertFalse(app.buttons["tablet.paneMenu"].exists) } if Atlas.model == "ipad", state.hasPrefix("welcome"), element("welcome.words").exists { XCTAssertLessThanOrEqual(element("welcome.words").frame.width, 525) } diff --git a/Phone/UITests/TasksTests.swift b/Phone/UITests/TasksTests.swift index af763acd..f792dfba 100644 --- a/Phone/UITests/TasksTests.swift +++ b/Phone/UITests/TasksTests.swift @@ -111,7 +111,7 @@ final class TasksTests: XCTestCase { XCTAssertLessThanOrEqual(sheet.frame.maxY, padTop - 8 + 2, "the sheet stands over the pad (\(padTop)): \(sheet.frame)") XCTAssertGreaterThanOrEqual(sheet.frame.maxY, padTop - 8 - 20, "the sheet stands on the pad (\(padTop)): \(sheet.frame)") XCTAssertEqual(sheet.frame.height, 220, accuracy: 2, "the code's sheet: \(sheet.frame)") - XCTAssertTrue(has("TAP sent a code to this iPhone")) + XCTAssertTrue(has("TAP sent a code to this \(Atlas.deviceWord)")) // As QuickType's code from Messages would: all six at once. field.typeText("482913") XCTAssertTrue(gone(sheet), "the sheet stays after the code") @@ -221,7 +221,7 @@ final class TasksTests: XCTestCase { retry.tap() // Again from the same step: the failure goes, the steps go on to the code. XCTAssertTrue(gone(retry, timeout: 5), "Retry stays after it was tapped") - XCTAssertTrue(has("Waiting for the code TAP sent to this iPhone", timeout: 20), "it never went on to the code") + XCTAssertTrue(has("Waiting for the code TAP sent to this \(Atlas.deviceWord)", timeout: 20), "it never went on to the code") app.descendants(matching: .any)["task.chat.who"].swipeDown(velocity: .fast) nowSays("Needs the code TAP sent you") }