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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import SwiftUI
struct PadColumnFlickNavigation: ViewModifier {
let columnWidth: CGFloat
let columnCount: Int
@State private var position = PadColumnFlickPosition()
func body(content: Content) -> some View {
content
.onScrollGeometryChange(for: CGRect.self) { geometry in
CGRect(
x: geometry.contentOffset.x + geometry.contentInsets.leading, y: 0,
width: geometry.containerSize.width, height: 0)
} action: { _, rect in
if position.isInteracting {
let movement = rect.minX - position.visibleRect.minX
let now = ProcessInfo.processInfo.systemUptime
let elapsed = now - position.lastSampleTime
if abs(movement) >= 1 {
position.direction = movement
if position.lastSampleTime > 0, elapsed > 0 {
position.lastVelocity = abs(movement) / CGFloat(elapsed)
}
position.lastMovementTime = now
}
position.lastSampleTime = now
position.releaseRect = rect
}
position.visibleRect = rect
}
.onScrollPhaseChange { oldPhase, phase in
if phase == .interacting && oldPhase != .interacting {
position.direction = 0
position.lastSampleTime = ProcessInfo.processInfo.systemUptime
position.lastMovementTime = 0
position.lastVelocity = 0
position.releaseRect = position.visibleRect
}
position.isInteracting = phase == .interacting
position.isUserScrolling = phase == .interacting || phase == .decelerating
}
.scrollTargetBehavior(
PadColumnFlickBehavior(columnWidth: columnWidth, columnCount: columnCount, position: position))
}
}
private final class PadColumnFlickPosition {
var visibleRect = CGRect.zero
var releaseRect = CGRect.zero
var direction: CGFloat = 0
var lastSampleTime: TimeInterval = 0
var lastMovementTime: TimeInterval = 0
var lastVelocity: CGFloat = 0
var isInteracting = false
var isUserScrolling = false
}
private struct PadColumnFlickBehavior: ScrollTargetBehavior {
let columnWidth: CGFloat
let columnCount: Int
let position: PadColumnFlickPosition
func updateTarget(_ target: inout ScrollTarget, context: TargetContext) {
// SwiftUI can report no momentum for a slow flick.
let recentFlick =
position.lastVelocity >= 60 && ProcessInfo.processInfo.systemUptime - position.lastMovementTime < 0.15
guard context.axes.contains(.horizontal), position.isUserScrolling,
abs(position.releaseRect.width - context.containerSize.width) < 1,
let offset = PadColumnLayout.flickTarget(
release: PadColumnFlick(
releaseOffset: position.releaseRect.minX,
projectedOffset: target.rect.minX,
direction: position.direction,
recentFlick: recentFlick
),
columnWidth: columnWidth,
columnCount: columnCount,
contentWidth: context.contentSize.width,
windowWidth: context.containerSize.width
)
else { return }
target.rect.origin.x = offset
target.rect.size.width = context.containerSize.width
target.anchor = .topLeading
}
}
struct PadColumnEdgeNavigation: ViewModifier {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
let columns: [PadColumn]
let columnWidth: CGFloat
let windowWidth: CGFloat
let scrollProxy: ScrollViewProxy
private var columnsFit: Bool {
PadColumnLayout.columnsFit(columnCount: columns.count, columnWidth: columnWidth, windowWidth: windowWidth)
}
private var showsLeftChevron: Bool {
!columnsFit && (visibleRange.map { $0.lowerBound > 0 } ?? false)
}
private var showsRightChevron: Bool {
!columnsFit && (visibleRange.map { $0.upperBound < columns.count - 1 } ?? false)
}
@State private var visibleRange: ClosedRange<Int>?
func body(content: Content) -> some View {
content
.onScrollGeometryChange(for: ClosedRange<Int>?.self) { geometry in
guard !columns.isEmpty, geometry.containerSize.width > 0 else { return nil }
let left = max(0, geometry.contentOffset.x + geometry.contentInsets.leading)
let right = left + geometry.containerSize.width
let stride = columnWidth + 12
let first = columns.indices.first(where: { 12 + CGFloat($0) * stride >= left - 1 }) ?? columns.count
let last = columns.indices.last(where: { 12 + CGFloat($0) * stride + columnWidth <= right + 1 }) ?? -1
// A narrow window can show only part of a column.
return min(first, max(0, last))...max(last, min(columns.count - 1, first))
} action: { _, range in
visibleRange = range
}
.overlay(alignment: .bottomLeading) {
HStack(spacing: PadColumnLayout.actionSpacing) {
if showsLeftChevron, let range = visibleRange {
edgeButton(direction: -1, target: range.lowerBound - 1)
.transition(.opacity.combined(with: .scale(scale: 0.85)))
}
if showsRightChevron, let range = visibleRange {
edgeButton(direction: 1, target: range.upperBound + 1)
.transition(.opacity.combined(with: .scale(scale: 0.85)))
}
}
.padding(.leading, 24)
.padding(.bottom, 24)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: showsLeftChevron)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: showsRightChevron)
}
}
private func edgeButton(direction: Int, target: Int) -> some View {
Button {
navigate(direction: direction, target: target)
} label: {
Image(systemName: direction < 0 ? "chevron.left" : "chevron.right")
.font(.body.weight(.semibold))
.frame(width: 44, height: 44)
}
.buttonStyle(.glass)
.buttonBorderShape(.circle)
.accessibilityLabel(direction < 0 ? "Show column to the left" : "Show column to the right")
.accessibilityIdentifier(direction < 0 ? "showLeftColumnButton" : "showRightColumnButton")
}
private func navigate(direction: Int, target: Int) {
guard columns.indices.contains(target) else { return }
let availableWidth = windowWidth - columnWidth
let inset = availableWidth > 0 ? min(0.5, PadColumnLayout.edgePadding / availableWidth) : 0
let anchor = UnitPoint(x: direction < 0 ? inset : 1 - inset, y: 0.5)
withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.25)) {
scrollProxy.scrollTo(columns[target].id, anchor: anchor)
}
}
}
@MainActor @Observable
final class PadColumnDragCoordinator {
var activeID: String?
var translation: CGFloat = 0
var settlingID: String?
var settlingOffset: CGFloat = 0
var settlingToken = UUID()
func destination(ids: [String], stride: CGFloat) -> Int? {
guard let activeID, let source = ids.firstIndex(of: activeID) else { return nil }
return max(0, min(ids.count - 1, source + Int((translation / stride).rounded())))
}
func offset(id: String, ids: [String], stride: CGFloat) -> CGFloat {
if id == settlingID { return settlingOffset }
guard let activeID, let source = ids.firstIndex(of: activeID),
let index = ids.firstIndex(of: id), let destination = destination(ids: ids, stride: stride)
else { return 0 }
if id == activeID { return translation }
if source < destination && index > source && index <= destination { return -stride }
if destination < source && index >= destination && index < source { return stride }
return 0
}
}
struct PadColumnMotion: ViewModifier {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
let id: String
let ids: [String]
let stride: CGFloat
let drag: PadColumnDragCoordinator
func body(content: Content) -> some View {
content
.offset(x: drag.offset(id: id, ids: ids, stride: stride))
.animation(
drag.activeID == nil || drag.activeID == id || reduceMotion
? nil : .spring(response: 0.35, dampingFraction: 0.82),
value: drag.destination(ids: ids, stride: stride)
)
.zIndex(drag.activeID == id || drag.settlingID == id ? 1 : 0)
.task(id: drag.settlingID == id) {
guard drag.settlingID == id else { return }
await Task.yield()
guard !Task.isCancelled, drag.settlingID == id else { return }
let token = drag.settlingToken
withAnimation(
reduceMotion ? nil : .spring(response: 0.3, dampingFraction: 0.72), completionCriteria: .removed
) {
drag.settlingOffset = 0
} completion: {
if drag.settlingID == id && drag.settlingToken == token { drag.settlingID = nil }
}
}
}
}
#if DEBUG
#Preview("Column controls") {
PreviewHost { _ in
PadColumnControls(column: .following, stride: 400, drag: PadColumnDragCoordinator(), isHandle: true)
.padding()
}
}
#endif
struct PadColumnControls: View {
@Environment(AppModel.self) private var model
@Environment(\.accessibilityReduceMotion) private var reduceMotion
let column: PadColumn
let stride: CGFloat
let drag: PadColumnDragCoordinator
let isHandle: Bool
@GestureState private var isDragging = false
private var columnAnimation: Animation? {
reduceMotion ? nil : .spring(response: 0.35, dampingFraction: 0.82)
}
var body: some View {
Group {
if isHandle {
Image(systemName: "line.3.horizontal")
.font(.body.weight(.semibold))
.foregroundStyle(.tint)
.frame(width: 44, height: 44)
.contentShape(Rectangle())
.gesture(
DragGesture(minimumDistance: 4, coordinateSpace: .global)
.updating($isDragging) { _, state, transaction in
transaction.animation = nil
state = true
}
.onChanged { value in
withTransaction(Transaction(animation: nil)) {
drag.settlingID = nil
drag.activeID = column.id
drag.translation = value.translation.width
}
}
.onEnded { value in
guard let source = model.padColumns.firstIndex(where: { $0.id == column.id }) else {
drag.activeID = nil
return
}
let destination = max(
0,
min(
model.padColumns.count - 1,
source + Int((value.translation.width / stride).rounded())))
var transaction = Transaction(animation: nil)
transaction.disablesAnimations = true
withTransaction(transaction) {
drag.settlingToken = UUID()
drag.settlingID = column.id
drag.settlingOffset =
value.translation.width - CGFloat(destination - source) * stride
drag.activeID = nil
model.movePadColumn(id: column.id, offset: destination - source)
}
}
)
.onChange(of: isDragging) { _, active in
if !active && drag.activeID == column.id { drag.activeID = nil }
}
.onDisappear {
if drag.activeID == column.id { drag.activeID = nil }
}
.accessibilityLabel("Reorder \(column.title)")
.accessibilityHint("Drag left or right to move this column.")
.accessibilityIdentifier("moveColumn-\(column.id)")
.accessibilityAction(named: "Move left") {
withAnimation(columnAnimation) { model.movePadColumn(id: column.id, offset: -1) }
}
.accessibilityAction(named: "Move right") {
withAnimation(columnAnimation) { model.movePadColumn(id: column.id, offset: 1) }
}
} else if column.feed != nil || column.detail != nil {
Button {
withAnimation(columnAnimation) { model.closePadColumn(id: column.id) }
} label: {
Image(systemName: "xmark")
.frame(minWidth: 44, minHeight: 44)
}
.accessibilityLabel("Close \(column.title)")
.accessibilityIdentifier("closeColumn-\(column.id)")
}
}
.accessibilityAction(named: "Move left") { model.movePadColumn(id: column.id, offset: -1) }
.accessibilityAction(named: "Move right") { model.movePadColumn(id: column.id, offset: 1) }
}
}
extension View {
func ipadColumnSurface() -> some View {
self
.background(Color(uiColor: .systemBackground))
.clipShape(RoundedRectangle(cornerRadius: 16))
.overlay {
RoundedRectangle(cornerRadius: 16)
.strokeBorder(.primary.opacity(0.09))
}
.shadow(color: .black.opacity(0.12), radius: 10, y: 4)
}
}