mastodon-ios/MastodonSDK/Sources/MastodonCore/FetchedResultsController/StatusFetchedResultsControl...

73 lines
2.1 KiB
Swift
Raw Normal View History

2021-04-01 08:39:15 +02:00
//
// StatusFetchedResultsController.swift
// Mastodon
//
// Created by MainasuK Cirno on 2021-3-30.
//
import UIKit
import Combine
import CoreData
import CoreDataStack
import MastodonSDK
2023-11-22 12:32:04 +01:00
public final class StatusFetchedResultsController {
@MainActor
2023-11-22 13:18:41 +01:00
@Published
public private(set) var records: [MastodonStatus] = []
2021-04-01 08:39:15 +02:00
2023-11-22 12:32:04 +01:00
@MainActor
public init(records: [MastodonStatus] = []) {
self.records = records
2021-04-01 08:39:15 +02:00
}
2023-11-22 12:32:04 +01:00
@MainActor
public func reset() {
records = []
}
2023-11-22 12:32:04 +01:00
@MainActor
public func setRecords(_ records: [MastodonStatus]) {
self.records = records
}
2023-11-22 12:32:04 +01:00
@MainActor
public func appendRecords(_ records: [MastodonStatus]) {
self.records += records
2021-04-01 08:39:15 +02:00
}
@MainActor
public func update(status: MastodonStatus) {
var newRecords = Array(records)
for (i, record) in newRecords.enumerated() {
if record.id == status.id {
newRecords[i] = status
} else if let reblog = status.reblog, reblog.id == record.id {
newRecords[i] = status
} else if let reblog = record.reblog, reblog.id == status.id {
// Handle reblogged state
switch status.entity.reblogged {
case .some(true):
newRecords[i] = {
let stat = MastodonStatus.fromEntity(records[i].entity)
stat.isSensitiveToggled = status.isSensitiveToggled
stat.reblog = .fromEntity(status.entity)
return stat
}()
case .some(false), .none:
newRecords[i] = {
let stat = MastodonStatus.fromEntity(status.entity)
stat.isSensitiveToggled = status.isSensitiveToggled
return stat
}()
}
} else if let reblog = record.reblog, reblog.id == status.reblog?.id {
// Handle re-reblogged state
newRecords[i] = status
}
}
records = newRecords
}
2021-04-01 08:39:15 +02:00
}