mycode/myApp/HaruDanim/IOS/Views/DiaryView.swift
songyc macbook 14fc5cb5bd feat(premium): complete StoreKit 2 purchase experience
기존 StoreKit 2 골격(상품 3종·구매·복원·권한 주입) 위에 실사용 경험 완성:
- PremiumStore.currentPlan: 현재 이용 중인 대표 플랜(평생 > 만료 먼 구독)
  추적, 구매·복원 후 위젯 타임라인 즉시 갱신
- 프리미엄 화면: '이용 중인 플랜' 섹션(플랜 이름·다음 갱신일·평생 안내),
  구독 관리 시트(manageSubscriptionsSheet), 구독 중 평생 이용권 전환 안내,
  년 구독 절약률·평생 '한 번 결제' 배지, 자동 갱신·해지·복원 안내 문구
- 잠금 안내 개선: 행동/목표/다짐 무료 한도 알림에 '프리미엄 알아보기'
  버튼 + PremiumSheetView 모달, 아이패드 일기 잠금 화면에도 버튼 추가
- 기능 소개에 '아이패드 일기' 추가, 새 문자열 en/ja 번역

가격(월 5,000/년 50,000/일회성 80,000)은 HaruDanim.storekit(로컬 테스트)과
App Store Connect에서 각각 수정 가능. DEBUG 강제 토글은 그대로 유지.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
2026-07-13 15:52:49 +09:00

1245 lines
47 KiB
Swift

//
// DiaryView.swift
// Haru_Danim
//
// (iPad , CLAUDE.md §7.2 ).
// :
// - DiaryRootView: . ( ) ,
// . / .
// - DiaryDetailView: . = ( ·· ·
// ·), = (DiaryNotePage.swift), = .
// - DiarySummaryPage: / (ExportBuilder)
// .
//
import SwiftUI
import SwiftData
import PhotosUI
// MARK: - ()
struct DiaryRootView: View {
@Environment(\.modelContext) private var context
@Query private var diaryEntries: [DiaryEntry]
@State private var premium = PremiumManager.shared
/// ( 1 )
@State private var monthAnchor: Date = DayMath().dayKey(for: .now)
@State private var showingExport = false
private var math: DayMath { DayMath() }
var body: some View {
Group {
if !premium.isPremium {
DiaryLockedView()
} else {
#if DEBUG
// : -diaryOpenToday YES
if UserDefaults.standard.bool(forKey: "diaryOpenToday") {
DiaryDetailView(dayKey: math.dayKey(for: .now))
} else {
calendar
}
#else
calendar
#endif
}
}
.background(AppTheme.background)
.navigationTitle("일기")
.navigationBarTitleDisplayMode(.inline)
.onAppear {
#if DEBUG
// : -diarySeed YES (· · )
if UserDefaults.standard.bool(forKey: "diarySeed") {
seedToday()
}
#endif
}
}
private var calendar: some View {
ScrollView {
VStack(spacing: 14) {
monthHeader
DiaryCalendarGrid(
monthAnchor: monthAnchor,
entriesByDay: entriesByDay,
math: math
)
monthSummary
}
.padding(20)
.frame(maxWidth: 760)
.frame(maxWidth: .infinity)
}
.navigationDestination(for: Date.self) { key in
DiaryDetailView(dayKey: key)
}
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button {
showingExport = true
} label: {
Image(systemName: "square.and.arrow.up")
}
}
}
.sheet(isPresented: $showingExport) {
DiaryExportSheet()
}
.onAppear {
#if DEBUG
if UserDefaults.standard.bool(forKey: "diaryShowExport") {
showingExport = true
}
#endif
}
}
/// ( )
private var entriesByDay: [Date: DiaryEntry] {
var result: [Date: DiaryEntry] = [:]
for entry in diaryEntries where entry.hasContent {
result[entry.dayKey] = entry
}
return result
}
// MARK:
private var monthHeader: some View {
HStack {
Button {
moveMonth(-1)
} label: {
Image(systemName: "chevron.left")
.frame(width: 44, height: 36)
.contentShape(Rectangle())
}
Spacer()
Text(monthAnchor.formatted(.dateTime.year().month()))
.font(.title3.weight(.bold))
Spacer()
Button {
moveMonth(1)
} label: {
Image(systemName: "chevron.right")
.frame(width: 44, height: 36)
.contentShape(Rectangle())
}
Button("이번 달") {
monthAnchor = math.dayKey(for: .now)
}
.font(.caption)
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
}
.tint(AppTheme.green)
}
private func moveMonth(_ delta: Int) {
monthAnchor = math.calendar.date(byAdding: .month, value: delta, to: monthAnchor)!
}
private var monthSummary: some View {
let range = math.monthRange(containing: monthAnchor)
let count = entriesByDay.keys.filter { range.contains(math.dayRange(forKey: $0).lowerBound) }.count
return HStack(spacing: 6) {
Image(systemName: "pencil.and.scribble")
.font(.caption)
Text("이번 달에 쓴 일기 \(count)")
.font(.caption.weight(.medium))
}
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
}
#if DEBUG
private func seedToday() {
let key = math.dayKey(for: .now)
let existing = diaryEntries.first { $0.dayKey == key }
guard existing == nil else { return }
let entry = DiaryEntry(dayKey: key)
entry.moodEmoji = "🙂"
context.insert(entry)
let todoTexts = ["물 2리터 마시기", "독서 30분", "저녁 달리기"]
for (index, text) in todoTexts.enumerated() {
let todo = DiaryTodo(text: text, sortOrder: index)
todo.isDone = index == 0
todo.entry = entry
context.insert(todo)
}
let page = DiaryPage(index: 0)
page.lined = true
page.entry = entry
context.insert(page)
let rect = DiaryPageItem(kind: .rectangle)
rect.centerX = 0.3; rect.centerY = 0.25; rect.widthRatio = 0.35
rect.page = page
context.insert(rect)
let arrow = DiaryPageItem(kind: .arrow)
arrow.colorHex = "#D9A621"
arrow.centerX = 0.62; arrow.centerY = 0.4; arrow.widthRatio = 0.3
arrow.page = page
context.insert(arrow)
try? context.save()
}
#endif
}
// MARK: -
struct DiaryLockedView: View {
@State private var showingPremiumSheet = false
var body: some View {
VStack(spacing: 12) {
Image(systemName: "crown.fill")
.font(.system(size: 40))
.foregroundStyle(AppTheme.yellow)
Text("일기는 프리미엄 기능이에요")
.font(.title3.weight(.semibold))
Text("하루의 기록·통계와 함께 애플 펜슬로 쓰는\n나만의 다이어리를 만들 수 있어요.")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
Button {
showingPremiumSheet = true
} label: {
Label("프리미엄 알아보기", systemImage: "crown")
.padding(.horizontal, 6)
}
.buttonStyle(.borderedProminent)
.buttonBorderShape(.capsule)
.tint(AppTheme.green)
.padding(.top, 6)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.sheet(isPresented: $showingPremiumSheet) {
PremiumSheetView()
}
}
}
// MARK: -
private struct DiaryCalendarGrid: View {
let monthAnchor: Date
let entriesByDay: [Date: DiaryEntry]
let math: DayMath
private var calendar: Calendar { math.calendar }
///
private var weekdayOrder: [Int] {
(0..<7).map { (calendar.firstWeekday - 1 + $0) % 7 + 1 }
}
/// ( nil)
private var cells: [Date?] {
let range = math.monthRange(containing: monthAnchor)
let keys = math.dayKeys(in: range)
guard let first = keys.first else { return [] }
let firstWeekday = calendar.component(.weekday, from: first)
let leading = (firstWeekday - calendar.firstWeekday + 7) % 7
return Array(repeating: nil, count: leading) + keys.map { Optional($0) }
}
var body: some View {
VStack(spacing: 6) {
HStack(spacing: 0) {
ForEach(weekdayOrder, id: \.self) { weekday in
Text(Format.weekdayShort(weekday))
.font(.caption.weight(.semibold))
.foregroundStyle(weekday == 1 ? Color.red.opacity(0.7) : .secondary)
.frame(maxWidth: .infinity)
}
}
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 4) {
ForEach(Array(cells.enumerated()), id: \.offset) { _, key in
if let key {
NavigationLink(value: key) {
dayCell(key)
}
.buttonStyle(.plain)
} else {
Color.clear
.frame(height: 74)
}
}
}
}
.padding(14)
.background(AppTheme.surface, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
}
private func dayCell(_ key: Date) -> some View {
let isToday = key == math.dayKey(for: .now)
let entry = entriesByDay[key]
return VStack(spacing: 3) {
Text("\(calendar.component(.day, from: key))")
.font(.callout.weight(isToday ? .bold : .regular))
.monospacedDigit()
.foregroundStyle(isToday ? AnyShapeStyle(.white) : AnyShapeStyle(.primary))
.frame(width: 32, height: 32)
.background(
Circle().fill(isToday ? AppTheme.green : Color.clear)
)
// : ,
Group {
if let entry {
if entry.moodEmoji.isEmpty {
Image(systemName: "applepencil.tip")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(AppTheme.green)
} else {
Text(entry.moodEmoji)
.font(.system(size: 15))
}
} else {
Color.clear
}
}
.frame(height: 20)
}
.frame(maxWidth: .infinity)
.frame(height: 74)
.background(
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(entry != nil ? AppTheme.green.opacity(0.07) : Color.clear)
)
.contentShape(Rectangle())
}
}
// MARK: - ( )
struct DiaryDetailView: View {
let dayKey: Date
@Environment(\.modelContext) private var context
@State private var entry: DiaryEntry?
@State private var showingSectionConfig: Bool = {
#if DEBUG
// : -diaryShowConfig YES
if UserDefaults.standard.bool(forKey: "diaryShowConfig") { return true }
#endif
return false
}()
@State private var pageIndex: Int = {
#if DEBUG
// : -diaryPage N (0=)
if let raw = UserDefaults.standard.string(forKey: "diaryPage"), let index = Int(raw) {
return index
}
#endif
return 0
}()
var body: some View {
Group {
if let entry {
pager(entry)
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.background(AppTheme.background)
.navigationTitle(Format.fullDate(dayKey))
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Menu {
Button {
showingSectionConfig = true
} label: {
Label("첫 화면 구성", systemImage: "slider.horizontal.3")
}
Button {
addPage()
} label: {
Label("페이지 추가", systemImage: "plus.square.on.square")
}
if let entry, pageIndex >= 1, pageIndex <= entry.pages.count {
Button(role: .destructive) {
deleteCurrentPage()
} label: {
Label("이 페이지 삭제", systemImage: "trash")
}
}
} label: {
Image(systemName: "ellipsis.circle")
}
}
}
.sheet(isPresented: $showingSectionConfig) {
DiarySectionConfigSheet()
}
.onAppear(perform: loadEntry)
}
private func pager(_ entry: DiaryEntry) -> some View {
TabView(selection: $pageIndex) {
DiarySummaryPage(entry: entry)
.tag(0)
ForEach(Array(entry.pages.enumerated()), id: \.element.uuid) { index, page in
DiaryNotePageView(page: page, isActive: pageIndex == index + 1)
.tag(index + 1)
}
addPagePlaceholder
.tag(entry.pages.count + 1)
}
.tabViewStyle(.page(indexDisplayMode: .always))
.indexViewStyle(.page(backgroundDisplayMode: .always))
}
/// : ( )
private var addPagePlaceholder: some View {
Button {
addPage()
} label: {
VStack(spacing: 12) {
Image(systemName: "plus")
.font(.system(size: 34, weight: .semibold))
Text("새 페이지")
.font(.headline)
Text("애플 펜슬로 자유롭게 쓰고 그려 보세요")
.font(.caption)
.foregroundStyle(.secondary)
}
.foregroundStyle(AppTheme.green)
.frame(maxWidth: 520, maxHeight: 680)
.background(
RoundedRectangle(cornerRadius: 20, style: .continuous)
.strokeBorder(style: StrokeStyle(lineWidth: 2, dash: [8, 6]))
.foregroundStyle(AppTheme.green.opacity(0.5))
)
.padding(40)
}
.buttonStyle(.plain)
}
private func loadEntry() {
guard entry == nil else { return }
let key = dayKey
let descriptor = FetchDescriptor<DiaryEntry>(predicate: #Predicate { $0.dayKey == key })
if let found = try? context.fetch(descriptor).first {
entry = found
} else {
let created = DiaryEntry(dayKey: key)
context.insert(created)
try? context.save()
entry = created
}
}
private func addPage() {
guard let entry else { return }
let page = DiaryPage(index: entry.pages.count)
page.entry = entry
context.insert(page)
entry.updatedAt = .now
try? context.save()
pageIndex = entry.pages.count //
}
private func deleteCurrentPage() {
guard let entry, pageIndex >= 1, pageIndex <= entry.pages.count else { return }
let page = entry.pages[pageIndex - 1]
context.delete(page)
//
for (index, remaining) in entry.pages.filter({ $0 !== page }).enumerated() {
remaining.index = index
}
entry.updatedAt = .now
try? context.save()
pageIndex = min(pageIndex, entry.pages.count)
}
}
// MARK: - ( + )
/// . rawValue .
enum DiarySection: String, CaseIterable, Identifiable {
case mood, hero, goals, todos, timetable, records, bars
var id: String { rawValue }
var label: LocalizedStringKey {
switch self {
case .mood: return "오늘 기분"
case .hero: return "요약 지표"
case .goals: return "이 날의 목표"
case .todos: return "오늘 할 일"
case .timetable: return "타임테이블"
case .records: return "기록 상세"
case .bars: return "통계 막대"
}
}
var symbol: String {
switch self {
case .mood: return "face.smiling"
case .hero: return "number.square"
case .goals: return "flag.checkered"
case .todos: return "checklist"
case .timetable: return "calendar.day.timeline.left"
case .records: return "list.bullet.rectangle"
case .bars: return "chart.bar.fill"
}
}
}
/// · UserDefaults ( ).
/// ( ) .
enum DiarySectionConfig {
static let orderKey = "diary.sectionOrder"
static let hiddenKey = "diary.hiddenSections"
static func order(from raw: String) -> [DiarySection] {
var result = raw.split(separator: ",").compactMap { DiarySection(rawValue: String($0)) }
for section in DiarySection.allCases where !result.contains(section) {
result.append(section)
}
return result
}
static func hidden(from raw: String) -> Set<DiarySection> {
Set(raw.split(separator: ",").compactMap { DiarySection(rawValue: String($0)) })
}
static func rawValue(_ sections: some Sequence<DiarySection>) -> String {
sections.map(\.rawValue).joined(separator: ",")
}
/// ' ' (diary.showMood) 1
static func migrateIfNeeded() {
let defaults = UserDefaults.standard
guard !defaults.bool(forKey: "diary.sectionsMigrated") else { return }
defaults.set(true, forKey: "diary.sectionsMigrated")
if let old = AppGroup.defaults.object(forKey: "diary.showMood") as? Bool, old == false {
var hiddenSet = hidden(from: defaults.string(forKey: hiddenKey) ?? "")
hiddenSet.insert(.mood)
defaults.set(rawValue(hiddenSet), forKey: hiddenKey)
}
}
}
/// : , /
struct DiarySectionConfigSheet: View {
@Environment(\.dismiss) private var dismiss
@AppStorage(DiarySectionConfig.orderKey) private var orderRaw = ""
@AppStorage(DiarySectionConfig.hiddenKey) private var hiddenRaw = ""
private var sections: [DiarySection] { DiarySectionConfig.order(from: orderRaw) }
private var hiddenSections: Set<DiarySection> { DiarySectionConfig.hidden(from: hiddenRaw) }
var body: some View {
NavigationStack {
List {
Section {
ForEach(sections) { section in
HStack(spacing: 12) {
Image(systemName: section.symbol)
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(AppTheme.green)
.frame(width: 26)
Toggle(isOn: visibilityBinding(section)) {
Text(section.label)
.font(.subheadline)
}
.tint(AppTheme.green)
}
}
.onMove(perform: move)
} footer: {
Text("드래그해서 순서를 바꾸고, 스위치로 표시 여부를 정할 수 있어요. 모든 날짜의 일기 첫 화면에 함께 적용돼요.")
}
}
.environment(\.editMode, .constant(.active))
.navigationTitle("첫 화면 구성")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("닫기") { dismiss() }
}
}
}
.presentationDetents([.medium, .large])
}
private func visibilityBinding(_ section: DiarySection) -> Binding<Bool> {
Binding(
get: { !hiddenSections.contains(section) },
set: { visible in
var hiddenSet = hiddenSections
if visible { hiddenSet.remove(section) } else { hiddenSet.insert(section) }
hiddenRaw = DiarySectionConfig.rawValue(
DiarySection.allCases.filter(hiddenSet.contains) //
)
}
)
}
private func move(from source: IndexSet, to destination: Int) {
var reordered = sections
reordered.move(fromOffsets: source, toOffset: destination)
orderRaw = DiarySectionConfig.rawValue(reordered)
}
}
// MARK: - ( )
/// " " .
/// - 24 (trimHours: false)
/// - .
/// / " " .
/// - · DiarySectionConfig( ) .
private struct DiarySummaryPage: View {
@Bindable var entry: DiaryEntry
@Environment(\.modelContext) private var context
@Query private var sessions: [TimeSession]
@Query private var countEntries: [CountEntry]
@Query(sort: \Action.createdAt) private var allActionsQuery: [Action]
@Query(sort: \Goal.sortOrder) private var allGoals: [Goal]
@AppStorage(LocalPrefsKeys.actionOrder, store: AppGroup.defaults) private var actionOrderRaw = ""
@AppStorage(DiarySectionConfig.orderKey) private var sectionOrderRaw = ""
@AppStorage(DiarySectionConfig.hiddenKey) private var hiddenSectionsRaw = ""
private var math: DayMath { DayMath() }
/// ( , )
private var visibleSections: [DiarySection] {
let hidden = DiarySectionConfig.hidden(from: hiddenSectionsRaw)
return DiarySectionConfig.order(from: sectionOrderRaw).filter { !hidden.contains($0) }
}
private var orderedActions: [Action] {
LocalPrefs.orderedActions(allActionsQuery, raw: actionOrderRaw)
}
/// : , /
private var referenceNow: Date {
let range = math.dayRange(forKey: entry.dayKey)
return range.contains(.now) ? .now : range.upperBound.addingTimeInterval(-1)
}
/// ( & )
private var activeGoals: [Goal] {
let day = math.dayRange(forKey: entry.dayKey).lowerBound
let cal = math.calendar
return allGoals.filter { goal in
guard cal.startOfDay(for: goal.startDate) <= day else { return false }
if let end = goal.endDate {
return cal.startOfDay(for: end) >= day
}
return true
}
}
/// ( 24 + )
private var daySnapshot: ExportSnapshot {
ExportBuilder.history(
dayKey: entry.dayKey,
weeklyTimetable: false,
sessions: sessions,
entries: countEntries,
orderedActions: orderedActions,
excludedActionIDs: [],
math: math,
trimHours: false
)
}
/// / ( )
private var statBars: [ExportSectionData] {
ExportBuilder.stats(
span: .day,
anchorDayKey: entry.dayKey,
sessions: sessions,
entries: countEntries,
orderedActions: orderedActions,
excludedActionIDs: [],
math: math
).sections.filter {
if case .bars = $0 { return true }
return false
}
}
var body: some View {
GeometryReader { geo in
let sections = visibleSections
// + 2 ( ,
// )
let wide = geo.size.width >= 720 && sections.contains(.timetable)
let timetableWidth: CGFloat = 300
let rightWidth = geo.size.width - 40 - timetableWidth - 16
let fullWidth = geo.size.width - 40
ScrollView {
VStack(alignment: .leading, spacing: 14) {
header
if sections.isEmpty {
Text("표시할 항목이 없어요. 오른쪽 위 메뉴의 '첫 화면 구성'에서 켜 주세요.")
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity)
.padding(.vertical, 40)
.background(AppTheme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
} else if wide {
HStack(alignment: .top, spacing: 16) {
VStack(spacing: 14) {
timetableSections(innerWidth: timetableWidth - 28)
}
.frame(width: timetableWidth)
VStack(spacing: 14) {
ForEach(sections.filter { $0 != .timetable }) { section in
sectionView(section, innerWidth: rightWidth - 28)
}
}
}
} else {
ForEach(sections) { section in
sectionView(section, innerWidth: fullWidth - 28)
}
}
}
.padding(20)
}
}
.onAppear(perform: DiarySectionConfig.migrateIfNeeded)
}
///
@ViewBuilder
private func sectionView(_ section: DiarySection, innerWidth: CGFloat) -> some View {
switch section {
case .mood:
DiaryMoodCard(entry: entry)
case .hero:
ExportHeroRow(stats: daySnapshot.hero)
case .goals:
DiaryGoalsCard(
goals: activeGoals,
dayKey: entry.dayKey,
referenceNow: referenceNow,
math: math
)
case .todos:
DiaryTodoCard(entry: entry)
case .timetable:
timetableSections(innerWidth: innerWidth)
case .records:
recordSections(innerWidth: innerWidth)
case .bars:
barSections(innerWidth: innerWidth)
}
}
private var header: some View {
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(Format.fullDate(entry.dayKey))
.font(.system(size: 28, weight: .bold))
if entry.dayKey == math.dayKey(for: .now) {
Text("오늘")
.font(.caption.weight(.bold))
.foregroundStyle(.white)
.padding(.horizontal, 10)
.padding(.vertical, 4)
.background(AppTheme.green, in: Capsule())
}
Spacer()
}
}
@ViewBuilder
private func timetableSections(innerWidth: CGFloat) -> some View {
ForEach(Array(daySnapshot.sections.enumerated()), id: \.offset) { _, section in
if case .timetable = section {
ExportSectionView(section: section, innerWidth: innerWidth)
}
}
}
@ViewBuilder
private func recordSections(innerWidth: CGFloat) -> some View {
let recordSections = daySnapshot.sections.filter {
if case .records = $0 { return true }
return false
}
if recordSections.isEmpty {
Text("이 날의 기록이 없어요")
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity)
.padding(.vertical, 30)
.background(AppTheme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
} else {
ForEach(Array(recordSections.enumerated()), id: \.offset) { _, section in
ExportSectionView(section: section, innerWidth: innerWidth)
}
}
}
@ViewBuilder
private func barSections(innerWidth: CGFloat) -> some View {
ForEach(Array(statBars.enumerated()), id: \.offset) { _, section in
ExportSectionView(section: section, innerWidth: innerWidth)
}
}
}
// MARK: - ·
/// .
/// - : /, " "
/// - // : " "
/// - ' ' (, )
private struct DiaryGoalsCard: View {
let goals: [Goal]
let dayKey: Date
let referenceNow: Date
let math: DayMath
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("이 날의 목표")
.font(.subheadline.weight(.semibold))
Spacer()
Text(String(localized: "\(goals.count)개 진행 중"))
.font(.caption2)
.foregroundStyle(.secondary)
}
if goals.isEmpty {
Text("이 날짜에 진행 중인 목표가 없어요")
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity)
.padding(.vertical, 14)
} else {
ForEach(Array(goals.enumerated()), id: \.element.uuid) { index, goal in
if index > 0 {
Divider()
}
goalBlock(goal)
}
}
}
.padding(14)
.background(AppTheme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
}
// MARK: ( + )
@ViewBuilder
private func goalBlock(_ goal: Goal) -> some View {
let dayRatio = goal.combinedSpanRatio(.day, math: math, now: referenceNow)
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 10) {
Image(systemName: goal.symbolName)
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(.white)
.frame(width: 28, height: 28)
.background(goal.color, in: RoundedRectangle(cornerRadius: 8, style: .continuous))
Text(goal.title)
.font(.footnote.weight(.semibold))
.lineLimit(1)
Spacer(minLength: 6)
Text("\(Int((dayRatio * 100).rounded()))%")
.font(.footnote.weight(.bold).monospacedDigit())
.foregroundStyle(goal.color)
}
// ( )
gaugeBar(ratio: dayRatio, color: goal.color)
if goal.sortedQuests.isEmpty {
Text("다짐이 아직 없는 목표예요")
.font(.caption2)
.foregroundStyle(.tertiary)
} else {
ForEach(goal.sortedQuests, id: \.uuid) { quest in
questRow(quest)
}
}
}
}
private func gaugeBar(ratio: Double, color: Color, height: CGFloat = 6) -> some View {
GeometryReader { geo in
ZStack(alignment: .leading) {
Capsule().fill(color.opacity(0.15))
Capsule()
.fill(color)
.frame(width: max(geo.size.width * min(max(ratio, 0), 1), ratio > 0 ? height : 0))
}
}
.frame(height: height)
}
// MARK:
private struct QuestStat {
var contextLabel: String
var value: Double?
var achieved: Bool
}
@ViewBuilder
private func questRow(_ quest: Quest) -> some View {
let stat = questStat(quest)
let target = quest.targetValue
let limit = quest.direction == .atMost
HStack(alignment: .firstTextBaseline, spacing: 8) {
Image(systemName: quest.targetSymbol)
.font(.system(size: 10, weight: .semibold))
.foregroundStyle(.white)
.frame(width: 20, height: 20)
.background(quest.targetColor, in: RoundedRectangle(cornerRadius: 6, style: .continuous))
VStack(alignment: .leading, spacing: 4) {
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(quest.targetName)
.font(.caption.weight(.medium))
.lineLimit(1)
Text(stat.contextLabel)
.font(.caption2)
.foregroundStyle(.tertiary)
Spacer(minLength: 4)
if let value = stat.value {
Group {
if limit {
Text("\(valueLabel(value, quest: quest)) / 한도 \(quest.targetValueLabel)")
} else {
Text("\(valueLabel(value, quest: quest)) / \(quest.targetValueLabel)")
}
}
.font(.caption2.monospacedDigit())
.foregroundStyle(.secondary)
if stat.achieved {
Image(systemName: "checkmark.circle.fill")
.font(.caption)
.foregroundStyle(AppTheme.green)
} else if limit {
Image(systemName: "exclamationmark.circle.fill")
.font(.caption)
.foregroundStyle(.red)
}
}
}
if let value = stat.value, target > 0 {
let ratio = value / target
gaugeBar(
ratio: ratio,
color: limit ? (ratio > 1 ? .red : AppTheme.yellow) : quest.targetColor,
height: 4
)
}
}
}
.opacity(stat.value == nil ? 0.55 : 1)
}
/// " " . value == nil ( / ).
private func questStat(_ quest: Quest) -> QuestStat {
let progress = QuestProgress(quest: quest, math: math)
let dayRange = math.dayRange(forKey: dayKey)
let measured: Range<Date>?
let context: String
switch quest.period {
case .daily:
if progress.isActiveDay(dayKey) {
measured = dayRange
context = String(localized: "하루 목표")
} else {
measured = nil
context = String(localized: "이 날은 수행일이 아니에요")
}
case .weekly:
let week = math.weekRange(containing: dayRange.lowerBound)
measured = week.lowerBound..<min(dayRange.upperBound, week.upperBound)
context = String(localized: "주간 목표 · 이 날까지 누적")
case .monthly:
let month = math.monthRange(containing: dayRange.lowerBound)
measured = month.lowerBound..<min(dayRange.upperBound, month.upperBound)
context = String(localized: "월간 목표 · 이 날까지 누적")
case .custom:
if let full = progress.currentPeriodRange(now: referenceNow), full.overlaps(dayRange) {
measured = full.lowerBound..<min(dayRange.upperBound, full.upperBound)
context = String(localized: "기간 목표 · 이 날까지 누적")
} else {
measured = nil
context = String(localized: "설정된 기간 밖이에요")
}
}
guard let measured else {
return QuestStat(contextLabel: context, value: nil, achieved: false)
}
let value = progress.value(in: measured, now: referenceNow)
let achieved: Bool
switch quest.direction {
case .atLeast: achieved = value >= quest.targetValue
case .atMost: achieved = value <= quest.targetValue
}
return QuestStat(contextLabel: context, value: value, achieved: achieved)
}
private func valueLabel(_ value: Double, quest: Quest) -> String {
switch quest.measure {
case .time: return Format.durationShort(value)
case .count: return String(localized: "\(Int(value))")
}
}
}
// MARK: -
private struct DiaryMoodCard: View {
@Bindable var entry: DiaryEntry
@Environment(\.modelContext) private var context
@State private var showingEmojiPicker = false
@State private var photoSelection: PhotosPickerItem?
///
private let tileSize: CGFloat = 200
static let emojiChoices = [
"😀", "🙂", "😌", "🥰", "🥳", "🤗", "😴", "😐",
"😔", "😢", "😡", "😤", "🤒", "🤯", "😱", "🙃",
]
var body: some View {
HStack(alignment: .top, spacing: 16) {
moodTile
VStack(alignment: .leading, spacing: 6) {
Text("오늘 기분")
.font(.headline)
Text("이모지나 사진으로\n오늘의 기분을 남겨 보세요")
.font(.caption)
.foregroundStyle(.secondary)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 8)
VStack(alignment: .leading, spacing: 8) {
Button {
showingEmojiPicker = true
} label: {
Label("이모지 선택", systemImage: "face.smiling")
}
.popover(isPresented: $showingEmojiPicker) {
emojiPicker
}
PhotosPicker(selection: $photoSelection, matching: .images) {
Label("사진 선택", systemImage: "photo.badge.plus")
}
if !entry.moodEmoji.isEmpty || entry.moodImageData != nil {
Button {
entry.moodEmoji = ""
entry.moodImageData = nil
touch()
} label: {
Label("지우기", systemImage: "xmark.circle")
}
.foregroundStyle(.secondary)
}
}
.font(.footnote)
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.tint(AppTheme.green)
}
.frame(maxWidth: .infinity, minHeight: tileSize, alignment: .leading)
}
.padding(14)
.background(AppTheme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
.onChange(of: photoSelection) {
guard let photoSelection else { return }
Task {
if let data = try? await photoSelection.loadTransferable(type: Data.self),
let image = UIImage(data: data) {
// + JPEG
entry.moodImageData = image.diaryCompressed()
touch()
}
self.photoSelection = nil
}
}
}
/// : ( ),
/// , .
private var moodTile: some View {
Button {
showingEmojiPicker = true
} label: {
ZStack {
RoundedRectangle(cornerRadius: 20, style: .continuous)
.fill(AppTheme.background)
if let data = entry.moodImageData, let image = UIImage(data: data) {
Image(uiImage: image)
.resizable()
.scaledToFill()
.frame(width: tileSize, height: tileSize)
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
if !entry.moodEmoji.isEmpty {
Text(entry.moodEmoji)
.font(.system(size: 40))
.padding(7)
.background(.thinMaterial, in: Circle())
.frame(maxWidth: .infinity, maxHeight: .infinity,
alignment: .bottomTrailing)
.padding(10)
}
} else if !entry.moodEmoji.isEmpty {
Text(entry.moodEmoji)
.font(.system(size: 110))
} else {
VStack(spacing: 10) {
Image(systemName: "face.smiling")
.font(.system(size: 44))
Text("탭해서 남기기")
.font(.caption)
}
.foregroundStyle(.tertiary)
}
}
.frame(width: tileSize, height: tileSize)
.contentShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
}
.buttonStyle(.plain)
}
private var emojiPicker: some View {
LazyVGrid(columns: Array(repeating: GridItem(.fixed(46)), count: 4), spacing: 8) {
ForEach(Self.emojiChoices, id: \.self) { emoji in
Button {
entry.moodEmoji = emoji
touch()
showingEmojiPicker = false
} label: {
Text(emoji)
.font(.system(size: 30))
.frame(width: 46, height: 46)
}
.buttonStyle(.plain)
}
}
.padding(12)
.presentationCompactAdaptation(.popover)
}
private func touch() {
entry.updatedAt = .now
try? context.save()
}
}
extension UIImage {
/// ( 900pt, JPEG 0.8)
func diaryCompressed() -> Data? {
let maxSide: CGFloat = 900
let longest = max(size.width, size.height)
let scale = longest > maxSide ? maxSide / longest : 1
let newSize = CGSize(width: size.width * scale, height: size.height * scale)
let renderer = UIGraphicsImageRenderer(size: newSize)
let resized = renderer.image { _ in
draw(in: CGRect(origin: .zero, size: newSize))
}
return resized.jpegData(compressionQuality: 0.8)
}
}
// MARK: - ( + )
private struct DiaryTodoCard: View {
@Bindable var entry: DiaryEntry
@Environment(\.modelContext) private var context
var body: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Text("오늘 할 일")
.font(.subheadline.weight(.semibold))
Spacer()
Button {
addTodo()
} label: {
Image(systemName: "plus.circle.fill")
.font(.title3)
.foregroundStyle(AppTheme.green)
}
.buttonStyle(.plain)
}
if entry.todos.isEmpty {
Text("펜슬이나 키보드로 할 일을 적고,\n체크 표시로 완료해 보세요")
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity)
.padding(.vertical, 14)
} else {
ForEach(entry.todos, id: \.uuid) { todo in
DiaryTodoRow(todo: todo, onDelete: { delete(todo) })
}
}
}
.padding(14)
.background(AppTheme.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
}
private func addTodo() {
let todo = DiaryTodo(text: "", sortOrder: (entry.todos.last?.sortOrder ?? -1) + 1)
todo.entry = entry
context.insert(todo)
entry.updatedAt = .now
try? context.save()
}
private func delete(_ todo: DiaryTodo) {
context.delete(todo)
entry.updatedAt = .now
try? context.save()
}
}
private struct DiaryTodoRow: View {
@Bindable var todo: DiaryTodo
let onDelete: () -> Void
@Environment(\.modelContext) private var context
var body: some View {
HStack(spacing: 10) {
Button {
todo.isDone.toggle()
try? context.save()
} label: {
Image(systemName: todo.isDone ? "checkmark.circle.fill" : "circle")
.font(.title3)
.foregroundStyle(todo.isDone ? AppTheme.green : .secondary)
}
.buttonStyle(.plain)
TextField("할 일", text: $todo.text)
.font(.subheadline)
.strikethrough(todo.isDone, color: .secondary)
.foregroundStyle(todo.isDone ? .secondary : .primary)
.onSubmit { try? context.save() }
Button(action: onDelete) {
Image(systemName: "xmark")
.font(.caption2.weight(.semibold))
.foregroundStyle(.tertiary)
.padding(4)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
}