Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions Example/Sources/List/ListViewController.swift
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's revert all these changes to the Example app.

I want to leave the existing tabs and models as-is and have a new example that's fully independent of everything else.

What I'd prefer to do is:

  1. Create a new "Outline" tab in the example app to exercise this functionality
  2. Create new models types to use in this new tab. Here's one idea using sections with emoji:
Produce >
    Fruit >
        🍌
        🍎
    Vegetables >
        🌽
        🫑
Junk Food >
    🍕

This gives us multiple opportunities for various layers of nesting.

Alternatively, we could do something similar with SF Symbols.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're up for it, it would be nice to get the basic ground work for this done in a separate PR -- just getting the basic scaffolding setup.

Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ final class ListViewController: ExampleViewController, CellEventCoordinator {

private func makeViewModel() -> CollectionViewModel {
// Create People Section
let peopleCellViewModels = self.model.people.map {
let peopleCellViewModels = self.model.people.enumerated().map { index, person in
let menuConfig = UIContextMenuConfiguration.configFor(
itemId: $0.id,
itemId: person.id,
favoriteAction: { [unowned self] in
self.toggleFavorite(id: $0)
},
Expand All @@ -92,9 +92,12 @@ final class ListViewController: ExampleViewController, CellEventCoordinator {
}
)

let children = makeViewModel(for: person.subPeople)

return PersonCellViewModelList(
person: $0,
contextMenuConfiguration: menuConfig
person: person,
contextMenuConfiguration: menuConfig,
children: children
).eraseToAnyViewModel()
}
let peopleHeader = HeaderViewModel(title: "People", style: .small)
Expand Down Expand Up @@ -134,6 +137,16 @@ final class ListViewController: ExampleViewController, CellEventCoordinator {
// Create final view model
return CollectionViewModel(id: "list_view", sections: [peopleSection, colorSection])
}

private func makeViewModel(for people: [PersonModel]) -> [AnyCellViewModel] {
let children: [AnyCellViewModel] = people.map {
PersonCellViewModelList(person: $0,
contextMenuConfiguration: nil,
children: makeViewModel(for: $0.subPeople)).eraseToAnyViewModel()
}

return children
}
}

extension ListViewController: UIScrollViewDelegate {
Expand Down
4 changes: 3 additions & 1 deletion Example/Sources/List/PersonCellViewModelList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ struct PersonCellViewModelList: CellViewModel {

let contextMenuConfiguration: UIContextMenuConfiguration?

let children: [AnyCellViewModel]

func configure(cell: UICollectionViewListCell) {
var contentConfiguration = UIListContentConfiguration.subtitleCell()
contentConfiguration.text = self.person.name
Expand All @@ -35,7 +37,7 @@ struct PersonCellViewModelList: CellViewModel {
let flagEmoji = UICellAccessory.customView(
configuration: .init(customView: label, placement: .leading())
)
var accessories = [flagEmoji, .disclosureIndicator()]
var accessories = [flagEmoji, .disclosureIndicator(), .outlineDisclosure()]

if self.person.isFavorite {
let imageView = UIImageView(image: UIImage(systemName: "star.fill"))
Expand Down
9 changes: 8 additions & 1 deletion Example/Sources/PersonModel/PersonModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ struct PersonModel: Hashable {
let birthdate: Date
let nationality: String
var isFavorite = false
var subPeople: [PersonModel] = []

var birthDateText: String {
self.birthdate.formatted(date: .long, time: .omitted)
Expand All @@ -45,7 +46,13 @@ extension Date {
extension PersonModel {
static func makePeople() -> [PersonModel] {
[
PersonModel(name: "Noam Chomsky", birthdate: Date(year: 1_928, month: 12, day: 7), nationality: "🇺🇸"),
PersonModel(name: "Noam Chomsky", birthdate: Date(year: 1_928, month: 12, day: 7), nationality: "🇺🇸", subPeople: [
.init(name: "Steve Jobs", birthdate: Date(year: 1955, month: 2, day: 24), nationality: "🇺🇸", subPeople: [
.init(name: "Another Steve Jobs", birthdate: Date(year: 1955, month: 2, day: 24), nationality: "🇺🇸", subPeople: [
.init(name: "Yet Another Steve Jobs", birthdate: Date(year: 1955, month: 2, day: 24), nationality: "🇺🇸")
])
])
]),
PersonModel(name: "Emma Goldman", birthdate: Date(year: 1_869, month: 6, day: 27), nationality: "🇷🇺"),
PersonModel(name: "Mikhail Bakunin", birthdate: Date(year: 1_814, month: 5, day: 30), nationality: "🇷🇺"),
PersonModel(name: "Ursula K. Le Guin", birthdate: Date(year: 1_929, month: 10, day: 21), nationality: "🇺🇸"),
Expand Down
12 changes: 12 additions & 0 deletions Sources/CellViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ public protocol CellViewModel: DiffableViewModel, ViewRegistrationProvider {
/// This corresponds to the delegate method `collectionView(_:contextMenuConfigurationForItemAt:point:)`.
var contextMenuConfiguration: UIContextMenuConfiguration? { get }

/// Returns an array of children for the cell.
/// These children correspond to the items that have been appended to this item as part of a `NSDiffableDataSourceSectionSnapshot`.
Comment on lines +41 to +42
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Returns an array of children for the cell.
/// These children correspond to the items that have been appended to this item as part of a `NSDiffableDataSourceSectionSnapshot`.
/// Returns an array of subitems for this cell.
/// This results in this cell becoming the parent item for this array of children items.

var children: [AnyCellViewModel] { get }

/// Configures the provided cell for display in the collection.
/// - Parameter cell: The cell to configure.
@MainActor
Expand Down Expand Up @@ -90,6 +94,9 @@ extension CellViewModel {
/// Default implementation. Returns `true`.
public var shouldHighlight: Bool { true }

/// Default implementation. Returns `[]`.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Default implementation. Returns `[]`.
/// Default implementation. Returns an empty array, `[]`.

public var children: [AnyCellViewModel] { [] }

/// Default implementation. Returns `nil`.
public var contextMenuConfiguration: UIContextMenuConfiguration? { nil }

Expand Down Expand Up @@ -198,6 +205,9 @@ public struct AnyCellViewModel: CellViewModel {
/// :nodoc:
public var shouldHighlight: Bool { self._shouldHighlight }

/// :nodoc:
public var children: [AnyCellViewModel] { self._children }

/// :nodoc:
public var contextMenuConfiguration: UIContextMenuConfiguration? { self._contextMenuConfiguration }

Expand Down Expand Up @@ -251,6 +261,7 @@ public struct AnyCellViewModel: CellViewModel {
private let _shouldDeselect: Bool
private let _shouldHighlight: Bool
private let _contextMenuConfiguration: UIContextMenuConfiguration?
private let _children: [AnyCellViewModel]
private let _configure: @Sendable @MainActor (CellType) -> Void
private let _didSelect: @Sendable @MainActor (CellEventCoordinator?) -> Void
private let _didDeselect: @Sendable @MainActor (CellEventCoordinator?) -> Void
Expand All @@ -276,6 +287,7 @@ public struct AnyCellViewModel: CellViewModel {
self._shouldSelect = viewModel.shouldSelect
self._shouldDeselect = viewModel.shouldDeselect
self._shouldHighlight = viewModel.shouldHighlight
self._children = viewModel.children
self._contextMenuConfiguration = viewModel.contextMenuConfiguration
self._configure = {
viewModel._configureGeneric(cell: $0)
Expand Down
20 changes: 10 additions & 10 deletions Sources/CollectionViewDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -328,45 +328,45 @@ extension CollectionViewDriver: UICollectionViewDelegate {
/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
shouldSelectItemAt indexPath: IndexPath) -> Bool {
self.viewModel.cellViewModel(at: indexPath).shouldSelect
self.viewModel.cellViewModel(at: indexPath, in: collectionView).shouldSelect
}

/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
self.viewModel.cellViewModel(at: indexPath).didSelect(with: self._cellEventCoordinator)
self.viewModel.cellViewModel(at: indexPath, in: collectionView).didSelect(with: self._cellEventCoordinator)
}

/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
shouldDeselectItemAt indexPath: IndexPath) -> Bool {
self.viewModel.cellViewModel(at: indexPath).shouldDeselect
self.viewModel.cellViewModel(at: indexPath, in: collectionView).shouldDeselect
}

/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
didDeselectItemAt indexPath: IndexPath) {
self.viewModel.cellViewModel(at: indexPath).didDeselect(with: self._cellEventCoordinator)
self.viewModel.cellViewModel(at: indexPath, in: collectionView).didDeselect(with: self._cellEventCoordinator)
}

// MARK: Managing cell highlighting

/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
shouldHighlightItemAt indexPath: IndexPath) -> Bool {
self.viewModel.cellViewModel(at: indexPath).shouldHighlight
self.viewModel.cellViewModel(at: indexPath, in: collectionView).shouldHighlight
}

/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
didHighlightItemAt indexPath: IndexPath) {
self.viewModel.cellViewModel(at: indexPath).didHighlight()
self.viewModel.cellViewModel(at: indexPath, in: collectionView).didHighlight()
}

/// :nodoc:
public func collectionView(_ collectionView: UICollectionView,
didUnhighlightItemAt indexPath: IndexPath) {
self.viewModel.cellViewModel(at: indexPath).didUnhighlight()
self.viewModel.cellViewModel(at: indexPath, in: collectionView).didUnhighlight()
}

// MARK: Managing context menus
Expand All @@ -375,7 +375,7 @@ extension CollectionViewDriver: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView,
contextMenuConfigurationForItemAt indexPath: IndexPath,
point: CGPoint) -> UIContextMenuConfiguration? {
self.viewModel.cellViewModel(at: indexPath).contextMenuConfiguration
self.viewModel.cellViewModel(at: indexPath, in: collectionView).contextMenuConfiguration
}

// MARK: Tracking the addition and removal of views
Expand All @@ -384,7 +384,7 @@ extension CollectionViewDriver: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
self.viewModel._safeCellViewModel(at: indexPath)?.willDisplay()
self.viewModel._safeCellViewModel(at: indexPath, in: collectionView)?.willDisplay()
}

/// :nodoc:
Expand All @@ -399,7 +399,7 @@ extension CollectionViewDriver: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath) {
self.viewModel._safeCellViewModel(at: indexPath)?.didEndDisplaying()
self.viewModel._safeCellViewModel(at: indexPath, in: collectionView)?.didEndDisplaying()
}

/// :nodoc:
Expand Down
45 changes: 38 additions & 7 deletions Sources/CollectionViewModel.swift

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to replace allCellsByIdentifier:

func allCellsByIdentifier() -> [UniqueIdentifier: AnyCellViewModel] {
        var allCellsDict = [UniqueIdentifier: AnyCellViewModel]()
        var cellsToProcess: [AnyCellViewModel] = []
        
        for section in self.sections {
            cellsToProcess.append(contentsOf: section.cells)
        }
        
        while let cell = cellsToProcess.popLast() {
            allCellsDict[cell.id] = cell
            cellsToProcess.append(contentsOf: cell.children)
        }
        
        return allCellsDict
    }

Note: maybe a place we can optimize performance? You have to call allCellsByIdentifier for both source and dest in _findItemsToReconfigure which size-wise can be >>> the # of cells you actually care about--visible items--which is probably around ~10 on mobile depending on ur design

Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,19 @@ public struct CollectionViewModel: DiffableViewModel {

// MARK: Accessing Cells

/// Returns the cell for the specified `id`.
/// Returns the cell for the specified `id` by traversing each section and all of the children of each cell.
///
/// - Parameter id: The identifier for the cell.
/// - Returns: The cell, if it exists.
public func cellViewModel(for id: UniqueIdentifier) -> AnyCellViewModel? {
for section in self.sections {
for cell in section.cells where cell.id == id {
return cell
for cell in section.cells {
if let foundViewModel = cellViewModel(in: cell, with: id) {
return foundViewModel
}
}
}

return nil
}

Expand All @@ -84,14 +87,42 @@ public struct CollectionViewModel: DiffableViewModel {
/// - Returns: The cell at `indexPath`.
///
/// - Precondition: The specified `indexPath` must be valid.
public func cellViewModel(at indexPath: IndexPath) -> AnyCellViewModel {
public func cellViewModel(at indexPath: IndexPath, in collectionView: UICollectionView) -> AnyCellViewModel {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of the changes here seem wrong. I'm very weary and skeptical of referencing the collection view, datasource, and snapshot here. This breaks a lot of encapsulation.

My first thought is that this method shouldn't change.

But that raises the question: what is the index path of a nested child cell? How does that work?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

per the video here, an item's index path changes depending on if there are expanded items preceding it.

I think this was part of why I went with the approach I did, because we need to know what's visible at the moment. Still need to look around some more to refresh myself.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another thing we can do is get the section from the collection view model, then ask the data source for the snapshot of that section, then grab the visibleItems off that and use those to get the cell view model.

something like:

let section = self.viewModel.sectionViewModel(at: sectionIndex)
let snapshot = self._dataSource.snapshot(for: section.id)
let visibleItems = Array(snapshot.visibleItems)

// ...

let identifier = visibleItems[indexPath.item]
if let cell = self.cellViewModel(for: identifier) {
    return cell
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This behavior seems to be mostly undocumented, as mentioned here in the first section:

https://swiftsenpai.com/development/undocumented-section-snapshot-facts/

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

per the video here, an item's index path changes depending on if there are expanded items preceding it.

I think this was part of why I went with the approach I did, because we need to know what's visible at the moment. Still need to look around some more to refresh myself.

Ahh thanks. Super helpful.

Another thing we can do is get the section from the collection view model, then ask the data source for the snapshot of that section, then grab the visibleItems off that and use those to get the cell view model.

I am still extremely apprehensive about having CollectionViewModel know anything about any other components. That really breaks a lot of paradigms and encapsulation.

The entire idea behind CollectionViewModel is that it is a full representation of the collection view state. This means it should model the item expand/collapse behavior. So here's what I'm thinking — since CellViewModel now has a children property, it should also have an isExpanded property. Once this is part of the model, we should be able to figure everything out regarding visibility and index paths without having to muck with dataSource, etc. Then everything makes sense. We know that if an item is expanded, then its children are "visible" (here visible means not necessarily on screen, but having a valid index path).

I have not experimented with any code yet, so the open questions on the feasibility of this approach are:

Do we have to keep isExpanded in sync with the data source somehow? Can we do that? It seems like there are callbacks for this, UICollectionViewDiffableDataSourceSectionSnapshotHandlers.

How exactly would this work? The Driver generates a new model and applies it?

How does all of this work with UI interactions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I'm understanding right, I think the DiffableDataSource would need a way to access the CollectionViewModel upon expand/collapse events, so it can then get the right cellViewModel and update its property. Is that what you had in mind, some sort of way for the data source to communicate up (or otherwise) that those events have happened?

precondition(indexPath.section < self.count)
let section = self.sectionViewModel(at: indexPath.section)

let cells = section.cells
precondition(indexPath.item < cells.count)

return cells[indexPath.item]
guard let diffableDataSource = collectionView.dataSource as? DiffableDataSource
else {
return cells[indexPath.item]
}

let snapshot = diffableDataSource.snapshot(for: section.id)
let id = snapshot.visibleItems[indexPath.item]

guard let cellViewModel = cellViewModel(for: id)
else {
return cells[indexPath.item]
}

return cellViewModel
}

/// Recursively traverse the children array of each child to locate a matching cell view model
private func cellViewModel(in viewModel: AnyCellViewModel, with id: UniqueIdentifier) -> AnyCellViewModel? {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should push some of this functionality to CellViewModel. We should be able to ask a cell for a specific child.

cellViewModel.childWithIdentifier(id)

if viewModel.id == id {
return viewModel
}

for child in viewModel.children {
if let foundChildViewModel = cellViewModel(in: child, with: id) {
return foundChildViewModel
}
}

return nil
}

// MARK: Accessing Supplementary Views
Expand Down Expand Up @@ -168,12 +199,12 @@ public struct CollectionViewModel: DiffableViewModel {
return self.sectionViewModel(at: index)
}

func _safeCellViewModel(at indexPath: IndexPath) -> AnyCellViewModel? {
func _safeCellViewModel(at indexPath: IndexPath, in collectionView: UICollectionView) -> AnyCellViewModel? {
guard let section = self._safeSectionViewModel(at: indexPath.section),
indexPath.item < section.cells.count else {
return nil
}
return self.cellViewModel(at: indexPath)
return self.cellViewModel(at: indexPath, in: collectionView)
}

func _safeSupplementaryViewModel(ofKind kind: String, at indexPath: IndexPath) -> AnySupplementaryViewModel? {
Expand Down
Loading