mycode/myApp/HaruDanim/IOS/Views/SettingsView.swift
songyc macbook 9e81cd3d03 feat: auto-adapt layout for iPadOS/macOS with NavigationSplitView and hide irrelevant settings
- Add SidebarRootView: iPad/Mac (Designed for iPad) uses a NavigationSplitView
  sidebar listing all 7 tabs, sharing every existing screen (rootView) untouched
- Branch by device idiom (DeviceLayout.isPad) so iPhone keeps its tab bar UI,
  logic, and Live Activity behavior pixel-for-pixel, including landscape
- AppRouter gains sidebar mode: cross-tab routing (기록 확인/통계 보기) selects
  the target tab directly instead of detouring through the More tab
- Hide iPhone-only settings on iPad/Mac: 탭바 구성 section and the main grid's
  per-row column picker are meaningless with a sidebar/adaptive grid
- Main tab wide-screen layout: pinned goal cards flow in an adaptive grid
  (340-520pt cards) instead of full-width paging; action buttons auto-fill
  columns at 150-220pt so nothing stretches on large displays
- Verified on iPad Pro 11" simulator (sidebar, settings, stats routing,
  timetable) and iPhone 17 Pro (unchanged tab bar); both build clean

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
2026-07-11 09:28:06 +09:00

398 lines
17 KiB
Swift

//
// SettingsView.swift
// Haru_Danim
//
// (CLAUDE.md §6.6)
//
import SwiftUI
import SwiftData
import StoreKit
import WidgetKit
struct SettingsView: View {
@Query(sort: [SortDescriptor(\Goal.sortOrder), SortDescriptor(\Goal.createdAt)]) private var goals: [Goal]
// (' ' ) App Group defaults
@AppStorage(SettingsKeys.theme, store: AppGroup.defaults) private var theme = "light"
@AppStorage(SettingsKeys.language) private var language = AppLanguage.ko.rawValue
// · App Group defaults
@AppStorage(SettingsKeys.weekStartWeekday, store: AppGroup.defaults) private var weekStartWeekday = 2
@AppStorage(SettingsKeys.dayStartMinutes, store: AppGroup.defaults) private var dayStartMinutes = 0
@AppStorage(SettingsKeys.liveActivityMode, store: AppGroup.defaults) private var liveActivityMode = LiveActivityMode.latest.rawValue
@AppStorage(SettingsKeys.minSessionSeconds, store: AppGroup.defaults) private var minSessionSeconds = 0
private let premium = PremiumManager.shared
@AppStorage(SettingsKeys.visibleTabs) private var visibleTabsRaw = TabBarConfig.defaultVisibleTabs
@AppStorage(SettingsKeys.goalCardStyle) private var goalCardStyle = GoalCardStyle.perQuest.rawValue
private var visibleTabs: [AppTab] {
AppTab.visibleTabs(from: visibleTabsRaw)
}
/// DatePicker
private var dayStartDate: Binding<Date> {
Binding {
let cal = Calendar.current
return cal.date(byAdding: .minute, value: dayStartMinutes, to: cal.startOfDay(for: .now))!
} set: { newValue in
let cal = Calendar.current
let comps = cal.dateComponents([.hour, .minute], from: newValue)
dayStartMinutes = (comps.hour ?? 0) * 60 + (comps.minute ?? 0)
}
}
var body: some View {
ScrollViewReader { proxy in
Form {
Section {
Picker("테마", selection: $theme) {
Text("라이트").tag("light")
Text("다크").tag("dark")
}
Picker("언어", selection: $language) {
ForEach(AppLanguage.allCases) { lang in
Text(lang.label).tag(lang.rawValue)
}
}
} header: {
Text("화면")
} footer: {
Text("언어를 바꾸면 앱을 완전히 종료했다가 다시 실행했을 때 적용돼요.")
}
// iPad·Mac
if !DeviceLayout.isPad {
Section {
ForEach(AppTab.allCases) { tab in
tabToggleRow(tab)
}
} header: {
Text("탭바 구성")
} footer: {
Text("선택한 탭(최대 \(TabBarConfig.maxVisible)개)이 하단 탭바에 바로 표시되고, 나머지 탭은 ‘더보기’에서 열 수 있어요.")
}
}
Section {
if goals.isEmpty {
Text("목표 탭에서 목표를 만들면 여기서 선택할 수 있어요.")
.font(.caption)
.foregroundStyle(.secondary)
} else {
ForEach(goals) { goal in
pinnedGoalRow(goal)
}
Picker("표시 방식", selection: $goalCardStyle) {
ForEach(GoalCardStyle.allCases) { style in
Text(style.label).tag(style.rawValue)
}
}
}
} header: {
Text("모음 탭 목표 진행 현황")
} footer: {
Text("선택한 목표의 진행 현황이 모음 탭 상단에 표시돼요. 탭하면 목표 상세로 이동해요. 2개 이상 선택하면 카드를 옆으로 쓸어 넘겨 한 장씩 볼 수 있고, 표시 방식(다짐별로 각각 / 전체 다짐 합산)은 모든 카드에 똑같이 적용돼요.")
}
.id("goalSection")
Section {
Picker("주 시작 요일", selection: $weekStartWeekday) {
ForEach(1...7, id: \.self) { weekday in
Text("\(Format.weekdayShort(weekday))요일").tag(weekday)
}
}
DatePicker("하루 시작 시간", selection: dayStartDate, displayedComponents: .hourAndMinute)
} header: {
Text("날짜 기준")
} footer: {
Text("하루 시작 시간을 걸치는 기록은 통계에서 자동으로 날짜별로 나누어 계산돼요.")
}
Section {
Picker("짧은 기록 무시", selection: $minSessionSeconds) {
ForEach(MinSessionOption.choices, id: \.seconds) { option in
Text(option.label).tag(option.seconds)
}
}
} header: {
Text("측정")
} footer: {
Text("설정한 시간보다 짧게 측정하고 종료한 기록은 저장하지 않아요. 버튼을 실수로 눌렀을 때 유용해요.")
}
Section {
Picker("대표 시간 기준", selection: $liveActivityMode) {
ForEach(LiveActivityMode.allCases) { mode in
Text(mode.label).tag(mode.rawValue)
}
}
} header: {
Text("다이나믹 아일랜드 · 잠금화면")
} footer: {
Text("여러 행동을 동시에 추적 중일 때 대표로 표시할 시간이에요. (Live Activity 지원은 추후 추가 예정)")
}
Section("프리미엄") {
NavigationLink {
PremiumView()
} label: {
HStack {
Label("프리미엄 기능", systemImage: "crown.fill")
.foregroundStyle(AppTheme.yellow)
Spacer()
Text(premium.isPremium ? String(localized: "사용 중") : String(localized: "무료 사용 중"))
.font(.caption)
.foregroundStyle(.secondary)
}
}
}
.id("premiumSection")
Section {
HStack {
Text("버전")
Spacer()
Text("1.0").foregroundStyle(.secondary)
}
}
}
.scrollContentBackground(.hidden)
.background(AppTheme.background)
.navigationTitle("설정")
.onChange(of: theme) {
// ' '
WidgetCenter.shared.reloadAllTimelines()
}
.onChange(of: weekStartWeekday) {
// / ·
WidgetCenter.shared.reloadAllTimelines()
}
.onChange(of: dayStartMinutes) {
WidgetCenter.shared.reloadAllTimelines()
}
.onChange(of: language) {
// :
UserDefaults.standard.set([language], forKey: "AppleLanguages")
}
#if DEBUG
// : -settingsScrollGoal YES , -settingsScrollPremium YES
.onAppear {
if UserDefaults.standard.bool(forKey: "settingsScrollGoal") {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
withAnimation { proxy.scrollTo("goalSection", anchor: .top) }
}
}
if UserDefaults.standard.bool(forKey: "settingsScrollPremium") {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
withAnimation { proxy.scrollTo("premiumSection", anchor: .top) }
}
}
}
#endif
}
}
// MARK: ( )
private func pinnedGoalRow(_ goal: Goal) -> some View {
Button {
goal.showsOnMain.toggle()
} label: {
HStack {
Label {
Text(goal.title)
.foregroundStyle(.primary)
.lineLimit(1)
} icon: {
Image(systemName: goal.symbolName)
.foregroundStyle(goal.color)
}
Spacer()
if goal.showsOnMain {
Image(systemName: "checkmark")
.foregroundStyle(AppTheme.green)
.fontWeight(.semibold)
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
// MARK:
private func tabToggleRow(_ tab: AppTab) -> some View {
let isVisible = visibleTabs.contains(tab)
let atMax = visibleTabs.count >= TabBarConfig.maxVisible
let atMin = visibleTabs.count <= TabBarConfig.minVisible
return Button {
toggleTab(tab)
} label: {
HStack {
Label {
Text(tab.label)
.foregroundStyle(.primary)
} icon: {
Image(systemName: tab.symbol)
.foregroundStyle(AppTheme.green)
}
Spacer()
if isVisible {
Image(systemName: "checkmark")
.foregroundStyle(AppTheme.green)
.fontWeight(.semibold)
} else {
Text("더보기")
.font(.caption)
.foregroundStyle(.tertiary)
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled((isVisible && atMin) || (!isVisible && atMax))
.opacity((isVisible && atMin) || (!isVisible && atMax) ? 0.5 : 1)
}
private func toggleTab(_ tab: AppTab) {
var current = visibleTabs
if let index = current.firstIndex(of: tab) {
guard current.count > TabBarConfig.minVisible else { return }
current.remove(at: index)
} else {
guard current.count < TabBarConfig.maxVisible else { return }
current.append(tab)
}
// ()
let ordered = AppTab.allCases.filter { current.contains($0) }
visibleTabsRaw = ordered.map(\.rawValue).joined(separator: ",")
}
}
// MARK: -
struct PremiumView: View {
private let premium = PremiumManager.shared
private let store = PremiumStore.shared
@AppStorage(DataStore.cloudSyncKey, store: AppGroup.defaults) private var cloudSync = false
var body: some View {
List {
Section {
featureRow("infinity", "개수 제한 해제", "행동·목표·다짐을 무제한으로 만들 수 있어요.")
featureRow("square.grid.2x2.fill", "홈·잠금화면 위젯", "위젯에서 바로 행동을 실행하고 달성률을 확인해요.")
featureRow("icloud.fill", "아이패드 동기화", "iCloud로 기기 간 데이터가 동기화돼요.")
featureRow("applewatch", "애플워치 앱", "워치에서 추적하고 컴플리케이션으로 확인해요.")
} header: {
Text("프리미엄으로 할 수 있는 것")
} footer: {
Text("무료: 행동 \(FreeLimits.actions)개 · 목표 \(FreeLimits.goals)개 · 목표당 다짐 \(FreeLimits.questsPerGoal)개까지")
}
if premium.isPremium {
Section {
Toggle("기기 간 동기화", isOn: $cloudSync)
} header: {
Text("동기화")
} footer: {
Text("iCloud로 아이패드 등 다른 기기와 데이터가 동기화돼요. 변경 사항은 앱을 완전히 종료했다가 다시 실행하면 적용돼요.")
}
} else {
purchaseSection
}
#if DEBUG
Section("개발용") {
Toggle("프리미엄 상태 (테스트)", isOn: Binding(
get: { premium.isPremium },
set: { premium.setMockPremium($0) }
))
}
#endif
}
.scrollContentBackground(.hidden)
.background(AppTheme.background)
.navigationTitle("프리미엄")
.navigationBarTitleDisplayMode(.inline)
.toolbar(.hidden, for: .tabBar)
.task {
await store.loadProducts()
}
}
// MARK: (StoreKit 2)
@ViewBuilder
private var purchaseSection: some View {
Section {
if store.products.isEmpty {
if store.isLoading {
HStack {
ProgressView()
Text("상품 정보를 불러오는 중...")
.font(.caption)
.foregroundStyle(.secondary)
}
} else {
// App Store Connect
Label("상품 정보를 불러올 수 없어요", systemImage: "wifi.exclamationmark")
.font(.callout)
.foregroundStyle(.secondary)
Button("다시 시도") {
Task { await store.loadProducts() }
}
}
} else {
ForEach(store.products) { product in
productRow(product)
}
}
Button {
Task { await store.restore() }
} label: {
Text("구매 복원")
.font(.callout)
}
.disabled(store.isPurchasing)
} header: {
Text("프리미엄 구매")
} footer: {
if let message = store.lastErrorMessage {
Text(message).foregroundStyle(.red)
} else {
Text("구독은 언제든 해지할 수 있고, 평생 이용권은 한 번 결제로 모든 기능을 계속 사용해요.")
}
}
}
private func productRow(_ product: Product) -> some View {
Button {
Task { await store.purchase(product) }
} label: {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(product.displayName)
.font(.body.weight(.semibold))
.foregroundStyle(.primary)
if !product.description.isEmpty {
Text(product.description)
.font(.caption)
.foregroundStyle(.secondary)
}
}
Spacer()
Text(product.displayPrice)
.font(.body.weight(.bold))
.foregroundStyle(AppTheme.green)
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled(store.isPurchasing)
}
private func featureRow(_ symbol: String, _ title: String, _ detail: String) -> some View {
HStack(alignment: .top, spacing: 12) {
Image(systemName: symbol)
.font(.system(size: 18))
.foregroundStyle(AppTheme.green)
.frame(width: 30)
VStack(alignment: .leading, spacing: 2) {
Text(title).font(.body.weight(.semibold))
Text(detail).font(.caption).foregroundStyle(.secondary)
}
}
.padding(.vertical, 2)
}
}