Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 44 additions & 11 deletions Modules/Sources/WordPressUI/Views/AlertView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ public struct AlertView<Header: View, Content: View, Actions: View>: View {
@ViewBuilder let content: () -> Content
@ViewBuilder var actions: () -> Actions

@State private var horizontalSafeArea: CGFloat = 0
/// Read before `body` caps the size at `xxLarge`.
@Environment(\.dynamicTypeSize) private var dynamicTypeSize

public init(
@ViewBuilder header: @escaping () -> Header,
@ViewBuilder content: @escaping () -> Content,
Expand All @@ -18,8 +22,12 @@ public struct AlertView<Header: View, Content: View, Actions: View>: View {

public var body: some View {
VStack(spacing: 0) {
content()
.frame(maxWidth: .infinity, maxHeight: .infinity)
// The content is an illustration. At accessibility text sizes, leave it out and give the text
// its room. The sheet then fits the text and buttons (see `alertView(hostedBy:)`).
if !dynamicTypeSize.isAccessibilitySize {
content()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
header()
.padding(.horizontal, 8)
.padding(.bottom, 32)
Expand All @@ -32,6 +40,15 @@ public struct AlertView<Header: View, Content: View, Actions: View>: View {
.dynamicTypeSize(...DynamicTypeSize.xLarge)
}
.padding(24)
// The sheet covers a side inset such as the strip on the iPhone Duo's outer screen, so keep only
// the part of the horizontal safe area that both sides share, and center the content in the sheet.
.padding(.horizontal, horizontalSafeArea)
.ignoresSafeArea(.container, edges: .horizontal)
.onGeometryChange(for: CGFloat.self) { proxy in
min(proxy.safeAreaInsets.leading, proxy.safeAreaInsets.trailing)
} action: {
horizontalSafeArea = $0
}
.dynamicTypeSize(...DynamicTypeSize.xxLarge)
}
}
Expand All @@ -47,6 +64,7 @@ extension AlertView {
extension UISheetPresentationController.Detent {
/// The height for a sheet that shows an ``AlertView``: half the screen, or taller when the
/// alert needs more room, such as on the iPhone Duo's outer screen or with a large text size.
/// At accessibility text sizes the alert has no illustration, so the sheet fits its text and buttons.
@MainActor
public static func alertView<Content: View>(
hostedBy hostVC: UIHostingController<Content>
Expand All @@ -57,7 +75,9 @@ extension UISheetPresentationController.Detent {
let medium = UISheetPresentationController.Detent.medium().resolvedValue(in: context) ?? halfHeight
guard let hostVC else { return medium }
// The sheet's width is only known once it has been laid out.
let width = hostVC.view.bounds.inset(by: hostVC.view.safeAreaInsets).width
// Match the content's width: the sheet keeps only the horizontal inset both sides share (see `body`).
let safeArea = hostVC.view.safeAreaInsets
let width = hostVC.view.bounds.width - 2 * min(safeArea.left, safeArea.right)
guard width > 0 else { return medium }
let sizeCategory = context.containerTraitCollection.preferredContentSizeCategory
let height = cache.height(width: width, sizeCategory: sizeCategory) {
Expand All @@ -66,7 +86,8 @@ extension UISheetPresentationController.Detent {
.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude))
.height
}
return min(max(medium, height), context.maximumDetentValue)
let minimum = sizeCategory.isAccessibilityCategory ? 0 : medium
return min(max(minimum, height), context.maximumDetentValue)
}
}
}
Expand Down Expand Up @@ -144,9 +165,15 @@ public struct AlertDismissButton: View {
dismiss()
onDismiss?()
} label: {
Text(AppLocalizedString("shared.button.ok", value: "OK", comment: "A shared button title used in different contexts"))
.font(.headline)
.frame(maxWidth: .infinity)
Text(
AppLocalizedString(
"shared.button.ok",
value: "OK",
comment: "A shared button title used in different contexts"
)
)
.font(.headline)
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle(radius: 8))
Expand All @@ -162,16 +189,22 @@ private final class PreviewAlertViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let button = UIButton(primaryAction: UIAction(title: "Show") { [weak self] _ in
self?.showAlertView()
})
let button = UIButton(
primaryAction: UIAction(title: "Show") { [weak self] _ in
self?.showAlertView()
}
)
view.addSubview(button)
button.pinCenter()
}

private func showAlertView() {
let alert = AlertView {
AlertHeaderView(title: "Post Saved", description: "Save this post, and come back to read it whenever you'd like. It will only be available on this device — saved posts don't sync to other devices.")
AlertHeaderView(
title: "Post Saved",
description:
"Save this post, and come back to read it whenever you'd like. It will only be available on this device — saved posts don't sync to other devices."
)
} content: {
ScaledImage("icon-bookmark", bundle: .module, height: 78)
.foregroundStyle(.secondary)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import Testing
import UIKit
@testable import WordPress

@MainActor
@Suite("AppFeedbackPromptView")
struct AppFeedbackPromptViewTests {
/// The width of the iPhone Duo's outer screen, and the strip on its right that holds the status bar and tab bar.
private static let width: CGFloat = 466
private static let sideStrip: CGFloat = 84

@Test("buttons stay inside the safe area when they don't fit beside a side inset")
func buttonsStayInsideTheSafeArea() throws {
// Leave less room than the buttons need side by side, but more than they need stacked.
let (window, prompt) = makePrompt(width: 360, trailingInset: Self.sideStrip)
defer { window.isHidden = true }

let (yes, no) = try buttons(in: prompt)
let safeFrame = prompt.bounds.inset(by: prompt.safeAreaInsets)
#expect(safeFrame.width < 360)
#expect(safeFrame.contains(yes.frame(in: prompt)))
#expect(safeFrame.contains(no.frame(in: prompt)))
#expect(no.frame(in: prompt).minY >= yes.frame(in: prompt).maxY, "the buttons should be stacked")
}

@Test("layout settles when the prompt is wider than its safe area")
func layoutSettles() throws {
let (window, prompt) = makePrompt(width: 360, trailingInset: Self.sideStrip)
defer { window.isHidden = true }

let (yes, no) = try buttons(in: prompt)
let frames = [yes.frame(in: prompt), no.frame(in: prompt)]

for _ in 0..<3 {
prompt.setNeedsLayout()
window.layoutIfNeeded()
}

#expect([yes.frame(in: prompt), no.frame(in: prompt)] == frames)
}

@Test("buttons stay side by side when they fit")
func buttonsSideBySideWhenTheyFit() throws {
let (window, prompt) = makePrompt(width: Self.width, trailingInset: 0)
defer { window.isHidden = true }

let (yes, no) = try buttons(in: prompt)
#expect(yes.frame(in: prompt).midY == no.frame(in: prompt).midY)
#expect(no.frame(in: prompt).minX > yes.frame(in: prompt).maxX)
}

// MARK: - Helpers

/// Pins the prompt to the full width of a window, like the Notifications table header, and sets it up as the
/// push-notification prompt.
private func makePrompt(width: CGFloat, trailingInset: CGFloat) -> (UIWindow, AppFeedbackPromptView) {
let window = UIWindow(frame: CGRect(x: 0, y: 0, width: width, height: 600))
let viewController = UIViewController()
viewController.additionalSafeAreaInsets.right = trailingInset
window.rootViewController = viewController
window.isHidden = false

let prompt = AppFeedbackPromptView()
viewController.view.addSubview(prompt)
NSLayoutConstraint.activate([
prompt.topAnchor.constraint(equalTo: viewController.view.topAnchor, constant: 100),
prompt.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor),
prompt.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor)
])
window.layoutIfNeeded()

prompt.setupHeading("We'll notify you when you get followers, comments, and likes.")
prompt.setupYesButton(title: "Allow notifications") { _ in }
prompt.setupNoButton(title: "Not now") { _ in }
window.layoutIfNeeded()

return (window, prompt)
}

private func buttons(in prompt: AppFeedbackPromptView) throws -> (yes: UIView, no: UIView) {
let yes = try #require(prompt.subview(withIdentifier: "yes-button"))
let no = try #require(prompt.subview(withIdentifier: "no-button"))
return (yes, no)
}
}

private extension UIView {
func frame(in view: UIView) -> CGRect {
convert(bounds, to: view)
}

func subview(withIdentifier identifier: String) -> UIView? {
if accessibilityIdentifier == identifier {
return self
}
return subviews.lazy.compactMap { $0.subview(withIdentifier: identifier) }.first
}
}
91 changes: 76 additions & 15 deletions WordPress/Classes/ViewRelated/Ratings/AppFeedbackPromptView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ class AppFeedbackPromptView: UIView {
private let leftButton = RoundedButton()
private let rightButton = RoundedButton()
private let buttonStack = UIStackView()
private var lastAvailableWidth: CGFloat?
/// Active while the buttons are stacked, so they span the same width as the text above them.
private var stackedWidthConstraints: [NSLayoutConstraint] = []

// MARK: - UIView's Methods

Expand Down Expand Up @@ -45,6 +48,9 @@ class AppFeedbackPromptView: UIView {
buttonStack.axis = .horizontal
buttonStack.spacing = LayoutConstants.buttonSpacing
buttonStack.isLayoutMarginsRelativeArrangement = true
// Margins taken from the safe area change as the row moves. Where the row overlaps a horizontal
// inset (the side strip on the iPhone Duo's outer screen), it never settles and layout loops.
buttonStack.insetsLayoutMarginsFromSafeArea = false
addSubview(buttonStack)

// Yes Button
Expand Down Expand Up @@ -74,6 +80,15 @@ class AppFeedbackPromptView: UIView {
}
}

override func layoutSubviews() {
let availableWidth = bounds.inset(by: safeAreaInsets).width
if availableWidth != lastAvailableWidth {
lastAvailableWidth = availableWidth
evaluateStackAxisMode()
}
super.layoutSubviews()
}

func setupHeading(_ title: String) {
label.text = title
}
Expand All @@ -92,42 +107,85 @@ class AppFeedbackPromptView: UIView {
evaluateStackAxisMode()
}

/// Evaluate the width of the buttons to determine if the stack view should go into vertical mode.
/// Stacks the buttons vertically when they don't fit side by side inside the safe area.
private func evaluateStackAxisMode() {
// measure the width of the view with the new font sizes to see if the buttons are too wide.
leftButton.updateFontSizeToMatchSystem()
rightButton.updateFontSizeToMatchSystem()
let newLayoutSize = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
// Several lines of large centered text are hard to read, so align it like body text.
label.textAlignment = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .natural : .center

// if the new width is too wide, change the axis of the stack view
guard let superviewSize = superview?.bounds.size else {
let availableWidth = bounds.inset(by: safeAreaInsets).width
guard availableWidth > 0 else {
return
}

if newLayoutSize.width > superviewSize.width {
buttonStack.axis = .vertical
// The yes button is at least as wide as the no button (see `setupConstraints`).
// Measure the titles on one line. A button that has already wrapped its title reports the wrapped width.
let unlimited = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let leftWidth = leftButton.sizeThatFits(unlimited).width
let rightWidth = rightButton.sizeThatFits(unlimited).width
let rowWidth = max(leftWidth, rightWidth) + LayoutConstants.buttonSpacing + rightWidth
let axis: NSLayoutConstraint.Axis =
rowWidth + 2 * LayoutConstants.basePadding > availableWidth ? .vertical : .horizontal

if buttonStack.axis != axis {
buttonStack.axis = axis
updateLayout(for: axis)
setNeedsLayout()
}
}

private func updateLayout(for axis: NSLayoutConstraint.Axis) {
let isStacked = axis == .vertical
for button in [leftButton, rightButton] {
button.verticalEdgeInset =
isStacked ? LayoutConstants.stackedButtonVerticalInset : LayoutConstants.buttonVerticalInset
}
if isStacked {
NSLayoutConstraint.activate(stackedWidthConstraints)
} else {
NSLayoutConstraint.deactivate(stackedWidthConstraints)
}
}

func setupConstraints() {
addConstraints([
let safeArea = safeAreaLayoutGuide
stackedWidthConstraints = [
buttonStack.leadingAnchor.constraint(equalTo: label.leadingAnchor),
buttonStack.trailingAnchor.constraint(equalTo: label.trailingAnchor)
]
NSLayoutConstraint.activate([
label.topAnchor.constraint(equalTo: topAnchor, constant: LayoutConstants.basePadding),
label.bottomAnchor.constraint(equalTo: buttonStack.topAnchor, constant: -LayoutConstants.basePadding),
label.heightAnchor.constraint(greaterThanOrEqualToConstant: LayoutConstants.labelMinimumHeight),
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: LayoutConstants.labelHorizontalPadding),
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -LayoutConstants.labelHorizontalPadding),
label.leadingAnchor.constraint(
equalTo: safeArea.leadingAnchor,
constant: LayoutConstants.labelHorizontalPadding
),
label.trailingAnchor.constraint(
equalTo: safeArea.trailingAnchor,
constant: -LayoutConstants.labelHorizontalPadding
),

// position the button stack view
bottomAnchor.constraint(greaterThanOrEqualTo: buttonStack.bottomAnchor, constant: LayoutConstants.basePadding),
buttonStack.centerXAnchor.constraint(equalTo: centerXAnchor),
bottomAnchor.constraint(
greaterThanOrEqualTo: buttonStack.bottomAnchor,
constant: LayoutConstants.basePadding
),
buttonStack.centerXAnchor.constraint(equalTo: safeArea.centerXAnchor),

// make sure the primary/yes button is always at least as big as the cancel/no button
leftButton.widthAnchor.constraint(greaterThanOrEqualTo: rightButton.widthAnchor),

// ensure the buttons have horizontal padding from the sides of the view
leftButton.leadingAnchor.constraint(greaterThanOrEqualTo: leadingAnchor, constant: LayoutConstants.basePadding),
trailingAnchor.constraint(greaterThanOrEqualTo: rightButton.trailingAnchor, constant: LayoutConstants.basePadding)
leftButton.leadingAnchor.constraint(
greaterThanOrEqualTo: safeArea.leadingAnchor,
constant: LayoutConstants.basePadding
),
safeArea.trailingAnchor.constraint(
greaterThanOrEqualTo: rightButton.trailingAnchor,
constant: LayoutConstants.basePadding
)
])
}

Expand All @@ -145,7 +203,10 @@ class AppFeedbackPromptView: UIView {
private struct LayoutConstants {
static let labelMinimumHeight: CGFloat = 18.0
static let basePadding: CGFloat = 15.0
static let labelHorizontalPadding: CGFloat = 37.0
// Lines the text up with the section titles in the list below.
static let labelHorizontalPadding: CGFloat = 20.0
static let buttonSpacing: CGFloat = 10.0
static let buttonVerticalInset: CGFloat = 5.0
static let stackedButtonVerticalInset: CGFloat = 12.0
}
}
14 changes: 12 additions & 2 deletions WordPress/Classes/ViewRelated/Views/RoundedButton.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,12 @@ class RoundedButton: UIButton {

fileprivate func updateAppearance() {
var configuration = self.configuration ?? UIButton.Configuration.plain()
configuration.contentInsets = NSDirectionalEdgeInsets(top: verticalEdgeInset, leading: horizontalEdgeInset, bottom: verticalEdgeInset, trailing: horizontalEdgeInset)
configuration.contentInsets = NSDirectionalEdgeInsets(
top: verticalEdgeInset,
leading: horizontalEdgeInset,
bottom: verticalEdgeInset,
trailing: horizontalEdgeInset
)
configuration.baseForegroundColor = tintColor
configuration.background.backgroundColor = .clear
self.configuration = configuration
Expand All @@ -105,7 +110,8 @@ class RoundedButton: UIButton {
configuration?.background.backgroundColor = button.tintColor
} else {
configuration?.baseForegroundColor = button.tintColor.withAlphaComponent(0.5)
configuration?.background.backgroundColor = button.selectedBackgroundColor ?? button.backgroundColor ?? .clear
configuration?.background.backgroundColor =
button.selectedBackgroundColor ?? button.backgroundColor ?? .clear
}
} else {
configuration?.baseForegroundColor = button.tintColor
Expand All @@ -128,6 +134,10 @@ class RoundedButton: UIButton {
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { attributes in
var attributes = attributes
attributes.font = WPStyleGuide.fontForTextStyle(.subheadline)
// Center a title that wraps at large text sizes. `titleAlignment` doesn't apply to wrapped lines.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
attributes.paragraphStyle = paragraphStyle
return attributes
}
self.configuration = configuration
Expand Down