라이브 액티비티(다이내믹 아일랜드) 워치 연동:
- 워치 실행 명령이 세션 활성화 전이거나 sendMessage 실패 시 유실되던 문제를
transferUserInfo 큐 폴백으로 보강 (iPhone didReceiveUserInfo 수신 처리 추가)
- 큐로 지연 도착한 실행 명령이 엉뚱한 토글을 일으키지 않도록 5분 유효 시간 부여
- 백그라운드에서 Live Activity 시작이 거부되면 pendingStartRetry로 기억했다가
앱 포그라운드 복귀(scenePhase active) 시 재시도 + DB 상태 재동기화
- WatchSync 진단용 os_log(notice) 추가, DEBUG -autoRunFirstAction 검증 훅 추가
- 시뮬레이터 검증: 워치 시작 → 아이폰 세션 시작 + 다이내믹 아일랜드 생성,
워치 종료 → 세션 종료 + 아일랜드 소멸 확인 (큐 폴백 채널은 시뮬레이터
transferUserInfo 한계로 실기기 확인 필요)
앱 이름 전역 띄어쓰기 ('하루다님' → '하루 다님'):
- pbxproj CFBundleDisplayName 6곳, InfoPlist.xcstrings 3개(ko), 스플래시(ContentView),
워치 내비게이션 타이틀, 컴플리케이션 문구, 문자열 카탈로그 키 일괄 변경
- 워치 카탈로그 영문 값 HaruDanim → Haru Danim 통일
통계 위젯 X축 라벨 겹침 방지:
- 날짜 축 포인트가 7개를 초과하면(한 달·일별 등) 라벨을 숨기고 눈금만 표시
위젯 설정 '선택 안 함' 옵션:
- Action/Goal/Quest 엔티티에 zero-UUID 센티널 추가, 제안 목록 최상단 노출
- 2·3번째 슬롯 선택을 되돌릴 수 있고, 위젯 조회 단계에서 자연스럽게 걸러짐
- ko/en/ja 번역 추가 (None / 選択しない)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
268 lines
9.7 KiB
Swift
268 lines
9.7 KiB
Swift
//
|
|
// StatsChartWidget.swift
|
|
// Haru_DanimWidgets
|
|
//
|
|
// 통계 위젯 (CLAUDE.md §8.3) — 선택한 행동들의 꺾은선 그래프
|
|
// 앱 통계 탭과 동일: 선 색 = 행동 색, 시간형은 h 단위, 횟수형은 회
|
|
//
|
|
|
|
import SwiftUI
|
|
import WidgetKit
|
|
import AppIntents
|
|
import Charts
|
|
|
|
// MARK: - 설정
|
|
|
|
enum StatsChartSpan: String, AppEnum {
|
|
case week
|
|
case monthByDay
|
|
case monthByWeek
|
|
|
|
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "통계 기간")
|
|
static let caseDisplayRepresentations: [StatsChartSpan: DisplayRepresentation] = [
|
|
.week: "일주일 (하루 단위)",
|
|
.monthByDay: "한 달 (하루 단위, 중형 이상)",
|
|
.monthByWeek: "한 달 (주 단위)",
|
|
]
|
|
|
|
var title: String {
|
|
switch self {
|
|
case .week: return String(localized: "일주일 통계")
|
|
case .monthByDay: return String(localized: "한 달 통계 (일별)")
|
|
case .monthByWeek: return String(localized: "한 달 통계 (주별)")
|
|
}
|
|
}
|
|
}
|
|
|
|
struct StatsChartConfigIntent: WidgetConfigurationIntent {
|
|
static let title: LocalizedStringResource = "통계 위젯"
|
|
static let description = IntentDescription("그래프로 보여줄 행동과 기간을 선택하세요.")
|
|
|
|
@Parameter(title: "통계 기간", default: .week)
|
|
var span: StatsChartSpan
|
|
|
|
@Parameter(title: "위젯 테마", default: .matchApp)
|
|
var theme: WidgetThemeOption
|
|
|
|
@Parameter(title: "행동 1")
|
|
var action1: ActionEntity?
|
|
|
|
@Parameter(title: "행동 2")
|
|
var action2: ActionEntity?
|
|
|
|
@Parameter(title: "행동 3")
|
|
var action3: ActionEntity?
|
|
}
|
|
|
|
// MARK: - 타임라인
|
|
|
|
struct StatsPoint: Identifiable {
|
|
let id = UUID()
|
|
/// 하루 단위 그래프의 x축 (일별)
|
|
let day: Date?
|
|
/// 주 단위 그래프의 x축 ("1주차" 등)
|
|
let weekLabel: String?
|
|
let actionName: String
|
|
let value: Double
|
|
}
|
|
|
|
struct StatsChartEntry: TimelineEntry {
|
|
let date: Date
|
|
let locked: Bool
|
|
let theme: WidgetThemeOption
|
|
let title: String
|
|
let isWeekAxis: Bool
|
|
let isTimeType: Bool
|
|
let names: [String]
|
|
let colorHexes: [String]
|
|
let points: [StatsPoint]
|
|
}
|
|
|
|
struct StatsChartProvider: AppIntentTimelineProvider {
|
|
@MainActor
|
|
static func makeEntry(_ configuration: StatsChartConfigIntent, family: WidgetFamily) -> StatsChartEntry {
|
|
guard WidgetStore.isUnlocked else {
|
|
return StatsChartEntry(date: .now, locked: true, theme: configuration.theme, title: "", isWeekAxis: false,
|
|
isTimeType: true, names: [], colorHexes: [], points: [])
|
|
}
|
|
// 소형은 "한 달 (하루 단위)" 제외 (CLAUDE.md §8.3) → 주 단위로 대체
|
|
var span = configuration.span
|
|
if family == .systemSmall && span == .monthByDay { span = .monthByWeek }
|
|
|
|
let chosen = [configuration.action1, configuration.action2, configuration.action3]
|
|
.compactMap { $0 }
|
|
.compactMap { WidgetStore.action($0.id) }
|
|
let actions = chosen.isEmpty ? WidgetStore.defaultActions(3) : chosen
|
|
let isTimeType = !actions.contains { $0.trackingType == .count }
|
|
|
|
let math = DayMath()
|
|
let agg = Aggregator(math: math)
|
|
let now = Date.now
|
|
var points: [StatsPoint] = []
|
|
|
|
func value(_ action: Action, in range: Range<Date>) -> Double {
|
|
switch action.trackingType {
|
|
case .time: return agg.seconds(for: action, in: range, now: now) / 3600
|
|
case .count: return Double(agg.count(for: action, in: range))
|
|
}
|
|
}
|
|
|
|
switch span {
|
|
case .week, .monthByDay:
|
|
let range = span == .week ? math.weekRange(containing: now) : math.monthRange(containing: now)
|
|
for key in math.dayKeys(in: range) {
|
|
let dayRange = math.dayRange(forKey: key)
|
|
for action in actions {
|
|
points.append(StatsPoint(day: key, weekLabel: nil, actionName: action.name,
|
|
value: value(action, in: dayRange)))
|
|
}
|
|
}
|
|
case .monthByWeek:
|
|
let month = math.monthRange(containing: now)
|
|
var cursor = month.lowerBound
|
|
var index = 1
|
|
while cursor < month.upperBound {
|
|
let week = math.weekRange(containing: cursor)
|
|
let clipped = max(week.lowerBound, month.lowerBound)..<min(week.upperBound, month.upperBound)
|
|
for action in actions {
|
|
points.append(StatsPoint(day: nil, weekLabel: "\(index)주", actionName: action.name,
|
|
value: value(action, in: clipped)))
|
|
}
|
|
cursor = week.upperBound
|
|
index += 1
|
|
}
|
|
}
|
|
|
|
return StatsChartEntry(
|
|
date: now,
|
|
locked: false,
|
|
theme: configuration.theme,
|
|
title: span.title,
|
|
isWeekAxis: span == .monthByWeek,
|
|
isTimeType: isTimeType,
|
|
names: actions.map(\.name),
|
|
colorHexes: actions.map { $0.tags.sorted { $0.createdAt < $1.createdAt }.first?.colorHex ?? "#2F6B4F" },
|
|
points: points
|
|
)
|
|
}
|
|
|
|
func placeholder(in context: Context) -> StatsChartEntry {
|
|
StatsChartEntry(date: .now, locked: false, theme: .matchApp, title: "일주일 통계", isWeekAxis: false,
|
|
isTimeType: true, names: [], colorHexes: [], points: [])
|
|
}
|
|
|
|
@MainActor
|
|
func snapshot(for configuration: StatsChartConfigIntent, in context: Context) async -> StatsChartEntry {
|
|
Self.makeEntry(configuration, family: context.family)
|
|
}
|
|
|
|
@MainActor
|
|
func timeline(for configuration: StatsChartConfigIntent, in context: Context) async -> Timeline<StatsChartEntry> {
|
|
Timeline(entries: [Self.makeEntry(configuration, family: context.family)],
|
|
policy: .after(.now.addingTimeInterval(30 * 60)))
|
|
}
|
|
}
|
|
|
|
// MARK: - 뷰
|
|
|
|
struct StatsChartWidgetView: View {
|
|
@Environment(\.widgetFamily) private var envFamily
|
|
/// 앱 내 DEBUG 미리보기에서 패밀리를 강제할 때 사용
|
|
var previewFamily: WidgetFamily? = nil
|
|
private var family: WidgetFamily { previewFamily ?? envFamily }
|
|
let entry: StatsChartEntry
|
|
|
|
var body: some View {
|
|
Group {
|
|
if entry.locked {
|
|
WidgetLockedView()
|
|
} else if entry.points.isEmpty {
|
|
Text("앱에서 행동을 만들고 기록하면 그래프가 표시돼요.")
|
|
.font(.caption2)
|
|
.foregroundStyle(.secondary)
|
|
.multilineTextAlignment(.center)
|
|
} else {
|
|
VStack(alignment: .leading, spacing: 4) {
|
|
Text(entry.title)
|
|
.font(.caption2.weight(.semibold))
|
|
.foregroundStyle(.secondary)
|
|
chart
|
|
}
|
|
}
|
|
}
|
|
.glassTextShadow()
|
|
.padding(13)
|
|
.widgetTheme(entry.theme)
|
|
}
|
|
|
|
private var colors: [Color] {
|
|
entry.colorHexes.map { Color(hex: $0) }
|
|
}
|
|
|
|
@ViewBuilder
|
|
private var chart: some View {
|
|
Chart(entry.points) { point in
|
|
if let day = point.day {
|
|
LineMark(
|
|
x: .value("날짜", day, unit: .day),
|
|
y: .value(entry.isTimeType ? String(localized: "시간") : String(localized: "값"), point.value)
|
|
)
|
|
.foregroundStyle(by: .value("행동", point.actionName))
|
|
.interpolationMethod(.monotone)
|
|
} else if let weekLabel = point.weekLabel {
|
|
LineMark(
|
|
x: .value("주차", weekLabel),
|
|
y: .value(entry.isTimeType ? String(localized: "시간") : String(localized: "값"), point.value)
|
|
)
|
|
.foregroundStyle(by: .value("행동", point.actionName))
|
|
.interpolationMethod(.monotone)
|
|
}
|
|
}
|
|
.chartForegroundStyleScale(domain: entry.names, range: colors)
|
|
.chartLegend(family == .systemSmall ? .hidden : .visible)
|
|
.chartYAxisLabel(family == .systemSmall ? "" : (entry.isTimeType ? String(localized: "시간(h)") : String(localized: "횟수")))
|
|
.chartXAxis {
|
|
if entry.isWeekAxis {
|
|
AxisMarks { _ in
|
|
AxisGridLine()
|
|
AxisValueLabel()
|
|
}
|
|
} else if dayCount > 7 {
|
|
// 한 달(일별) 등 포인트가 많으면 라벨이 서로 겹치므로 눈금만 표시
|
|
AxisMarks(values: .stride(by: .day)) { _ in
|
|
AxisGridLine()
|
|
AxisTick()
|
|
}
|
|
} else {
|
|
AxisMarks(values: .stride(by: .day, count: family == .systemSmall ? 2 : 1)) { value in
|
|
AxisGridLine()
|
|
AxisValueLabel(format: .dateTime.day(), centered: false)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// X축에 표시될 날짜 개수 (라벨 겹침 판단용)
|
|
private var dayCount: Int {
|
|
Set(entry.points.compactMap(\.day)).count
|
|
}
|
|
}
|
|
|
|
// MARK: - 위젯 정의
|
|
|
|
struct StatsChartWidget: Widget {
|
|
var body: some WidgetConfiguration {
|
|
AppIntentConfiguration(
|
|
kind: "HaruStatsChartWidget",
|
|
intent: StatsChartConfigIntent.self,
|
|
provider: StatsChartProvider()
|
|
) { entry in
|
|
StatsChartWidgetView(entry: entry)
|
|
}
|
|
.configurationDisplayName("행동 통계")
|
|
.description("선택한 행동들의 통계 꺾은선 그래프를 확인해요. (프리미엄)")
|
|
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
|
|
.contentMarginsDisabled()
|
|
}
|
|
}
|