willowtreeapps / tablediff

MIT License
11 stars 4 forks source link

TableDiff

TableDiff is a small library that takes two collections and generates a diff that is suitable for feeding into UITableView or UICollectionView to animate the changes. It additionally tracks which items have been updated so that UI code can adjust individual rows or cells.

We created it to animate between distinct collection states in a Redux-like architecture like ReSwift.

Table of Contents

Getting Started

Please see the demo app for a working example.

Initially you will want to make the elements in your datasource to conform to the protocol SequenceDiffable. This means you need to

The identifier is used to determine if two items are the same, while equality checks to see if the same item has been updated.

When you want to update the datasource you will need to calculate the diff:

let (diff, updates) = originalData.tableDiff(newData)

Then you can choose to either perform all the updates yourself or you can use the convenience extensions to handle the moves/inserts/deletes:

tableView.applyDiff(diff)
collectionView.applyDiff(diff)

Updates still need to be managed manually, as this is app specific code. You can change the animation styles with additional parameters on the helpers.

Implementations

We originally approached this problem with a Longest Common Subsequence algorithm, based on the work of Dwifft. However, that algorithm only speaks in inserts and deletes, while for some use cases we would prefer to use UITableView's move capabilities.

We provide three different implementation options:

You can choose which implementation to use via a parameter. The default value is .allMoves.

tableView.applyDiff(diff, implementation: .lcs)

Updates

Updates to an individual item are tracked while the diff is created. But since an update implies the same item is in both collections, you have the choice of which collection's indices you'd like to use. You can choose to have the first collection's indices with .pre, or the second collection's with .post. The default is .pre.

tableView.applyDiff(diff, updateStyle: .post)

Goals

Bugs and Feature Requests

Have a bug or a feature request? Please first read the issue guidelines and search for existing and closed issues. If your problem or idea is not addressed yet, please open a new issue.

Contributing

Please read through our contributing guidelines. Included are directions for opening issues, coding standards, and notes on development.