diff --git a/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift b/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift new file mode 100644 index 0000000000..fbfda08c29 --- /dev/null +++ b/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift @@ -0,0 +1,605 @@ +import SwiftUI +import UIKit + +/// A recycled, diffable Home surface. SwiftUI still owns the surrounding shell, +/// while UIKit keeps row creation and updates proportional to visible threads. +struct HomeThreadCollectionView: UIViewRepresentable { + let presentation: HomePresentation + let query: String + let selectedThreadID: String? + let forceRichRows: Bool + let isSnoozedExpanded: Bool + let isSettledExpanded: Bool + let isArchiveExpanded: Bool + let settledLimit: Int + let onOpen: (String) -> Void + let onToggleSnoozed: () -> Void + let onToggleSettled: () -> Void + let onToggleArchive: () -> Void + let onShowMoreSettled: () -> Void + let onRename: (FeatureThread) -> Void + let onArchive: (FeatureThread, Bool) -> Void + let onSettle: (FeatureThread, Bool) -> Void + let onSnooze: (FeatureThread, Date?) -> Void + let onDelete: (FeatureThread) -> Void + + func makeCoordinator() -> Coordinator { + Coordinator(parent: self) + } + + func makeUIView(context: Context) -> UICollectionView { + var configuration = UICollectionLayoutListConfiguration(appearance: .plain) + configuration.backgroundColor = .black + configuration.showsSeparators = false + configuration.headerMode = .none + configuration.footerMode = .none + configuration.trailingSwipeActionsConfigurationProvider = { [weak coordinator = context.coordinator] indexPath in + coordinator?.trailingSwipeActions(at: indexPath) + } + + let collectionView = UICollectionView( + frame: .zero, + collectionViewLayout: UICollectionViewCompositionalLayout.list(using: configuration) + ) + collectionView.backgroundColor = .black + collectionView.alwaysBounceVertical = true + collectionView.keyboardDismissMode = .interactive + collectionView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 74, right: 0) + collectionView.verticalScrollIndicatorInsets = UIEdgeInsets(top: 4, left: 0, bottom: 74, right: 0) + collectionView.delegate = context.coordinator + context.coordinator.configure(collectionView) + return collectionView + } + + func updateUIView(_ collectionView: UICollectionView, context: Context) { + context.coordinator.update(parent: self, collectionView: collectionView) + } + + static func dismantleUIView(_ collectionView: UICollectionView, coordinator: Coordinator) { + coordinator.invalidateTimer() + collectionView.delegate = nil + } + + @MainActor + final class Coordinator: NSObject, UICollectionViewDelegate { + private enum Section: Hashable { + case main + } + + private var parent: HomeThreadCollectionView + private var dataSource: UICollectionViewDiffableDataSource? + private var registration: UICollectionView.CellRegistration? + private var itemsByID: [HomeCollectionItem.ID: HomeCollectionItem] = [:] + private var selectedThreadID: String? + private weak var collectionView: UICollectionView? + private var timer: Timer? + private var timerTick = 0 + + init(parent: HomeThreadCollectionView) { + self.parent = parent + selectedThreadID = parent.selectedThreadID + } + + func configure(_ collectionView: UICollectionView) { + self.collectionView = collectionView + + let registration = UICollectionView.CellRegistration { + [weak self] cell, _, identifier in + self?.configure(cell, identifier: identifier, now: .now) + } + self.registration = registration + + dataSource = UICollectionViewDiffableDataSource( + collectionView: collectionView + ) { [weak self] collectionView, indexPath, identifier in + guard let self, let registration = self.registration else { return nil } + return collectionView.dequeueConfiguredReusableCell( + using: registration, + for: indexPath, + item: identifier + ) + } + + startTimer() + update(parent: parent, collectionView: collectionView) + } + + func update(parent: HomeThreadCollectionView, collectionView: UICollectionView) { + let previousItems = itemsByID + let previousSelection = selectedThreadID + self.parent = parent + selectedThreadID = parent.selectedThreadID + + var seenIdentifiers = Set() + let items = parent.collectionItems.filter { item in + seenIdentifiers.insert(item.id).inserted + } + itemsByID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) }) + + guard let dataSource else { return } + let currentIdentifiers = dataSource.snapshot().itemIdentifiers + let newIdentifiers = items.map(\.id) + + if currentIdentifiers == newIdentifiers { + let changed = newIdentifiers.filter { previousItems[$0] != itemsByID[$0] } + let selectionChanged = [previousSelection, selectedThreadID] + .compactMap { $0.map(HomeCollectionItem.ID.thread) } + .filter { newIdentifiers.contains($0) } + let identifiers = Array(Set(changed + selectionChanged)) + if !identifiers.isEmpty { + var snapshot = dataSource.snapshot() + snapshot.reconfigureItems(identifiers) + dataSource.apply(snapshot, animatingDifferences: false) + } + } else { + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([.main]) + snapshot.appendItems(newIdentifiers, toSection: .main) + dataSource.apply(snapshot, animatingDifferences: false) + } + + synchronizeSelection(in: collectionView) + } + + func invalidateTimer() { + timer?.invalidate() + timer = nil + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + guard let item = item(at: indexPath) else { return } + switch item { + case let .thread(thread, _, _, _, _): + let previousSelection = selectedThreadID + selectedThreadID = thread.id + parent.onOpen(thread.id) + refreshSelection( + in: collectionView, + ids: [previousSelection, thread.id].compactMap { $0 } + ) + case let .shelfHeader(shelf, _, _): + collectionView.deselectItem(at: indexPath, animated: false) + toggle(shelf) + case .showMoreSettled: + collectionView.deselectItem(at: indexPath, animated: false) + parent.onShowMoreSettled() + case .empty, .searchEmpty: + collectionView.deselectItem(at: indexPath, animated: false) + } + } + + func collectionView( + _ collectionView: UICollectionView, + contextMenuConfigurationForItemAt indexPath: IndexPath, + point: CGPoint + ) -> UIContextMenuConfiguration? { + guard case let .thread(thread, _, _, isArchived, _) = item(at: indexPath) else { + return nil + } + + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in + guard let self else { return nil } + return UIMenu(children: self.menuActions(for: thread, isArchived: isArchived)) + } + } + + func trailingSwipeActions(at indexPath: IndexPath) -> UISwipeActionsConfiguration? { + guard case let .thread(thread, _, _, isArchived, _) = item(at: indexPath) else { + return nil + } + + let delete = UIContextualAction(style: .destructive, title: "Delete") { [weak self] _, _, finish in + self?.parent.onDelete(thread) + finish(true) + } + delete.image = UIImage(systemName: "trash") + + let archive = UIContextualAction(style: .normal, title: isArchived ? "Restore" : "Archive") { + [weak self] _, _, finish in + self?.parent.onArchive(thread, !isArchived) + finish(true) + } + archive.image = UIImage(systemName: isArchived ? "arrow.uturn.backward" : "archivebox") + archive.backgroundColor = isArchived ? .systemBlue : .systemOrange + + let configuration = UISwipeActionsConfiguration(actions: [delete, archive]) + configuration.performsFirstActionWithFullSwipe = false + return configuration + } + + private func configure( + _ cell: HomeCollectionCell, + identifier: HomeCollectionItem.ID, + now: Date + ) { + guard let item = itemsByID[identifier] else { return } + cell.contentConfiguration = UIHostingConfiguration { + HomeCollectionCellContent( + item: item, + isSelected: identifier.threadID == selectedThreadID, + now: now + ) + } + .margins(.all, 0) + + cell.backgroundConfiguration = UIBackgroundConfiguration.clear() + cell.accessories = [] + cell.tintColor = .white + cell.contentView.accessibilityElementsHidden = true + configureAccessibility(cell, item: item) + } + + private func configureAccessibility(_ cell: HomeCollectionCell, item: HomeCollectionItem) { + switch item { + case let .thread(thread, context, _, _, _): + cell.isAccessibilityElement = true + cell.accessibilityTraits = selectedThreadID == thread.id + ? [.button, .selected] + : .button + cell.accessibilityLabel = thread.title + cell.accessibilityValue = threadAccessibilityValue(thread, context: context) + cell.accessibilityHint = "Opens task" + cell.onAccessibilityActivate = { [weak self] in + guard let self else { return } + let previousSelection = self.selectedThreadID + self.selectedThreadID = thread.id + self.parent.onOpen(thread.id) + if let collectionView = self.collectionView { + self.refreshSelection( + in: collectionView, + ids: [previousSelection, thread.id].compactMap { $0 } + ) + } + } + case let .shelfHeader(shelf, count, isExpanded): + cell.isAccessibilityElement = true + cell.accessibilityTraits = .button + cell.accessibilityLabel = "\(shelf.title), \(count) tasks" + cell.accessibilityValue = isExpanded ? "Expanded" : "Collapsed" + cell.accessibilityHint = nil + cell.onAccessibilityActivate = { [weak self] in self?.toggle(shelf) } + case let .showMoreSettled(remaining): + cell.isAccessibilityElement = true + cell.accessibilityTraits = .button + cell.accessibilityLabel = "Show \(remaining) more settled tasks" + cell.accessibilityValue = nil + cell.accessibilityHint = nil + cell.onAccessibilityActivate = { [weak self] in + self?.parent.onShowMoreSettled() + } + case let .empty(shelf): + cell.isAccessibilityElement = true + cell.accessibilityTraits = .staticText + cell.accessibilityLabel = shelf == .active ? "No active tasks" : "No \(shelf.title.lowercased()) tasks" + cell.accessibilityValue = nil + cell.accessibilityHint = nil + cell.onAccessibilityActivate = nil + case .searchEmpty: + cell.isAccessibilityElement = true + cell.accessibilityTraits = .staticText + cell.accessibilityLabel = "No matching tasks" + cell.accessibilityValue = nil + cell.accessibilityHint = nil + cell.onAccessibilityActivate = nil + } + } + + private func threadAccessibilityValue( + _ thread: FeatureThread, + context: HomeThreadRowContext + ) -> String { + var values = [thread.homeStatusLabel ?? "Ready", "Project \(context.projectName)"] + if let duration = thread.homeWorkingDuration(at: .now) { + values.append("for \(duration)") + } + if let environment = context.environmentLabel { + values.append("on \(environment)") + } + return values.joined(separator: ". ") + } + + private func synchronizeSelection(in collectionView: UICollectionView) { + for indexPath in collectionView.indexPathsForSelectedItems ?? [] { + guard dataSource?.itemIdentifier(for: indexPath)?.threadID != selectedThreadID else { + continue + } + collectionView.deselectItem(at: indexPath, animated: false) + } + guard let selectedThreadID, + let indexPath = dataSource?.indexPath(for: .thread(selectedThreadID)), + !collectionView.indexPathsForSelectedItems.orEmpty.contains(indexPath) else { + return + } + collectionView.selectItem(at: indexPath, animated: false, scrollPosition: []) + } + + private func refreshSelection(in collectionView: UICollectionView, ids: [String]) { + for id in ids { + guard let indexPath = dataSource?.indexPath(for: .thread(id)), + let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionCell else { + continue + } + configure(cell, identifier: .thread(id), now: .now) + } + } + + private func item(at indexPath: IndexPath) -> HomeCollectionItem? { + guard let identifier = dataSource?.itemIdentifier(for: indexPath) else { return nil } + return itemsByID[identifier] + } + + private func toggle(_ shelf: HomeShelf) { + switch shelf { + case .snoozed: parent.onToggleSnoozed() + case .settled: parent.onToggleSettled() + case .archived: parent.onToggleArchive() + case .active: break + } + } + + private func menuActions(for thread: FeatureThread, isArchived: Bool) -> [UIMenuElement] { + let rename = UIAction(title: "Rename", image: UIImage(systemName: "pencil")) { [weak self] _ in + self?.parent.onRename(thread) + } + let archive = UIAction( + title: isArchived ? "Restore" : "Archive", + image: UIImage(systemName: isArchived ? "arrow.uturn.backward" : "archivebox") + ) { [weak self] _ in + self?.parent.onArchive(thread, !isArchived) + } + + var actions: [UIMenuElement] = [rename, archive] + if !isArchived { + let isSettled = thread.isEffectivelySettled(at: .now) + actions.append( + UIAction( + title: isSettled ? "Reopen" : "Mark done", + image: UIImage(systemName: isSettled ? "arrow.counterclockwise" : "checkmark") + ) { [weak self] _ in + self?.parent.onSettle(thread, !isSettled) + } + ) + + let isSnoozed = thread.isEffectivelySnoozed(at: .now) + let snooze = UIAction( + title: isSnoozed ? "Unsnooze" : "Snooze 1 hour", + image: UIImage(systemName: isSnoozed ? "bell" : "clock") + ) { [weak self] _ in + self?.parent.onSnooze( + thread, + isSnoozed ? nil : Date.now.addingTimeInterval(60 * 60) + ) + } + if thread.state == .queued + || thread.state == .waitingForApproval + || thread.state == .waitingForInput { + snooze.attributes = .disabled + } + actions.append(snooze) + } + + actions.append( + UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { + [weak self] _ in + self?.parent.onDelete(thread) + } + ) + return actions + } + + private func startTimer() { + invalidateTimer() + timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { + self?.refreshVisibleTimes() + } + } + timer?.tolerance = 0.12 + } + + private func refreshVisibleTimes() { + guard let collectionView, let dataSource else { return } + timerTick = (timerTick + 1) % 60 + let refreshRelativeAges = timerTick == 0 + let now = Date.now + + for indexPath in collectionView.indexPathsForVisibleItems { + guard let identifier = dataSource.itemIdentifier(for: indexPath), + case let .thread(thread, _, _, _, _) = itemsByID[identifier], + refreshRelativeAges || thread.homeStatus == .working, + let cell = collectionView.cellForItem(at: indexPath) as? HomeCollectionCell else { + continue + } + configure(cell, identifier: identifier, now: now) + } + } + } + + private var collectionItems: [HomeCollectionItem] { + let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + if !normalizedQuery.isEmpty { + if presentation.searchResults.isEmpty { + return [.searchEmpty(normalizedQuery)] + } + return presentation.searchResults.map { + .thread( + $0, + presentation.rowContexts[$0.id] ?? .fallback, + .rich, + $0.isArchived, + forceRichRows + ) + } + } + + var items: [HomeCollectionItem] = presentation.active.isEmpty + ? [.empty(.active)] + : presentation.active.map { + .thread( + $0, + presentation.rowContexts[$0.id] ?? .fallback, + .rich, + false, + forceRichRows + ) + } + + items.append(.shelfHeader(.snoozed, presentation.snoozed.count, isSnoozedExpanded)) + if isSnoozedExpanded { + items.append(contentsOf: presentation.snoozed.isEmpty + ? [.empty(.snoozed)] + : presentation.snoozed.map { + .thread( + $0, + presentation.rowContexts[$0.id] ?? .fallback, + forceRichRows ? .rich : .slim, + false, + forceRichRows + ) + }) + } + + items.append(.shelfHeader(.settled, presentation.settled.count, isSettledExpanded)) + if isSettledExpanded { + items.append(contentsOf: presentation.settled.prefix(settledLimit).map { + .thread( + $0, + presentation.rowContexts[$0.id] ?? .fallback, + forceRichRows ? .rich : .slim, + false, + forceRichRows + ) + }) + if presentation.settled.count > settledLimit { + items.append(.showMoreSettled(presentation.settled.count - settledLimit)) + } + } + + if !presentation.archived.isEmpty { + items.append(.shelfHeader(.archived, presentation.archived.count, isArchiveExpanded)) + if isArchiveExpanded { + items.append(contentsOf: presentation.archived.map { + .thread( + $0, + presentation.rowContexts[$0.id] ?? .fallback, + forceRichRows ? .rich : .slim, + true, + forceRichRows + ) + }) + } + } + return items + } +} + +private final class HomeCollectionCell: UICollectionViewListCell { + var onAccessibilityActivate: (() -> Void)? + + override func accessibilityActivate() -> Bool { + guard let onAccessibilityActivate else { return super.accessibilityActivate() } + onAccessibilityActivate() + return true + } + + override func prepareForReuse() { + super.prepareForReuse() + onAccessibilityActivate = nil + } +} + +private enum HomeShelf: String, Hashable { + case active + case snoozed + case settled + case archived + + var title: String { + rawValue.capitalized + } +} + +private enum HomeCollectionItem: Equatable { + enum ID: Hashable { + case thread(String) + case shelfHeader(HomeShelf) + case empty(HomeShelf) + case showMoreSettled + case searchEmpty + + var threadID: String? { + guard case let .thread(id) = self else { return nil } + return id + } + } + + case thread(FeatureThread, HomeThreadRowContext, FeatureThreadRow.Style, Bool, Bool) + case shelfHeader(HomeShelf, Int, Bool) + case empty(HomeShelf) + case showMoreSettled(Int) + case searchEmpty(String) + + var id: ID { + switch self { + case let .thread(thread, _, _, _, _): .thread(thread.id) + case let .shelfHeader(shelf, _, _): .shelfHeader(shelf) + case let .empty(shelf): .empty(shelf) + case .showMoreSettled: .showMoreSettled + case .searchEmpty: .searchEmpty + } + } +} + +private struct HomeCollectionCellContent: View { + let item: HomeCollectionItem + let isSelected: Bool + let now: Date + + @ViewBuilder + var body: some View { + switch item { + case let .thread(thread, context, style, _, allowsMultilineTitle): + FeatureThreadRow( + thread: thread, + context: context, + isSelected: isSelected, + style: style, + now: now, + allowsMultilineTitle: allowsMultilineTitle + ) + .equatable() + case let .shelfHeader(shelf, count, isExpanded): + HomeShelfHeader( + title: shelf.title, + count: count, + isExpanded: isExpanded, + accent: shelf == .snoozed ? T3Colors.accent : nil + ) + case let .empty(shelf): + Text(shelf == .active ? "No active tasks" : "None") + .font(T3Typography.homeMetadata) + .foregroundStyle(T3Colors.textTertiary) + .frame(maxWidth: .infinity, minHeight: shelf == .active ? 68 : 34, alignment: .center) + case let .showMoreSettled(remaining): + HStack { + Text("Show more") + Spacer() + Text("\(remaining)") + .monospacedDigit() + .foregroundStyle(T3Colors.textTertiary) + } + .font(T3Typography.homeMetadata.weight(.semibold)) + .foregroundStyle(T3Colors.textSecondary) + .padding(.horizontal, 34) + .frame(minHeight: T3Metrics.minimumTapTarget) + case .searchEmpty: + ContentUnavailableView("No matching tasks", systemImage: "magnifyingglass") + .foregroundStyle(T3Colors.textSecondary) + .frame(maxWidth: .infinity, minHeight: 160) + } + } +} + +private extension Optional where Wrapped == [IndexPath] { + var orEmpty: [IndexPath] { self ?? [] } +} diff --git a/apps/swift-ios/Features/Workspace/WorkspaceView.swift b/apps/swift-ios/Features/Workspace/WorkspaceView.swift index 510ab982e4..aa08de63e9 100644 --- a/apps/swift-ios/Features/Workspace/WorkspaceView.swift +++ b/apps/swift-ios/Features/Workspace/WorkspaceView.swift @@ -22,6 +22,7 @@ public struct WorkspaceView: View { @State private var renameTitle = "" @State private var sidebarBoundaryNow = Date.now @State private var preferredCompactColumn = NavigationSplitViewColumn.sidebar + @State private var homePresentationCache = HomePresentationCache() @FocusState private var isSearchFocused: Bool public init( @@ -153,58 +154,48 @@ public struct WorkspaceView: View { } private var threadList: some View { - let presentation = HomePresentation( + let presentation = homePresentationCache.presentation( snapshot: model.snapshot, + revision: model.homePresentationRevision, query: searchText, projectID: selectedProjectID, now: sidebarBoundaryNow ) - return List(selection: $selectedThreadID) { - projectFilter(presentation) - - if searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - activeRows(presentation) - shelfRows( - title: "Snoozed", - threads: presentation.snoozed, - rowContexts: presentation.rowContexts, - isExpanded: $isSnoozedExpanded, - accent: T3Colors.accent, - isArchived: false - ) - shelfRows( - title: "Settled", - threads: Array(presentation.settled.prefix(settledLimit)), - rowContexts: presentation.rowContexts, - totalCount: presentation.settled.count, - isExpanded: $isSettledExpanded, - accent: nil, - isArchived: false - ) - if presentation.settled.count > settledLimit, isSettledExpanded { - showMoreSettled(presentation.settled.count - settledLimit) + return VStack(spacing: 0) { + projectFilter + HomeThreadCollectionView( + presentation: presentation, + query: searchText, + selectedThreadID: selectedThreadID, + forceRichRows: dynamicTypeSize.isAccessibilitySize, + isSnoozedExpanded: isSnoozedExpanded, + isSettledExpanded: isSettledExpanded, + isArchiveExpanded: isArchiveExpanded, + settledLimit: settledLimit, + onOpen: openThread, + onToggleSnoozed: { isSnoozedExpanded.toggle() }, + onToggleSettled: { isSettledExpanded.toggle() }, + onToggleArchive: { isArchiveExpanded.toggle() }, + onShowMoreSettled: { settledLimit += 25 }, + onRename: { thread in + renameTitle = thread.title + renamingThread = thread + }, + onArchive: { thread, archived in + Task { await model.setArchived(thread.id, archived: archived) } + }, + onSettle: { thread, settled in + Task { await model.setSettled(thread.id, settled: settled) } + }, + onSnooze: { thread, until in + Task { await model.setSnoozed(thread.id, until: until) } + }, + onDelete: { thread in + Task { await model.deleteThread(thread.id) } } - if !presentation.archived.isEmpty { - shelfRows( - title: "Archived", - threads: presentation.archived, - rowContexts: presentation.rowContexts, - isExpanded: $isArchiveExpanded, - accent: nil, - isArchived: true - ) - } - } else { - searchRows(presentation) - } + ) } - .listStyle(.plain) - .environment(\.defaultMinListRowHeight, 0) - .scrollContentBackground(.hidden) - .scrollDismissesKeyboard(.interactively) - .contentMargins(.top, 4, for: .scrollContent) - .contentMargins(.bottom, 74, for: .scrollContent) .background(T3Colors.background) } @@ -428,7 +419,7 @@ public struct WorkspaceView: View { .accessibilityIdentifier("sidebar-new-task-button") } - private func projectFilter(_ presentation: HomePresentation) -> some View { + private var projectFilter: some View { HStack(spacing: 0) { Menu { Button { @@ -483,237 +474,9 @@ public struct WorkspaceView: View { } .padding(.leading, 10) .padding(.trailing, 2) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) .accessibilityElement(children: .contain) } - @ViewBuilder - private func activeRows(_ presentation: HomePresentation) -> some View { - if presentation.active.isEmpty { - Text("No active tasks") - .font(.footnote) - .foregroundStyle(T3Colors.textTertiary) - .frame(maxWidth: .infinity, minHeight: 68, alignment: .center) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } else { - ForEach(presentation.active) { thread in - threadLink( - thread, - context: presentation.rowContexts[thread.id] ?? .fallback, - style: .rich, - isArchived: false - ) - } - } - } - - @ViewBuilder - private func shelfRows( - title: String, - threads: [FeatureThread], - rowContexts: [String: HomeThreadRowContext], - totalCount: Int? = nil, - isExpanded: Binding, - accent: Color?, - isArchived: Bool - ) -> some View { - Button { - withAnimation(.easeOut(duration: 0.16)) { - isExpanded.wrappedValue.toggle() - } - } label: { - HomeShelfHeader( - title: title, - count: totalCount ?? threads.count, - isExpanded: isExpanded.wrappedValue, - accent: accent - ) - } - .buttonStyle(.plain) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - .accessibilityLabel("\(title), \(totalCount ?? threads.count) tasks") - .accessibilityValue(isExpanded.wrappedValue ? "Expanded" : "Collapsed") - - if isExpanded.wrappedValue { - if threads.isEmpty { - Text("None") - .font(.caption) - .foregroundStyle(T3Colors.textTertiary) - .padding(.leading, 34) - .frame(minHeight: 34) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } else { - ForEach(threads) { thread in - threadLink( - thread, - context: rowContexts[thread.id] ?? .fallback, - style: .slim, - isArchived: isArchived - ) - } - } - } - } - - private func showMoreSettled(_ remaining: Int) -> some View { - Button { - settledLimit += 25 - } label: { - HStack { - Text("Show more") - Spacer() - Text("\(remaining)") - .monospacedDigit() - .foregroundStyle(T3Colors.textTertiary) - } - .font(.caption.weight(.semibold)) - .foregroundStyle(T3Colors.textSecondary) - .padding(.horizontal, 34) - .frame(height: T3Metrics.minimumTapTarget) - } - .buttonStyle(.plain) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } - - @ViewBuilder - private func searchRows(_ presentation: HomePresentation) -> some View { - if presentation.searchResults.isEmpty { - ContentUnavailableView.search(text: searchText) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } else { - ForEach(presentation.searchResults) { thread in - threadLink( - thread, - context: presentation.rowContexts[thread.id] ?? .fallback, - style: .rich, - isArchived: thread.isArchived - ) - } - } - } - - private func threadLink( - _ thread: FeatureThread, - context: HomeThreadRowContext, - style: FeatureThreadRow.Style, - isArchived: Bool - ) -> some View { - NavigationLink(value: thread.id) { - FeatureThreadRow( - thread: thread, - context: context, - isSelected: selectedThreadID == thread.id, - style: dynamicTypeSize.isAccessibilitySize ? .rich : style - ) - .equatable() - } - .tag(thread.id) - .buttonStyle(.plain) - .navigationLinkIndicatorVisibility(.hidden) - .listRowInsets(EdgeInsets()) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - .swipeActions(edge: .trailing, allowsFullSwipe: false) { - Button(role: .destructive) { - Task { await model.deleteThread(thread.id) } - } label: { - Label("Delete", systemImage: "trash") - } - if isArchived { - Button { - Task { await model.setArchived(thread.id, archived: false) } - } label: { - Label("Restore", systemImage: "arrow.uturn.backward") - } - .tint(.blue) - } else { - Button { - Task { await model.setArchived(thread.id, archived: true) } - } label: { - Label("Archive", systemImage: "archivebox") - } - .tint(.orange) - } - } - .contextMenu { - Button { - renameTitle = thread.title - renamingThread = thread - } label: { - Label("Rename", systemImage: "pencil") - } - - if isArchived { - Button { - Task { await model.setArchived(thread.id, archived: false) } - } label: { - Label("Restore", systemImage: "arrow.uturn.backward") - } - } else { - Button { - Task { await model.setArchived(thread.id, archived: true) } - } label: { - Label("Archive", systemImage: "archivebox") - } - - Button { - Task { - await model.setSettled( - thread.id, - settled: !thread.isEffectivelySettled(at: sidebarBoundaryNow) - ) - } - } label: { - Label( - thread.isEffectivelySettled(at: sidebarBoundaryNow) ? "Reopen" : "Mark done", - systemImage: thread.isEffectivelySettled(at: sidebarBoundaryNow) - ? "arrow.counterclockwise" - : "checkmark" - ) - } - - Button { - let snoozed = thread.isEffectivelySnoozed(at: sidebarBoundaryNow) - Task { - await model.setSnoozed( - thread.id, - until: snoozed ? nil : Date().addingTimeInterval(60 * 60) - ) - } - } label: { - let snoozed = thread.isEffectivelySnoozed(at: sidebarBoundaryNow) - Label( - snoozed ? "Unsnooze" : "Snooze 1 hour", - systemImage: snoozed ? "bell" : "clock" - ) - } - .disabled( - thread.state == .queued - || thread.state == .waitingForApproval - || thread.state == .waitingForInput - ) - } - - Button(role: .destructive) { - Task { await model.deleteThread(thread.id) } - } label: { - Label("Delete", systemImage: "trash") - } - } - } - private var selectedProject: FeatureProject? { model.snapshot.projects.first { $0.id == selectedProjectID } } @@ -793,7 +556,7 @@ private extension FeatureDraftAttachment { } } -private struct HomePresentation { +struct HomePresentation { let active: [FeatureThread] let snoozed: [FeatureThread] let settled: [FeatureThread] @@ -821,16 +584,60 @@ private struct HomePresentation { snoozed = index.snoozed settled = index.settled self.archived = archived - searchResults = DailyUXSidebarIndex.matchingThreads( - index.active + index.snoozed + index.settled + archived, - snapshot: snapshot, - query: query - ) + let normalizedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) + searchResults = normalizedQuery.isEmpty + ? [] + : DailyUXSidebarIndex.matchingThreads( + index.active + index.snoozed + index.settled + archived, + snapshot: snapshot, + query: normalizedQuery + ) rowContexts = HomeThreadRowContext.index(snapshot: snapshot) } } -private struct HomeShelfHeader: View { +@MainActor +private final class HomePresentationCache { + private struct Key: Equatable { + let revision: UInt64 + let query: String + let projectID: String? + let now: Date + } + + private var cachedKey: Key? + private var cachedPresentation: HomePresentation? + + func presentation( + snapshot: FeatureSnapshot, + revision: UInt64, + query: String, + projectID: String?, + now: Date + ) -> HomePresentation { + let key = Key( + revision: revision, + query: query, + projectID: projectID, + now: now + ) + if cachedKey == key, let cachedPresentation { + return cachedPresentation + } + + let presentation = HomePresentation( + snapshot: snapshot, + query: query, + projectID: projectID, + now: now + ) + cachedKey = key + cachedPresentation = presentation + return presentation + } +} + +struct HomeShelfHeader: View { let title: String let count: Int let isExpanded: Bool @@ -855,7 +662,7 @@ private struct HomeShelfHeader: View { } } -private struct HomeThreadRowContext: Equatable { +struct HomeThreadRowContext: Equatable { let projectName: String let environmentLabel: String? let providerLooksTerminal: Bool @@ -928,29 +735,33 @@ struct FeatureThreadRow: View, Equatable { private let context: HomeThreadRowContext let isSelected: Bool let style: Style + let now: Date + let allowsMultilineTitle: Bool - fileprivate init( + init( thread: FeatureThread, context: HomeThreadRowContext, isSelected: Bool = false, - style: Style = .rich + style: Style = .rich, + now: Date = .now, + allowsMultilineTitle: Bool = false ) { self.thread = thread self.context = context self.isSelected = isSelected self.style = style + self.now = now + self.allowsMultilineTitle = allowsMultilineTitle } var body: some View { - TimelineView(.periodic(from: .now, by: refreshCadence)) { timeline in - row(at: timeline.date) - .accessibilityElement(children: .ignore) - .accessibilityLabel(thread.title) - .accessibilityValue(accessibilityValue(at: timeline.date)) - .accessibilityHint("Opens task") - .accessibilityIdentifier("thread-\(thread.id)") - .accessibilityAddTraits(isSelected ? .isSelected : []) - } + row(at: now) + .accessibilityElement(children: .ignore) + .accessibilityLabel(thread.title) + .accessibilityValue(accessibilityValue(at: now)) + .accessibilityHint("Opens task") + .accessibilityIdentifier("thread-\(thread.id)") + .accessibilityAddTraits(isSelected ? .isSelected : []) } @ViewBuilder @@ -981,7 +792,7 @@ struct FeatureThreadRow: View, Equatable { .font(T3Typography.homeTitle) .tracking(-0.14) .foregroundStyle(T3Colors.textPrimary) - .lineLimit(1) + .lineLimit(allowsMultilineTitle ? 2 : 1) .padding(.top, 4) HStack(spacing: 6) { @@ -1031,7 +842,7 @@ struct FeatureThreadRow: View, Equatable { Text(thread.title) .font(T3Typography.homeTitle) .foregroundStyle(T3Colors.textSecondary) - .lineLimit(1) + .lineLimit(allowsMultilineTitle ? 2 : 1) Spacer(minLength: 8) Text(SidebarRelativeAge.compact(since: thread.updatedAt, now: now)) .font(T3Typography.homeMetadata.monospacedDigit()) @@ -1145,9 +956,6 @@ struct FeatureThreadRow: View, Equatable { return values.joined(separator: ". ") } - private var refreshCadence: TimeInterval { - thread.homeStatus == .working ? 1 : 60 - } } private struct ProjectBadge: View {