Skip to content

Commit

Permalink
fix: update the current date when changing tabs (Dimillian#327)
Browse files Browse the repository at this point in the history
* fix: update the current date when changing tabs

* Fix Dimillian#325
* Previously the date was only update once the app start. So at some
point if the app survive a night, the date will be wrong. To prevent
that, we update now the date every time the tab is changed

* fix: pass the actual current date to Items
  • Loading branch information
renaudjenny authored Oct 10, 2020
1 parent 4bbe1a1 commit 0dd3547
Showing 21 changed files with 105 additions and 46 deletions.
4 changes: 4 additions & 0 deletions ACHNBrowserUI/ACHNBrowserUI.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@
3DFC04E424D6DAA3002A6CED /* DreamCodeListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DFC04E324D6DAA3002A6CED /* DreamCodeListView.swift */; };
3DFC04E624D6DAAE002A6CED /* DreamCodeRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DFC04E524D6DAAE002A6CED /* DreamCodeRow.swift */; };
3DFC04E824D6DABC002A6CED /* DreamCodeDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DFC04E724D6DABC002A6CED /* DreamCodeDetailView.swift */; };
4C062B12252BB5BE004DCFA3 /* CurrentDateEnvironment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C062B11252BB5BE004DCFA3 /* CurrentDateEnvironment.swift */; };
4C30BFC3249627FD003E96A2 /* Sequence+Unique.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C30BFC2249627FC003E96A2 /* Sequence+Unique.swift */; };
4C6E95FD24842F690074433B /* Collection+SafeDirectAccess.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C6E95FC24842F690074433B /* Collection+SafeDirectAccess.swift */; };
4C7F555D248B91C80089F26C /* TodayVillagerVisitsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C7F555C248B91C80089F26C /* TodayVillagerVisitsSection.swift */; };
@@ -237,6 +238,7 @@
3DFC04E324D6DAA3002A6CED /* DreamCodeListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DreamCodeListView.swift; sourceTree = "<group>"; };
3DFC04E524D6DAAE002A6CED /* DreamCodeRow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DreamCodeRow.swift; sourceTree = "<group>"; };
3DFC04E724D6DABC002A6CED /* DreamCodeDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DreamCodeDetailView.swift; sourceTree = "<group>"; };
4C062B11252BB5BE004DCFA3 /* CurrentDateEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CurrentDateEnvironment.swift; sourceTree = "<group>"; };
4C2D676A245DA41E005831C4 /* TurnipsChartView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TurnipsChartView.swift; sourceTree = "<group>"; };
4C2D676D245F0666005831C4 /* TurnipsChartBottomLegendView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TurnipsChartBottomLegendView.swift; sourceTree = "<group>"; };
4C2D676F245F0698005831C4 /* TurnipsChart.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TurnipsChart.swift; sourceTree = "<group>"; };
@@ -564,6 +566,7 @@
children = (
696B454B247A948A00E16252 /* MusicPlayerManager.swift */,
693E728D245D71DD00CD26F4 /* UIState.swift */,
4C062B11252BB5BE004DCFA3 /* CurrentDateEnvironment.swift */,
);
path = env;
sourceTree = "<group>";
@@ -1253,6 +1256,7 @@
4C6E95FD24842F690074433B /* Collection+SafeDirectAccess.swift in Sources */,
AE2D7EFC247E9726006C1F1A /* DesignListView.swift in Sources */,
69157BC12471A5A1005B9002 /* ItemsViewModel.swift in Sources */,
4C062B12252BB5BE004DCFA3 /* CurrentDateEnvironment.swift in Sources */,
69157BC22471A5A1005B9002 /* TodayEventsSection.swift in Sources */,
69157BC32471A5A1005B9002 /* FeedbackGenerator.swift in Sources */,
3DFC04E824D6DABC002A6CED /* DreamCodeDetailView.swift in Sources */,
20 changes: 20 additions & 0 deletions ACHNBrowserUI/ACHNBrowserUI/env/CurrentDateEnvironment.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// CurrentDateEnvironment.swift
// ACHNBrowserUI
//
// Created by Renaud JENNY on 05/10/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//

import SwiftUI

struct CurrentDateKey: EnvironmentKey {
static let defaultValue = Date()
}

extension EnvironmentValues {
var currentDate: Date {
get { self[CurrentDateKey.self] }
set { self[CurrentDateKey.self] = newValue }
}
}
3 changes: 1 addition & 2 deletions ACHNBrowserUI/ACHNBrowserUI/utils/EventsDescription.swift
Original file line number Diff line number Diff line change
@@ -38,9 +38,8 @@ extension Event {
}
}

static func nextEvent() -> (Date, Event?) {
static func nextEvent(today: Date) -> (Date, Event?) {
let aDay: TimeInterval = 24*60*60
let today = Date()
let endDate = today.addingTimeInterval(aDay * 365)
var nextDate = today.addingTimeInterval(aDay)
var event: Event? = nil
Original file line number Diff line number Diff line change
@@ -49,40 +49,44 @@ class ActiveCrittersViewModel: ObservableObject {

private let items: Items
private let collection: UserCollection
private let filterOutInCollection: Bool

private var cancellable: AnyCancellable?

init(filterOutInCollection: Bool = false, items: Items = .shared, collection: UserCollection = .shared) {
self.items = items
self.collection = collection
self.isLoading = true

self.filterOutInCollection = filterOutInCollection
}

func updateCritters(for currentDate: Date) {
cancellable = Publishers.CombineLatest(items.$categories, collection.$critters)
.receive(on: DispatchQueue.main)
.sink { [weak self] (items, critters) in
guard let self = self else { return }
for type in CritterType.allCases {
var active = items[type.category()]?.filterActiveThisMonth() ?? []
var new = active.filter{ $0.isNewThisMonth() }
var leaving = active.filter{ $0.leavingThisMonth() }
var active = items[type.category()]?.filterActiveThisMonth(currentDate: currentDate) ?? []
var new = active.filter{ $0.isNewThisMonth(currentDate: currentDate) }
var leaving = active.filter{ $0.leavingThisMonth(currentDate: currentDate) }
let caught = active.filter{ critters.contains($0) }
let toCatchNow = active.filter{ !caught.contains($0) && $0.isActiveAtThisHour() }
let toCatchNow = active.filter{ !caught.contains($0) && $0.isActiveAtThisHour(currentDate: currentDate) }
let toCatchLater = active.filter{ !caught.contains($0) && !toCatchNow.contains($0) }
if filterOutInCollection {

if self.filterOutInCollection {
new = new.filter{ !critters.contains($0) }
leaving = leaving.filter{ !critters.contains($0) }
active = active.filter{ !critters.contains($0) }
}

self.crittersInfo[type] = CritterInfo(active: active,
new: new,
leaving: leaving,
caught: caught,
toCatchNow: toCatchNow,
toCatchLater: toCatchLater)
new: new,
leaving: leaving,
caught: caught,
toCatchNow: toCatchNow,
toCatchLater: toCatchLater)
self.isLoading = false
}
}
}
}
}
9 changes: 9 additions & 0 deletions ACHNBrowserUI/ACHNBrowserUI/viewModels/TabbarViewModel.swift
Original file line number Diff line number Diff line change
@@ -16,6 +16,8 @@ class TabbarViewModel: ObservableObject {
private var musicPlayerPlayingCancellable: AnyCancellable?

@Published var showPlayerView = false
@Published private(set) var currentDate = Date()
@Published private(set) var cancellables: Set<AnyCancellable> = []

init(musicPlayerManager: MusicPlayerManager) {
self.musicPlayerManager = musicPlayerManager
@@ -27,4 +29,11 @@ class TabbarViewModel: ObservableObject {
}
}
}

func updateCurrentDateOnTabChange(selectedTabPublisher: Published<UIState.Tab>.Publisher) {
selectedTabPublisher
.removeDuplicates()
.sink { [weak self] _ in self?.currentDate = Date() }
.store(in: &cancellables)
}
}
Original file line number Diff line number Diff line change
@@ -10,6 +10,7 @@ import SwiftUI
import Backend

struct ActiveCritterSections: View {
@Environment(\.currentDate) private var currentDate
@ObservedObject var viewModel: ActiveCrittersViewModel
@Binding var selectedTab: ActiveCrittersViewModel.CritterType

@@ -53,6 +54,9 @@ struct ActiveCritterSections: View {
content: sectionContent)
}
}
.onAppear {
viewModel.updateCritters(for: currentDate)
}
}
}

6 changes: 5 additions & 1 deletion ACHNBrowserUI/ACHNBrowserUI/views/home/TabbarView.swift
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@

import SwiftUI
import Backend
import Combine

struct TabbarView: View {
@EnvironmentObject private var uiState: UIState
@@ -51,7 +52,10 @@ struct TabbarView: View {
Text("Collection")
}
.tag(UIState.Tab.collection)

}
.environment(\.currentDate, viewModel.currentDate)
.onAppear {
viewModel.updateCurrentDateOnTabChange(selectedTabPublisher: uiState.$selectedTab)
}

if viewModel.showPlayerView {
5 changes: 3 additions & 2 deletions ACHNBrowserUI/ACHNBrowserUI/views/shared/CalendarView.swift
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ import SwiftUI
import Backend

struct CalendarView: View {
@Environment(\.currentDate) private var currentDate
let activeMonths: [Int]

private let currentMonth = Int(Item.monthFormatter.string(from: Date()))!

private let months = [[Calendar.current.shortMonthSymbols[0],
Calendar.current.shortMonthSymbols[1],
Calendar.current.shortMonthSymbols[2],
@@ -32,6 +32,7 @@ struct CalendarView: View {

private func makeMonthPill(month: String, selected: Bool) -> some View {
let monthsArray = months.flatMap({ $0 })
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
let isCurrentMonth = monthsArray.firstIndex(of: month) == currentMonth - 1
let border = RoundedRectangle(cornerRadius: 10)
.stroke(lineWidth: isCurrentMonth ? 5 : 0)
Original file line number Diff line number Diff line change
@@ -10,6 +10,7 @@ import SwiftUI
import Backend

struct TodayCurrentlyAvailableSection: View {
@Environment(\.currentDate) private var currentDate
@StateObject private var viewModel = ActiveCrittersViewModel()
@State private var isNavigationLinkActive = false
@State private var openingTab: ActiveCrittersViewModel.CritterType = .fish
@@ -102,7 +103,7 @@ struct TodayCurrentlyAvailableSection: View {
}

private func dayNumber() -> Int {
return Calendar.current.dateComponents([.day], from: Date()).day ?? 0
return Calendar.current.dateComponents([.day], from: currentDate).day ?? 0
}
}

Original file line number Diff line number Diff line change
@@ -11,10 +11,7 @@ import ACNHEvents
import Backend

struct TodayEventsSection: View {

let todaysEvents = Date().events(for: AppUserDefaults.shared.hemisphere == .north ? .north : .south)
let nextEvent = Event.nextEvent()

@Environment(\.currentDate) private var currentDate

var body: some View {
VStack(alignment: .leading) {
@@ -40,6 +37,12 @@ struct TodayEventsSection: View {
}
}

private var todaysEvents: [Event] {
currentDate.events(for: AppUserDefaults.shared.hemisphere == .north ? .north : .south)
}

private var nextEvent: (Date, Event?) { Event.nextEvent(today: currentDate) }

private func subsectionHeader(_ text: String) -> some View {
Text(LocalizedStringKey(text))
.font(.system(.caption, design: .rounded))
Original file line number Diff line number Diff line change
@@ -11,11 +11,12 @@ import SwiftUIKit
import Backend

struct TodaySpecialCharactersSection: View {
@Environment(\.currentDate) private var currentDate
@State private var selectedCharacter: SpecialCharacters?
@Namespace private var namespace

private var currentIcon: String {
let hour = Calendar.current.component(.hour, from: Date())
let hour = Calendar.current.component(.hour, from: currentDate)
if hour < 9 {
return "sunrise.fill"
} else if hour < 17 {
@@ -54,7 +55,7 @@ struct TodaySpecialCharactersSection: View {
.aspectRatio(contentMode: .fit)
.frame(width: 25)
.foregroundColor(.acHeaderBackground)
Text(Date(), style: .time)
Text(currentDate, style: .time)
.style(appStyle: .rowDetail)
}
.padding(16)
@@ -96,7 +97,7 @@ struct TodaySpecialCharactersSection: View {
} else {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 16) {
ForEach(SpecialCharacters.now(), id: \.self) { character in
ForEach(SpecialCharacters.forDate(currentDate), id: \.self) { character in
Image(character.rawValue)
.resizable()
.aspectRatio(contentMode: .fit)
Original file line number Diff line number Diff line change
@@ -10,10 +10,11 @@ import SwiftUI
import Backend

struct TodayTurnipSection: View {
@Environment(\.currentDate) private var currentDate
@EnvironmentObject private var turnipService: TurnipPredictionsService

var isSunday: Bool {
Calendar.current.component(.weekday, from: Date()) == 1
Calendar.current.component(.weekday, from: currentDate) == 1
}

var body: some View {
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@ import UI
struct TodayView: View {

// MARK: - Vars
@Environment(\.currentDate) private var currentDate
@StateObject private var viewModel = DashboardViewModel()
@State private var selectedSheet: Sheet.SheetType?

@@ -88,7 +89,7 @@ struct TodayView: View {
private var dateString: String {
let f = DateFormatter()
f.setLocalizedDateFormatFromTemplate("EEEE, MMM d")
return f.string(from: Date())
return f.string(from: currentDate)
}
}

Original file line number Diff line number Diff line change
@@ -13,6 +13,7 @@ struct TurnipsFormView: View {
// MARK: - Properties
@EnvironmentObject private var subscriptionManager: SubscriptionManager
@Environment(\.presentationMode) private var presentationMode
@Environment(\.currentDate) private var currentDate

@State private var fields = TurnipFields.decode()
@State private var enableNotifications = SubscriptionManager.shared.subscriptionStatus == .subscribed
Original file line number Diff line number Diff line change
@@ -119,7 +119,8 @@ struct TurnipsChartView_Previews: PreviewProvider {
minBuyPrice: 83,
averagePrices: averagePrices,
minMax: minMax,
averageProfits: averageProfits
averageProfits: averageProfits,
currentDate: Date()
)

static let averagePrices = [89, 85, 88, 104, 110, 111, 111, 111, 106, 98, 82, 77]
Original file line number Diff line number Diff line change
@@ -10,8 +10,8 @@ import Foundation


public extension BidirectionalCollection where Element == Item {
func filterActiveThisMonth() -> [Item] {
self.filter({ $0.isActiveThisMonth() })
func filterActiveThisMonth(currentDate: Date) -> [Item] {
self.filter({ $0.isActiveThisMonth(currentDate: currentDate) })
}
}

16 changes: 8 additions & 8 deletions ACHNBrowserUI/Packages/Backend/Sources/Backend/Models/Item.swift
Original file line number Diff line number Diff line change
@@ -163,17 +163,17 @@ public extension Item {
return nil
}

func isActiveThisMonth() -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: Date()))!
func isActiveThisMonth(currentDate: Date) -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
return activeMonthsCalendar?.contains(currentMonth - 1) == true
}

func isActiveAtThisHour() -> Bool {
func isActiveAtThisHour(currentDate: Date) -> Bool {
guard let hours = activeHours() else { return false }

if hours.start == 0 && hours.end == 0 { return true } // All day

let thisHour = Calendar.current.dateComponents([.hour], from: Date()).hour ?? 0
let thisHour = Calendar.current.dateComponents([.hour], from: currentDate).hour ?? 0

if hours.start < hours.end { // Same day
return thisHour >= hours.start && thisHour < hours.end
@@ -182,13 +182,13 @@ public extension Item {
}
}

func isNewThisMonth() -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: Date()))!
func isNewThisMonth(currentDate: Date) -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
return activeMonthsCalendar?.contains(currentMonth - 2) == false
}

func leavingThisMonth() -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: Date()))!
func leavingThisMonth(currentDate: Date) -> Bool {
let currentMonth = Int(Item.monthFormatter.string(from: currentDate))!
return activeMonthsCalendar?.contains(currentMonth) == false
}

Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ import SwiftUI
public enum SpecialCharacters: String, CaseIterable {
case kk, daisy, cj, flick, kicks, saharah, gulliver, label, leif, redd, wisp, celeste

public static func now() -> [SpecialCharacters] {
let day = Calendar.current.component(.weekday, from: Date())
let hour = Calendar.current.component(.hour, from: Date())
public static func forDate(_ currentDate: Date) -> [SpecialCharacters] {
let day = Calendar.current.component(.weekday, from: currentDate)
let hour = Calendar.current.component(.hour, from: currentDate)
if day == 1 {
return [.daisy]
} else if day == 7 {
Loading

0 comments on commit 0dd3547

Please sign in to comment.