mycode/myApp/HaruDanim/Widgets/QuestRingWidget.swift
songyc macbook ed8b52792a feat(widgets): 홈/잠금화면 위젯 6종 + Interactive Widgets (CLAUDE.md §8)
- 행동 실행(A): 소형1/중형3/대형4칸, Button(intent:)로 앱 없이 즉시 실행,
  측정 중 실시간 타이머 + 노란 테두리, 표시 기간(오늘/이번 주/이번 달) 옵션
- 목표 진행률(B): 하루/주간/월간 가로 진행바, 소형1/중형2/대형4
- 다짐 진행률(C): 원형 링 + 기간 옵션, 단일 행동 다짐은 눌러서 실행,
  '이하 유지'는 한도 지킴/초과로 표현
- 다짐 현황(D): 목표명 + 원형 링 그리드 (소형 2x2 / 중형 최대 8 / 대형 목표 2개)
- 통계: 행동 최대 3개 꺾은선 그래프, 앱 통계 탭과 동일 산식·색,
  소형은 '한 달 일별' 제외 (스펙 §8.3)
- 잠금화면: circular/rectangular/inline, 표시 방식 3종(게이지/숫자/다짐 점)
- 전 위젯 프리미엄 게이트 (미결제 시 잠금 안내)
- DEBUG 미리보기 화면: -widgetPreview YES|lock, -widgetPreviewScroll B|C|D|S

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
2026-07-10 08:59:47 +09:00

206 lines
6.8 KiB
Swift

//
// QuestRingWidget.swift
// Haru_DanimWidgets
//
// (CLAUDE.md §8.2 C / C / C)
// (Interactive)
//
import SwiftUI
import WidgetKit
import AppIntents
// MARK: -
struct QuestRingConfigIntent: WidgetConfigurationIntent {
static let title: LocalizedStringResource = "다짐 진행률 위젯"
static let description = IntentDescription("원형 진행률로 표시할 다짐과 기간을 선택하세요.")
@Parameter(title: "진행률 기간", default: .day)
var span: SpanOption
@Parameter(title: "다짐 1")
var quest1: QuestEntity?
@Parameter(title: "다짐 2")
var quest2: QuestEntity?
@Parameter(title: "다짐 3")
var quest3: QuestEntity?
@Parameter(title: "다짐 4")
var quest4: QuestEntity?
}
// MARK: -
struct QuestRingEntry: TimelineEntry {
let date: Date
let locked: Bool
let spanLabel: String
let cells: [QuestCellSnapshot]
}
struct QuestRingProvider: AppIntentTimelineProvider {
@MainActor
static func makeEntry(_ configuration: QuestRingConfigIntent) -> QuestRingEntry {
guard WidgetStore.isUnlocked else {
return QuestRingEntry(date: .now, locked: true, spanLabel: "", cells: [])
}
let span = configuration.span.statSpan
var quests = [configuration.quest1, configuration.quest2, configuration.quest3, configuration.quest4]
.compactMap { $0 }
.compactMap { WidgetStore.quest($0.id) }
if quests.isEmpty {
quests = Array(WidgetStore.defaultGoals(1).flatMap(\.sortedQuests).prefix(4))
}
return QuestRingEntry(
date: .now,
locked: false,
spanLabel: configuration.span.label,
cells: quests.map { QuestCellSnapshot.make(quest: $0, span: span) }
)
}
func placeholder(in context: Context) -> QuestRingEntry {
QuestRingEntry(date: .now, locked: false, spanLabel: "오늘", cells: [])
}
@MainActor
func snapshot(for configuration: QuestRingConfigIntent, in context: Context) async -> QuestRingEntry {
Self.makeEntry(configuration)
}
@MainActor
func timeline(for configuration: QuestRingConfigIntent, in context: Context) async -> Timeline<QuestRingEntry> {
Timeline(entries: [Self.makeEntry(configuration)], policy: .after(.now.addingTimeInterval(15 * 60)))
}
}
// MARK: -
struct QuestRingActionCellView: View {
let cell: QuestCellSnapshot
let spanLabel: String
var ringSize: CGFloat = 52
var body: some View {
if let target = cell.runTarget {
Button(intent: RunActionIntent(action: target)) {
content
}
.buttonStyle(.plain)
} else {
content
}
}
private var content: some View {
VStack(spacing: 4) {
ZStack {
QuestRingView(snapshot: cell, lineWidth: 5, iconSize: ringSize * 0.34)
.frame(width: ringSize, height: ringSize)
if cell.isRunning {
Circle()
.fill(AppTheme.yellow)
.frame(width: 9, height: 9)
.offset(x: ringSize * 0.38, y: -ringSize * 0.38)
}
}
Text(cell.targetName)
.font(.caption2.weight(.semibold))
.lineLimit(1)
Text(percentText)
.font(.caption2.monospacedDigit())
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.padding(6)
.background(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(AppTheme.surface)
)
}
private var percentText: String {
if cell.isAtMost {
return cell.isAchieved ? "\(spanLabel) 한도 지킴" : "\(spanLabel) 한도 초과"
}
return "\(spanLabel) \(Format.percent(cell.displayRatio))"
}
}
struct QuestRingWidgetView: View {
@Environment(\.widgetFamily) private var envFamily
/// DEBUG
var previewFamily: WidgetFamily? = nil
private var family: WidgetFamily { previewFamily ?? envFamily }
let entry: QuestRingEntry
private var visibleCount: Int {
switch family {
case .systemMedium: return 2
case .systemLarge: return 4
default: return 1
}
}
var body: some View {
Group {
if entry.locked {
WidgetLockedView()
} else if entry.cells.isEmpty {
Text("앱의 목표 탭에서 다짐을 만들면 진행률이 표시돼요.")
.font(.caption2)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
} else {
let cells = Array(entry.cells.prefix(visibleCount))
switch family {
case .systemMedium:
HStack(spacing: 8) {
ForEach(cells) { QuestRingActionCellView(cell: $0, spanLabel: entry.spanLabel) }
}
case .systemLarge:
VStack(spacing: 8) {
HStack(spacing: 8) {
ForEach(cells.prefix(2)) {
QuestRingActionCellView(cell: $0, spanLabel: entry.spanLabel, ringSize: 60)
}
}
if cells.count > 2 {
HStack(spacing: 8) {
ForEach(cells.dropFirst(2)) {
QuestRingActionCellView(cell: $0, spanLabel: entry.spanLabel, ringSize: 60)
}
}
}
}
default:
if let cell = cells.first {
QuestRingActionCellView(cell: cell, spanLabel: entry.spanLabel, ringSize: 58)
}
}
}
}
.containerBackground(AppTheme.background, for: .widget)
}
}
// MARK: -
struct QuestRingWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(
kind: "HaruQuestRingWidget",
intent: QuestRingConfigIntent.self,
provider: QuestRingProvider()
) { entry in
QuestRingWidgetView(entry: entry)
}
.configurationDisplayName("다짐 진행률")
.description("다짐의 진행률을 원형 링으로 보고, 눌러서 바로 실행해요. (프리미엄)")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}