From db7cd43658a8d9a506b46b04a2811199c444b88e Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Sun, 5 Feb 2023 12:22:56 -0800 Subject: [PATCH] Make the cloud cloudier --- MemoryTree/CloudView.swift | 66 +++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 5 deletions(-) diff --git a/MemoryTree/CloudView.swift b/MemoryTree/CloudView.swift index 6409a4b..600ceb3 100644 --- a/MemoryTree/CloudView.swift +++ b/MemoryTree/CloudView.swift @@ -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) }