Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

iOS shell: the Controllers and Settings chips in iPhone Duo's side column

v0lumehi6901d447a11f
diff --git a/frontend-ios/README.md b/frontend-ios/README.md
index bd37d3fb..356637ad 100644
--- a/frontend-ios/README.md
+++ b/frontend-ios/README.md
@@ -96,6 +96,8 @@ Only the available size decides, never the device model, idiom or orientation (`
| Regular width and height, not wide (iPad portrait, an unfolded foldable held like a book) | The library alone: the same hero with Play and the settings button in it, a grid of wide cards, recently played. Settings, when asked for, float in as a panel from the right over the dimmed library. |
| Wider than tall (iPhone and iPad landscape, an unfolded foldable on its side) | Cover Flow over the blurred banner, wide cards in a calm deck. Settings, when asked for, float in as the same panel (regular) or take the whole screen (compact). |
+iPhone Duo keeps a column on one side for the status bar and the system's vertical bars (#622). Where the system names that edge (`toolbarVerticalEdge`, iOS 27.1) and the column is wide enough, the Controllers and Settings chips leave the header and sit at the bottom of the column, above the home indicator and clear of the camera (`reservedRegions(kind: .occlusion)`). The top half stays free for the status bar. Everywhere else nothing changes (`SideBar`, tested in `SideBarTests`, rendered on a simulated outer display by `SideBarCaptureTests`). A shell built with an SDK older than iOS 27.1 keeps the chips in the header.
+
Settings appear only when asked for (the settings button, X on a controller) and close with Back, B or a tap outside. They are one view in one place for every layout, with the game's banner as their header, so the selected game, open settings and both scroll positions survive a fold, a rotation or a Stage Manager resize.
Choice rows with 2 to 4 short labels that fit their equal segment (`ChoicePresentation.resolve`, by option count, label length, row width and Dynamic Type) are segmented. Every other choice is a compact row (label, current value, chevron) that opens a list in the shell's own card: D-pad moves, A picks and closes, B closes without a change, touch and keyboard work the same, the current value carries a checkmark. The settings keep a non-scrolling top bar with an opaque backing that holds Library, so scrolled content never shows under it.
diff --git a/frontend-ios/Sources/ShellUI/CoverFlowView.swift b/frontend-ios/Sources/ShellUI/CoverFlowView.swift
index 8651917b..0a9ef492 100644
--- a/frontend-ios/Sources/ShellUI/CoverFlowView.swift
+++ b/frontend-ios/Sources/ShellUI/CoverFlowView.swift
@@ -11,6 +11,8 @@ struct CoverFlowView: View, Equatable {
let showsHints: Bool
/// The screen's safe areas around this view, so the cards can sit in the middle of the whole screen.
var screenInsets = EdgeInsets()
+ /// The Controllers and Settings chips sit in the side column (SideBar), not in the top bar.
+ var chipsInSideBar = false
let select: (String) -> Void
let primary: (GameDetail) -> Void
let openSettings: () -> Void
@@ -34,6 +36,7 @@ struct CoverFlowView: View, Equatable {
nonisolated static func == (lhs: Self, rhs: Self) -> Bool {
lhs.games.map(\.game) == rhs.games.map(\.game) && lhs.selected.game == rhs.selected.game
&& lhs.controllers == rhs.controllers && lhs.showsHints == rhs.showsHints && lhs.screenInsets == rhs.screenInsets
+ && lhs.chipsInSideBar == rhs.chipsInSideBar
}
var body: some View {
@@ -106,8 +109,10 @@ struct CoverFlowView: View, Equatable {
.accessibilityLabel(ShellStrings.text("Game settings") + ", " + selected.game.title)
.accessibilityIdentifier("settings.open")
.shellTarget("lib.settings", radius: 22, action: openSettings)
- ControllerChip(count: controllers, action: openControllers)
- ShellSettingsChip(action: openShellSettings)
+ if !chipsInSideBar {
+ ControllerChip(count: controllers, action: openControllers)
+ ShellSettingsChip(action: openShellSettings)
+ }
}
// On a phone on its side the hints share the row. At the largest sizes they would wrap into a tall block and the
// title and chips, centred in it, would sink away from the top edge, so the row stops growing at xxLarge, as the
@@ -381,13 +386,17 @@ struct CoverFlowBackdrop: View {
/// The controller count on top of art, which opens Controllers.
struct ControllerChip: View {
let count: Int
+ /// In the side column (SideBar): the count under the symbol, so the chip is as narrow as the gear.
+ var vertical = false
let action: () -> Void
var body: some View {
Button(action: action) {
- HStack(spacing: 8) {
+ let layout = vertical ? AnyLayout(VStackLayout(spacing: 2)) : AnyLayout(HStackLayout(spacing: 8))
+ layout {
Image(systemName: count == 0 ? "gamecontroller" : "gamecontroller.fill")
Text("\(count)").monospacedDigit()
}
+ .frame(width: vertical ? SideBar.chipWidth - 28 : nil, height: vertical ? SideBar.heights[0] : nil)
}
.buttonStyle(ChipButtonStyle())
.accessibilityLabel(ShellStrings.text("Controllers") + ", \(count)")
@@ -398,9 +407,13 @@ struct ControllerChip: View {
/// The gear at the top-right corner, which opens the shell's own settings.
struct ShellSettingsChip: View {
+ var vertical = false
let action: () -> Void
var body: some View {
- Button(action: action) { Image(systemName: "gearshape").frame(minWidth: 18) }
+ Button(action: action) {
+ Image(systemName: "gearshape").frame(minWidth: 18)
+ .frame(width: vertical ? SideBar.chipWidth - 28 : nil, height: vertical ? SideBar.heights[1] : nil)
+ }
.buttonStyle(ChipButtonStyle())
.accessibilityLabel(ShellStrings.text("Settings"))
.accessibilityIdentifier("shellSettings.open")
diff --git a/frontend-ios/Sources/ShellUI/LibraryView.swift b/frontend-ios/Sources/ShellUI/LibraryView.swift
index 5af85eae..96028758 100644
--- a/frontend-ios/Sources/ShellUI/LibraryView.swift
+++ b/frontend-ios/Sources/ShellUI/LibraryView.swift
@@ -68,6 +68,9 @@ public struct LibraryView: View {
@FocusState private var keyboardFocus: Bool
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@Environment(\.dynamicTypeSize) private var typeSize
+ /// The side column of iPhone Duo (#622): the captures set it, otherwise the system's values from SideBarProbe.
+ @Environment(\.shellSideBar) private var sideBarOverride
+ @State private var probedSideBar = SideBar(edge: nil)
public init(games: [GameDetail], controllers: [ControllerInfo] = [], actions: ShellActions = ShellActions(),
input: ShellInput? = nil, initialSelection: String? = nil, initialDetailOpen: Bool = false,
@@ -105,23 +108,35 @@ public struct LibraryView: View {
let floating = layout.settingsFloat(width)
let paneCovers = settingsOpen && !floating
let panelOverLibrary = settingsOpen && floating
+ // The chips go into the side column where the system has one. At the accessibility text sizes they stay in the header.
+ let column = typeSize.isAccessibilitySize ? nil : (sideBarOverride ?? probedSideBar).column(screen: whole, insets: insets)
ZStack(alignment: .topLeading) {
if layout.isCoverFlow, let selected { CoverFlowBackdrop(game: selected.game) } else { ShellPalette.background.ignoresSafeArea() }
if games.isEmpty {
EmptyLibraryView()
.overlay(alignment: .topTrailing) {
- HStack(spacing: 10) {
- ControllerChip(count: controllers.count, action: openControllers)
- ShellSettingsChip(action: openShellSettings)
- }.padding(.top, 6).padding(.trailing, 16)
+ if column == nil {
+ HStack(spacing: 10) {
+ ControllerChip(count: controllers.count, action: openControllers)
+ ShellSettingsChip(action: openShellSettings)
+ }.padding(.top, 6).padding(.trailing, 16)
+ }
}
+ if let column { sideChips(column, insets: insets) }
} else if let selected {
- library(selected, layout: layout, size: geometry.size, insets: insets)
+ library(selected, layout: layout, size: geometry.size, insets: insets, chipsInSideBar: column != nil)
.frame(width: width, height: geometry.size.height)
.opacity(paneCovers && edgeDrag == 0 ? 0 : 1)
.allowsHitTesting(!settingsOpen)
.accessibilityHidden(settingsOpen || helpGameID != nil || deleteGameID != nil)
.transformPreference(FocusTargets.self) { if settingsOpen { $0.removeAll() } }
+ if let column {
+ sideChips(column, insets: insets)
+ .opacity(paneCovers && edgeDrag == 0 ? 0 : 1)
+ .allowsHitTesting(!settingsOpen)
+ .accessibilityHidden(settingsOpen || helpGameID != nil || deleteGameID != nil)
+ .transformPreference(FocusTargets.self) { if settingsOpen { $0.removeAll() } }
+ }
if panelOverLibrary {
// The same dimming and dismissal as the Controllers overlay.
Color.black.opacity(0.55 * (settingsOpen && !controllersOpen ? 1 - min(1, edgeDrag / pane) : 1)).ignoresSafeArea()
@@ -256,6 +271,7 @@ public struct LibraryView: View {
}
}
.coordinateSpace(name: "shell")
+ .background { SideBarProbe { probedSideBar = $0 }.ignoresSafeArea().accessibilityHidden(true) }
.environment(\.shellOpenTouchLayout, { openTouchLayout(whole, insets) })
.background {
EdgeSwipeBack(enabled: (settingsOpen || controllersOpen || shellSettingsOpen) && choice == nil && helpGameID == nil && deleteGameID == nil
@@ -306,15 +322,25 @@ public struct LibraryView: View {
}
}
- @ViewBuilder private func library(_ selected: GameDetail, layout: ShellLayout, size: CGSize, insets: EdgeInsets) -> some View {
+ /// The Controllers and Settings chips in the side column, `column` in the screen's coordinates.
+ private func sideChips(_ column: CGRect, insets: EdgeInsets) -> some View {
+ SideBarChips(controllers: controllers.count, openControllers: openControllers, openShellSettings: openShellSettings)
+ .frame(width: column.width, height: column.height)
+ .offset(x: column.minX - insets.leading, y: column.minY - insets.top)
+ }
+
+ @ViewBuilder private func library(_ selected: GameDetail, layout: ShellLayout, size: CGSize, insets: EdgeInsets,
+ chipsInSideBar: Bool) -> some View {
if layout.isCoverFlow {
CoverFlowView(games: games, selected: selected, controllers: controllers.count, showsHints: !touchMode, screenInsets: insets,
+ chipsInSideBar: chipsInSideBar,
select: select, primary: primary, openSettings: openSettings, openControllers: openControllers,
openShellSettings: openShellSettings)
.equatable()
.transition(.opacity)
} else {
PortraitLibrary(games: games, selected: selected, wide: layout == .grid, size: size, topInset: insets.top, bottomInset: insets.bottom,
+ chipsInSideBar: chipsInSideBar,
controllers: controllers.count, select: select, primary: primary,
openSettings: openSettings, openControllers: openControllers, openShellSettings: openShellSettings,
position: $libraryPosition)
diff --git a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
index e61f3cb0..ef07270d 100644
--- a/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
+++ b/frontend-ios/Sources/ShellUI/PortraitLibrary.swift
@@ -20,6 +20,8 @@ struct PortraitLibrary: View, Equatable {
let topInset: CGFloat
/// The home indicator's height. Without a bottom bar the library scrolls under it to the bottom edge.
var bottomInset: CGFloat = 0
+ /// The Controllers and Settings chips sit in the side column (SideBar), not over the hero.
+ var chipsInSideBar = false
let controllers: Int
let select: (String) -> Void
let primary: (GameDetail) -> Void
@@ -56,7 +58,7 @@ struct PortraitLibrary: View, Equatable {
nonisolated static func == (lhs: Self, rhs: Self) -> Bool {
lhs.games.map(\.game) == rhs.games.map(\.game) && lhs.selected.game == rhs.selected.game && lhs.wide == rhs.wide
&& lhs.size == rhs.size && lhs.topInset == rhs.topInset && lhs.bottomInset == rhs.bottomInset
- && lhs.controllers == rhs.controllers
+ && lhs.controllers == rhs.controllers && lhs.chipsInSideBar == rhs.chipsInSideBar
}
var body: some View {
@@ -87,10 +89,12 @@ struct PortraitLibrary: View, Equatable {
.ignoresSafeArea(edges: wide ? [.top, .bottom] : .top)
.safeAreaInset(edge: .bottom, spacing: 0) { if !wide { bottomBar } }
.overlay(alignment: .topTrailing) {
- HStack(spacing: 10) {
- ControllerChip(count: controllers, action: openControllers)
- ShellSettingsChip(action: openShellSettings)
- }.padding(.top, 6).padding(.trailing, 16)
+ if !chipsInSideBar {
+ HStack(spacing: 10) {
+ ControllerChip(count: controllers, action: openControllers)
+ ShellSettingsChip(action: openShellSettings)
+ }.padding(.top, 6).padding(.trailing, 16)
+ }
}
.onChange(of: focus.id) { _, id in
guard let id, id.hasPrefix("lib.tile.") || id.hasPrefix("lib.recent.") else { return }
diff --git a/frontend-ios/Sources/ShellUI/SideBar.swift b/frontend-ios/Sources/ShellUI/SideBar.swift
new file mode 100644
index 00000000..9f3d8f2b
--- /dev/null
+++ b/frontend-ios/Sources/ShellUI/SideBar.swift
@@ -0,0 +1,88 @@
+import SwiftUI
+
+/// iPhone Duo (#622) keeps a column on one side of the screen for the status bar and the system's vertical bars: the Dynamic
+/// Island and the status bar at the top, then the app's toolbar and tab bar. The column lies outside the safe area, so the library
+/// leaves it empty. Apple's design guide counts the app's own controls among the controls on the side, and
+/// `toolbarVerticalEdge` (iOS 27.1) is there to place custom bars beside the system's. So where the system uses that column,
+/// the Controllers and Settings chips go into it, at its bottom end, away from the status bar at the top.
+/// Nothing here knows the device: only the edge the system names, the safe area and the occluded areas decide.
+public struct SideBar: Equatable, Sendable {
+ /// The edge of the system's vertical bar, nil where the system never places one (every other iPhone and iPad).
+ public var edge: HorizontalEdge?
+ /// Areas a camera or the Dynamic Island covers, in the screen's coordinates (`reservedRegions(kind: .occlusion)`).
+ public var occlusions: [CGRect]
+
+ public init(edge: HorizontalEdge?, occlusions: [CGRect] = []) {
+ self.edge = edge
+ self.occlusions = occlusions
+ }
+
+ /// A chip in the column: this wide, and the Controllers chip a little taller for its count under the symbol.
+ public static let chipWidth: CGFloat = 52
+ public static let heights: [CGFloat] = [56, 44]
+ public static let gap: CGFloat = 10
+ public static let margin: CGFloat = 12
+
+ /// The column's frame in the screen's coordinates for chips of `heights`, or nil to keep them in the header: no vertical
+ /// bar, a column too narrow for a chip, or no room below the status bar's half of the column. The chips sit at the bottom of
+ /// the column above the home indicator, and move up past any occluded area they would touch.
+ public func column(screen: CGSize, insets: EdgeInsets, heights: [CGFloat] = SideBar.heights) -> CGRect? {
+ guard let edge, !heights.isEmpty else { return nil }
+ let side = edge == .trailing ? insets.trailing : insets.leading
+ guard side >= Self.chipWidth else { return nil }
+ let height = heights.reduce(0, +) + Self.gap * CGFloat(heights.count - 1)
+ let x = (edge == .trailing ? screen.width - side : 0) + (side - Self.chipWidth) / 2
+ var frame = CGRect(x: x, y: screen.height - insets.bottom - Self.margin - height, width: Self.chipWidth, height: height)
+ for _ in 0...occlusions.count {
+ guard let top = occlusions.filter({ $0.intersects(frame) }).map(\.minY).min() else { break }
+ frame.origin.y = top - Self.margin - height
+ }
+ if occlusions.contains(where: { $0.intersects(frame) }) { return nil }
+ // The top half belongs to the Dynamic Island and the status bar, which no API reports as an area to avoid.
+ return frame.minY >= screen.height / 2 ? frame : nil
+ }
+}
+
+extension EnvironmentValues {
+ /// The side column as the shell sees it. Nil reads it from the system (iOS 27.1). The captures set it to simulate iPhone Duo.
+ @Entry public var shellSideBar: SideBar? = nil
+}
+
+/// Reads the system's vertical-bar edge and the occluded areas, in the coordinates of the view it is the background of.
+struct SideBarProbe: View {
+ let report: (SideBar) -> Void
+ var body: some View {
+ #if canImport(SwiftUI, _version: 8.1)
+ if #available(iOS 27.1, macOS 27.1, *) { SideBarReader(report: report) } else { Color.clear }
+ #else
+ Color.clear
+ #endif
+ }
+}
+
+#if canImport(SwiftUI, _version: 8.1)
+@available(iOS 27.1, macOS 27.1, *)
+private struct SideBarReader: View {
+ let report: (SideBar) -> Void
+ @Environment(\.toolbarVerticalEdge) private var edge
+ var body: some View {
+ GeometryReader { proxy in
+ let bar = SideBar(edge: edge, occlusions: proxy.reservedRegions(kind: .occlusion).map(\.frame))
+ Color.clear.onChange(of: bar, initial: true) { _, new in report(new) }
+ }
+ }
+}
+#endif
+
+/// The Controllers and Settings chips stacked in the side column.
+struct SideBarChips: View {
+ let controllers: Int
+ let openControllers: () -> Void
+ let openShellSettings: () -> Void
+ var body: some View {
+ VStack(spacing: SideBar.gap) {
+ ControllerChip(count: controllers, vertical: true, action: openControllers)
+ ShellSettingsChip(vertical: true, action: openShellSettings)
+ }
+ }
+}
diff --git a/frontend-ios/Tests/ShellHostTests/SideBarCaptureTests.swift b/frontend-ios/Tests/ShellHostTests/SideBarCaptureTests.swift
new file mode 100644
index 00000000..552b2eff
--- /dev/null
+++ b/frontend-ios/Tests/ShellHostTests/SideBarCaptureTests.swift
@@ -0,0 +1,79 @@
+#if os(macOS)
+import AppKit
+import SwiftUI
+import XCTest
+@testable import ShellUI
+@testable import ShellHost
+
+/// Visual QA of the library on iPhone Duo's outer display (#622), rendered on the Mac from the fixture games. The Mac has no Duo, so
+/// the screen is simulated: the outer display's size (466 x 678 points, from the Simulator's device profile) and a column of safe
+/// area on the trailing side where the status bar sits. The column's width is measured from the reporter's screenshots, so it is an
+/// estimate. The status bar's place in it is drawn as a light strip with a time. Set NX_SHELL_CAPTURE_DIR to write the PNGs, NX_SHELL_CAPTURE_LANG for the language.
+@MainActor
+final class SideBarCaptureTests: XCTestCase {
+ private var lang: String { ProcessInfo.processInfo.environment["NX_SHELL_CAPTURE_LANG"] ?? "en" }
+
+ override func setUp() async throws {
+ guard ProcessInfo.processInfo.environment["NX_SHELL_CAPTURE_DIR"] != nil else { throw XCTSkip("Set NX_SHELL_CAPTURE_DIR to capture the shell") }
+ let code = lang == "zh" ? "zh-Hans" : lang
+ if let ui = ShellStrings.bundle.path(forResource: code, ofType: "lproj") { ShellStrings.captureBundle = Bundle(path: ui) }
+ if let host = HostStrings.bundle.path(forResource: code, ofType: "lproj") { HostStrings.captureBundle = Bundle(path: host) }
+ }
+ override func tearDown() async throws {
+ ShellStrings.captureBundle = nil
+ HostStrings.captureBundle = nil
+ }
+
+ /// The view inside a screen of `size` whose safe area leaves `insets` free, with the status bar's column drawn as a dim strip
+ /// along the trailing edge's top so the image shows where the system's time and Wi-Fi would be.
+ private func capture<V: View>(_ name: String, size: CGSize, insets: EdgeInsets, statusHeight: CGFloat, _ view: V) throws {
+ let dir = try XCTUnwrap(ProcessInfo.processInfo.environment["NX_SHELL_CAPTURE_DIR"])
+ NSApplication.shared.setActivationPolicy(.accessory)
+ let screen = ZStack(alignment: .topTrailing) {
+ // The system's vertical bar on the trailing edge, as `toolbarVerticalEdge` reports it on iPhone Duo.
+ view.safeAreaPadding(insets).environment(\.shellSideBar, SideBar(edge: .trailing))
+ Rectangle().fill(.white.opacity(0.18)).frame(width: insets.trailing, height: statusHeight)
+ .overlay { Text("9:41").font(.system(size: 13, weight: .semibold)).foregroundStyle(.white.opacity(0.7)) }
+ .allowsHitTesting(false)
+ }
+ let framed = screen.frame(width: size.width, height: size.height).background(ShellPalette.background).environment(\.colorScheme, .dark)
+ let host = NSHostingView(rootView: framed)
+ host.frame = NSRect(origin: .zero, size: size)
+ let window = NSWindow(contentRect: NSRect(origin: NSPoint(x: -100_000, y: -100_000), size: size),
+ styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = host
+ window.orderFront(nil)
+ defer { window.orderOut(nil); window.contentView = nil }
+ RunLoop.main.run(until: Date().addingTimeInterval(0.5))
+ host.layoutSubtreeIfNeeded()
+ let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: rep)
+ try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name)-\(lang).png"))
+ }
+
+ private func model(_ box: Sandbox) throws -> ShellHostModel {
+ try box.giveAppData(Fixtures.orbit)
+ let shell = ShellSettingsStore(defaults: UserDefaults(suiteName: "capture-duo-\(UUID().uuidString)")!)
+ let model = ShellHostModel(config: box.config(), shellSettings: shell)
+ model.reload()
+ return model
+ }
+
+ /// The outer display upright and on its side, the library and a game's settings open over it.
+ func testCaptureTheOuterDisplay() throws {
+ let box = try Sandbox()
+ let model = try model(box)
+ let upright = CGSize(width: 466, height: 678), sideways = CGSize(width: 678, height: 466)
+ let uprightInsets = EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 80)
+ let sidewaysInsets = EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 56)
+ try capture("duo-outer-upright", size: upright, insets: uprightInsets, statusHeight: 165,
+ LibraryView(games: model.details, initialSelection: Fixtures.orbit))
+ try capture("duo-outer-sideways", size: sideways, insets: sidewaysInsets, statusHeight: 80,
+ LibraryView(games: model.details, initialSelection: Fixtures.orbit))
+ try capture("duo-outer-sideways-settings", size: sideways, insets: sidewaysInsets, statusHeight: 80,
+ LibraryView(games: model.details, initialSelection: Fixtures.orbit, initialDetailOpen: true))
+ try capture("duo-outer-empty", size: upright, insets: uprightInsets, statusHeight: 165, LibraryView(games: []))
+ }
+}
+#endif
diff --git a/frontend-ios/Tests/ShellUITests/SideBarTests.swift b/frontend-ios/Tests/ShellUITests/SideBarTests.swift
new file mode 100644
index 00000000..f0399be6
--- /dev/null
+++ b/frontend-ios/Tests/ShellUITests/SideBarTests.swift
@@ -0,0 +1,95 @@
+import SwiftUI
+import XCTest
+@testable import ShellUI
+
+/// The side column of iPhone Duo (#622): where the Controllers and Settings chips may go, and where they may not.
+final class SideBarTests: XCTestCase {
+ /// iPhone Duo's outer display upright, 466 x 678 points, with the status bar's column on the trailing side.
+ private let outer = CGSize(width: 466, height: 678)
+ private let outerInsets = EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: 80)
+
+ func testNoVerticalBarKeepsTheChipsInTheHeader() {
+ XCTAssertNil(SideBar(edge: nil).column(screen: outer, insets: outerInsets))
+ // Every other iPhone in landscape has side insets too, but the system names no vertical bar there.
+ XCTAssertNil(SideBar(edge: nil).column(screen: CGSize(width: 956, height: 440), insets: EdgeInsets(top: 0, leading: 62, bottom: 20, trailing: 62)))
+ }
+
+ func testTheChipsSitAtTheBottomOfTheTrailingColumn() throws {
+ let column = try XCTUnwrap(SideBar(edge: .trailing).column(screen: outer, insets: outerInsets))
+ XCTAssertGreaterThanOrEqual(column.minX, outer.width - outerInsets.trailing)
+ XCTAssertLessThanOrEqual(column.maxX, outer.width)
+ XCTAssertEqual(column.midX, outer.width - outerInsets.trailing / 2, accuracy: 0.5)
+ XCTAssertEqual(column.maxY, outer.height - outerInsets.bottom - SideBar.margin, accuracy: 0.5)
+ XCTAssertEqual(column.height, SideBar.heights.reduce(0, +) + SideBar.gap, accuracy: 0.5)
+ }
+
+ func testTheLeadingColumnMirrorsIt() throws {
+ let insets = EdgeInsets(top: 0, leading: 80, bottom: 20, trailing: 0)
+ let column = try XCTUnwrap(SideBar(edge: .leading).column(screen: outer, insets: insets))
+ XCTAssertGreaterThanOrEqual(column.minX, 0)
+ XCTAssertLessThanOrEqual(column.maxX, insets.leading)
+ }
+
+ func testAColumnNarrowerThanAChipKeepsThemInTheHeader() {
+ let insets = EdgeInsets(top: 0, leading: 0, bottom: 20, trailing: SideBar.chipWidth - 1)
+ XCTAssertNil(SideBar(edge: .trailing).column(screen: outer, insets: insets))
+ // The edge names a side whose inset is empty: nothing to put the chips in.
+ XCTAssertNil(SideBar(edge: .leading).column(screen: outer, insets: outerInsets))
+ }
+
+ func testTheChipsMoveUpPastACamera() throws {
+ let camera = CGRect(x: outer.width - 70, y: outer.height - 90, width: 60, height: 60)
+ let column = try XCTUnwrap(SideBar(edge: .trailing, occlusions: [camera]).column(screen: outer, insets: outerInsets))
+ XCTAssertFalse(column.intersects(camera))
+ XCTAssertLessThanOrEqual(column.maxY, camera.minY)
+ }
+
+ func testNoRoomBelowTheStatusBarKeepsThemInTheHeader() {
+ // An occluded area over the whole lower half of the column.
+ let cover = CGRect(x: outer.width - 80, y: outer.height * 0.45, width: 80, height: outer.height * 0.55)
+ XCTAssertNil(SideBar(edge: .trailing, occlusions: [cover]).column(screen: outer, insets: outerInsets))
+ // A screen so short that the chips would reach into the status bar's half.
+ XCTAssertNil(SideBar(edge: .trailing).column(screen: CGSize(width: 466, height: 200), insets: outerInsets))
+ }
+
+ /// Seeded random screens, insets and occluded areas: a column, where there is one, lies in the side inset on the screen, in the
+ /// bottom half, clear of every occluded area and of the safe area the library uses.
+ func testRandomScreensNeverPutTheChipsOnContentOrACamera() {
+ var rng = SplitMix(seed: 622)
+ var placed = 0
+ for _ in 0..<5000 {
+ let size = CGSize(width: rng.next(in: 200...1400), height: rng.next(in: 200...1400))
+ let insets = EdgeInsets(top: rng.next(in: 0...70), leading: rng.next(in: 0...100), bottom: rng.next(in: 0...40), trailing: rng.next(in: 0...100))
+ let edge: HorizontalEdge? = [nil, .leading, .trailing][Int(rng.next(in: 0...2.99))]
+ let occlusions = (0..<Int(rng.next(in: 0...3.99))).map { _ in
+ CGRect(x: rng.next(in: -50...size.width), y: rng.next(in: -50...size.height), width: rng.next(in: 1...120), height: rng.next(in: 1...200))
+ }
+ guard let column = SideBar(edge: edge, occlusions: occlusions).column(screen: size, insets: insets) else { continue }
+ placed += 1
+ let safe = CGRect(x: insets.leading, y: insets.top, width: size.width - insets.leading - insets.trailing,
+ height: size.height - insets.top - insets.bottom)
+ XCTAssertFalse(column.intersects(safe), "on the library's content: \(column) \(safe)")
+ XCTAssertTrue(CGRect(origin: .zero, size: size).contains(column), "off the screen: \(column) \(size)")
+ XCTAssertGreaterThanOrEqual(column.minY, size.height / 2, "in the status bar's half: \(column) \(size)")
+ XCTAssertLessThanOrEqual(column.maxY, size.height - insets.bottom, "on the home indicator: \(column)")
+ for area in occlusions { XCTAssertFalse(column.intersects(area), "on an occluded area: \(column) \(area)") }
+ }
+ XCTAssertGreaterThan(placed, 500, "the random cases should reach the column often")
+ }
+}
+
+/// A small seeded generator, so a failure repeats.
+private struct SplitMix {
+ var state: UInt64
+ init(seed: UInt64) { state = seed }
+ mutating func next() -> UInt64 {
+ state &+= 0x9E37_79B9_7F4A_7C15
+ var z = state
+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+ return z ^ (z >> 31)
+ }
+ mutating func next(in range: ClosedRange<CGFloat>) -> CGFloat {
+ range.lowerBound + CGFloat(Double(next() >> 11) / Double(1 << 53)) * (range.upperBound - range.lowerBound)
+ }
+}