Files
buzz/mobile/ios/Runner/NativeAttachmentPopoverCoordinator.swift
klopez4212 d647c9fd98 Refine iOS composer and transcribe recordings into drafts (#9574)
Refine the iOS composer with 40-point glass controls, native attachment
menus, persistent emoji access, and selected-text formatting. The mic
now transcribes recordings on device into an editable, unsent draft;
Dictation has no five-minute recording cap or timer label, and its
waveform fills the space between the controls. Voice note remains
available in attachments with its five-minute cap. Unsupported devices
fail before recording, and audio is retained until the draft is durably
saved. Stopped dictation remains recoverable across editor teardown;
failed retention and cleanup can be retried. Recovered transcripts are
inserted only once across navigation or restart, preserving live exact
mention bindings.

Preserve selection handles over glass with animated avatars. Reduce the
conversation fade to 100 points above the keyboard and transition
continuously to 180 as the keyboard closes, without a first-frame jump
when opening; Home is unchanged.

Validation: 5,117 mobile tests and 27 crypto tests pass; analysis
passes. Prior native suite on iPhone 16/iOS 26.5: 119 pass, one
pre-existing expected failure, zero unexpected failures. Physical Air
preview approved; simulator selection/dragging and attachment flows
exercised. Fixed the native navigation test's timing race and a
community-cache cleanup test that checked a parent directory before its
asynchronous removal completed. Repository-wide `just ci` previously
stopped in unchanged `buzz-test-client` load-generator tests; new-head
hosted checks are pending.

Snapshots: production composer in an iPhone Air simulator fixture with
fictional conversation text; Photos snapshot retained from the
attachment preview.

| Composer | Attachments | Photos |
| --- | --- | --- |
| ![Keyboard-up
composer](https://github.com/user-attachments/assets/b7c8f0a4-25f8-4ca2-b8ae-11e18655e64a)
| ![Native attachment
menu](https://github.com/user-attachments/assets/5eaf5259-8e04-4da7-93f5-1b2eccab3c3c)
|
![Photos](https://github.com/user-attachments/assets/a6216b7d-5eaf-482c-b587-6052825b88fc)
|

---------

Signed-off-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
Signed-off-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Princess Donut <b238ea756dee4d98afa5883fc7f1de61eeabe65bf700e3a5a5a80db5e42e2c2b@buzz.block.builderlab.xyz>
2026-11-20 16:35:20 +00:00

458 lines
13 KiB
Swift

import CoreText
import Flutter
import UIKit
enum NativeAttachmentExpandedSurfaceBehavior {
@MainActor
static func dismissKeyboard(in window: UIWindow?) {
window?.endEditing(true)
}
static func keyboardOverlap(
containerBounds: CGRect,
keyboardLayoutFrame: CGRect
) -> CGFloat {
guard
!keyboardLayoutFrame.isNull,
!keyboardLayoutFrame.isInfinite,
keyboardLayoutFrame.minY < containerBounds.maxY
else {
return 0
}
return max(0, containerBounds.maxY - keyboardLayoutFrame.minY)
}
}
enum NativeAttachmentPopoverAnchorLayout {
static let expandedVerticalOffset: CGFloat = 40
static func sourceRect(
anchorBounds: CGRect,
keyboardDismissalOffset: CGFloat,
isExpanded: Bool
) -> CGRect {
anchorBounds.offsetBy(
dx: 0,
dy: keyboardDismissalOffset
+ (isExpanded ? expandedVerticalOffset : 0)
)
}
}
enum NativeAttachmentPopoverPresentationLayout {
@MainActor
static func transitionSource(in host: UIView, sourceRect: CGRect) -> UIView? {
var candidate = host.hitTest(
CGPoint(x: sourceRect.midX, y: sourceRect.midY), with: nil
)
while let view = candidate, view !== host {
if view is UIButton { return view }
candidate = view.superview
}
return nil
}
static func keyboardDismissalOffset(
sourceRect: CGRect,
containerBounds: CGRect,
safeAreaInsets: UIEdgeInsets,
keyboardLayoutFrame: CGRect,
menuHeight: CGFloat
) -> CGFloat {
let keyboardOverlap =
NativeAttachmentExpandedSurfaceBehavior.keyboardOverlap(
containerBounds: containerBounds,
keyboardLayoutFrame: keyboardLayoutFrame
)
guard keyboardOverlap > 0 else { return 0 }
let availableHeight =
sourceRect.minY - (containerBounds.minY + safeAreaInsets.top)
return availableHeight >= menuHeight ? 0 : keyboardOverlap
}
static func sourceRect(
_ sourceRect: CGRect,
keyboardDismissalOffset: CGFloat
) -> CGRect {
sourceRect.offsetBy(dx: 0, dy: keyboardDismissalOffset)
}
}
final class NativeAttachmentPopoverCoordinator: NSObject {
private let channel: FlutterMethodChannel
private weak var parentViewController: UIViewController?
private weak var presentedController: UIViewController?
private weak var sourceAnchorView: UIView?
init(
messenger: FlutterBinaryMessenger,
parentViewController: UIViewController?
) {
channel = FlutterMethodChannel(
name: "buzz/native_attachment_popover",
binaryMessenger: messenger
)
self.parentViewController = parentViewController
super.init()
channel.setMethodCallHandler { [weak self] call, result in
self?.handle(call, result: result)
}
}
private func handle(
_ call: FlutterMethodCall,
result: @escaping FlutterResult
) {
switch call.method {
case "isSupported":
if #available(iOS 26.0, *) {
result(true)
} else {
result(false)
}
case "present":
guard
let arguments = call.arguments as? [String: Any],
let x = arguments["x"] as? NSNumber,
let y = arguments["y"] as? NSNumber,
let width = arguments["width"] as? NSNumber,
let height = arguments["height"] as? NSNumber
else {
result(
FlutterError(
code: "invalid_arguments",
message: "Expected the attachment trigger bounds.",
details: nil
)
)
return
}
let sourceRect = CGRect(
x: CGFloat(truncating: x),
y: CGFloat(truncating: y),
width: CGFloat(truncating: width),
height: CGFloat(truncating: height)
)
DispatchQueue.main.async { [weak self] in
result(
self?.presentPopover(
sourceRect: sourceRect
) ?? false
)
}
case "dismiss":
DispatchQueue.main.async { [weak self] in
if #available(iOS 26.0, *),
let controller =
self?.presentedController
as? NativeAttachmentPopoverViewController
{
controller.dismissAndNotify()
} else {
self?.presentedController?.dismiss(animated: true)
}
result(nil)
}
default:
result(FlutterMethodNotImplemented)
}
}
@MainActor
private func presentPopover(sourceRect: CGRect) -> Bool {
guard #available(iOS 26.0, *) else { return false }
guard presentedController == nil else { return true }
let rootViewController =
parentViewController ?? activeWindowRootViewController()
guard let presenter = topViewController(from: rootViewController) else {
return false
}
let sourceView = presenter.view
var convertedRect: CGRect
if let window = sourceView?.window {
convertedRect = sourceView?.convert(sourceRect, from: window) ?? sourceRect
} else {
convertedRect = sourceRect
}
// Zoom from the actual glass control, rather than an invisible rectangle.
// Keep a separate anchor for popover positioning as expanded panels move.
let transitionSource = sourceView.flatMap { host in
NativeAttachmentPopoverPresentationLayout.transitionSource(
in: host, sourceRect: convertedRect
)
}
if let sourceView {
let keyboardDismissalOffset =
NativeAttachmentPopoverPresentationLayout.keyboardDismissalOffset(
sourceRect: convertedRect,
containerBounds: sourceView.bounds,
safeAreaInsets: sourceView.safeAreaInsets,
keyboardLayoutFrame: sourceView.keyboardLayoutGuide.layoutFrame,
menuHeight: NativeAttachmentMenuLayout.size(
compatibleWith: sourceView.traitCollection
).height
)
if keyboardDismissalOffset > 0 {
NativeAttachmentExpandedSurfaceBehavior.dismissKeyboard(
in: sourceView.window
)
convertedRect =
NativeAttachmentPopoverPresentationLayout.sourceRect(
convertedRect,
keyboardDismissalOffset: keyboardDismissalOffset
)
}
}
let anchorView = makeSourceAnchor(frame: convertedRect)
sourceView?.addSubview(anchorView)
sourceAnchorView = anchorView
let availableWidth = max(
320,
min(
(sourceView?.bounds.width ?? UIScreen.main.bounds.width) - 40,
430
)
)
let controller = NativeAttachmentPopoverViewController(
channel: channel,
expandedWidth: availableWidth
)
controller.modalPresentationStyle = .popover
controller.preferredTransition = .zoom { [weak transitionSource, weak anchorView] _ in
transitionSource ?? anchorView
}
controller.onDismiss = { [weak self] in
self?.presentedController = nil
self?.sourceAnchorView?.removeFromSuperview()
self?.channel.invokeMethod("dismissed", arguments: nil)
}
guard let popover = controller.popoverPresentationController else {
anchorView.removeFromSuperview()
return false
}
popover.sourceView = anchorView
popover.sourceRect = anchorView.bounds
popover.permittedArrowDirections = [.down]
// iOS 27 adds a 28-point system inset to these margins. Compensate
// for it so the expanded content meets the 20-point message rail.
let horizontalMargin: CGFloat
if #available(iOS 27.0, *) {
horizontalMargin = -8
} else {
horizontalMargin = 20
}
popover.popoverLayoutMargins.left = horizontalMargin
popover.popoverLayoutMargins.right = horizontalMargin
popover.backgroundColor = .clear
popover.delegate = controller
presentedController = controller
presenter.present(controller, animated: true)
return true
}
@MainActor
private func makeSourceAnchor(frame: CGRect) -> UIView {
let anchor = UIView(frame: frame)
anchor.isUserInteractionEnabled = false
anchor.accessibilityElementsHidden = true
anchor.backgroundColor = .clear
anchor.layer.cornerRadius = min(frame.width, frame.height) / 2
anchor.layer.cornerCurve = .continuous
return anchor
}
@MainActor
private func activeWindowRootViewController() -> UIViewController? {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { $0.activationState == .foregroundActive }
.flatMap(\.windows)
.first(where: \.isKeyWindow)?
.rootViewController
}
@MainActor
private func topViewController(
from viewController: UIViewController?
) -> UIViewController? {
if let presented = viewController?.presentedViewController {
return topViewController(from: presented)
}
if let navigation = viewController as? UINavigationController {
return topViewController(from: navigation.visibleViewController)
}
if let tab = viewController as? UITabBarController {
return topViewController(from: tab.selectedViewController)
}
return viewController
}
}
enum NativeAttachmentMenuLayout {
static let itemCount: CGFloat = 4
static let contentPadding: CGFloat = 16
static let minimumItemHeight: CGFloat = 52
static let itemSpacing: CGFloat = 8
static let itemVerticalPadding: CGFloat = 8
static let maximumHeight: CGFloat = 372
static let width: CGFloat = 216
static let labelTextStyle: UIFont.TextStyle = .title3
static func itemHeight(
compatibleWith traitCollection: UITraitCollection
) -> CGFloat {
let labelHeight = NativeAttachmentMenuTypography.font(
forTextStyle: labelTextStyle,
compatibleWith: traitCollection
).lineHeight
return max(
minimumItemHeight,
ceil(labelHeight + (itemVerticalPadding * 2))
)
}
static func itemsHeight(
compatibleWith traitCollection: UITraitCollection
) -> CGFloat {
(itemHeight(compatibleWith: traitCollection) * itemCount)
+ (itemSpacing * (itemCount - 1))
}
static func contentHeight(
compatibleWith traitCollection: UITraitCollection
) -> CGFloat {
(contentPadding * 2) + itemsHeight(compatibleWith: traitCollection)
}
static func size(
compatibleWith traitCollection: UITraitCollection,
maximumHeight: CGFloat = NativeAttachmentMenuLayout.maximumHeight
) -> CGSize {
CGSize(
width: width,
height: min(
contentHeight(compatibleWith: traitCollection),
maximumHeight
)
)
}
}
enum NativeAttachmentMenuTypography {
static let interPostScriptName = "InterVariable"
private static let registeredInter: Bool = {
let fontURL = Bundle.main.bundleURL
.appendingPathComponent("Frameworks")
.appendingPathComponent("App.framework")
.appendingPathComponent("flutter_assets")
.appendingPathComponent("assets")
.appendingPathComponent("fonts")
.appendingPathComponent("InterVariable.ttf")
guard FileManager.default.fileExists(atPath: fontURL.path) else {
return false
}
return CTFontManagerRegisterFontsForURL(
fontURL as CFURL,
.process,
nil
)
}()
static func font(
forTextStyle textStyle: UIFont.TextStyle,
compatibleWith traitCollection: UITraitCollection? = nil
) -> UIFont {
_ = registeredInter
let scaledPointSize = UIFontMetrics(forTextStyle: textStyle).scaledValue(
for: 20,
compatibleWith: traitCollection
)
let preferredFont = UIFont.preferredFont(
forTextStyle: textStyle,
compatibleWith: traitCollection
)
guard
let interFont = UIFont(
name: interPostScriptName,
size: scaledPointSize
)
else {
return preferredFont
}
return interFont
}
}
enum NativeAttachmentPopoverStyle {
static let cornerRadius: CGFloat = 20
static let shadowOpacity: Float = 0.18
static let shadowRadius: CGFloat = 12
static let shadowOffset = CGSize(width: 0, height: 6)
static let borderWidth: CGFloat = 1
}
func makeNativeAttachmentMenuButton(
title: String,
symbol: String,
action: @escaping () -> Void
) -> UIButton {
let button = UIButton(
primaryAction: UIAction { _ in
UISelectionFeedbackGenerator().selectionChanged()
action()
}
)
button.accessibilityLabel = title
let iconView = UIImageView(
image: NativeTabler.image(symbol, size: 18)
)
iconView.tintColor = .label
iconView.contentMode = .center
iconView.translatesAutoresizingMaskIntoConstraints = false
let titleLabel = UILabel()
titleLabel.text = title
titleLabel.textColor = .label
titleLabel.font = NativeAttachmentMenuTypography.font(
forTextStyle: NativeAttachmentMenuLayout.labelTextStyle
)
titleLabel.adjustsFontForContentSizeCategory = true
titleLabel.textAlignment = .left
titleLabel.translatesAutoresizingMaskIntoConstraints = false
button.addSubview(iconView)
button.addSubview(titleLabel)
NSLayoutConstraint.activate([
iconView.leadingAnchor.constraint(
equalTo: button.leadingAnchor,
constant: 8
),
iconView.centerYAnchor.constraint(equalTo: button.centerYAnchor),
iconView.widthAnchor.constraint(equalToConstant: 26),
titleLabel.leadingAnchor.constraint(
equalTo: iconView.trailingAnchor,
constant: 12
),
titleLabel.trailingAnchor.constraint(
equalTo: button.trailingAnchor,
constant: -8
),
titleLabel.centerYAnchor.constraint(equalTo: button.centerYAnchor),
])
button.configurationUpdateHandler = { button in
button.alpha = button.isHighlighted ? 0.62 : 1
}
return button
}