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

HomeThreadCollectionView.swift

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