Files
buzz/mobile/ios/Runner/NativeEmojiPickerView.swift
Tom Brow ff652ed06c perf(mobile): cache and animate custom emoji in the iOS picker (#9479)
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.

Now each custom emoji downloads once per install and plays its
animation:

- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.

### Why it refetched

The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.

### Validation

Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):

| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |

Before (main): every reopen downloads again, and animated emoji are
still.


https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965

After (this PR): reopening shows cached emoji immediately, and animated
emoji play.


https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389

Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (359fdc8) with a warm cache: 0 downloads across open,
re-entering the channel and relaunch, all emoji rendered. The run used
the simulator only; device and hosted-relay behavior were not exercised.

Added tests:

- `media_disk_cache_test.dart`: encoded bytes for a native surface
download once, survive a relaunch, and bytes that never decode are not
saved.
- `emoji_picker_test.dart`: the native sheet's `mediaBytes` call returns
authorized bytes, a second call makes no request, and a cancelled call
fails.
- `emoji_picker_test.dart`: at most four loads run at once, a queued
load cancelled before it starts never downloads, and a saved emoji
doesn't wait for a slot.
- `media_disk_cache_test.dart`: a damaged saved copy (including a
truncated PNG) is evicted and downloaded again.
- `media_image_test.dart`: encoded-bytes requests share one download
with simultaneous image loads, and only decoded bytes reach observers.

- `NativeMessageImageLoaderTests.swift`: a GIF with uneven delays keeps
each frame's share, a cancelled decode returns nothing, and the decode
gate admits four in order and drops a cancelled waiter.

Removed `NativeEmojiRedirectPolicyTests` and the native concurrency test
along with the Swift loader they covered.

### Regressions

- Network: fewer requests. Cold loads keep the old picker's
four-at-a-time limit, so on a slow HTTP/1.1 origin queued requests don't
time out waiting for a connection. Downloads use the shared media HTTP
client, the same one other app images use, which on iOS now runs over
HTTP/2 since [#8897 iOS
HTTP/2](https://github.com/block/buzz/pull/8897).
- Memory: the picker keeps no image cache of its own. Each view decodes,
downsampled to 84 px and at most four at a time, from bytes Flutter
already holds in memory or on disk.
- Disk: emoji go into the existing 250 MB LRU media cache.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
2026-11-17 09:04:38 -08:00

551 lines
17 KiB
Swift

import ImageIO
import SwiftUI
import UIKit
struct NativeEmojiPickerView: View {
let data: NativeEmojiPickerData
let appearance: NativeEmojiPickerAppearance
let largeEmoji: Bool
let onSelect: (String) -> Void
let onSkinToneChanged: (Int) -> Void
let onClose: () -> Void
@State private var query = ""
@State private var categorySelection: NativeEmojiCategorySelection
@State private var selectedSkinTone: Int
private var columns: [GridItem] {
Array(
repeating: GridItem(.flexible(minimum: 36), spacing: 0),
count: largeEmoji ? 5 : 8
)
}
private let sectionListSpace = "buzz.emoji.sectionList"
init(
data: NativeEmojiPickerData,
appearance: NativeEmojiPickerAppearance,
largeEmoji: Bool = false,
initialSkinTone: Int,
onSelect: @escaping (String) -> Void,
onSkinToneChanged: @escaping (Int) -> Void,
onClose: @escaping () -> Void
) {
self.data = data
self.appearance = appearance
self.largeEmoji = largeEmoji
self.onSelect = onSelect
self.onSkinToneChanged = onSkinToneChanged
self.onClose = onClose
_categorySelection = State(
initialValue: NativeEmojiCategorySelection(
initialSectionID: data.sections.first?.id
)
)
_selectedSkinTone = State(
initialValue: validNativeEmojiSkinTone(initialSkinTone)
)
}
var body: some View {
ScrollViewReader { proxy in
VStack(spacing: 0) {
header
if query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
categoryRail(proxy)
}
Divider().overlay(Color(uiColor: appearance.divider))
pickerContent
}
.background(Color(uiColor: appearance.surface))
}
}
private var header: some View {
HStack(spacing: 8) {
HStack(spacing: 10) {
TablerNativeIcon(symbol: "magnifyingglass")
.font(.system(size: 17, weight: .medium))
.foregroundStyle(Color(uiColor: appearance.secondaryText))
TextField("Search emoji", text: $query)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
.submitLabel(.search)
.foregroundStyle(Color(uiColor: appearance.text))
if !query.isEmpty {
Button {
query = ""
} label: {
TablerNativeIcon(symbol: "xmark.circle.fill")
.foregroundStyle(Color(uiColor: appearance.secondaryText))
}
.buttonStyle(.plain)
.accessibilityLabel("Clear search")
}
}
.padding(.horizontal, 14)
.frame(height: 44)
.background(Color(uiColor: appearance.control), in: Capsule())
.overlay {
Capsule()
.stroke(Color(uiColor: appearance.divider), lineWidth: 1)
}
Button(action: onClose) {
TablerNativeIcon(symbol: "xmark")
.font(.system(size: 17, weight: .semibold))
.foregroundStyle(Color(uiColor: appearance.text))
.frame(width: 44, height: 44)
.background(Color(uiColor: appearance.control), in: Circle())
}
.buttonStyle(.plain)
.accessibilityLabel("Close sheet")
}
.padding(.horizontal, 16)
.padding(.top, 16)
.padding(.bottom, 8)
}
private func categoryRail(_ proxy: ScrollViewProxy) -> some View {
HStack(spacing: 0) {
ForEach(data.sections) { section in
NativeEmojiCategoryButton(
section: section,
appearance: appearance,
selection: categorySelection
) {
categorySelection.select(section.id)
// Category navigation is a frequent shortcut. Keeping it immediate
// means an in-progress proxy animation can never fight a finger drag.
proxy.scrollTo("section-\(section.id)", anchor: .top)
}
.frame(maxWidth: .infinity)
}
Divider()
.frame(height: 24)
.overlay(Color(uiColor: appearance.divider))
skinToneSelector
.frame(maxWidth: .infinity)
}
.padding(.horizontal, 16)
.frame(height: 44)
}
private var skinToneSelector: some View {
Menu {
ForEach(nativeEmojiSkinTones) { tone in
Button {
selectedSkinTone = tone.id
onSkinToneChanged(tone.id)
} label: {
Label {
Text(tone.label)
} icon: {
Image(uiImage: skinTonePreviewImage(tone))
.renderingMode(.original)
}
}
}
} label: {
skinToneDot(nativeEmojiSkinTones[selectedSkinTone])
.frame(maxWidth: .infinity)
.frame(height: 36)
}
.buttonStyle(.plain)
.accessibilityLabel("Skin tone")
}
private func skinToneDot(_ tone: NativeEmojiSkinTone) -> some View {
Circle()
.fill(Color(uiColor: tone.color))
.frame(width: 16, height: 16)
.overlay {
Circle()
.fill(
LinearGradient(
colors: [.white.opacity(0.2), .clear],
startPoint: .top,
endPoint: .bottom
)
)
.blendMode(.overlay)
}
.overlay {
Circle().stroke(.black.opacity(0.8), lineWidth: 1)
}
}
private func skinTonePreviewImage(_ tone: NativeEmojiSkinTone) -> UIImage {
let size = CGSize(width: 16, height: 16)
return UIGraphicsImageRenderer(size: size).image { rendererContext in
let context = rendererContext.cgContext
let rect = CGRect(origin: .zero, size: size).insetBy(dx: 0.5, dy: 0.5)
let circle = UIBezierPath(ovalIn: rect)
tone.color.setFill()
circle.fill()
if let gradient = CGGradient(
colorsSpace: CGColorSpaceCreateDeviceRGB(),
colors: [
UIColor.white.withAlphaComponent(0.2).cgColor,
UIColor.clear.cgColor,
] as CFArray,
locations: [0, 1]
) {
context.saveGState()
circle.addClip()
context.setBlendMode(.overlay)
context.drawLinearGradient(
gradient,
start: CGPoint(x: size.width / 2, y: 0),
end: CGPoint(x: size.width / 2, y: size.height),
options: []
)
context.restoreGState()
}
UIColor.black.withAlphaComponent(0.8).setStroke()
circle.lineWidth = 1
circle.stroke()
}
}
@ViewBuilder
private var pickerContent: some View {
let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmedQuery.isEmpty {
sectionList(data.sections, tracksSelection: true)
} else {
let custom = NativeEmojiSearch.results(
query: trimmedQuery,
items: data.customItems
)
let standard = NativeEmojiSearch.results(
query: trimmedQuery,
items: data.standardItems
)
let sections = [
NativeEmojiSection(
id: "search-custom",
title: "Custom",
systemImage: "sparkles",
items: custom
),
NativeEmojiSection(
id: "search-standard",
title: "Emoji",
systemImage: "face.smiling",
items: standard
),
].filter { !$0.items.isEmpty }
if sections.isEmpty {
VStack(spacing: 10) {
TablerNativeIcon(symbol: "magnifyingglass")
.font(.system(size: 28))
Text("No emoji found").font(.body)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.foregroundStyle(Color(uiColor: appearance.secondaryText))
} else {
sectionList(sections, tracksSelection: false)
}
}
}
private func sectionList(
_ sections: [NativeEmojiSection],
tracksSelection: Bool
) -> some View {
ScrollView {
LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
ForEach(sections) { section in
Section {
LazyVGrid(columns: columns, spacing: 0) {
ForEach(section.items) { item in
emojiButton(item)
}
}
.padding(.horizontal, 16)
} header: {
HStack {
Text(section.title)
.font(.footnote.weight(.semibold))
.foregroundStyle(Color(uiColor: appearance.secondaryText))
Spacer()
}
.padding(.horizontal, 16)
.frame(height: 30)
.background(Color(uiColor: appearance.surface))
.background(sectionOffsetReporter(id: section.id))
.id("section-\(section.id)")
}
}
}
.padding(.bottom, 8)
.background(contentBoundaryReporter())
}
.coordinateSpace(name: sectionListSpace)
.background(viewportBoundaryReporter())
.scrollDismissesKeyboard(.interactively)
.onPreferenceChange(NativeEmojiSectionOffsetsKey.self) { offsets in
guard tracksSelection else { return }
categorySelection.select(
NativeEmojiCategoryTracker.selectedSectionID(
order: data.sections.map(\.id),
offsets: offsets,
viewportTop: 0,
viewportBottom: offsets[nativeEmojiViewportBottomKey],
contentBottom: offsets[nativeEmojiContentBottomKey],
currentSelection: categorySelection.selectedSectionID
)
)
}
}
private func sectionOffsetReporter(id: String) -> some View {
GeometryReader { geometry in
Color.clear.preference(
key: NativeEmojiSectionOffsetsKey.self,
value: [id: geometry.frame(in: .named(sectionListSpace)).minY]
)
}
}
// The end of the scrolling content, relative to the viewport top. At the
// clamped bottom of an overflowing list this converges on the viewport
// height, which lets the tracker highlight a short final section that can
// never scroll its own header to the top.
private func contentBoundaryReporter() -> some View {
GeometryReader { geometry in
Color.clear.preference(
key: NativeEmojiSectionOffsetsKey.self,
value: [
nativeEmojiContentBottomKey:
geometry.frame(in: .named(sectionListSpace)).maxY
]
)
}
}
// The fixed viewport height, reported through the same preference stream so
// it stays consistent with the section offsets in each update.
private func viewportBoundaryReporter() -> some View {
GeometryReader { geometry in
Color.clear.preference(
key: NativeEmojiSectionOffsetsKey.self,
value: [nativeEmojiViewportBottomKey: geometry.size.height]
)
}
}
private func emojiButton(_ item: NativeEmojiItem) -> some View {
let value = displayValue(for: item)
return Button {
onSelect(value)
} label: {
Group {
if let url = item.imageURL {
NativeEmojiRemoteImage(
url: url,
fallbackColor: appearance.secondaryText
)
.frame(width: largeEmoji ? 48 : 28, height: largeEmoji ? 48 : 28)
} else {
Text(value).font(.system(size: largeEmoji ? 48 : 28))
}
}
.frame(maxWidth: .infinity)
.frame(height: largeEmoji ? 60 : 44)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel(item.name)
}
private func displayValue(for item: NativeEmojiItem) -> String {
guard item.imageURL == nil else { return item.value }
guard item.skinVariants.indices.contains(selectedSkinTone) else {
return item.skinVariants.first ?? item.value
}
return item.skinVariants[selectedSkinTone]
}
}
/// Observes only the rail selection. Keeping this in a leaf view prevents a
/// scroll-frame highlight update from rebuilding the picker grid itself.
private struct NativeEmojiCategoryButton: View {
let section: NativeEmojiSection
let appearance: NativeEmojiPickerAppearance
@ObservedObject var selection: NativeEmojiCategorySelection
let onSelect: () -> Void
var body: some View {
let isSelected = selection.selectedSectionID == section.id
Button(action: onSelect) {
TablerNativeIcon(symbol: section.systemImage)
.font(.system(size: 18, weight: .medium))
.foregroundStyle(
Color(
uiColor: isSelected
? appearance.accent : appearance.secondaryText
)
)
.frame(maxWidth: .infinity)
.frame(height: 36)
.background(
isSelected ? Color(uiColor: appearance.control) : Color.clear,
in: Circle()
)
}
.buttonStyle(.plain)
.accessibilityLabel(section.title)
.accessibilityAddTraits(isSelected ? .isSelected : [])
}
}
struct NativeEmojiRemoteImage: View {
let url: URL
let fallbackColor: UIColor
@State private var phase: Phase = .loading
private enum Phase {
case loading
case success(UIImage)
case failure
}
var body: some View {
Group {
switch phase {
case .loading:
ProgressView().controlSize(.mini)
case .success(let image):
NativeEmojiAnimatedImage(image: image)
case .failure:
TablerNativeIcon(symbol: "sparkles")
.foregroundStyle(Color(uiColor: fallbackColor))
}
}
.task(id: url) {
do {
phase = .success(try await NativeEmojiRemoteImageLoader.image(for: url))
} catch {
if !Task.isCancelled { phase = .failure }
}
}
// Keep only the first frame of a cell scrolled away, as before animation:
// reappearing decodes every frame again anyway.
.onDisappear {
if case .success(let image) = phase, let first = image.images?.first {
phase = .success(first)
}
}
}
}
/// SwiftUI's `Image` draws only the first frame of an animated `UIImage`;
/// a `UIImageView` plays every frame.
/// With Reduce Motion on it shows the first frame, following the setting live.
private struct NativeEmojiAnimatedImage: UIViewRepresentable {
let image: UIImage
@Environment(\.accessibilityReduceMotion) private var reduceMotion
func makeUIView(context: Context) -> UIImageView {
let view = UIImageView()
view.contentMode = .scaleAspectFit
view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
view.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
return view
}
func updateUIView(_ view: UIImageView, context: Context) {
let shown = reduceMotion ? image.images?.first ?? image : image
if view.image !== shown { view.image = shown }
}
}
/// Custom emoji, decoded at the picker's glyph size. Flutter serves the bytes
/// from its memory and disk caches, so a reopen never downloads again.
enum NativeEmojiRemoteImageLoader {
/// The picker's 28-point custom emoji glyph at 3x.
private static let maximumPixelSize = 84
@MainActor
static func image(for url: URL) async throws -> UIImage {
let bytes = try await NativeEmojiPickerCoordinator.mediaBytes(for: url)
// Bytes can arrive after the cell left; don't decode for a dead view
// while visible cells wait for the decode threads.
try Task.checkCancellation()
// Cached bytes skip Flutter's download gate, so decodes have their own.
try await NativeEmojiDecodeGate.acquire()
defer { NativeEmojiDecodeGate.release() }
let decode = Task.detached(priority: .userInitiated) {
NativeMessageImageLoader.decode(bytes, maximumPixelSize: maximumPixelSize) {
Task.isCancelled
}
}
// A cell that leaves stops its decode between frames.
let decoded = await withTaskCancellationHandler {
await decode.value
} onCancel: {
decode.cancel()
}
try Task.checkCancellation()
guard let decoded else { throw NativeEmojiRemoteImageError.invalidImage }
return decoded
}
}
/// Admits four custom emoji decodes at a time, in request order. A waiter
/// whose cell leaves gives up its place.
@MainActor
enum NativeEmojiDecodeGate {
static let limit = 4
private static var active = 0
private static var waiting: [(id: UUID, continuation: CheckedContinuation<Void, Error>)] = []
static func acquire() async throws {
if active < limit {
active += 1
return
}
let id = UUID()
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
waiting.append((id, continuation))
}
} onCancel: {
Task { @MainActor in
guard let index = waiting.firstIndex(where: { $0.id == id }) else { return }
waiting.remove(at: index).continuation.resume(throwing: CancellationError())
}
}
}
/// Hands the slot to the next waiter, if any.
static func release() {
if waiting.isEmpty {
active -= 1
} else {
waiting.removeFirst().continuation.resume()
}
}
}
enum NativeEmojiRemoteImageError: Error {
case invalidImage
}
private struct TablerNativeIcon: View {
let symbol: String
var body: some View {
if let image = NativeTabler.image(symbol) {
Image(uiImage: image).renderingMode(.template)
}
}
}