Created
October 20, 2024 20:14
-
-
Save colinfwren/8906099167d85d91a8e4936b4502c540 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import SwiftData | |
import Algorithms | |
struct EntryListView: View { | |
@Query(sort: \Entry.created, order: .reverse) private var entries: [Entry] | |
let entryDateFormatter = DateFormatter() | |
let sectionDateFormatter = DateFormatter() | |
init() { | |
entryDateFormatter.dateFormat = "EEEE, dd MMM yyyy" | |
sectionDateFormatter.dateFormat = "MMM yyyy" | |
} | |
var body: some View { | |
List { | |
ForEach(sectionedEntries, id: \.self.0) { title, entries in | |
Section(title) { | |
ForEach(entries) { entry in | |
VStack(alignment: .leading, spacing: 4) { | |
Text(entry.text) | |
Text(entryDateFormatter.string(from: entry.created)) | |
} | |
} | |
} | |
} | |
} | |
} | |
var sectionedEntries: [(String, [Entry])] { | |
chunkEntries(entriesToChunk: entries) | |
} | |
func chunkEntries(entriesToChunk: [Entry]) -> [(String, [Entry])] { | |
let chunks = entriesToChunk.chunked(on: { | |
Calendar.current.dateComponents([.year, .month], from: $0.created) | |
}) | |
return chunks.map { | |
let chunkDate = Calendar.current.date(from: $0.0) | |
return (sectionDateFormatter.string(from: chunkDate!), Array($0.1)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment