-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContentView.swift
More file actions
237 lines (219 loc) · 10.5 KB
/
Copy pathContentView.swift
File metadata and controls
237 lines (219 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// Copyright PolyAI Limited
// ContentView.swift
// Examples/SwiftUI/01-Hello
//
// Mirrors README:
// - § "Get started > Use in your app > SwiftUI"
//
import SwiftUI
import PolyMessaging
struct ContentView: View {
// Matches the web's MAX_MESSAGE_LENGTH cap.
static let maxMessageLength = 500
// @StateObject survives view re-renders — one ChatSession per chat surface.
@StateObject var session = PolyMessaging.chat()
@State private var input = ""
// F1: WhatsApp-style follow. `autoFollow` is sticky — new content scrolls to
// the bottom while it's true, and surfaces a "New messages" pill instead while
// it's false. ONLY the user's own dragging flips it: pulling up away from the
// bottom stops following; scrolling back (or tapping the pill, or sending)
// resumes it. Keeping it sticky stops a streaming reply or an in-flight scroll
// from being misread as "the user scrolled up".
@State private var isNearBottom = true
@State private var hasNewBelow = false
@State private var autoFollow = true
@State private var userIsDragging = false
// Timestamp of our last programmatic follow-scroll. A "far from bottom"
// reading within a brief window after one is our own animation/streaming
// lag; outside it, the only thing that can have moved the list is the user.
@State private var lastFollowScrollAt = Date.distantPast
private var sendDisabled: Bool {
input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || session.hasEnded
}
/// `failureReason` is non-nil once the SDK hits a terminal failure it
/// can't auto-recover from — most notably an invalid `apiKey`. We
/// bind it to `.alert` so an obvious "Couldn't connect" dialog appears
/// instead of letting the app sit silently with an empty message list.
private var failureAlertBinding: Binding<Bool> {
Binding(
get: { session.failureReason != nil },
set: { _ in }
)
}
var body: some View {
VStack(spacing: 0) {
// ScrollViewReader gives us scrollTo(id:); the ".id("bottom")"
// sentinel at the end of the LazyVStack is the anchor we scroll to
// on every message change AND on every text-length change (so the
// view tracks the growing bubble while streaming).
GeometryReader { outer in
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 8) {
ForEach(session.messages) { message in
Text(message.text ?? "")
.padding(10)
.background(Color(.systemGray6))
.cornerRadius(12)
// Cap bubble width at ~75% of the actual container
// width (tracks rotation / iPad split-view, F5) so
// long messages wrap instead of spanning edge-to-edge.
.frame(maxWidth: outer.size.width > 0 ? outer.size.width * 0.75 : .infinity, alignment: .leading)
}
// Stable scroll anchor + bottom-visibility probe.
Color.clear.frame(height: 1).id("bottom")
.background(GeometryReader { g in
Color.clear.preference(
key: BottomVisibleKey.self,
value: g.frame(in: .named("chatScroll")).maxY
)
})
}
.padding()
}
.coordinateSpace(name: "chatScroll")
.accessibilityIdentifier("messageList")
.onPreferenceChange(BottomVisibleKey.self) { bottomMaxY in
let near = bottomMaxY <= outer.size.height + 80
if near != isNearBottom { isNearBottom = near }
if near {
// Parked at the bottom (scrolled back, or our follow landed):
// resume following and clear the pill.
if !autoFollow { autoFollow = true }
if hasNewBelow { hasNewBelow = false }
} else if userIsDragging
|| Date().timeIntervalSince(lastFollowScrollAt) > 0.3 {
// The user pulled up away from the bottom — either an
// active drag, or a "far" reading with no recent
// follow-scroll behind it. Transient lag while
// streaming/auto-scrolling stays inside the window.
if autoFollow { autoFollow = false }
}
}
// The SwiftUI equivalent of scrollViewWillBeginDragging: a
// non-consuming drag that just tells us the user is scrolling.
.simultaneousGesture(
DragGesture(minimumDistance: 8)
.onChanged { _ in userIsDragging = true }
.onEnded { _ in userIsDragging = false }
)
.overlay(alignment: .bottom) {
if hasNewBelow {
newMessagesPill(proxy: proxy)
.padding(.bottom, 10)
.transition(.move(edge: .bottom).combined(with: .opacity))
}
}
.onChange(of: session.messages.count) { _ in
onNewContent(proxy: proxy)
}
// Streaming grows the last agent message's text in place
// (messages.count doesn't change), so also follow its length.
.onChange(of: session.messages.last?.text ?? "") { _ in
if autoFollow { scrollToBottom(proxy: proxy) } else { hasNewBelow = true }
}
}
}
HStack(alignment: .bottom, spacing: 12) {
composerField
.textFieldStyle(.plain)
.padding(.horizontal, 12).padding(.vertical, 10)
.background(Color(.systemGray6)).clipShape(RoundedRectangle(cornerRadius: 18))
.accessibilityIdentifier("composer")
Button(action: send) {
Image(systemName: "arrow.up.circle.fill")
.font(.system(size: 36))
.foregroundColor(sendDisabled ? .gray : .blue)
}
.disabled(sendDisabled)
.accessibilityIdentifier("sendButton")
}
.padding(.horizontal).padding(.vertical, 8).background(.bar)
}
.alert("Couldn't connect", isPresented: failureAlertBinding) {
Button("Try Again") {
Task { try? await session.client.resume() }
}
} message: {
// gives a useful "auth(unauthorized)" instead of the generic
// "The operation couldn't be completed" .localizedDescription.
Text(session.failureReason.map { String(describing: $0) } ?? "")
}
}
// F4: a composer that grows 1–5 lines on iOS 16+ (web parity); single-line
// fallback on iOS 15. Return sends in both cases (newlines arrive via paste).
@ViewBuilder
private var composerField: some View {
if #available(iOS 16.0, *) {
TextField("Message...", text: $input, axis: .vertical)
.lineLimit(1...5)
.onChange(of: input) { handleComposerChange($0) }
} else {
TextField("Message...", text: $input)
.submitLabel(.send)
.onChange(of: input) { newValue in
if newValue.count > Self.maxMessageLength {
input = String(newValue.prefix(Self.maxMessageLength))
}
}
.onSubmit(send)
}
}
/// iOS 16+ growing field: Return inserts '\n', so detect a trailing newline and
/// treat it as a send; otherwise enforce the length cap.
private func handleComposerChange(_ newValue: String) {
if newValue.hasSuffix("\n") {
send()
return
}
if newValue.count > Self.maxMessageLength {
input = String(newValue.prefix(Self.maxMessageLength))
}
}
// MARK: - Scroll
/// A new message/turn arrived: follow it only if the user is already at the
/// bottom; otherwise leave them where they are and show the pill.
private func onNewContent(proxy: ScrollViewProxy) {
if autoFollow {
scrollToBottom(proxy: proxy)
} else {
hasNewBelow = true
}
}
private func scrollToBottom(proxy: ScrollViewProxy) {
lastFollowScrollAt = Date()
withAnimation { proxy.scrollTo("bottom", anchor: .bottom) }
}
private func newMessagesPill(proxy: ScrollViewProxy) -> some View {
Button {
withAnimation { proxy.scrollTo("bottom", anchor: .bottom) }
hasNewBelow = false
isNearBottom = true
autoFollow = true
} label: {
Label("New messages", systemImage: "arrow.down")
.font(.caption.bold())
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(Capsule().fill(Color.blue))
.foregroundColor(.white)
.shadow(color: .black.opacity(0.2), radius: 4, y: 2)
}
.accessibilityLabel("Scroll to newest messages")
}
private func send() {
let text = input.trimmingCharacters(in: .whitespacesAndNewlines)
input = ""
guard !text.isEmpty else { return }
autoFollow = true // follow the agent's reply while we wait
Task { try? await session.send(text) }
}
}
/// Reports the bottom sentinel's maxY within the scroll viewport so the view can
/// tell whether the user is parked near the bottom.
private struct BottomVisibleKey: PreferenceKey {
static let defaultValue: CGFloat = .greatestFiniteMagnitude
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = min(value, nextValue())
}
}