Use a table to look up TimelineItem position instead of spinning through the TimelineItems

This commit is contained in:
Maurice Parker 2020-07-18 16:36:20 -05:00
parent 3899fe7fd9
commit 271f7433d4
1 changed files with 27 additions and 4 deletions

View File

@ -26,7 +26,6 @@ class TimelineModel: ObservableObject, UndoableCommandRunner {
weak var delegate: TimelineModelDelegate?
@Published var nameForDisplay = ""
@Published var timelineItems = [TimelineItem]()
@Published var selectedArticleIDs = Set<String>() // Don't use directly. Use selectedArticles
@Published var selectedArticleID: String? = .none // Don't use directly. Use selectedArticles
@Published var selectedArticles = [Article]()
@ -38,6 +37,12 @@ class TimelineModel: ObservableObject, UndoableCommandRunner {
articleDictionaryNeedsUpdate = true
}
}
@Published var timelineItems = [TimelineItem]() {
didSet {
timelineItemDictionaryNeedsUpdate = true
}
}
var undoManager: UndoManager?
var undoableCommands = [UndoableCommand]()
@ -58,6 +63,15 @@ class TimelineModel: ObservableObject, UndoableCommandRunner {
return _idToArticleDictionary
}
private var timelineItemDictionaryNeedsUpdate = true
private var _idToTimelineItemDictionary = [String: Int]()
private var idToTimelineItemDictionary: [String: Int] {
if timelineItemDictionaryNeedsUpdate {
rebuildTimelineItemDictionaries()
}
return _idToTimelineItemDictionary
}
private var sortDirection = AppDefaults.shared.timelineSortDirection {
didSet {
if sortDirection != oldValue {
@ -79,9 +93,9 @@ class TimelineModel: ObservableObject, UndoableCommandRunner {
guard let self = self, let articleIDs = note.userInfo?[Account.UserInfoKey.articleIDs] as? Set<String> else {
return
}
for i in 0..<self.timelineItems.count {
if articleIDs.contains(self.timelineItems[i].article.articleID) {
self.timelineItems[i].updateStatus()
articleIDs.forEach { articleID in
if let timelineItemIndex = self.idToTimelineItemDictionary[articleID] {
self.timelineItems[timelineItemIndex].updateStatus()
}
}
}.store(in: &cancellables)
@ -377,6 +391,15 @@ private extension TimelineModel {
articleDictionaryNeedsUpdate = false
}
func rebuildTimelineItemDictionaries() {
var idDictionary = [String: Int]()
for (index, timelineItem) in timelineItems.enumerated() {
idDictionary[timelineItem.article.articleID] = index
}
_idToTimelineItemDictionary = idDictionary
timelineItemDictionaryNeedsUpdate = false
}
// MARK: Article Fetching
func fetchArticles() {