mycode/myApp/HaruDanim/IOS/ContentView.swift
songyc macbook 0e6804b531 feat(progress): 주기 몫 채운 주간·월간 다짐의 하루 진행률을 '이번 주/달 달성' 상태로 표시
- 주간/월간 '이상 달성' 다짐이 현재 주기 몫을 채우면 하루 게이지가 0% 대신
  완료 상태(게이지 가득+초록 ✓+문구)로 표시 — 목표 탭 행·모음 카드·위젯 ②(체크)·
  ③(문구)·④(링 가득)·시리 하루 응답 공유
- 목표 하루 평균(combinedSpanRatio)에도 해당 다짐을 1.0으로 반영 —
  위젯 ② 목표 바·워치 목표 게이지·시리 목표 응답·일기 헤더 자동 반영
- 판정은 QuestProgress.isPeriodFulfilled 단일 지점 — 기준일의 논리적 하루 끝
  클리핑으로 일기 과거 날짜 소급 차단. spanProgress 수치·판정(judgment)·연속(streak)
  불변(표시 계층 전용). 하루 다짐·특정 기간·atMost는 비대상, 잠금화면·워치
  컴플리케이션은 공간 제약으로 수치 유지
- 도움말 '진행률 읽는 법' 문구 갱신, l10n en/ja 완료(전 카탈로그 stale 0·missing 0)
- 검증: -progressSelfTest 37→49건 ALL PASS(기존 37건 수치 무변경), 신규
  -seedPeriodFulfilled 시드로 ko/en/ja·위젯 실렌더 확인, 시리 스모크 10건 OK,
  Debug/Store 빌드 성공(워치 타깃은 Shared 미포함·무변경)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FVeduv1eNdXjk1ay4tSgBg
2026-08-01 06:45:01 +09:00

405 lines
16 KiB
Swift

//
// ContentView.swift
// Haru_Danim
//
// + (CLAUDE.md §5, )
//
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var context
@AppStorage(SettingsKeys.theme, store: AppGroup.defaults) private var theme: String = "system"
@State private var showSplash = true
@State private var showOnboarding = false
var body: some View {
ZStack {
#if DEBUG
// : -widgetPreview YES( ) / lock( ) / marketing( )
// -premiumPreview YES
// -helpPreview YES
if let mode = UserDefaults.standard.string(forKey: "widgetPreview") {
if mode == "marketing" {
MarketingWidgetScreen()
} else {
WidgetPreviewScreen(showLock: mode == "lock")
}
} else if UserDefaults.standard.bool(forKey: "premiumPreview") {
NavigationStack { PremiumView() }
} else if UserDefaults.standard.bool(forKey: "helpPreview") {
NavigationStack { HelpView() }
} else if UserDefaults.standard.bool(forKey: "dataExportPreview") {
NavigationStack { DataExportView() }
} else if UserDefaults.standard.bool(forKey: "dataImportPreview") {
NavigationStack { DataImportView() }
} else {
RootNavigationView()
}
#else
RootNavigationView()
#endif
if showSplash {
SplashView()
.transition(.opacity)
.zIndex(1)
}
}
.tint(AppTheme.green)
// "system"() /
.preferredColorScheme(theme == "dark" ? .dark : theme == "light" ? .light : nil)
.fullScreenCover(isPresented: $showOnboarding) {
OnboardingView { showOnboarding = false }
}
// (Designed for iPad)
// .
.transformEnvironment(\.dynamicTypeSize) { size in
if DeviceLayout.isMac, size < .xLarge { size = .xLarge }
}
.task {
#if DEBUG
DebugSeed.seedIfRequested(context: context)
DebugSeed.seedEmptyGoalIfRequested(context: context)
DebugSeed.seedPeriodFulfilledIfRequested(context: context)
DebugSeed.seedBulkIfRequested(context: context)
DebugSeed.autoStartIfRequested(context: context)
DebugSeed.pinGoalsIfRequested(context: context)
DebugSeed.watchGoalsIfRequested(context: context)
DebugSeed.endGoalYesterdayIfRequested(context: context)
DebugSeed.dumpStreaksIfRequested(context: context)
DebugSeed.runProgressSelfTestIfRequested()
CSVImport.selfTestIfRequested()
await DebugSeed.runIntentSmokeTestIfRequested()
// : -themeAutoToggle YES 3 (App Group defaults)
// ' '
if UserDefaults.standard.bool(forKey: "themeAutoToggle") {
Task {
try? await Task.sleep(for: .seconds(3))
AppGroup.defaults.set(theme == "dark" ? "light" : "dark", forKey: SettingsKeys.theme)
}
}
#endif
// (1.20.7)
try? await Task.sleep(for: .seconds(0.7))
withAnimation(.easeOut(duration: 0.4)) {
showSplash = false
}
// : 1 .
// (DEBUG) · .
#if DEBUG
if UserDefaults.standard.bool(forKey: "showOnboarding") {
showOnboarding = true
return
}
#endif
if !UserDefaults.standard.bool(forKey: OnboardingView.doneKey),
((try? context.fetchCount(FetchDescriptor<Action>())) ?? 0) == 0 {
showOnboarding = true
}
}
}
}
// MARK: - ( + + , CLAUDE.md §5.1)
struct SplashView: View {
@State private var appeared = false
var body: some View {
ZStack {
// ( ) /
AppTheme.background.ignoresSafeArea()
VStack(spacing: 18) {
Image("AppLogo")
.resizable()
.scaledToFit()
.frame(width: 150, height: 150)
.clipShape(RoundedRectangle(cornerRadius: 34, style: .continuous))
.shadow(color: .black.opacity(0.12), radius: 14, y: 6)
.scaleEffect(appeared ? 1 : 0.85)
.opacity(appeared ? 1 : 0)
Text("하루 다님", comment: "앱 이름")
.font(.largeTitle.bold())
.foregroundStyle(AppTheme.green)
.opacity(appeared ? 1 : 0)
Text("당신의 하루에 다녀가다", comment: "스플래시 브랜드 멘트")
.font(.subheadline)
.foregroundStyle(.secondary)
.opacity(appeared ? 1 : 0)
}
}
.onAppear {
withAnimation(.spring(duration: 0.5)) {
appeared = true
}
}
}
}
// MARK: - (iPhone=, iPad·Mac=)
/// (rootView) .
/// iPhone (NavStyle) / ,
/// iPad·Mac ( iPhone ).
struct RootNavigationView: View {
@AppStorage(SettingsKeys.navStyle) private var navStyleRaw = NavStyle.tabBar.rawValue
private let refresh = AppRefresh.shared
/// DEBUG : `-navStyle radial`
private var effectiveNavStyle: NavStyle {
#if DEBUG
if let forced = UserDefaults.standard.string(forKey: "navStyle"),
let style = NavStyle(rawValue: forced) {
return style
}
#endif
return NavStyle(rawValue: navStyleRaw) ?? .tabBar
}
var body: some View {
Group {
if DeviceLayout.isPad {
SidebarRootView()
} else if effectiveNavStyle == .radial {
RadialTabView()
} else {
MainTabView()
}
}
// @Query
.id(refresh.token)
}
}
// MARK: -
/// (: ' ' )
@Observable
final class AppRouter {
/// (NavigationSplitView) .
/// '' .
var usesSidebar = false
/// ( ) .
/// '' .
var allTabsDirect = false
var tabSelection: String = {
#if DEBUG
if let raw = UserDefaults.standard.string(forKey: "startTab") {
return raw
}
#endif
return AppTab.main.rawValue
}()
/// ( nil )
var pendingHistoryActionID: PersistentIdentifier?
/// ( nil )
var pendingStatsActionID: PersistentIdentifier?
/// . .
var morePath: [AppTab] = []
/// . .
func openHistory(filtering actionID: PersistentIdentifier, visibleTabsRaw: String) {
pendingHistoryActionID = actionID
open(.history, visibleTabsRaw: visibleTabsRaw)
}
/// . .
func openStats(filtering actionID: PersistentIdentifier, visibleTabsRaw: String) {
pendingStatsActionID = actionID
open(.stats, visibleTabsRaw: visibleTabsRaw)
}
private func open(_ tab: AppTab, visibleTabsRaw: String) {
if usesSidebar || allTabsDirect {
tabSelection = tab.rawValue
return
}
let visible = AppTab.visibleTabs(from: visibleTabsRaw)
if visible.contains(tab) {
tabSelection = tab.rawValue
} else {
morePath = [tab]
tabSelection = AppTab.moreTabValue
}
}
}
// MARK: -
enum AppTab: String, CaseIterable, Identifiable {
case main, action, tag, goal, history, stats, diary, settings
static let moreTabValue = "more"
/// iPhone ( iPad // )
static var phoneCases: [AppTab] {
allCases.filter { $0 != .diary }
}
/// (iPad·Mac) .
/// 1.0 (Designed for iPad) 1.1
/// '' (§6.7).
static var sidebarCases: [AppTab] {
allCases
}
var id: String { rawValue }
var label: String {
switch self {
case .main: return String(localized: "모음")
case .action: return String(localized: "행동")
case .tag: return String(localized: "꼬리표")
case .goal: return String(localized: "목표")
case .history: return String(localized: "기록")
case .stats: return String(localized: "통계")
case .diary: return String(localized: "일기")
case .settings: return String(localized: "설정")
}
}
var symbol: String {
switch self {
case .main: return "square.grid.2x2.fill"
case .action: return "figure.walk"
case .tag: return "tag.fill"
case .goal: return "flag.checkered"
case .history: return "calendar"
case .stats: return "chart.xyaxis.line"
case .diary: return "book.closed.fill"
case .settings: return "gearshape.fill"
}
}
/// ("main,action,history")
static func visibleTabs(from raw: String) -> [AppTab] {
let chosen = Set(raw.split(separator: ",").map(String.init))
let tabs = AppTab.phoneCases.filter { chosen.contains($0.rawValue) }
return tabs.isEmpty ? [.main] : Array(tabs.prefix(TabBarConfig.maxVisible))
}
/// .
/// : (: ) () .
static func radialOrder(from raw: String) -> [AppTab] {
var result: [AppTab] = []
var seen: Set<AppTab> = []
for part in raw.split(separator: ",") {
if let tab = AppTab(rawValue: String(part)), seen.insert(tab).inserted {
result.append(tab)
}
}
for tab in AppTab.phoneCases where !seen.contains(tab) {
result.append(tab)
}
return result.filter { $0 != .diary }
}
@ViewBuilder
var rootView: some View {
switch self {
case .main: MainView()
case .action: ActionListView()
case .tag: TagListView()
case .goal: GoalListView()
case .history: HistoryView()
case .stats: StatsTabView()
case .diary: DiaryRootView()
case .settings: SettingsView()
}
}
}
// MARK: - ( 1~3 + , = )
struct MainTabView: View {
@AppStorage(SettingsKeys.visibleTabs) private var visibleTabsRaw = TabBarConfig.defaultVisibleTabs
@State private var router = AppRouter()
private var visibleTabs: [AppTab] {
AppTab.visibleTabs(from: visibleTabsRaw)
}
private var moreTabs: [AppTab] {
AppTab.phoneCases.filter { !visibleTabs.contains($0) }
}
var body: some View {
TabView(selection: $router.tabSelection) {
ForEach(visibleTabs) { tab in
Tab(tab.label, systemImage: tab.symbol, value: tab.rawValue) {
NavigationStack {
tab.rootView
}
}
}
Tab("더보기", systemImage: "ellipsis", value: AppTab.moreTabValue) {
MoreTabView(tabs: moreTabs)
}
}
.environment(router)
.onChange(of: visibleTabsRaw) {
//
let valid = visibleTabs.map(\.rawValue) + [AppTab.moreTabValue]
if !valid.contains(router.tabSelection) {
router.tabSelection = AppTab.moreTabValue
}
}
.onAppear {
#if DEBUG
// : -startTab
let valid = visibleTabs.map(\.rawValue) + [AppTab.moreTabValue]
if !valid.contains(router.tabSelection) {
if let hidden = AppTab(rawValue: router.tabSelection) {
router.morePath = [hidden]
}
router.tabSelection = AppTab.moreTabValue
}
#endif
}
}
}
// MARK: -
struct MoreTabView: View {
@Environment(AppRouter.self) private var router
let tabs: [AppTab]
var body: some View {
@Bindable var router = router
NavigationStack(path: $router.morePath) {
List(tabs) { tab in
NavigationLink(value: tab) {
Label {
Text(tab.label)
} icon: {
Image(systemName: tab.symbol)
.foregroundStyle(AppTheme.green)
}
}
}
.scrollContentBackground(.hidden)
.background(AppTheme.background)
.navigationTitle("더보기")
.navigationDestination(for: AppTab.self) { tab in
tab.rootView
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: [
Tag.self, Action.self, TimeSession.self,
CountEntry.self, Goal.self, Quest.self,
], inMemory: true)
}