Make the cloud cloudier

This commit is contained in:
Sami Samhuri 2023-02-05 12:22:56 -08:00
parent b25908d22d
commit db7cd43658
No known key found for this signature in database
GPG key ID: 4B4195422742FC16

View file

@ -10,14 +10,27 @@ import SwiftUI
struct CloudView: View {
// @Stored(in: .entriesStore) var entries
@Binding var entries: [Entry]
@Binding var entries: [Entry] {
didSet {
countedWords = countWords()
}
}
@State var countedWords: [String: Int] = [:]
var words: [String] {
Array(countedWords.keys)
}
@Environment(\.dismiss) var dismiss
var body: some View {
VStack {
ForEach(entries) { entry in
Text(entry.text)
ForEach(words, id: \.self) { word in
let count = countedWords[word, default: 1]
Text(word)
.font(fontForCount(count))
.bold(count > 2)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
@ -38,6 +51,26 @@ struct CloudView: View {
}
}
}
func fontForCount(_ count: Int) -> Font {
switch count {
case 0, 1: return .body
case 2: return .title3
case 3: return .title2
case 4: return .title
default: return .largeTitle
}
}
func countWords() -> [String: Int] {
let words = entries
.map(\.text)
.flatMap { $0.split(separator: " ") }
.map(String.init)
return words.reduce(into: [:]) { partialResult, word in
partialResult[word, default: 0] += 1
}
}
}
struct CloudView_Previews: PreviewProvider {
@ -45,9 +78,32 @@ struct CloudView_Previews: PreviewProvider {
Group {
NavigationStack {
CloudView(entries: .constant([]))
CloudView(entries: .constant([Entry(text: "Coffee"), Entry(text: "Trees")]))
}
.previewDisplayName("Empty")
NavigationStack {
CloudView(entries: .constant([]), countedWords: [
"Coffee" : 2,
"Trees" : 1,
"Mountains" : 1,
])
}
.previewDisplayName("Few entries")
NavigationStack {
CloudView(entries: .constant([]), countedWords: [
"Coffee" : 4,
"Trees" : 2,
"Mountains" : 3,
"Burritos" : 1,
"Home" : 5,
"My Cat": 2,
"Love": 3,
"Clean water": 2,
"Health": 3,
])
}
.previewDisplayName("Many entries")
}
.tint(.white)
}