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

HomeThreadCollectionView.swift

836 lines32.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 isSnoozedExpanded: Bool
13 let isSettledExpanded: Bool
14 let isArchiveExpanded: Bool
15 let settledLimit: Int
16 let onOpen: (String) -> Void
17 let onToggleSnoozed: () -> Void
18 let onToggleSettled: () -> Void
19 let onToggleArchive: () -> Void
20 let onShowMoreSettled: () -> Void
21 let onRename: (FeatureThread) -> Void
22 let onRegenerateTitle: (FeatureThread) -> Void
23 let onArchive: (FeatureThread, Bool) -> Void
24 let onSettle: (FeatureThread, Bool) -> Void
25 let onSnooze: (FeatureThread, Date?) -> Void
26 let onPin: (FeatureThread, Bool) -> Void
27 let onDelete: (FeatureThread) -> Void
28​
29 func makeCoordinator() -> Coordinator {
30 Coordinator(parent: self)
31 }
32​
33 func makeUIView(context: Context) -> UICollectionView {
34 var configuration = UICollectionLayoutListConfiguration(appearance: .plain)
35 configuration.backgroundColor = T3Colors.uiBackground
36 configuration.showsSeparators = false
37 configuration.headerMode = .none
38 configuration.footerMode = .none
39 configuration.trailingSwipeActionsConfigurationProvider = { [weak coordinator = context.coordinator] indexPath in
40 coordinator?.trailingSwipeActions(at: indexPath)
41 }
42​
43 let collectionView = UICollectionView(
44 frame: .zero,
45 collectionViewLayout: UICollectionViewCompositionalLayout.list(using: configuration)
46 )
47 collectionView.backgroundColor = T3Colors.uiBackground
48 collectionView.alwaysBounceVertical = true
49 collectionView.keyboardDismissMode = .interactive
50 collectionView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 74, right: 0)
51 collectionView.verticalScrollIndicatorInsets = UIEdgeInsets(top: 4, left: 0, bottom: 74, right: 0)
52 collectionView.delegate = context.coordinator
53 context.coordinator.configure(collectionView)
54 return collectionView
55 }
56​
57 func updateUIView(_ collectionView: UICollectionView, context: Context) {
58 context.coordinator.update(parent: self, collectionView: collectionView)
59 }
60​
61 static func dismantleUIView(_ collectionView: UICollectionView, coordinator: Coordinator) {
62 coordinator.invalidateTimer()
63 collectionView.delegate = nil
64 }
65​
66 @MainActor
67 final class Coordinator: NSObject, UICollectionViewDelegate {
68 private enum Section: Hashable {
69 case main
70 }
71​
72 private var parent: HomeThreadCollectionView
73 private var dataSource: UICollectionViewDiffableDataSource<Section, HomeCollectionItem.ID>?
74 private var registration: UICollectionView.CellRegistration<HomeCollectionCell, HomeCollectionItem.ID>?
75 private var itemsByID: [HomeCollectionItem.ID: HomeCollectionItem] = [:]
76 private var selectedThreadID: String?
77 private weak var collectionView: UICollectionView?
78 private var timer: Timer?
79 private var timerTick = 0
80 private var timerInterval: TimeInterval = 0
81​
82 init(parent: HomeThreadCollectionView) {
83 self.parent = parent
84 selectedThreadID = parent.selectedThreadID
85 }
86​
87 func configure(_ collectionView: UICollectionView) {
88 self.collectionView = collectionView
89​
90 let registration = UICollectionView.CellRegistration<HomeCollectionCell, HomeCollectionItem.ID> {
91 [weak self] cell, _, identifier in
92 self?.configure(cell, identifier: identifier, now: .now)
93 }
94 self.registration = registration
95​
96 dataSource = UICollectionViewDiffableDataSource<Section, HomeCollectionItem.ID>(
97 collectionView: collectionView
98 ) { [weak self] collectionView, indexPath, identifier in
99 guard let self, let registration = self.registration else { return nil }
100 return collectionView.dequeueConfiguredReusableCell(
101 using: registration,
102 for: indexPath,
103 item: identifier
104 )
105 }
106​
107 update(parent: parent, collectionView: collectionView)
108 }
109​
110 func update(parent: HomeThreadCollectionView, collectionView: UICollectionView) {
111 let previousItems = itemsByID
112 let previousSelection = selectedThreadID
113 self.parent = parent
114 selectedThreadID = parent.selectedThreadID
115​
116 var seenIdentifiers = Set<HomeCollectionItem.ID>()
117 let items = parent.collectionItems.filter { item in
118 seenIdentifiers.insert(item.id).inserted
119 }
120 itemsByID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) })
121 // After items land: picks 1 Hz when a working thread is present,
122 // 60s otherwise, and is a no-op when the interval is unchanged.
123 startTimer()
124​
125 guard let dataSource else { return }
126 let currentIdentifiers = dataSource.snapshot().itemIdentifiers
127 let newIdentifiers = items.map(\.id)
128​
129 if currentIdentifiers == newIdentifiers {
130 let changed = newIdentifiers.filter { previousItems[$0] != itemsByID[$0] }
131 let selectionChanged = [previousSelection, selectedThreadID]
132 .compactMap { $0.map(HomeCollectionItem.ID.thread) }
133 .filter { newIdentifiers.contains($0) }
134 let identifiers = Array(Set(changed + selectionChanged))
135 if !identifiers.isEmpty {
136 var snapshot = dataSource.snapshot()
137 snapshot.reconfigureItems(identifiers)
138 dataSource.apply(snapshot, animatingDifferences: false)
139 }
140 } else {
141 var snapshot = NSDiffableDataSourceSnapshot<Section, HomeCollectionItem.ID>()
142 snapshot.appendSections([.main])
143 snapshot.appendItems(newIdentifiers, toSection: .main)
144 dataSource.apply(snapshot, animatingDifferences: false)
145 }
146​
147 synchronizeSelection(in: collectionView)
148 }
149​
150 func invalidateTimer() {
151 timer?.invalidate()
152 timer = nil
153 }
154​
155 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
156 guard let item = item(at: indexPath) else { return }
157 switch item {
158 case let .thread(thread, _, _, _, _):
159 let previousSelection = selectedThreadID
160 selectedThreadID = thread.id
161 parent.onOpen(thread.id)
162 refreshSelection(
163 in: collectionView,
164 ids: [previousSelection, thread.id].compactMap { $0 }
165 )
166 case let .shelfHeader(shelf, _, _):
167 collectionView.deselectItem(at: indexPath, animated: false)
168 toggle(shelf)
169 case .showMoreSettled:
170 collectionView.deselectItem(at: indexPath, animated: false)
171 parent.onShowMoreSettled()
172 case .empty, .searchEmpty, .pinnedDivider:
173 collectionView.deselectItem(at: indexPath, animated: false)
174 }
175 }
176​
177 func collectionView(
178 _ collectionView: UICollectionView,
179 contextMenuConfigurationForItemAt indexPath: IndexPath,
180 point: CGPoint
181 ) -> UIContextMenuConfiguration? {
182 guard case let .thread(thread, _, _, isArchived, _) = item(at: indexPath) else {
183 return nil
184 }
185​
186 return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in
187 guard let self else { return nil }
188 return UIMenu(children: self.menuActions(for: thread, isArchived: isArchived))
189 }
190 }
191​
192 func trailingSwipeActions(at indexPath: IndexPath) -> UISwipeActionsConfiguration? {
193 guard case let .thread(thread, _, _, isArchived, _) = item(at: indexPath) else {
194 return nil
195 }
196​
197 let actions = HomeThreadSwipeAction
198 .trailingActions(for: thread, isArchived: isArchived, at: .now)
199 let configuration = UISwipeActionsConfiguration(
200 actions: actions.map { contextualAction($0, for: thread) }
201 )
202 // A full swipe runs the edge action, which is only ever settlement.
203 // Delete can never reach that slot, so the gesture cannot destroy a
204 // thread; rows with nothing to settle keep the full swipe disabled.
205 configuration.performsFirstActionWithFullSwipe =
206 HomeThreadSwipeAction.performsFullSwipe(with: actions)
207 return configuration
208 }
209​
210 private func contextualAction(
211 _ action: HomeThreadSwipeAction,
212 for thread: FeatureThread
213 ) -> UIContextualAction {
214 let contextualAction = UIContextualAction(
215 style: action.style,
216 title: action.title
217 ) { [weak self] _, _, finish in
218 self?.perform(action.intent, for: thread)
219 finish(true)
220 }
221 contextualAction.image = UIImage(systemName: action.systemImage)
222 if let backgroundColor = action.backgroundColor {
223 contextualAction.backgroundColor = backgroundColor
224 }
225 return contextualAction
226 }
227​
228 /// Swipe actions reuse the same closures the context menu does, so a
229 /// settle from either surface takes the one real settlement path.
230 private func perform(_ intent: HomeThreadSwipeAction.Intent, for thread: FeatureThread) {
231 switch intent {
232 case .delete:
233 parent.onDelete(thread)
234 case let .setArchived(archived):
235 parent.onArchive(thread, archived)
236 case let .setPinned(pinned):
237 parent.onPin(thread, pinned)
238 case let .setSettled(settled):
239 parent.onSettle(thread, settled)
240 }
241 }
242​
243 private func configure(
244 _ cell: HomeCollectionCell,
245 identifier: HomeCollectionItem.ID,
246 now: Date
247 ) {
248 guard let item = itemsByID[identifier] else { return }
249 cell.contentConfiguration = UIHostingConfiguration {
250 HomeCollectionCellContent(
251 item: item,
252 projectFaviconClient: parent.projectFaviconClient,
253 isSelected: identifier.threadID == selectedThreadID,
254 now: now
255 )
256 }
257 .margins(.all, 0)
258​
259 cell.backgroundConfiguration = UIBackgroundConfiguration.clear()
260 cell.accessories = []
261 cell.tintColor = T3Colors.uiTextPrimary
262 cell.contentView.accessibilityElementsHidden = true
263 configureAccessibility(cell, item: item)
264 }
265​
266 private func configureAccessibility(_ cell: HomeCollectionCell, item: HomeCollectionItem) {
267 switch item {
268 case let .thread(thread, context, _, _, _):
269 cell.isAccessibilityElement = true
270 cell.accessibilityTraits = selectedThreadID == thread.id
271 ? [.button, .selected]
272 : .button
273 cell.accessibilityLabel = thread.title
274 cell.accessibilityValue = threadAccessibilityValue(thread, context: context)
275 cell.accessibilityHint = "Opens task"
276 cell.onAccessibilityActivate = { [weak self] in
277 guard let self else { return }
278 let previousSelection = self.selectedThreadID
279 self.selectedThreadID = thread.id
280 self.parent.onOpen(thread.id)
281 if let collectionView = self.collectionView {
282 self.refreshSelection(
283 in: collectionView,
284 ids: [previousSelection, thread.id].compactMap { $0 }
285 )
286 }
287 }
288 case let .shelfHeader(shelf, count, isExpanded):
289 cell.isAccessibilityElement = true
290 cell.accessibilityTraits = .button
291 cell.accessibilityLabel = "\(shelf.title), \(count) tasks"
292 cell.accessibilityValue = isExpanded ? "Expanded" : "Collapsed"
293 cell.accessibilityHint = nil
294 cell.onAccessibilityActivate = { [weak self] in self?.toggle(shelf) }
295 case let .showMoreSettled(remaining):
296 cell.isAccessibilityElement = true
297 cell.accessibilityTraits = .button
298 cell.accessibilityLabel = "Show \(remaining) more settled tasks"
299 cell.accessibilityValue = nil
300 cell.accessibilityHint = nil
301 cell.onAccessibilityActivate = { [weak self] in
302 self?.parent.onShowMoreSettled()
303 }
304 case let .empty(shelf):
305 cell.isAccessibilityElement = true
306 cell.accessibilityTraits = .staticText
307 cell.accessibilityLabel = shelf == .active ? "No active tasks" : "No \(shelf.title.lowercased()) tasks"
308 cell.accessibilityValue = nil
309 cell.accessibilityHint = nil
310 cell.onAccessibilityActivate = nil
311 case .searchEmpty:
312 cell.isAccessibilityElement = true
313 cell.accessibilityTraits = .staticText
314 cell.accessibilityLabel = "No matching tasks"
315 cell.accessibilityValue = nil
316 cell.accessibilityHint = nil
317 cell.onAccessibilityActivate = nil
318 case .pinnedDivider:
319 cell.isAccessibilityElement = false
320 cell.onAccessibilityActivate = nil
321 }
322 }
323​
324 private func threadAccessibilityValue(
325 _ thread: FeatureThread,
326 context: HomeThreadRowContext
327 ) -> String {
328 var values = [thread.homeStatusLabel ?? "Ready", "Project \(context.projectName)"]
329 values.append("Harness \(context.providerName)")
330 if let duration = thread.homeWorkingDuration(at: .now) {
331 values.append("for \(duration)")
332 }
333 if let environment = context.environmentLabel {
334 values.append("on \(environment)")
335 }
336 return values.joined(separator: ". ")
337 }
338​
339 private func synchronizeSelection(in collectionView: UICollectionView) {
340 for indexPath in collectionView.indexPathsForSelectedItems ?? [] {
341 guard dataSource?.itemIdentifier(for: indexPath)?.threadID != selectedThreadID else {
342 continue
343 }
344 collectionView.deselectItem(at: indexPath, animated: false)
345 }
346 guard let selectedThreadID,
347 let indexPath = dataSource?.indexPath(for: .thread(selectedThreadID)),
348 !collectionView.indexPathsForSelectedItems.orEmpty.contains(indexPath) else {
349 return
350 }
351 collectionView.selectItem(at: indexPath, animated: false, scrollPosition: [])
352 }
353​
354 private func refreshSelection(in collectionView: UICollectionView, ids: [String]) {
355 for id in ids {
356 guard let indexPath = dataSource?.indexPath(for: .thread(id)),
357 let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionCell else {
358 continue
359 }
360 configure(cell, identifier: .thread(id), now: .now)
361 }
362 }
363​
364 private func item(at indexPath: IndexPath) -> HomeCollectionItem? {
365 guard let identifier = dataSource?.itemIdentifier(for: indexPath) else { return nil }
366 return itemsByID[identifier]
367 }
368​
369 private func toggle(_ shelf: HomeShelf) {
370 switch shelf {
371 case .snoozed: parent.onToggleSnoozed()
372 case .settled: parent.onToggleSettled()
373 case .archived: parent.onToggleArchive()
374 case .active: break
375 }
376 }
377​
378 private func menuActions(for thread: FeatureThread, isArchived: Bool) -> [UIMenuElement] {
379 let rename = UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in
380 self?.parent.onRename(thread)
381 }
382 let archive = UIAction(
383 title: isArchived ? "Restore" : "Archive",
384 image: UIImage(systemName: isArchived ? "arrow.uturn.backward" : "archivebox")
385 ) { [weak self] _ in
386 self?.parent.onArchive(thread, !isArchived)
387 }
388​
389 var actions: [UIMenuElement] = [rename]
390 if thread.supportsTitleRegeneration == true {
391 actions.append(
392 UIAction(
393 title: "Regenerate title",
394 image: UIImage(systemName: "sparkles")
395 ) { [weak self] _ in
396 self?.parent.onRegenerateTitle(thread)
397 }
398 )
399 }
400 actions.append(archive)
401 if !isArchived {
402 if thread.canTogglePin {
403 let isPinned = thread.pinnedAt != nil
404 actions.append(
405 UIAction(
406 title: isPinned ? "Unpin" : "Pin",
407 image: UIImage(systemName: isPinned ? "pin.slash" : "pin")
408 ) { [weak self] _ in
409 self?.parent.onPin(thread, !isPinned)
410 }
411 )
412 }
413 if thread.canToggleSettlement {
414 let isSettled = thread.isEffectivelySettled(at: .now)
415 actions.append(
416 UIAction(
417 title: isSettled ? "Reopen" : "Settle",
418 image: UIImage(
419 systemName: isSettled ? "arrow.counterclockwise" : "checkmark"
420 )
421 ) { [weak self] _ in
422 self?.parent.onSettle(thread, !isSettled)
423 }
424 )
425 }
426​
427 if thread.canToggleSnooze {
428 let isSnoozed = thread.isEffectivelySnoozed(at: .now)
429 if isSnoozed {
430 actions.append(
431 UIAction(title: "Wake thread", image: UIImage(systemName: "bell")) {
432 [weak self] _ in
433 self?.parent.onSnooze(thread, nil)
434 }
435 )
436 } else {
437 let presets = DailyUXSnoozePresets.resolve(now: .now)
438 let children = presets.map { preset in
439 UIAction(title: preset.label) { [weak self] _ in
440 self?.parent.onSnooze(thread, preset.until)
441 }
442 }
443 let snoozeIsDisabled = thread.state == .queued
444 || thread.state == .waitingForApproval
445 || thread.state == .waitingForInput
446 if snoozeIsDisabled {
447 children.forEach { $0.attributes = .disabled }
448 }
449 let snooze = UIMenu(
450 title: "Snooze",
451 image: UIImage(systemName: "clock"),
452 children: children
453 )
454 actions.append(snooze)
455 }
456 }
457 }
458​
459 actions.append(
460 UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) {
461 [weak self] _ in
462 self?.parent.onDelete(thread)
463 }
464 )
465 return actions
466 }
467​
468 /// Working rows show a live per-second duration, so they need a 1 Hz
469 /// tick. Without any, relative ages only change by the minute, and the
470 /// timer idles down to match instead of waking the main thread every
471 /// second for the lifetime of the sidebar.
472 private func startTimer() {
473 let interval: TimeInterval = itemsByID.values.contains {
474 if case let .thread(thread, _, _, _, _) = $0 {
475 return thread.homeStatus == .working
476 }
477 return false
478 } ? 1 : 60
479​
480 if timer != nil, timerInterval == interval { return }
481 invalidateTimer()
482 timerInterval = interval
483 timerTick = 0
484 timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
485 MainActor.assumeIsolated {
486 self?.refreshVisibleTimes()
487 }
488 }
489 timer?.tolerance = interval * 0.12
490 }
491​
492 private func refreshVisibleTimes() {
493 guard let collectionView, let dataSource else { return }
494 timerTick = (timerTick + 1) % 60
495 let refreshRelativeAges = timerInterval >= 60 || timerTick == 0
496 let now = Date.now
497​
498 for indexPath in collectionView.indexPathsForVisibleItems {
499 guard let identifier = dataSource.itemIdentifier(for: indexPath),
500 case let .thread(thread, _, _, _, _) = itemsByID[identifier],
501 refreshRelativeAges || thread.homeStatus == .working,
502 let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionCell else {
503 continue
504 }
505 configure(cell, identifier: identifier, now: now)
506 }
507 }
508 }
509​
510 private var collectionItems: [HomeCollectionItem] {
511 let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
512 if !normalizedQuery.isEmpty {
513 if presentation.searchResults.isEmpty {
514 return [.searchEmpty(normalizedQuery)]
515 }
516 return presentation.searchResults.map {
517 .thread(
518 $0,
519 presentation.rowContexts[$0.id] ?? .fallback,
520 .rich,
521 $0.isArchived,
522 forceRichRows
523 )
524 }
525 }
526​
527 var items = presentation.pinned.map {
528 HomeCollectionItem.thread(
529 $0,
530 presentation.rowContexts[$0.id] ?? .fallback,
531 .rich,
532 false,
533 forceRichRows
534 )
535 }
536 if !presentation.pinned.isEmpty, !presentation.active.isEmpty {
537 items.append(.pinnedDivider)
538 }
539 if presentation.active.isEmpty, presentation.pinned.isEmpty {
540 items.append(.empty(.active))
541 } else {
542 items.append(contentsOf: presentation.active.map {
543 .thread(
544 $0,
545 presentation.rowContexts[$0.id] ?? .fallback,
546 .rich,
547 false,
548 forceRichRows
549 )
550 })
551 }
552​
553 items.append(.shelfHeader(.snoozed, presentation.snoozed.count, isSnoozedExpanded))
554 if isSnoozedExpanded {
555 items.append(contentsOf: presentation.snoozed.isEmpty
556 ? [.empty(.snoozed)]
557 : presentation.snoozed.map {
558 .thread(
559 $0,
560 presentation.rowContexts[$0.id] ?? .fallback,
561 forceRichRows ? .rich : .slim,
562 false,
563 forceRichRows
564 )
565 })
566 }
567​
568 items.append(.shelfHeader(.settled, presentation.settled.count, isSettledExpanded))
569 if isSettledExpanded {
570 items.append(contentsOf: presentation.settled.prefix(settledLimit).map {
571 .thread(
572 $0,
573 presentation.rowContexts[$0.id] ?? .fallback,
574 forceRichRows ? .rich : .slim,
575 false,
576 forceRichRows
577 )
578 })
579 if presentation.settled.count > settledLimit {
580 items.append(.showMoreSettled(presentation.settled.count - settledLimit))
581 }
582 }
583​
584 if !presentation.archived.isEmpty {
585 items.append(.shelfHeader(.archived, presentation.archived.count, isArchiveExpanded))
586 if isArchiveExpanded {
587 items.append(contentsOf: presentation.archived.map {
588 .thread(
589 $0,
590 presentation.rowContexts[$0.id] ?? .fallback,
591 forceRichRows ? .rich : .slim,
592 true,
593 forceRichRows
594 )
595 })
596 }
597 }
598 return items
599 }
601​
602/// The trailing swipe actions a Home row offers, resolved as data so the row's
603/// gesture semantics stay deterministic and testable without hosting a
604/// collection view. Order is outermost-first, matching
605/// `UISwipeActionsConfiguration`, which lays trailing actions out from the
606/// trailing edge inward and runs the first action on a full swipe.
607enum HomeThreadSwipeAction: Equatable {
608 case delete
609 case restore
610 case unpin
611 case settle
612 case reopen
613 case archive
614​
615 /// The lifecycle mutation an action requests. Keeping it separate from the
616 /// action keeps the swipe wiring verifiable and forces every case through
617 /// the row's existing callbacks instead of a second settlement path.
618 enum Intent: Equatable {
619 case delete
620 case setArchived(Bool)
621 case setPinned(Bool)
622 case setSettled(Bool)
623 }
624​
625 /// Settlement owns the edge slot on every row that can settle, so a full
626 /// swipe clears the task in one motion and a partial swipe still reveals
627 /// every button. Delete is always last and therefore can never be the
628 /// full-swipe action. A pinned row keeps Unpin between the two: settling
629 /// already clears the pin, so the full swipe unpins and settles together.
630 /// Archived rows stay restore-only, and a row with nothing to settle keeps
631 /// its reversible action at the edge with the full swipe turned off.
632 static func trailingActions(
633 for thread: FeatureThread,
634 isArchived: Bool,
635 at now: Date
636 ) -> [HomeThreadSwipeAction] {
637 guard !isArchived else { return [.restore, .delete] }
638​
639 let settlement: HomeThreadSwipeAction? = thread.canToggleSettlement
640 ? (thread.isEffectivelySettled(at: now) ? .reopen : .settle)
641 : nil
642 let isPinned = thread.pinnedAt != nil && thread.canTogglePin
643​
644 var actions: [HomeThreadSwipeAction] = []
645 if let settlement {
646 actions.append(settlement)
647 if isPinned {
648 actions.append(.unpin)
649 }
650 } else if isPinned {
651 actions.append(.unpin)
652 } else {
653 actions.append(.archive)
654 }
655 actions.append(.delete)
656 return actions
657 }
658​
659 /// The full swipe is armed only when the edge action settles or reopens.
660 /// Nothing else may run from the gesture alone.
661 static func performsFullSwipe(with actions: [HomeThreadSwipeAction]) -> Bool {
662 actions.first?.isSettlement ?? false
663 }
664​
665 var isSettlement: Bool {
666 self == .settle || self == .reopen
667 }
668​
669 var intent: Intent {
670 switch self {
671 case .delete: .delete
672 case .restore: .setArchived(false)
673 case .archive: .setArchived(true)
674 case .unpin: .setPinned(false)
675 case .settle: .setSettled(true)
676 case .reopen: .setSettled(false)
677 }
678 }
679​
680 var title: String {
681 switch self {
682 case .delete: "Delete"
683 case .restore: "Restore"
684 case .unpin: "Unpin"
685 case .settle: "Settle"
686 case .reopen: "Reopen"
687 case .archive: "Archive"
688 }
689 }
690​
691 var systemImage: String {
692 switch self {
693 case .delete: "trash"
694 case .restore: "arrow.uturn.backward"
695 case .unpin: "pin.slash"
696 case .settle: "checkmark"
697 case .reopen: "arrow.counterclockwise"
698 case .archive: "archivebox"
699 }
700 }
701​
702 var style: UIContextualAction.Style {
703 self == .delete ? .destructive : .normal
704 }
705​
706 /// Destructive actions keep UIKit's own tint.
707 var backgroundColor: UIColor? {
708 switch self {
709 case .delete: nil
710 case .restore, .unpin, .reopen: .systemBlue
711 case .settle: .systemGreen
712 case .archive: .systemGray
713 }
714 }
716​
717private final class HomeCollectionCell: UICollectionViewListCell {
718 var onAccessibilityActivate: (() -> Void)?
719​
720 override func accessibilityActivate() -> Bool {
721 guard let onAccessibilityActivate else { return super.accessibilityActivate() }
722 onAccessibilityActivate()
723 return true
724 }
725​
726 override func prepareForReuse() {
727 super.prepareForReuse()
728 onAccessibilityActivate = nil
729 }
731​
732private enum HomeShelf: String, Hashable {
733 case active
734 case snoozed
735 case settled
736 case archived
737​
738 var title: String {
739 rawValue.capitalized
740 }
742​
743private enum HomeCollectionItem: Equatable {
744 enum ID: Hashable {
745 case thread(String)
746 case shelfHeader(HomeShelf)
747 case empty(HomeShelf)
748 case showMoreSettled
749 case searchEmpty
750 case pinnedDivider
751​
752 var threadID: String? {
753 guard case let .thread(id) = self else { return nil }
754 return id
755 }
756 }
757​
758 case thread(FeatureThread, HomeThreadRowContext, FeatureThreadRow.Style, Bool, Bool)
759 case shelfHeader(HomeShelf, Int, Bool)
760 case empty(HomeShelf)
761 case showMoreSettled(Int)
762 case searchEmpty(String)
763 case pinnedDivider
764​
765 var id: ID {
766 switch self {
767 case let .thread(thread, _, _, _, _): .thread(thread.id)
768 case let .shelfHeader(shelf, _, _): .shelfHeader(shelf)
769 case let .empty(shelf): .empty(shelf)
770 case .showMoreSettled: .showMoreSettled
771 case .searchEmpty: .searchEmpty
772 case .pinnedDivider: .pinnedDivider
773 }
774 }
776​
777private struct HomeCollectionCellContent: View {
778 let item: HomeCollectionItem
779 let projectFaviconClient: any FeatureClient
780 let isSelected: Bool
781 let now: Date
782​
783 @ViewBuilder
784 var body: some View {
785 switch item {
786 case let .thread(thread, context, style, _, allowsMultilineTitle):
787 FeatureThreadRow(
788 thread: thread,
789 context: context,
790 projectFaviconClient: projectFaviconClient,
791 isSelected: isSelected,
792 style: style,
793 now: now,
794 allowsMultilineTitle: allowsMultilineTitle
795 )
796 case let .shelfHeader(shelf, count, isExpanded):
797 HomeShelfHeader(
798 title: shelf.title,
799 count: count,
800 isExpanded: isExpanded,
801 accent: shelf == .snoozed ? T3Colors.accent : nil
802 )
803 case let .empty(shelf):
804 Text(shelf == .active ? "No active tasks" : "None")
805 .font(T3Typography.homeMetadata)
806 .foregroundStyle(T3Colors.textTertiary)
807 .frame(maxWidth: .infinity, minHeight: shelf == .active ? 68 : 34, alignment: .center)
808 case let .showMoreSettled(remaining):
809 HStack {
810 Text("Show more")
811 Spacer()
812 Text("\(remaining)")
813 .monospacedDigit()
814 .foregroundStyle(T3Colors.textTertiary)
815 }
816 .font(T3Typography.homeMetadata.weight(.semibold))
817 .foregroundStyle(T3Colors.textSecondary)
818 .padding(.horizontal, 34)
819 .frame(minHeight: T3Metrics.minimumTapTarget)
820 case .searchEmpty:
821 ContentUnavailableView("No matching tasks", systemImage: "magnifyingglass")
822 .foregroundStyle(T3Colors.textSecondary)
823 .frame(maxWidth: .infinity, minHeight: 160)
824 case .pinnedDivider:
825 Rectangle()
826 .fill(T3Colors.textTertiary.opacity(0.18))
827 .frame(height: 1)
828 .padding(.horizontal, 18)
829 .padding(.vertical, 3)
830 }
831 }
833​
834private extension Optional where Wrapped == [IndexPath] {
835 var orEmpty: [IndexPath] { self ?? [] }