Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HomeThreadCollectionView.swift

1,171 lines47.8 KB

1import SwiftUI
2import UIKit
3​
4/// A recycled, diffable Home surface. SwiftUI still owns the surrounding shell,
5/// while UIKit keeps row creation and updates proportional to visible threads.
6struct HomeThreadCollectionView: UIViewRepresentable {
7 let presentation: HomePresentation
8 let projectFaviconClient: any FeatureClient
9 let query: String
10 let selectedThreadID: String?
11 let forceRichRows: Bool
12 let hapticsEnabled: Bool
13 let settings: FeatureSettings
14 let pullRequestsByThreadID: [String: HomeThreadPullRequestPresentation]
15 let isSnoozedExpanded: Bool
16 let isSettledExpanded: Bool
17 let isArchiveExpanded: Bool
18 let settledLimit: Int
19 let onOpen: (String) -> Void
20 let onToggleSnoozed: () -> Void
21 let onToggleSettled: () -> Void
22 let onToggleArchive: () -> Void
23 let onShowMoreSettled: () -> Void
24 let onRename: (FeatureThread) -> Void
25 let onRegenerateTitle: (FeatureThread) -> Void
26 let onArchive: (FeatureThread, Bool) -> Void
27 let onSettle: (FeatureThread, Bool, @escaping (Bool) -> Void) -> Void
28 let onSnooze: (FeatureThread, Date?) -> Void
29 let onPin: (FeatureThread, Bool) -> Void
30 let onDelete: (FeatureThread) -> Void
31 let onPullRequestChange: (String, String, HomeThreadPullRequestPresentation?) -> Void
32​
33 func makeCoordinator() -> Coordinator {
34 Coordinator(parent: self)
35 }
36​
37 func makeUIView(context: Context) -> UICollectionView {
38 var configuration = UICollectionLayoutListConfiguration(appearance: .plain)
39 configuration.backgroundColor = T3Colors.uiBackground
40 configuration.showsSeparators = false
41 configuration.headerMode = .none
42 configuration.footerMode = .none
43 configuration.trailingSwipeActionsConfigurationProvider = { [weak coordinator = context.coordinator] indexPath in
44 coordinator?.trailingSwipeActions(at: indexPath)
45 }
46​
47 let collectionView = UICollectionView(
48 frame: .zero,
49 collectionViewLayout: UICollectionViewCompositionalLayout.list(using: configuration)
50 )
51 collectionView.backgroundColor = T3Colors.uiBackground
52 collectionView.alwaysBounceVertical = true
53 collectionView.keyboardDismissMode = .interactive
54 collectionView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 74, right: 0)
55 collectionView.verticalScrollIndicatorInsets = UIEdgeInsets(top: 4, left: 0, bottom: 74, right: 0)
56 collectionView.delegate = context.coordinator
57 context.coordinator.configure(collectionView)
58 return collectionView
59 }
60​
61 func updateUIView(_ collectionView: UICollectionView, context: Context) {
62 context.coordinator.update(parent: self, collectionView: collectionView)
63 }
64​
65 static func dismantleUIView(_ collectionView: UICollectionView, coordinator: Coordinator) {
66 coordinator.invalidateTimer()
67 coordinator.cancelPendingSwipeActions()
68 collectionView.delegate = nil
69 }
70​
71 @MainActor
72 final class Coordinator: NSObject, UICollectionViewDelegate {
73 private enum Section: Hashable {
74 case main
75 }
76​
77 private struct PendingSwipeCompletion {
78 let id: UUID
79 let settled: Bool
80 let finish: (Bool) -> Void
81 }
82​
83 private var parent: HomeThreadCollectionView
84 private var dataSource: UICollectionViewDiffableDataSource<Section, HomeCollectionItem.ID>?
85 private var registration: UICollectionView.CellRegistration<HomeCollectionCell, HomeCollectionItem.ID>?
86 private var itemsByID: [HomeCollectionItem.ID: HomeCollectionItem] = [:]
87 private var threadItemIDs: [String: HomeCollectionItem.ID] = [:]
88 private var pullRequestsByThreadID: [String: HomeThreadPullRequestPresentation] = [:]
89 private var selectedThreadID: String?
90 private weak var collectionView: UICollectionView?
91 private var timer: Timer?
92 private var timerTick = 0
93 private var timerInterval: TimeInterval = 0
94 private var pendingSwipeCompletions: [String: PendingSwipeCompletion] = [:]
95 private var isApplyingSnapshot = false
96 private var hasQueuedUpdate = false
97​
98 init(parent: HomeThreadCollectionView) {
99 self.parent = parent
100 selectedThreadID = parent.selectedThreadID
101 }
102​
103 func configure(_ collectionView: UICollectionView) {
104 self.collectionView = collectionView
105​
106 let registration = UICollectionView.CellRegistration<HomeCollectionCell, HomeCollectionItem.ID> {
107 [weak self] cell, _, identifier in
108 self?.configure(cell, identifier: identifier, now: .now)
109 }
110 self.registration = registration
111​
112 dataSource = UICollectionViewDiffableDataSource<Section, HomeCollectionItem.ID>(
113 collectionView: collectionView
114 ) { [weak self] collectionView, indexPath, identifier in
115 guard let self, let registration = self.registration else { return nil }
116 return collectionView.dequeueConfiguredReusableCell(
117 using: registration,
118 for: indexPath,
119 item: identifier
120 )
121 }
122​
123 update(parent: parent, collectionView: collectionView)
124 }
125​
126 func update(parent: HomeThreadCollectionView, collectionView: UICollectionView) {
127 self.parent = parent
128 hasQueuedUpdate = true
129 applyLatestSnapshot(in: collectionView)
130 }
131​
132 /// Keep a row's content and size fixed during its removal. Stream updates
133 /// that arrive mid-animation are applied together after that animation.
134 private func applyLatestSnapshot(in collectionView: UICollectionView) {
135 guard !isApplyingSnapshot, hasQueuedUpdate, let dataSource else { return }
136 hasQueuedUpdate = false
137 let previousItems = itemsByID
138 let previousThreadItemIDs = threadItemIDs
139 let previousSelection = selectedThreadID
140 selectedThreadID = parent.selectedThreadID
141​
142 var seenIdentifiers = Set<HomeCollectionItem.ID>()
143 var seenThreadIDs = Set<String>()
144 let items = parent.collectionItems.filter { item in
145 if let threadID = item.id.threadID, !seenThreadIDs.insert(threadID).inserted {
146 return false
147 }
148 return seenIdentifiers.insert(item.id).inserted
149 }
150 itemsByID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })
151 threadItemIDs = Dictionary(uniqueKeysWithValues: items.compactMap { item in
152 item.id.threadID.map { ($0, item.id) }
153 })
154 pullRequestsByThreadID = pullRequestsByThreadID.filter {
155 threadItemIDs[$0.key] != nil
156 }
157 // After items land: picks 1 Hz when a working thread is present,
158 // 60s otherwise, and is a no-op when the interval is unchanged.
159 startTimer()
160​
161 let currentIdentifiers = dataSource.snapshot().itemIdentifiers
162 let newIdentifiers = items.map(\.id)
163 let resolvedSwipes = pendingSwipeCompletions.filter { threadID, pending in
164 guard let identifier = threadItemIDs[threadID],
165 case let .thread(thread, _, _, _, _, _) = itemsByID[identifier] else {
166 return true
167 }
168 return thread.isEffectivelySettled() == pending.settled
169 }
170 let finishUpdate = { [weak self, weak collectionView] in
171 guard let self else { return }
172 for (threadID, pending) in resolvedSwipes {
173 guard self.pendingSwipeCompletions[threadID]?.id == pending.id else { continue }
174 self.pendingSwipeCompletions.removeValue(forKey: threadID)?.finish(true)
175 }
176 self.isApplyingSnapshot = false
177 guard let collectionView else { return }
178 self.synchronizeSelection(in: collectionView)
179 self.applyLatestSnapshot(in: collectionView)
180 }
181​
182 if currentIdentifiers == newIdentifiers {
183 let changed = newIdentifiers.filter { previousItems[$0] != itemsByID[$0] }
184 let selectionChanged = (previousSelection != selectedThreadID
185 ? [previousSelection, selectedThreadID] : [])
186 .compactMap { $0.flatMap { threadItemIDs[$0] } }
187 let identifiers = Array(Set(changed + selectionChanged))
188 if !identifiers.isEmpty {
189 var snapshot = dataSource.snapshot()
190 snapshot.reconfigureItems(identifiers)
191 isApplyingSnapshot = true
192 dataSource.apply(
193 snapshot,
194 animatingDifferences: false,
195 completion: finishUpdate
196 )
197 } else {
198 finishUpdate()
199 }
200 } else {
201 var snapshot = NSDiffableDataSourceSnapshot<Section, HomeCollectionItem.ID>()
202 snapshot.appendSections([.main])
203 snapshot.appendItems(newIdentifiers, toSection: .main)
204 // Retained rows also need fresh content when another row moves,
205 // arrives, or leaves in the same update.
206 let retained = Set(currentIdentifiers)
207 let selectionChanged = previousSelection != selectedThreadID
208 ? Set([previousSelection, selectedThreadID].compactMap { $0 }) : []
209 snapshot.reconfigureItems(newIdentifiers.filter { identifier in
210 retained.contains(identifier)
211 && (previousItems[identifier] != itemsByID[identifier]
212 || identifier.threadID.map(selectionChanged.contains) == true)
213 })
214 let shouldAnimate = !resolvedSwipes.isEmpty
215 && !currentIdentifiers.isEmpty
216 && collectionView.window != nil
217 && !UIAccessibility.isReduceMotionEnabled
218 if shouldAnimate {
219 for threadID in resolvedSwipes.keys {
220 guard let identifier = previousThreadItemIDs[threadID],
221 identifier != threadItemIDs[threadID],
222 let indexPath = dataSource.indexPath(for: identifier),
223 let cell = collectionView.cellForItem(at: indexPath) else { continue }
224 // UIKit fades deleted cells while their neighbors move up.
225 // Hide the departed text so it cannot show through those rows.
226 // The native swipe action view is outside contentView.
227 cell.contentView.isHidden = true
228 }
229 }
230 isApplyingSnapshot = true
231 dataSource.apply(
232 snapshot,
233 animatingDifferences: shouldAnimate,
234 completion: finishUpdate
235 )
236 }
237​
238 synchronizeSelection(in: collectionView)
239 }
240​
241 func invalidateTimer() {
242 timer?.invalidate()
243 timer = nil
244 }
245​
246 func cancelPendingSwipeActions() {
247 hasQueuedUpdate = false
248 pendingSwipeCompletions.values.forEach { $0.finish(false) }
249 pendingSwipeCompletions.removeAll()
250 }
251​
252 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
253 guard let item = item(at: indexPath) else { return }
254 switch item {
255 case let .thread(thread, _, _, _, _, _):
256 let previousSelection = selectedThreadID
257 selectedThreadID = thread.id
258 parent.onOpen(thread.id)
259 refreshSelection(
260 in: collectionView,
261 ids: [previousSelection, thread.id].compactMap { $0 }
262 )
263 case let .shelfHeader(shelf, _, _):
264 collectionView.deselectItem(at: indexPath, animated: false)
265 toggle(shelf)
266 case .showMoreSettled:
267 collectionView.deselectItem(at: indexPath, animated: false)
268 parent.onShowMoreSettled()
269 case .empty, .searchEmpty, .pinnedDivider:
270 collectionView.deselectItem(at: indexPath, animated: false)
271 }
272 }
273​
274 func collectionView(
275 _ collectionView: UICollectionView,
276 contextMenuConfigurationForItemAt indexPath: IndexPath,
277 point: CGPoint
278 ) -> UIContextMenuConfiguration? {
279 guard case let .thread(thread, context, _, isArchived, _, _) = item(at: indexPath) else {
280 return nil
281 }
282​
283 return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in
284 guard let self else { return nil }
285 return UIMenu(
286 children: self.menuActions(
287 for: thread,
288 context: context,
289 isArchived: isArchived
290 )
291 )
292 }
293 }
294​
295 func trailingSwipeActions(at indexPath: IndexPath) -> UISwipeActionsConfiguration? {
296 guard case let .thread(thread, _, _, isArchived, _, _) = item(at: indexPath) else {
297 return nil
298 }
299​
300 let actions = HomeThreadSwipeAction
301 .trailingActions(
302 for: thread,
303 isArchived: isArchived,
304 at: .now
305 )
306 let configuration = UISwipeActionsConfiguration(
307 actions: actions.map { contextualAction($0, for: thread) }
308 )
309 // A full swipe runs the edge action, which is only ever settlement.
310 // Delete can never reach that slot, so the gesture cannot destroy a
311 // thread; rows with nothing to settle keep the full swipe disabled.
312 configuration.performsFirstActionWithFullSwipe =
313 HomeThreadSwipeAction.performsFullSwipe(with: actions)
314 return configuration
315 }
316​
317 private func contextualAction(
318 _ action: HomeThreadSwipeAction,
319 for thread: FeatureThread
320 ) -> UIContextualAction {
321 let contextualAction = UIContextualAction(
322 style: action.style,
323 title: action.title
324 ) { [weak self] _, _, finish in
325 guard let self else {
326 finish(false)
327 return
328 }
329 self.performSwipe(action, for: thread, finish: finish)
330 }
331 contextualAction.image = UIImage(systemName: action.systemImage)
332 if let backgroundColor = action.backgroundColor {
333 contextualAction.backgroundColor = backgroundColor
334 }
335 return contextualAction
336 }
337​
338 func performSwipe(
339 _ action: HomeThreadSwipeAction,
340 for thread: FeatureThread,
341 finish: @escaping (Bool) -> Void
342 ) {
343 if case let .setSettled(settled) = action.intent {
344 guard pendingSwipeCompletions[thread.id] == nil else {
345 finish(false)
346 return
347 }
348 let completionID = UUID()
349 pendingSwipeCompletions[thread.id] = PendingSwipeCompletion(
350 id: completionID,
351 settled: settled,
352 finish: finish
353 )
354 PlatformHapticEngine.shared.selection(enabled: parent.hapticsEnabled)
355 parent.onSettle(thread, settled) { [weak self] succeeded in
356 guard !succeeded,
357 let self,
358 self.pendingSwipeCompletions[thread.id]?.id == completionID else {
359 return
360 }
361 self.pendingSwipeCompletions.removeValue(forKey: thread.id)?.finish(false)
362 }
363 } else {
364 perform(action.intent, for: thread)
365 finish(true)
366 }
367 }
368​
369 /// Swipe actions reuse the same closures the context menu does, so a
370 /// settle from either surface takes the one real settlement path.
371 private func perform(_ intent: HomeThreadSwipeAction.Intent, for thread: FeatureThread) {
372 switch intent {
373 case .delete:
374 parent.onDelete(thread)
375 case let .setArchived(archived):
376 parent.onArchive(thread, archived)
377 case let .setPinned(pinned):
378 parent.onPin(thread, pinned)
379 case let .setSettled(settled):
380 parent.onSettle(thread, settled) { _ in }
381 }
382 }
383​
384 private func configure(
385 _ cell: HomeCollectionCell,
386 identifier: HomeCollectionItem.ID,
387 now: Date
388 ) {
389 guard let item = itemsByID[identifier] else { return }
390 cell.contentView.isHidden = false
391 let pullRequestObservationIdentity: String?
392 if case let .thread(thread, _, _, _, _, _) = item {
393 pullRequestObservationIdentity = thread.pullRequestObservationIdentity
394 } else {
395 pullRequestObservationIdentity = nil
396 }
397 cell.contentConfiguration = UIHostingConfiguration {
398 HomeCollectionCellContent(
399 item: item,
400 projectFaviconClient: parent.projectFaviconClient,
401 isSelected: identifier.threadID == selectedThreadID,
402 now: now,
403 onPullRequestChange: { [weak self, weak cell] pullRequest in
404 guard let self,
405 let cell,
406 let threadID = identifier.threadID else {
407 return
408 }
409 self.updatePullRequestAccessibility(
410 pullRequest,
411 threadID: threadID,
412 cell: cell
413 )
414 if let observationIdentity = pullRequestObservationIdentity {
415 self.parent.onPullRequestChange(
416 threadID,
417 observationIdentity,
418 pullRequest
419 )
420 }
421 }
422 )
423 }
424 .margins(.all, 0)
425​
426 cell.backgroundConfiguration = UIBackgroundConfiguration.clear()
427 cell.accessories = []
428 cell.tintColor = T3Colors.uiTextPrimary
429 cell.clipsToBounds = true
430 cell.contentView.clipsToBounds = true
431 cell.contentView.accessibilityElementsHidden = true
432 configureAccessibility(cell, item: item)
433 }
434​
435 private func configureAccessibility(_ cell: HomeCollectionCell, item: HomeCollectionItem) {
436 cell.accessibilityCustomActions = nil
437 switch item {
438 case let .thread(thread, context, _, isArchived, _, _):
439 cell.isAccessibilityElement = true
440 cell.accessibilityTraits = selectedThreadID == thread.id
441 ? [.button, .selected]
442 : .button
443 cell.accessibilityLabel = thread.title
444 cell.accessibilityValue = threadAccessibilityValue(thread, context: context)
445 cell.accessibilityHint = "Opens thread. More actions are available."
446 cell.accessibilityCustomActions = threadAccessibilityActions(
447 for: thread,
448 isArchived: isArchived
449 )
450 cell.onAccessibilityActivate = { [weak self] in
451 guard let self else { return }
452 let previousSelection = self.selectedThreadID
453 self.selectedThreadID = thread.id
454 self.parent.onOpen(thread.id)
455 if let collectionView = self.collectionView {
456 self.refreshSelection(
457 in: collectionView,
458 ids: [previousSelection, thread.id].compactMap { $0 }
459 )
460 }
461 }
462 case let .shelfHeader(shelf, count, isExpanded):
463 cell.isAccessibilityElement = true
464 cell.accessibilityTraits = .button
465 cell.accessibilityLabel = "\(shelf.title), \(count) \(count == 1 ? "task" : "tasks")"
466 cell.accessibilityValue = isExpanded ? "Expanded" : "Collapsed"
467 cell.accessibilityHint = isExpanded ? "Collapses the task list" : "Expands the task list"
468 cell.onAccessibilityActivate = { [weak self] in self?.toggle(shelf) }
469 case let .showMoreSettled(remaining):
470 cell.isAccessibilityElement = true
471 cell.accessibilityTraits = .button
472 cell.accessibilityLabel = "Show \(remaining) more settled \(remaining == 1 ? "task" : "tasks")"
473 cell.accessibilityValue = nil
474 cell.accessibilityHint = nil
475 cell.onAccessibilityActivate = { [weak self] in
476 self?.parent.onShowMoreSettled()
477 }
478 case let .empty(shelf):
479 cell.isAccessibilityElement = true
480 cell.accessibilityTraits = .staticText
481 cell.accessibilityLabel = shelf == .active ? "No active tasks" : "No \(shelf.title.lowercased()) tasks"
482 cell.accessibilityValue = nil
483 cell.accessibilityHint = nil
484 cell.onAccessibilityActivate = nil
485 case .searchEmpty:
486 cell.isAccessibilityElement = true
487 cell.accessibilityTraits = .staticText
488 cell.accessibilityLabel = "No matching tasks"
489 cell.accessibilityValue = nil
490 cell.accessibilityHint = nil
491 cell.onAccessibilityActivate = nil
492 case .pinnedDivider:
493 cell.isAccessibilityElement = false
494 cell.onAccessibilityActivate = nil
495 }
496 }
497​
498 private func threadAccessibilityValue(
499 _ thread: FeatureThread,
500 context: HomeThreadRowContext
501 ) -> String {
502 var status = thread.homeStatusLabel ?? "Ready"
503 if let duration = thread.homeWorkingDuration(at: .now) {
504 status += " for \(duration)"
505 }
506 var values = [status, "Project \(context.projectName)"]
507 if let pullRequest = pullRequestsByThreadID[thread.id] {
508 values.append(pullRequest.accessibilityLabel)
509 }
510 if thread.pinnedAt != nil {
511 values.append("Pinned")
512 }
513 if thread.isArchived {
514 values.append("Archived")
515 } else if thread.isEffectivelySnoozed(at: .now) {
516 values.append("Snoozed")
517 } else if thread.isEffectivelySettled() {
518 values.append("Settled")
519 }
520 values.append("Provider \(context.providerName)")
521 if let environment = context.environmentLabel {
522 values.append("on \(environment)")
523 }
524 return values.joined(separator: ". ")
525 }
526​
527 private func updatePullRequestAccessibility(
528 _ pullRequest: HomeThreadPullRequestPresentation?,
529 threadID: String,
530 cell: HomeCollectionCell
531 ) {
532 guard let identifier = threadItemIDs[threadID],
533 case let .thread(thread, context, _, _, _, _) = itemsByID[identifier],
534 let indexPath = dataSource?.indexPath(for: identifier),
535 collectionView?.cellForItem(at: indexPath) === cell else {
536 return
537 }
538 if let pullRequest {
539 pullRequestsByThreadID[threadID] = pullRequest
540 } else {
541 pullRequestsByThreadID.removeValue(forKey: threadID)
542 }
543 cell.accessibilityValue = threadAccessibilityValue(thread, context: context)
544 }
545​
546 private func threadAccessibilityActions(
547 for thread: FeatureThread,
548 isArchived: Bool
549 ) -> [UIAccessibilityCustomAction] {
550 var actions = [accessibilityAction("Rename", systemImage: "pencil") { coordinator in
551 coordinator.parent.onRename(thread)
552 }]
553​
554 if thread.supportsTitleRegeneration == true {
555 actions.append(accessibilityAction("Regenerate title", systemImage: "sparkles") { coordinator in
556 coordinator.parent.onRegenerateTitle(thread)
557 })
558 }
559​
560 if !isArchived {
561 if thread.canTogglePin {
562 let isPinned = thread.pinnedAt != nil
563 actions.append(accessibilityAction(
564 isPinned ? "Unpin" : "Pin",
565 systemImage: isPinned ? "pin.slash" : "pin"
566 ) { coordinator in
567 coordinator.parent.onPin(thread, !isPinned)
568 })
569 }
570​
571 let isSettled = thread.isEffectivelySettled()
572 if isSettled || thread.canSettleNow() {
573 actions.append(accessibilityAction(
574 isSettled ? "Reopen" : "Settle",
575 systemImage: isSettled ? "arrow.counterclockwise" : "checkmark"
576 ) { coordinator in
577 coordinator.parent.onSettle(thread, !isSettled) { _ in }
578 })
579 }
580​
581 if thread.canToggleSnooze {
582 if thread.isEffectivelySnoozed(at: .now) {
583 actions.append(accessibilityAction("Wake", systemImage: "bell") { coordinator in
584 coordinator.parent.onSnooze(thread, nil)
585 })
586 } else if thread.state != .queued,
587 thread.state != .waitingForApproval,
588 thread.state != .waitingForInput {
589 actions.append(contentsOf: DailyUXSnoozePresets.resolve(now: .now).map { preset in
590 accessibilityAction("Snooze: \(preset.label)", systemImage: "clock") { coordinator in
591 coordinator.parent.onSnooze(thread, preset.until)
592 }
593 })
594 }
595 }
596 }
597​
598 actions.append(accessibilityAction(
599 isArchived ? "Restore" : "Archive",
600 systemImage: isArchived ? "arrow.uturn.backward" : "archivebox"
601 ) { coordinator in
602 coordinator.parent.onArchive(thread, !isArchived)
603 })
604 actions.append(accessibilityAction("Delete thread", systemImage: "trash") { coordinator in
605 coordinator.parent.onDelete(thread)
606 })
607 return actions
608 }
609​
610 private func accessibilityAction(
611 _ title: String,
612 systemImage: String,
613 perform: @escaping (Coordinator) -> Void
614 ) -> UIAccessibilityCustomAction {
615 UIAccessibilityCustomAction(name: title, image: UIImage(systemName: systemImage)) { [weak self] _ in
616 guard let self else { return false }
617 perform(self)
618 return true
619 }
620 }
621​
622 private func synchronizeSelection(in collectionView: UICollectionView) {
623 for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
624 guard dataSource?.itemIdentifier(for: indexPath)?.threadID != selectedThreadID else {
625 continue
626 }
627 collectionView.deselectItem(at: indexPath, animated: false)
628 }
629 guard let selectedThreadID,
630 let identifier = threadItemIDs[selectedThreadID],
631 let indexPath = dataSource?.indexPath(for: identifier),
632 !collectionView.indexPathsForSelectedItems.orEmpty.contains(indexPath) else {
633 return
634 }
635 collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
636 }
637​
638 private func refreshSelection(in collectionView: UICollectionView, ids: [String]) {
639 for id in ids {
640 guard let identifier = threadItemIDs[id],
641 let indexPath = dataSource?.indexPath(for: identifier),
642 let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionCell else {
643 continue
644 }
645 configure(cell, identifier: identifier, now: .now)
646 }
647 }
648​
649 private func item(at indexPath: IndexPath) -> HomeCollectionItem? {
650 guard let identifier = dataSource?.itemIdentifier(for: indexPath) else { return nil }
651 return itemsByID[identifier]
652 }
653​
654 private func toggle(_ shelf: HomeShelf) {
655 switch shelf {
656 case .snoozed: parent.onToggleSnoozed()
657 case .settled: parent.onToggleSettled()
658 case .archived: parent.onToggleArchive()
659 case .active: break
660 }
661 }
662​
663 private func menuActions(
664 for thread: FeatureThread,
665 context: HomeThreadRowContext,
666 isArchived: Bool
667 ) -> [UIMenuElement] {
668 let rename = UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in
669 self?.parent.onRename(thread)
670 }
671​
672 var titleActions: [UIMenuElement] = [rename]
673 if thread.supportsTitleRegeneration == true {
674 titleActions.append(
675 UIAction(
676 title: "Regenerate title",
677 image: UIImage(systemName: "sparkles")
678 ) { [weak self] _ in
679 self?.parent.onRegenerateTitle(thread)
680 }
681 )
682 }
683 let copyActions = ThreadCopyModel.menuActions(
684 for: thread,
685 context: context.copyContext
686 )
687 if !copyActions.isEmpty {
688 titleActions.append(
689 UIMenu(
690 title: "Copy",
691 image: UIImage(systemName: "doc.on.doc"),
692 children: copyActions.map { action in
693 UIAction(
694 title: action.kind.title,
695 image: UIImage(systemName: action.kind.systemImage),
696 attributes: action.isAvailable ? [] : .disabled
697 ) { _ in
698 ThreadCopyClipboard.copy(action)
699 }
700 }
701 )
702 )
703 }
704​
705 var statusActions: [UIMenuElement] = []
706 if !isArchived {
707 if thread.canTogglePin {
708 let isPinned = thread.pinnedAt != nil
709 statusActions.append(
710 UIAction(
711 title: isPinned ? "Unpin" : "Pin",
712 image: UIImage(systemName: isPinned ? "pin.slash" : "pin")
713 ) { [weak self] _ in
714 self?.parent.onPin(thread, !isPinned)
715 }
716 )
717 }
718 let isSettled = thread.isEffectivelySettled()
719 if isSettled || thread.canSettleNow() {
720 statusActions.append(
721 UIAction(
722 title: isSettled ? "Reopen" : "Settle",
723 image: UIImage(
724 systemName: isSettled ? "arrow.counterclockwise" : "checkmark"
725 )
726 ) { [weak self] _ in
727 self?.parent.onSettle(thread, !isSettled) { _ in }
728 }
729 )
730 }
731​
732 if thread.canToggleSnooze {
733 let isSnoozed = thread.isEffectivelySnoozed(at: .now)
734 if isSnoozed {
735 statusActions.append(
736 UIAction(title: "Wake", image: UIImage(systemName: "bell")) {
737 [weak self] _ in
738 self?.parent.onSnooze(thread, nil)
739 }
740 )
741 } else {
742 let presets = DailyUXSnoozePresets.resolve(now: .now)
743 let children = presets.map { preset in
744 UIAction(title: preset.label) { [weak self] _ in
745 self?.parent.onSnooze(thread, preset.until)
746 }
747 }
748 let snoozeIsDisabled = thread.state == .queued
749 || thread.state == .waitingForApproval
750 || thread.state == .waitingForInput
751 if snoozeIsDisabled {
752 children.forEach { $0.attributes = .disabled }
753 }
754 let snooze = UIMenu(
755 title: "Snooze",
756 image: UIImage(systemName: "clock"),
757 children: children
758 )
759 statusActions.append(snooze)
760 }
761 }
762 }
763​
764 let archive = UIAction(
765 title: isArchived ? "Restore" : "Archive",
766 image: UIImage(systemName: isArchived ? "arrow.uturn.backward" : "archivebox")
767 ) { [weak self] _ in
768 self?.parent.onArchive(thread, !isArchived)
769 }
770 let delete = UIAction(
771 title: "Delete thread",
772 image: UIImage(systemName: "trash"),
773 attributes: .destructive
774 ) { [weak self] _ in
775 self?.parent.onDelete(thread)
776 }
777​
778 var sections = [UIMenu(options: .displayInline, children: titleActions)]
779 if !statusActions.isEmpty {
780 sections.append(UIMenu(options: .displayInline, children: statusActions))
781 }
782 sections.append(UIMenu(options: .displayInline, children: [archive]))
783 sections.append(UIMenu(options: .displayInline, children: [delete]))
784 return sections
785 }
786​
787 /// Working rows show a live per-second duration, so they need a 1 Hz
788 /// tick. Without any, relative ages only change by the minute, and the
789 /// timer idles down to match instead of waking the main thread every
790 /// second for the lifetime of the sidebar.
791 private func startTimer() {
792 let interval: TimeInterval = itemsByID.values.contains {
793 if case let .thread(thread, _, _, _, _, _) = $0 {
794 return thread.homeStatus == .working
795 }
796 return false
797 } ? 1 : 60
798​
799 if timer != nil, timerInterval == interval { return }
800 invalidateTimer()
801 timerInterval = interval
802 timerTick = 0
803 timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
804 MainActor.assumeIsolated {
805 self?.refreshVisibleTimes()
806 }
807 }
808 timer?.tolerance = interval * 0.12
809 }
810​
811 private func refreshVisibleTimes() {
812 guard !isApplyingSnapshot,
813 let collectionView, let dataSource,
814 !collectionView.isTracking, !collectionView.isDecelerating else { return }
815 timerTick = (timerTick + 1) % 60
816 let refreshRelativeAges = timerInterval >= 60 || timerTick == 0
817 let now = Date.now
818​
819 for indexPath in collectionView.indexPathsForVisibleItems {
820 guard let identifier = dataSource.itemIdentifier(for: indexPath),
821 case let .thread(thread, _, _, _, _, _) = itemsByID[identifier],
822 refreshRelativeAges || thread.homeStatus == .working,
823 let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionCell else {
824 continue
825 }
826 configure(cell, identifier: identifier, now: now)
827 }
828 }
829 }
830​
831 var collectionItems: [HomeCollectionItem] {
832 let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
833 if !normalizedQuery.isEmpty {
834 if presentation.searchResults.isEmpty {
835 return [.searchEmpty(normalizedQuery)]
836 }
837 return presentation.searchResults.map {
838 .thread(
839 $0,
840 presentation.rowContexts[$0.id] ?? .fallback,
841 .rich,
842 $0.isArchived,
843 forceRichRows,
844 nil
845 )
846 }
847 }
848​
849 var items = presentation.pinned.map {
850 HomeCollectionItem.thread(
851 $0,
852 presentation.rowContexts[$0.id] ?? .fallback,
853 .rich,
854 false,
855 forceRichRows,
856 .active
857 )
858 }
859 if !presentation.pinned.isEmpty, !presentation.active.isEmpty {
860 items.append(.pinnedDivider)
861 }
862 if presentation.active.isEmpty, presentation.pinned.isEmpty {
863 items.append(.empty(.active))
864 } else {
865 items.append(contentsOf: presentation.active.map {
866 .thread(
867 $0,
868 presentation.rowContexts[$0.id] ?? .fallback,
869 .rich,
870 false,
871 forceRichRows,
872 .active
873 )
874 })
875 }
876​
877 if !presentation.snoozed.isEmpty {
878 items.append(.shelfHeader(.snoozed, presentation.snoozed.count, isSnoozedExpanded))
879 if isSnoozedExpanded {
880 items.append(contentsOf: presentation.snoozed.map {
881 .thread(
882 $0,
883 presentation.rowContexts[$0.id] ?? .fallback,
884 forceRichRows ? .rich : .slim,
885 false,
886 forceRichRows,
887 .snoozed
888 )
889 })
890 }
891 }
892​
893 if !presentation.settled.isEmpty {
894 items.append(.shelfHeader(.settled, presentation.settled.count, isSettledExpanded))
895 if isSettledExpanded {
896 items.append(contentsOf: presentation.settled.prefix(settledLimit).map {
897 .thread(
898 $0,
899 presentation.rowContexts[$0.id] ?? .fallback,
900 forceRichRows ? .rich : .slim,
901 false,
902 forceRichRows,
903 .settled
904 )
905 })
906 if presentation.settled.count > settledLimit {
907 items.append(.showMoreSettled(presentation.settled.count - settledLimit))
908 }
909 }
910 }
911​
912 if !presentation.archived.isEmpty {
913 items.append(.shelfHeader(.archived, presentation.archived.count, isArchiveExpanded))
914 if isArchiveExpanded {
915 items.append(contentsOf: presentation.archived.map {
916 .thread(
917 $0,
918 presentation.rowContexts[$0.id] ?? .fallback,
919 forceRichRows ? .rich : .slim,
920 true,
921 forceRichRows,
922 .archived
923 )
924 })
925 }
926 }
927 return items
928 }
930​
931/// The trailing swipe actions a Home row offers, resolved as data so the row's
932/// gesture semantics stay deterministic and testable without hosting a
933/// collection view. Order is outermost-first, matching
934/// `UISwipeActionsConfiguration`, which lays trailing actions out from the
935/// trailing edge inward and runs the first action on a full swipe.
936enum HomeThreadSwipeAction: Equatable {
937 case delete
938 case restore
939 case unpin
940 case settle
941 case reopen
942 case archive
943​
944 /// The lifecycle mutation an action requests. Keeping it separate from the
945 /// action keeps the swipe wiring verifiable and forces every case through
946 /// the row's existing callbacks instead of a second settlement path.
947 enum Intent: Equatable {
948 case delete
949 case setArchived(Bool)
950 case setPinned(Bool)
951 case setSettled(Bool)
952 }
953​
954 /// Settlement owns the edge slot on every row that can settle, so a full
955 /// swipe clears the task in one motion and a partial swipe still reveals
956 /// every button. Delete is always last and therefore can never be the
957 /// full-swipe action. A pinned row keeps Unpin between the two: settling
958 /// already clears the pin, so the full swipe unpins and settles together.
959 /// Archived rows stay restore-only, and a row with nothing to settle keeps
960 /// its reversible action at the edge with the full swipe turned off.
961 static func trailingActions(
962 for thread: FeatureThread,
963 isArchived: Bool,
964 at now: Date
965 ) -> [HomeThreadSwipeAction] {
966 guard !isArchived else { return [.restore, .delete] }
967​
968 let isSettled = thread.isEffectivelySettled()
969 let settlement: HomeThreadSwipeAction? = isSettled
970 ? .reopen
971 : (thread.canSettleNow(at: now) ? .settle : nil)
972 let isPinned = thread.pinnedAt != nil && thread.canTogglePin
973​
974 var actions: [HomeThreadSwipeAction] = []
975 if let settlement {
976 actions.append(settlement)
977 if isPinned {
978 actions.append(.unpin)
979 }
980 } else if isPinned {
981 actions.append(.unpin)
982 } else {
983 actions.append(.archive)
984 }
985 actions.append(.delete)
986 return actions
987 }
988​
989 /// The full swipe is armed only when the edge action settles or reopens.
990 /// Nothing else may run from the gesture alone.
991 static func performsFullSwipe(with actions: [HomeThreadSwipeAction]) -> Bool {
992 actions.first?.isSettlement ?? false
993 }
994​
995 var isSettlement: Bool {
996 self == .settle || self == .reopen
997 }
998​
999 var intent: Intent {
1000 switch self {
1001 case .delete: .delete
1002 case .restore: .setArchived(false)
1003 case .archive: .setArchived(true)
1004 case .unpin: .setPinned(false)
1005 case .settle: .setSettled(true)
1006 case .reopen: .setSettled(false)
1009​
1010 var title: String {
1011 switch self {
1012 case .delete: "Delete"
1013 case .restore: "Restore"
1014 case .unpin: "Unpin"
1015 case .settle: "Settle"
1016 case .reopen: "Reopen"
1017 case .archive: "Archive"
1020​
1021 var systemImage: String {
1022 switch self {
1023 case .delete: "trash"
1024 case .restore: "arrow.uturn.backward"
1025 case .unpin: "pin.slash"
1026 case .settle: "checkmark"
1027 case .reopen: "arrow.counterclockwise"
1028 case .archive: "archivebox"
1031​
1032 var style: UIContextualAction.Style {
1033 self == .delete ? .destructive : .normal
1035​
1036 /// Destructive actions keep UIKit's own tint.
1037 var backgroundColor: UIColor? {
1038 switch self {
1039 case .delete: nil
1040 case .restore, .unpin, .reopen: .systemBlue
1041 case .settle: .systemGreen
1042 case .archive: .systemGray
1046​
1047private final class HomeCollectionCell: UICollectionViewListCell {
1048 var onAccessibilityActivate: (() -> Void)?
1049​
1050 override func accessibilityActivate() -> Bool {
1051 guard let onAccessibilityActivate else { return super.accessibilityActivate() }
1052 onAccessibilityActivate()
1053 return true
1055​
1056 override func prepareForReuse() {
1057 super.prepareForReuse()
1058 contentView.isHidden = false
1059 onAccessibilityActivate = nil
1062​
1063enum HomeShelf: String, Hashable {
1064 case active
1065 case snoozed
1066 case settled
1067 case archived
1068​
1069 var title: String {
1070 rawValue.capitalized
1073​
1074enum HomeCollectionItem: Equatable {
1075 enum ID: Hashable {
1076 // A shelf change replaces the cell. Moving the same cell while it
1077 // changes between rich and slim layouts makes its height jump mid-swipe.
1078 case thread(String, HomeShelf?)
1079 case shelfHeader(HomeShelf)
1080 case empty(HomeShelf)
1081 case showMoreSettled
1082 case searchEmpty
1083 case pinnedDivider
1084​
1085 var threadID: String? {
1086 guard case let .thread(id, _) = self else { return nil }
1087 return id
1090​
1091 case thread(FeatureThread, HomeThreadRowContext, FeatureThreadRow.Style, Bool, Bool, HomeShelf?)
1092 case shelfHeader(HomeShelf, Int, Bool)
1093 case empty(HomeShelf)
1094 case showMoreSettled(Int)
1095 case searchEmpty(String)
1096 case pinnedDivider
1097​
1098 var id: ID {
1099 switch self {
1100 case let .thread(thread, _, _, _, _, shelf): .thread(thread.id, shelf)
1101 case let .shelfHeader(shelf, _, _): .shelfHeader(shelf)
1102 case let .empty(shelf): .empty(shelf)
1103 case .showMoreSettled: .showMoreSettled
1104 case .searchEmpty: .searchEmpty
1105 case .pinnedDivider: .pinnedDivider
1109​
1110private struct HomeCollectionCellContent: View {
1111 let item: HomeCollectionItem
1112 let projectFaviconClient: any FeatureClient
1113 let isSelected: Bool
1114 let now: Date
1115 let onPullRequestChange: (HomeThreadPullRequestPresentation?) -> Void
1116​
1117 @ViewBuilder
1118 var body: some View {
1119 switch item {
1120 case let .thread(thread, context, style, _, allowsMultilineTitle, _):
1121 FeatureThreadRow(
1122 thread: thread,
1123 context: context,
1124 projectFaviconClient: projectFaviconClient,
1125 onPullRequestChange: onPullRequestChange,
1126 isSelected: isSelected,
1127 style: style,
1128 now: now,
1129 allowsMultilineTitle: allowsMultilineTitle
1131 case let .shelfHeader(shelf, count, isExpanded):
1132 HomeShelfHeader(
1133 title: shelf.title,
1134 count: count,
1135 isExpanded: isExpanded,
1136 accent: shelf == .snoozed ? T3Colors.accent : nil
1138 case let .empty(shelf):
1139 Text(shelf == .active ? "No active tasks" : "None")
1140 .font(T3Typography.homeMetadata)
1141 .foregroundStyle(T3Colors.textTertiary)
1142 .frame(maxWidth: .infinity, minHeight: shelf == .active ? 68 : 34, alignment: .center)
1143 case let .showMoreSettled(remaining):
1144 HStack {
1145 Text("Show more")
1146 Spacer()
1147 Text("\(remaining)")
1148 .monospacedDigit()
1149 .foregroundStyle(T3Colors.textTertiary)
1151 .font(T3Typography.homeMetadata.weight(.semibold))
1152 .foregroundStyle(T3Colors.textSecondary)
1153 .padding(.horizontal, 34)
1154 .frame(minHeight: T3Metrics.minimumTapTarget)
1155 case .searchEmpty:
1156 ContentUnavailableView("No matching tasks", systemImage: "magnifyingglass")
1157 .foregroundStyle(T3Colors.textSecondary)
1158 .frame(maxWidth: .infinity, minHeight: 160)
1159 case .pinnedDivider:
1160 Rectangle()
1161 .fill(T3Colors.textTertiary.opacity(0.18))
1162 .frame(height: 1)
1163 .padding(.horizontal, 18)
1164 .padding(.vertical, 3)
1168​
1169private extension Optional where Wrapped == [IndexPath] {
1170 var orEmpty: [IndexPath] { self ?? [] }