76 lines
2.2 KiB
Swift
76 lines
2.2 KiB
Swift
import Foundation
|
|
import SwiftDate
|
|
|
|
public struct DateSection<T: Identifiable> {
|
|
|
|
var timestamp: Double = 0
|
|
var dateString: String
|
|
public var elements: [T]
|
|
|
|
public var header: String {
|
|
"\(dateString) (\(elements.count))"
|
|
}
|
|
|
|
public init(source: DateSection<T>, elements: [T]) {
|
|
self.timestamp = source.timestamp
|
|
self.dateString = source.dateString
|
|
self.elements = elements
|
|
}
|
|
|
|
public init(original: DateSection, items: [T]) {
|
|
self = original
|
|
self.elements = items
|
|
}
|
|
|
|
public init(timestamp: Double, items: [T]) {
|
|
let formatter = DateFormatter()
|
|
formatter.dateStyle = .medium
|
|
formatter.timeStyle = .medium
|
|
|
|
let monthStart = DateCache.shared.monthStart
|
|
let weekStart = DateCache.shared.weekStart
|
|
|
|
let date = Date(timeIntervalSince1970: timestamp)
|
|
let dateInRegion = DateInRegion(date, region: Region.current)
|
|
if dateInRegion.isToday {
|
|
self.dateString = NSLocalizedString("Today", comment: "")
|
|
}
|
|
else if dateInRegion.isYesterday {
|
|
self.dateString = NSLocalizedString("Yesterday", comment: "")
|
|
} else if dateInRegion.isAfterDate(weekStart, granularity: .day) {
|
|
formatter.dateFormat = "EEEE"
|
|
self.dateString = formatter.string(from: date)
|
|
} else if dateInRegion.isAfterDate(monthStart, orEqual: false, granularity: .day) {
|
|
formatter.dateStyle = .medium
|
|
formatter.timeStyle = .none
|
|
self.dateString = formatter.string(from: date)
|
|
} else {
|
|
formatter.dateFormat = "LLLL yyyy"
|
|
self.dateString = formatter.string(from: date)
|
|
}
|
|
|
|
self.timestamp = timestamp
|
|
self.elements = items
|
|
}
|
|
|
|
public mutating func append(_ element: T) {
|
|
self.elements.append(element)
|
|
}
|
|
|
|
public mutating func insert(_ element: T, at index: Int) {
|
|
self.elements.insert(element, at: index)
|
|
}
|
|
|
|
public func index(of element: T) -> Int? {
|
|
elements.firstIndex { $0.id == element.id }
|
|
}
|
|
|
|
public mutating func replace(_ element: T, at index: Int) {
|
|
elements[index] = element
|
|
}
|
|
|
|
public mutating func remove(at index: Int) {
|
|
elements.remove(at: index)
|
|
}
|
|
}
|