Open History to see the last commit
1import SwiftUI
2import UIKit
3
4/// Lives on the workspace, not a row, so moving the source to another shelf
5/// does not dismiss the sheet.
6struct ThreadArrangementView: View {
7 @SwiftUI.Environment(\.dismiss) private var dismiss
8 @Bindable var model: FeatureRootModel
9 @State private var action: String?
10 @State private var now = Date.now
11
12 var body: some View {
13 NavigationStack {
14 ThreadArrangementCollection(
15 model: model,
16 revision: model.homePresentationRevision,
17 busy: model.isArrangingThreads,
18 now: now,
19 onAction: { action = $0 }
20 )
21 .background(.black)
22 .navigationTitle(action ?? "Arrange threads")
23 .navigationBarTitleDisplayMode(.inline)
24 .toolbar {
25 ToolbarItem(placement: .confirmationAction) {
26 Button("Done") { dismiss() }
27 .disabled(model.isArrangingThreads)
28 }
29 }
30 }
31 .preferredColorScheme(.dark)
32 .interactiveDismissDisabled(model.isArrangingThreads)
33 .alert("Could not arrange threads", isPresented: Binding(
34 get: { model.errorMessage != nil },
35 set: { if !$0 { model.errorMessage = nil } }
36 )) {
37 Button("OK") { model.errorMessage = nil }
38 } message: {
39 Text(model.errorMessage ?? "The move failed.")
40 }
41 .task(id: nextWake) {
42 guard let wake = nextWake else { return }
43 do {
44 try await Task.sleep(for: .seconds(max(0, wake.timeIntervalSinceNow)))
45 now = max(.now, wake)
46 } catch {}
47 }
48 }
49
50 private var nextWake: Date? {
51 model.snapshot.threads.compactMap(\.snoozedUntil).filter { $0 > now }.min()
52 }
53}
54
55private struct ThreadArrangementCollection: UIViewRepresentable {
56 let model: FeatureRootModel
57 let revision: UInt64
58 let busy: Bool
59 let now: Date
60 let onAction: (String?) -> Void
61
62 func makeCoordinator() -> Coordinator { Coordinator(parent: self) }
63
64 func makeUIView(context: Context) -> UICollectionView {
65 var layout = UICollectionLayoutListConfiguration(appearance: .plain)
66 layout.backgroundColor = .black
67 layout.showsSeparators = false
68 let view = UICollectionView(
69 frame: .zero,
70 collectionViewLayout: UICollectionViewCompositionalLayout.list(using: layout)
71 )
72 view.backgroundColor = .black
73 view.alwaysBounceVertical = true
74 view.dragInteractionEnabled = true
75 view.delegate = context.coordinator
76 view.dragDelegate = context.coordinator
77 view.dropDelegate = context.coordinator
78 context.coordinator.configure(view)
79 return view
80 }
81
82 func updateUIView(_ view: UICollectionView, context: Context) {
83 context.coordinator.parent = self
84 context.coordinator.update()
85 }
86
87 static func dismantleUIView(_ view: UICollectionView, coordinator: Coordinator) {
88 view.delegate = nil
89 view.dragDelegate = nil
90 view.dropDelegate = nil
91 }
92
93 @MainActor
94 final class Coordinator: NSObject, UICollectionViewDelegate,
95 UICollectionViewDragDelegate, UICollectionViewDropDelegate {
96 typealias Row = ThreadArrangementRow
97
98 var parent: ThreadArrangementCollection
99 private weak var view: UICollectionView?
100 private var dataSource: UICollectionViewDiffableDataSource<Int, String>?
101 private var rows: [Row] = []
102 private var expanded = Set<ThreadArrangementSection>()
103 private var draggedID: String?
104 private var pendingRows: [Row]?
105
106 init(parent: ThreadArrangementCollection) { self.parent = parent }
107
108 func configure(_ view: UICollectionView) {
109 self.view = view
110 let registration = UICollectionView.CellRegistration<UICollectionViewListCell, String> {
111 [weak self] cell, _, id in
112 self?.configure(cell, id: id)
113 }
114 dataSource = UICollectionViewDiffableDataSource<Int, String>(collectionView: view) {
115 collection, indexPath, id in
116 collection.dequeueConfiguredReusableCell(using: registration, for: indexPath, item: id)
117 }
118 update()
119 }
120
121 func update(completion: (() -> Void)? = nil) {
122 guard draggedID == nil || pendingRows != nil else { return }
123 if let pendingRows {
124 rows = pendingRows
125 } else {
126 let index = DailyUXSidebarIndex(snapshot: parent.model.snapshot, query: "", now: parent.now)
127 rows = ThreadArrangementSection.allCases.flatMap { section -> [Row] in
128 let threads: [FeatureThread]
129 switch section {
130 case .pinned: threads = index.pinned
131 case .active: threads = index.active
132 case .snoozed: threads = index.snoozed
133 case .settled: threads = index.settled
134 }
135 if section == .snoozed, threads.isEmpty { return [] }
136 let visible = section.orderSection != nil || expanded.contains(section)
137 return [Row(section: section)] + (visible ? threads.map { Row(section: section, thread: $0) } : [])
138 }
139 }
140 var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
141 snapshot.appendSections([0])
142 snapshot.appendItems(rows.map(\.id))
143 if let existing = dataSource?.snapshot().itemIdentifiers {
144 let previousIDs = Set(existing)
145 snapshot.reconfigureItems(rows.map(\.id).filter { previousIDs.contains($0) })
146 }
147 dataSource?.apply(snapshot, animatingDifferences: !UIAccessibility.isReduceMotionEnabled, completion: completion)
148 }
149
150 private func configure(_ cell: UICollectionViewListCell, id: String) {
151 guard let row = rows.first(where: { $0.id == id }) else { return }
152 cell.backgroundConfiguration = .clear()
153 cell.accessories = []
154 if let thread = row.thread {
155 let enabled = !parent.model.isArrangingThreads && canLift(thread)
156 cell.contentConfiguration = UIHostingConfiguration {
157 HStack(spacing: 12) {
158 VStack(alignment: .leading, spacing: 2) {
159 Text(thread.title).font(.system(size: 15)).foregroundStyle(.white).lineLimit(1)
160 if let name = thread.environmentName {
161 Text(name).font(.system(size: 11)).foregroundStyle(.gray).lineLimit(1)
162 }
163 }
164 Spacer(minLength: 0)
165 Image(systemName: "line.3.horizontal")
166 .foregroundStyle(enabled ? Color.white : Color.gray)
167 .frame(width: 48, height: 48)
168 }
169 .frame(height: 56)
170 .padding(.horizontal, 16)
171 .background(.black)
172 }.margins(.all, 0)
173 cell.isAccessibilityElement = true
174 cell.accessibilityLabel = thread.title
175 cell.accessibilityValue = row.section.title
176 cell.accessibilityHint = "Use actions to change order or section."
177 cell.accessibilityTraits = .button
178 cell.accessibilityCustomActions = accessibilityActions(thread, section: row.section)
179 } else {
180 let expandable = row.section.orderSection == nil
181 let isExpanded = expanded.contains(row.section)
182 cell.contentConfiguration = UIHostingConfiguration {
183 HStack {
184 Text(row.section.title).font(.system(size: 14, weight: .semibold))
185 Spacer()
186 if expandable {
187 Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
188 }
189 }
190 .foregroundStyle(.white)
191 .padding(.horizontal, 16)
192 .frame(height: 48)
193 .background(.black)
194 }.margins(.all, 0)
195 cell.isAccessibilityElement = true
196 cell.accessibilityLabel = row.section.title
197 cell.accessibilityValue = expandable ? (expanded.contains(row.section) ? "Expanded" : "Collapsed") : nil
198 cell.accessibilityHint = nil
199 cell.accessibilityTraits = expandable ? [.header, .button] : .header
200 cell.accessibilityCustomActions = []
201 }
202 }
203
204 private func canLift(_ thread: FeatureThread) -> Bool {
205 guard !thread.isArchived,
206 parent.model.snapshot.environments.contains(where: {
207 $0.id == thread.environmentID && $0.isEnabled && $0.connectionState == .connected
208 }) else { return false }
209 return ThreadArrangementPlanner.canEnter(thread, section: .pinned, now: .now)
210 || ThreadArrangementPlanner.canEnter(thread, section: .active, now: .now)
211 || (thread.supportsSettlement == true && !thread.isEffectivelySettled() && thread.canSettleNow())
212 }
213
214 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
215 guard rows.indices.contains(indexPath.item), rows[indexPath.item].thread == nil,
216 !parent.model.isArrangingThreads else { return }
217 let section = rows[indexPath.item].section
218 guard section.orderSection == nil else { return }
219 if expanded.contains(section) { expanded.remove(section) } else { expanded.insert(section) }
220 update()
221 }
222
223 func collectionView(
224 _ collectionView: UICollectionView,
225 itemsForBeginning session: UIDragSession,
226 at indexPath: IndexPath
227 ) -> [UIDragItem] {
228 guard !parent.model.isArrangingThreads, pendingRows == nil, rows.indices.contains(indexPath.item),
229 let thread = rows[indexPath.item].thread, canLift(thread),
230 let cell = collectionView.cellForItem(at: indexPath),
231 session.location(in: cell).x >= cell.bounds.maxX - 64 else { return [] }
232 draggedID = thread.id
233 let item = UIDragItem(itemProvider: NSItemProvider(object: thread.id as NSString))
234 item.localObject = thread.id
235 return [item]
236 }
237
238 func collectionView(
239 _ collectionView: UICollectionView,
240 dragSessionIsRestrictedToDraggingApplication session: UIDragSession
241 ) -> Bool { true }
242
243 func collectionView(
244 _ collectionView: UICollectionView,
245 dragSessionAllowsMoveOperation session: UIDragSession
246 ) -> Bool { true }
247
248 func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) {
249 draggedID = nil
250 parent.onAction(nil)
251 update()
252 }
253
254 private func destination(at indexPath: IndexPath?, location: CGPoint) -> ThreadArrangementDestination? {
255 guard let indexPath, indexPath.section == 0 else { return nil }
256 let frame = view?.layoutAttributesForItem(at: indexPath)?.frame
257 return ThreadArrangementPlanner.destination(
258 rows: rows,
259 insertionIndex: indexPath.item,
260 isBeforeHeader: frame.map { location.y < $0.minY } ?? false
261 )
262 }
263
264 func collectionView(
265 _ collectionView: UICollectionView,
266 dropSessionDidUpdate session: UIDropSession,
267 withDestinationIndexPath indexPath: IndexPath?
268 ) -> UICollectionViewDropProposal {
269 guard session.localDragSession != nil, let id = draggedID,
270 let destination = destination(at: indexPath, location: session.location(in: collectionView)),
271 parent.model.arrangementPlan(id: id, destination: destination) != nil else {
272 parent.onAction(nil)
273 return UICollectionViewDropProposal(operation: .forbidden)
274 }
275 if let source = rows.first(where: { $0.thread?.id == id }) {
276 parent.onAction(action(source: source.section, destination: destination.section))
277 }
278 return UICollectionViewDropProposal(
279 operation: .move,
280 intent: destination.targetID == nil ? .insertIntoDestinationIndexPath : .insertAtDestinationIndexPath
281 )
282 }
283
284 func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
285 guard let id = draggedID, let item = coordinator.items.first,
286 let destination = destination(
287 at: coordinator.destinationIndexPath,
288 location: coordinator.session.location(in: collectionView)
289 ),
290 parent.model.arrangementPlan(id: id, destination: destination) != nil,
291 let moved = rows.first(where: { $0.thread?.id == id })?.thread else { return }
292 var next = rows.filter { $0.thread?.id != id }
293 let target = destination.targetID.flatMap { id in next.firstIndex { $0.thread?.id == id } }
294 ?? next.firstIndex { $0.thread == nil && $0.section == destination.section }
295 guard let target else { return }
296 let insertAt = target + (destination.targetID == nil || destination.after ? 1 : 0)
297 if destination.section.orderSection != nil || expanded.contains(destination.section) {
298 next.insert(Row(section: destination.section, thread: moved), at: insertAt)
299 }
300 pendingRows = next
301 let dropPath = IndexPath(item: min(insertAt, next.count - 1), section: 0)
302 update {
303 coordinator.drop(item.dragItem, toItemAt: dropPath)
304 }
305 commit(id, destination: destination)
306 }
307
308 private func commit(_ id: String, destination: ThreadArrangementDestination) {
309 Task { [weak self] in
310 guard let self else { return }
311 _ = await parent.model.arrangeThread(id, destination: destination)
312 pendingRows = nil
313 draggedID = nil
314 parent.onAction(nil)
315 update()
316 }
317 }
318
319 private func action(source: ThreadArrangementSection, destination: ThreadArrangementSection) -> String {
320 if destination == .settled { return "Settle" }
321 if source == destination { return "Reorder" }
322 if destination == .pinned { return "Pin" }
323 if source == .pinned { return "Unpin" }
324 return source == .settled ? "Unsettle" : "Unsnooze"
325 }
326
327 private func accessibilityActions(_ thread: FeatureThread, section: ThreadArrangementSection) -> [UIAccessibilityCustomAction] {
328 var choices: [(String, ThreadArrangementDestination)] = []
329 if let orderSection = section.orderSection {
330 let ordered = DailyUXSidebarIndex.orderedSection(parent.model.snapshot.threads, section: orderSection, now: .now)
331 if let index = ordered.firstIndex(where: { $0.id == thread.id }) {
332 if index > 0 {
333 choices.append(("Move up", .init(section: section, targetID: ordered[index - 1].id)))
334 }
335 if index + 1 < ordered.count {
336 choices.append(("Move down", .init(section: section, targetID: ordered[index + 1].id, after: true)))
337 }
338 }
339 }
340 for destination in [ThreadArrangementSection.pinned, .active, .settled] where destination != section {
341 choices.append((action(source: section, destination: destination), .init(section: destination)))
342 }
343 return choices.compactMap { name, destination in
344 guard parent.model.arrangementPlan(id: thread.id, destination: destination) != nil else { return nil }
345 return UIAccessibilityCustomAction(name: name) { [weak self] _ in
346 guard let self, self.parent.model.arrangementPlan(id: thread.id, destination: destination) != nil else { return false }
347 self.commit(thread.id, destination: destination)
348 return true
349 }
350 }
351 }
352 }
353}